Personal Project for managing Bookmarks - View Part

Overall, this is pretty nicely written.

Abstractions and code structure

  I am mainly concerned with the quality of the abstractions. Other reviews are also welcome but I am mainly concerned with the structure of the code.

The models are nice and simple, no comments there.

The classes in the views file are not great.
Since they only have static methods,
they are essentially utility classes.
As such, the methods don't really need to be in a class at all,
they could be simply top-level functions.
For example, these kind of calls are a bit awkward:

    return Autocomplete.autocomplete(request, Category, 'name')

Normally a class should help you avoid repeating terms.
For example a Person class would have a get_name method instead of get_person_name. Since Person is already implied by the class,
methods in it don't need to repeat the term "person".
The presence of calls like Autocomplete.autocomplete is a symptom of a problem with the class structure.

Possibly you created a class for Autocomplete to hide the private method _get_json.
That's not a bad idea.
However, since that method is only called from autocomplete itself,
it could just as well be inside autocomplete itself.
Also note that another way to group methods is to put them in a separate file.

Overall, I think classes with only static methods are not great.
They would be better converted to regular functions at the top level,
or in their dedicated file.
The same goes for GetBookmarks and GetCategories too.
And this is especially true for classes that only contain one public method.

Going back to your main question:
such classes don't represent useful abstractions,
they are simple groupings of related methods.
Utility classes are useful,
but if you only have a single method in them,
then they are a bit of an overkill and might not help all that much.

Coding practices

A couple of things are not very Pythonic or can be improved.

Instead of this:

    if ids_string == '':
        return []

It's more Pythonic to write this way:

    if not ids_string:
        return []

Instead of this:

    def _get_json(cur_objects, func):
        results = []
        for cur_object in cur_objects:
            results.append(func(cur_object))
        return json.dumps(results)

The common approach is to use a list comprehension, which makes it more compact and Pythonic:

    def _get_json(cur_objects, func):
        return json.dumps([func(cur_object) for cur_object in cur_objects])

Similar to earlier:

        if exclude_value != "":
            # ...

The Pythonic way would be:

        if exclude_value:
            # ...

This is more complicated than it needs to be:

        data = Autocomplete._get_json(
            objects,
            lambda x: getattr(x, attr_name)
        )

Since the _get_json function will simply call the lambda on the elements,
it would be more natural to use a simple list comprehension here,
and pass a list to _get_json without needing a lambda at all:

        data = Autocomplete._get_json([getattr(x, attr_name) for x in objects])

And since we know just how simple is _get_json,
we could simply bypass it entirely:

        data = json.dumps([getattr(x, attr_name) for x in objects])


A function for convenient string concatenation with variadic templates

I don't like the idea in any way, but it is my personal opinion. The approach may bring up problems such as occasional buffer override if your buffer happens to be smaller than needed.

If you really don't want to write c_str() all the time you can wrap std::stringstream with some kind of proxy, that would have operator const char*() as a member function. The only problem is to get all the copies of member operator << of the stringstream. I solved it using a template.

#include <sstream>
#include <string>

class sstream_proxy
{
    std::stringstream stream;
    std::string last;
public:
    template <typename T>
    sstream_proxy& operator<<(const T& value)
    {
        stream << value;
        return *this;
    }

    operator const char*()
    {
        last = stream.str();
        stream.clear();
        stream.str("");
        return last.c_str();
    }
};

The buffer will have the same content unless you call converting operator again. If you want to have multiple buffers, you can have multiple instances of sstream_proxy. The code is not bulletproof, but much easier to read and understand.

The code will be much more natural on its part.


It is easy to get a general understanding of what your code does.  You did a good job separating the code into functions.  It could be made more readable in a few ways though, mostly by doing things in a simpler way.  For example, your add_prime function (which appends a number to the end of a list) could be written in one line (I'll get to how later).

I recommend reading the Python tutorial.  By the time you get to chapter 4, you'll notice a lot of thing you would have done differently. :)

The variable names are good and make it easy to follow what you're doing, but the are a couple of names that are a bit confusing.  In particular, prime_number should be prime_numbers or simply primes because it is a list of numbers.  Also, limit isn't very descriptive at all.  The difference between the limit function and the upper_limit variable is that one gets the value from the user, and the other stores it.  limit should be get_limit or get_limit_from_user.

I like the way you comment.  The amount of comments is good and they improve readability.  Keep commenting like that.  I have one note, though:  When you're writing a comment that describes what a whole function or a whole program does, use a docstring.  This makes it clearer to other programmers what you commenting about, and makes it possible to access the comment in the code.

Here is what an improved version of the code could look like (comments starting with ## are part of this review and don't belong to the program):

"""Generate prime numbers."""    ## This is a docstring.

WELCOME_TEXT = """Welcome to the prime number generator!

This program generates all prime numbers starting from zero to an upper limit.
You'll decide the upper limit.

Have fun :)
"""

LIMIT_PROMPT = ("Type the upper limit and press enter. It has to be a natural "
                "number expressed in digits: ")

ALL_CAPS_NAMES are a convention meaning a value should be treated as constant.  In general, you should set constant values at the start of your program.  In this case, this also has the advantage that the WELCOME_TEXT won't be indented.

The two strings in LIMIT_PROMPT will automatically be concatenated.  This way, you can write a one-line string in two lines of code.

def welcome():
    """Introduce user."""    ## Also a docstring.  If your function definition starts
    print(WELCOME_TEXT)      ## with a string, the string will be made a docstring.

def get_limit():
    """Let user input a an upper limit for checking prime numbers.

    The input must be a natural number."""

    while True:
        try:
            return int(input(LIMIT_PROMPT))
        except ValueError:
            pass

I made a few changes to the get_limit function.  You should always catch only specific exceptions (ValueError in this case.) Also, I think it's better not to mix strings and numbers in one variable.

def is_prime(current_number, prime_numbers):
    """Check whether the number is a prime number.

    prime_numbers must contain all prime numbers lower than current_number."""

    for prime in prime_numbers:
        if current_number % prime == 0:    ## (current_number % prime) is the remainder
            return False                   ## when current_number is divided by prime.
    return True

You can loop over a list can be done easier this way.  Making is_prime return a boolean will make things easier for you in the main part of the program.

def main():
    welcome()
    upper_limit = get_limit()
    prime_numbers = []
    for number in range(2, upper_limit+1):
        if is_prime(number, prime_numbers):
            prime_numbers.append(number)    ## This adds number to the end of prime_numbers,
                                            ## so you don't need add_prime anymore.
    print("\n", prime_numbers, "\n\nThanks for generating prime numbers :)")

main()

I put the main part of the program into a main function (this is a useful convention).  Again, you can simplify the loop, this time using the range function.  For simple loops, there is usually a way of using a very readable for loop instead of a while loop.  I also changed the name lower_limit to number, which fits better in my opinion.

If you have any questions, feel free to ask them.  Welcome to codereview. :)


Thread-safe Phoenix Singleton class template with Boost

I'm not a threading specialist, so won't be able to tell you for sure if your code is 100% race condition free. However, there are a few other code smells that I would like to warn you about:

Reserved names: A name starting with an underscore and an uppercase letter is reserved in any scope. _CreateInstance, _Phoenix and _KillPhoenix are not safe to be used, even inside a class.
inline is redundant for a template class or function. The class is always inline, so you don't have to add the keyword.
explicit makes no sense for a constructor that takes 0 arguments. You usually apply explicit if you have a constructor taking 1 argument and you wish to avoid an implicit conversion.
Do you really plan on allowing classes to inherit from TSingleton? It doesn't seem like there is a need for that, since the singleton type is a template parameter. Maybe I'm missing something, but if it is not to be inherited, make all currently protected members private and remove virtual from the destructor.
This initialization style is mighty strange: _destroyed = (boost::atomic<bool>) false; A plain assignment _destroyed = false; or using the constructor syntax: _destroyed(false); would be much better.
When calling a static method or accessing a static variable of a class, inside the given class, prefixing the call with ClassName is optional. So you could, for example, simply use _instance instead of TSingleton::_instance.
VS 2013 should have most if not all C++11 features and libraries working. So you could replace Boost with the new threading and atomics libraries to reduce dependencies.
If you switch to C++11, you can delete the copy constructor and assignment operator.


Iteration over an XDocument based on some existing elements and conditions

There are several ways how you can process an XML using Linq2XML.
As I can understand you want to process only those XML files that are matching a given format. You can check this with XML native tools, like XSD or DTD schema definitions and validation or manually via XLinq.
If you want to check that with XLinq I would suggest to use the following methods:  Descendants, Elements and Attributes. Each returns those items where the predicate is met. If there is no match, then it will return an empty collection.
If you combine this logic with the Any extension method then you can turn your query operators into existence operators. If the queried collection's length is zero then it returns false otherwise true.

I would suggest to break your logic into two sub-functions:

Check whether or not the given xml meets the desired format
Process only that xml, which satisfies the preconditions

EDIT: To reflect new requirements
Check the presence of the Group element and act based on its existence:
var xml = "<Project><Group><Content Include = \"buildings\" /></Group></Project>";
var xDocument = XDocument.Parse(xml);
var project = xDocument.Root;
var isGroupExist = project.Elements("Group").Any();
if (!isGroupExist)
{
    var group = new XElement("Group") { ... };
    project.AddAfterSelf(group);
}
//Process it


Since letters is a list of characters (1 length strings) you logistically have made letters a string. And so you can simplify writing it as a string rather than a list of characters.

letters = "ABCDE..."

You can remove the need to define letters by using string.ascii_uppercase.
It's good to see some type hints. Good job!
I would suggest changing your function to only take in the base and the number, and return a new number, rather than print it.
You don't need to use math.floor you have a couple of alternate options:

Use int - int(div / base).
Use the floordiv operator - div // base.

Rather than using div % base and math.floor(div / base) you can use divmod to divide and get the modulo in one command.
Rather than using list.insert I would recommend using list.append and then using reversed.

This is because inserting at the start of a list in Python has to move every other item from the beginning of the list to the end of the list. Append on the other hand only needs to append to the end of the list and it doesn't have to touch the rest of the list.

I also find it cleaner to just use .append.
The check len(str(div % base)) > 1 would be better described as (div % base) >= 10. This is as we're working with numbers - /, %, divmod - and so thinking of the value as a number is easier.
If you change letters to string.digits + string.ascii_uppercase then you can remove the need for the if.
I suggest you change the order of your function's arguments, so it's inline with other base conversion functions. num then base.
It's Pythonic to have constants be UPPER_SNAKE_CASE and so letters should be all caps.

There's a lot of points above, but for a beginner your code is good. Good job!

import string

LETTERS = string.digits + string.ascii_uppercase

def to_base(num: int, base: int) -> str:
    new_num = []
    while num != 0:
        num, mod = divmod(num, base)
        new_num.append(LETTERS[mod])
    return "".join(reversed(new_num))

while True:
    while True:
        try:
            num = int(input("Please enter a number in base 10: "))
            break
        except (NameError, ValueError):
            print("Please use numbers only")
    for base in range(2, 37):
        new_num = to_base(num, base)
        print(f"{int(new_num, base)} in base {base} is {new_num}")


Flatten a nested dict structure in Python

Both algorithms recurse using the length of keys to stop, so I am going to assume that the nested dictionaries always have the same level of nesting too. If your input can be of the form:

{'foo': {
          'cat': {'name': 'Hodor',  'age': 7},
          'dog': {'name': 'Mordor', 'age': 5}},
 'bar': { 'rat': {'name': 'Izidor', 'age': 3}},
 'baz': 'woops',
}

then your approach can't handle it and neither will mine.

I quickly stopped trying to understand how your algorithm work and started to think about how I would implement it myself. This indicates that:

your algorithm is not that trivial;
it is poorly documented.

You should at least have comments indicating why you use some approaches: reversing the keys and iterating over them in decreasing order, storing your group names/values (values[keys[id]] = key) as you go into nesting levels and updating the last dictionary when you reach it…

Speaking about updating the last dictionary, note that data = copy.copy(data) does not protect your node.update(values) to modify the original data in place. You either need to use copy.deepcopy or to change the updated dictionary (create a new one and update it with both node and values).

Now let me show you an other approach. Rather than wrapping a function that access global variables (this is what visit look like) into flatten, you can make flatten the recursive function by splitting keys into its head and tail part. When there is no element left, you won't be able to do it and you can stop the recursion by returning the data you're on: this is one of the most nested dictionaries.

Otherwise, you can iterate over the key/values pairs, flatten the values using the tail as a new set of keys and then, build a list out of the flattened values and the {head: key} dictionary.

To make things a bit more efficient, I'll use generators instead of building lists, so you’ll want to change your calls from out = flatten(a, ['foobar', 'animal']) to out = list(flatten(a, ['foobar', 'animal'])) (calls of the form for flattened in flatten(a, ['foobar', 'animal']): don't need to be changed though):

def flatten(data, group_names):
    try:
        group, group_names = group_names[0], group_names[1:]
    except IndexError:
        # No more key to extract, we just reached the most nested dictionnary
        yield data.copy()  # Build a new dict so we don't modify data in place
        return  # Nothing more to do, it is already considered flattened

    for key, value in data.iteritems():
        # value can contain nested dictionaries
        # so flatten it and iterate over the result
        for flattened in flatten(value, group_names):
            flattened.update({group: key})
            yield flattened

I also changed keys to group_names to be able to use the generic names key and value when iterating over data.

In case the input data can ever contain less nested levels than the amount of items in group_names, you'll reach a point where data.iteritems() will raise and AttributeError. You can catch that if you so choose:

def flatten(data, group_names):
    try:
        group, group_names = group_names[0], group_names[1:]
    except IndexError:
        # No more key to extract, we just reached the most nested dictionnary
        yield data.copy()  # Build a new dict so we don't modify data in place
        return  # Nothing more to do, it is already considered flattened

    try:
        for key, value in data.iteritems():
            # value can contain nested dictionaries
            # so flatten it and iterate over the result
            for flattened in flatten(value, group_names):
                flattened.update({group: key})
                yield flattened
    except AttributeError:
        yield {group: data}

So

a = {
    'foo': {
        'cat': {'name': 'Hodor',  'age': 7},
        'dog': {'name': 'Mordor', 'age': 5},
    },
    'bar': {
        'rat': {'name': 'Izidor', 'age': 3},
    },
    'baz': 'woops',
}

list(flatten(a, ['foobar', 'animal']))

will return

[{'animal': 'woops', 'foobar': 'baz'},
 {'age': 5, 'animal': 'dog', 'foobar': 'foo', 'name': 'Mordor'},
 {'age': 7, 'animal': 'cat', 'foobar': 'foo', 'name': 'Hodor'},
 {'age': 3, 'animal': 'rat', 'foobar': 'bar', 'name': 'Izidor'}]


Proper way to wait end of a service and singleton design

Bug?

The catch block is a bit suspicious here:

try
{
    FileTestSingleton.getIstance(); //this could be long, read from file
} catch (Exception e)
{
    Log.e(LoadDataService.class.getName(), "FILE DATA LOADING ERROR \n" + e);
    result = Activity.RESULT_CANCELED;
}
result = Activity.RESULT_OK;
publishResults(result);

When you catch the exception, you set result = Activity.RESULT_CANCELED;,
but execution continues and on the next line comes result = Activity.RESULT_OK;.
In short, the method will return with success as if nothing happened.

Don't catch Exception

Always catch the most specific Exception type possible.
By catching something overly generic,
you may not notice when something truly unexpected is thrown.
In most practical situations there is a more specific exception class that you should check.

Don't declare a method to throw Exception

A method that's declared to throw Exception is very poorly designed.
It gives no clue to the caller about the kind of failure that can happen,
and it's impossible to know how to recover from it.
Surely you can think of something more specific,
to give the chance to callers to handle the failure gracefully.

Coding style

There is a standard in Java for placing braces:
the opening braces should be on the same line as their statement. Follow this style:

try {
    // ...
} catch (Exception e) {
    // ...
}

Proper way to wait for end of X

In other words, the proper way to execute a long operation without freezing the client. I think it's using an AsyncTask, with a ProgressDialog. Here's a rough sketch:

class WaitForServiceAsyncTask extends AsyncTask<Void, Integer, Void> {
    ProgressDialog mProgressDialog;

    protected void onPreExecute() {
        mProgressDialog = ProgressDialog.show(YourActivity.this, "",
                YourActivity.this.getString(R.string.msg_waiting_for_service), false, true);
    }

    protected Void doInBackground(Void... params) {
        // the long task -- calling the service
    }
}

This won't freeze the UI thread and will let the user know that the app is not dead, but actually doing something.


I see a flurry of downloading activity, but I don't see that you do anything with the pages that you download except parse some URLs for more downloading.  There's no rate limiting or any attempt to check robots.txt, making your web crawler a poor Internet citizen.

PEP 8 mandates four spaces per level of indentation.  Since whitespace is significant in Python, you should stick to the convention.  Furthermore, function names should be lower_case(), so Update() and getLinks() should be renamed.

Just a simple call to gevent.monkey.patch_all() will do.  There is no need to from gevent import monkey, nor is there any need to list all of the keyword parameters, since you're accepting all of the defaults.

Your linkregex fails if the <a> tag contains any intervening attributes before href.  For example, <a target="_blank" href="…"> will cause a link to be skipped.

I don't believe that your code is a well behaved multithreaded program.  For one thing, you indiscriminately spawn and start one thread per second.  If the average processing time per request exceeds one second, you'll end up with an uncontrolled proliferation of threads.

Another issue is that you add() and pop() tocrawl elements without any kind of locking.  Also, if one thread fails to pop() anything (probably when the tocrawl list becomes empty), you rudely call quit() without giving other threads a chance to finish what they are doing.

Finally, you process the URLs using a stack.  Web crawling is usually done using a queue, to avoid processing clusters of closely related URLs together and concentrating the load on one unfortunate webserver at a time.


Single price grid component (HTML & CSS Project)

HTML
Several elements are marked up as headlines, although they certainly aren't ones:

The text "Gain access..." in the description element should be two(!) paragraphs. (Don't use
 to create paragraph-like line breaks.)

Gain access to our full library of tutorials along with expert code reviews.

Perfect for any developers who are serious about honing their skills.

"$29 per month" and "Full access..." in pricing shouldn't be headlines either - especially not h2s after a h3. Also the price ("$29") itself needs to be markuped separately, since it's highlighted compared to the rest of the line. For example:

$29 per month

Full access for less than $1 a day

"Why us?" looks identical and is structurally identical to the headline "Monthly Subscription" in pricing, so it should have the same headline level.

The "button" "Sign up" functionally looks more like a link, than a <button>. (Buttons are primarily used to submit forms, which this is not.)
The class names are too generic and so can collide with other classes used on the site. Instead of container something like price-component would be more appropriate. And for the inner components either use a child/descendant selector in the CSS so that the rules only apply to your component:
.price-component > .description

Or use a CSS naming scheme (such as BEM) to create a unique class names for the inner components such as price-component__description.
CSS
Avoid absolute positioning. Centering the price component like that is only appropriate, if it's only used as a modal dialog, that covers the rest of the content of the page and the screen shot doesn't seem to indicate that. In order to "just" center it, use CSS grid or flex.
Also the use of relative positioning isn't appropriate. On those floats it is strange. It just creates a gap where there shouldn't be one and lets the elements overlap the bottom border. And on the list use either a left-margin or just a general padding on the featuredContent element.
Float is not appropriate for layout any more. This component is the perfect example for a grid layout.
Hard coding the width and height in pixels makes the component unresponsive to the screen and font size. For the max-width use relative units such as rem and don't set the height at all, letting it resize dynamically based on the content size. Also consider an alternative media query based layout for smaller screen sizes where it would be too wide.
Don't center all the text. For one, it contradicts the screen shot, but more importantly centered text is difficult to read.
Example: https://jsfiddle.net/vjr2ogpq/


Getting a key's value in a nested dictionary

Great job so far! I have a few suggestions for your code:

Avoid writing functions with side effects such as printed output. Side effects make a function much less reusable. Instead, you may return a generator that yields the next entry. This gives the caller maximum control over what to do with the result set: print it, iterate one by one, just get the first few items without searching the entire structure, etc.
Consider adhering more strictly to Python naming conventions. For example, functions should be lower_camel_cased. Since your function returns multiple PLUs, the function name seems more accurately written as get_plus. You can remove the pass keyword in your function and pay close attention to spacing, for example in the print (data[item]) function call and your else : block.
Clean up lines like

else :
    if item == 'PLU':
        print (data[item])

Which is logically equivalent to:

elif item == 'PLU':
    print(data[item])

Use data.items() to iterate through your dictionary's keys and values rather than only keys. This allows cleaner syntax to access values.
Make your function more general for maximum reusability. Fetching a list of values by key from a dictionary is a task that should work for any key. Why not make "PLU" a search parameter? If you want to keep the original get_plus version, write both functions and have get_plus wrap the generalized version.
isinstance may be a more accurate choice than type if you wish to allow collection subclasses of dictionary to use your function.

Here's my version for consideration:

def find_by_key(data, target):
    for key, value in data.items():
        if isinstance(value, dict):
            yield from find_by_key(value, target)
        elif key == target:
            yield value

def main():
    menu = {
      'PLU' : '234',
      'Salad': {
        'salad': {
            'ceaser':{
                'PLU': '32'
            },
            'italian':{
                'PLU': '33'
            }
        }
      },
      'Dessert': {
        'cookie': {
          'PLU': '334',
          'NAME': 'cookie ',
        }
      },
      'Appetizer': {
        'extra sauce': {
          'PLU': '61',
          'NAME': 'extra sauce',
        }
      }
    }

    for x in find_by_key(menu, "PLU"):
        print(x)

if __name__ == '__main__':
    main()


Design

The problem with getName is already mentioned in the comments. firstName + lastName is at least missing a space. Note that there are multiple ways of creating a full name - you may want to leave the construction of a full name to the caller. For instance, Germans are a bit more formal and may prefer "lastname, firstname". Usually initials are also an important part of a name (and then there is title, junior/senior etc.).

Second is the age. An age is a property of a person, but it is not one that keeps constant in time. You generally store the birthday of a person. Usually the precise day is stored (YYYY-MM-DD), or in more complex systems just the month (YYYY-MM) or even just the year (YYYY) if the other information is unknown. This may seem strange, but not everybody knows their exact birthday. The age can then be calculated from that using comparison with the current date.

Related, using 0 to signify that no age is known is choosing a bad magic value (or sentinel). Magic values are already not recommended, but choosing a valid age for a baby as magic value is not a good idea at all.

Returning return NO_ADDRESS; is dangerous, especially if you don't have any method to indicate that NO_ADDRESS is indeed not an address. It is generally up to the caller to choose what to insert as string if no address is known, otherwise you may get packages posted to NO_ADDRESS. A hasAddress method would solve this. If you have an unknown address then you may use an Optional value instead. Accepting and returning an Optional<String> would remove the issue altogether and may bring down the number of methods and constructors. Storing the address as optional is not recommended because it cannot be serialized; probably best to use null, but make sure that you don't return null.

As you may notice, currently your Person instances can change completely by calling the setters. That's no good if you want to keep track of a person. This is why almost all organizations will create a unique ID for each person. That way any property can change without them becoming someone else. The ID can then represent the person in e.g. a transaction system.

Code

The code is generally well formed.

However there are some remarks to be made:

fields default to false so there is no need to initialize them to that value; it might be a good idea to set all fields in the various constructors so that they are not forgotten;
the if statement does not use braces; always use braces to subsequent changes do not result in unmaintainable code;
similarly, you will probably use class instances in collections, so you need to implement the hashCode and equals methods;
implementing toString is recommended for any class really.

Ideas

Using set methods is generally not a good idea. Having immutable objects often makes more sense. Other variants you may consider is having a Map of properties or having a factory / factory methods to create Person instances.

In Java, you may want to implement Serializable for data classes (and the static serializable UID - Eclipse will warn you about this) - that way you can more easily communicate data over a binary connection / stream. This is contended in the comments. In general, I would however try and keep in mind that you may want to be able to serialize a class in the future and - therefore - try and use serializable fields.


Excel VBA code midStr() function using left and right position instead of length used with mid()

While the Optional ByVal rightPos As Variant is a cool idea because you can use the IsMissing function, it introduces unnecessary errors. For example, Debug.Print midStr("Hello World", 1, Nothing) will print "Error 2015" in the Immediate window. That line should not be allowed to compile.
I would declare the rightPos parameter as Long. The compiler will take care of some of the issues - for example you won't be able to pass an Object. The Long will default to 0 so you can replace If IsMissing(rightPos) Then rightPos = Len(textin) with If rightPos = 0 Then rightPos = Len(textin).
The generally accepted convention in VBA is that method names are written with PascalCase and variable names are written with camelCase. Moreover, an Excel User Defined Function (UDF) is usually written with UPPERCASE.
This function seems to be designed as an Excel UDF. What if you need to use it in VBA? The Excel errors mean nothing to another VBA method. I would write this as a separate VBA only function that will work in any VBA-capable application host (no need to return a Variant):
Public Function MidStr(ByVal textin As String, _
                       ByVal leftPos As Long, _
              Optional ByVal rightPos As Long _
) As String
    Const methodName As String = "MidStr"

    If leftPos < 0 Then Err.Raise 5, methodName, "Invalid left position"
    If rightPos < 0 Then Err.Raise 5, methodName, "Invalid right position"

    If rightPos = 0 Then rightPos = Len(textin)
    If rightPos < leftPos Then
        MidStr = vbNullString
    Else
        MidStr = VBA.Mid$(textin, leftPos, rightPos - leftPos + 1)
    End If
End Function

I would then have an Excel UDF:
Public Function MID_STR(ByVal textin As String, _
                        ByVal leftPos As Long, _
               Optional ByVal rightPos As Long _
) As Variant
    On Error GoTo ErrorHandler
    MID_STR = MidStr(textin, leftPos, rightPos)
Exit Function
ErrorHandler:
    MID_STR = CVErr(xlErrValue)
End Function

This allows the use of MidStr function in other VBA methods and the MID_STR is only going to be called via the Excel interface.


Replacing the second word of some matching lines in a file

Here are some comments to your solution:

Try avoiding reading the entire files into memory – Using readlines() means you read the entire file into memory, which can be eat a lot of memory. Usually it is better to read and process the file line by line
Use with open(...) for pythonic file reading/writing – This can be used both for reading and writing files, and can also be combined into a double with in your case to read and write at the same time
Make functions a little more generic – To have a function to change just one explicitly named config value seems a little strange. Two natural extensions: 1) Allow for an arbitrary config value to be changed, 2) Allow for multiple config values to be changed in one go.
Note that "OutputFilename" in line matches in the entire line – If you write "OutputFilename" at end of line it matches, or at start, or as part of another word. This could lead to a lot of failing changes.
Set the new config line directly – If you have a positive hit on the line you want to change, you know how the line is supposed to look, so no need to split, append and change it. Set it directly to the correct value.
Add some blank lines in your script to make it easier to read – A lot of people are afraid of having blank lines in script, and that is said. It can make the script a lot easier to read.

Refactored code

Here is two functions (within a program) to illustrate a better approach:

def change_configuration_option(
    option,
    new_value,
    sourcefile = "cuts.txt",
    destinationfile = "cuts_new.txt"):
    """Change option_name in sourcefile to new_value in destinationfile."""

    with open(sourcefile) as source, open(destinationfile, "w") as destination:
        for line in source:

            if option in line: # Buggy match on line...
                destination.write('{} {}\n'.format(option, new_value))
            else:
                destination.write(line)

def change_configuration_options(
    change_options,
    sourcefile="cuts.txt",
    destinationfile = "cuts_multiple.txt"):
    """From sourcefile to destinationfile do change_options."""

    with open(sourcefile) as source, open(destinationfile, "w") as destination:
        for line in source:

            # For every line, match against new_options
            for option in change_options:
                if line.startswith(option + ' '):
                    destination.write('{} {}\n'.format(option, change_options[option]))
                    break

            else:
                destination.write(line)

def main():
    """Replace output.root with new_output.root in config file."""

    change_configuration_option("OutputFilename", "new_output_file.txt")

    change_configuration_options(
        { "OutputFilename" : "new_output_file.txt",
          "YetAnother" : "bites the dust",
          "AnotherConfig" : "And another one",
         })

if __name__ == '__main__':
    main()

The change_configuration_options() takes a dictionary of new configuration option changes, and it uses a little trick within the inner loop to check write non-matching options to the output file. That trick is the for ... else loop. If the for loop completes normally, the else will execute, but if a matching option is found and it break's out of the loop then the else: will not be executed.

Also note that in the multiple variant, I've changed the matching on the line to be line.startswith(option + " "), which limits the option to be at the start of the line, and a complete word followed by a space. This avoids false hits, as are present in your original code and in my change_configuration_option() for changing the single option. (Left as proof of concept, see tests below)

Test run

I tested this using the following cuts.txt file:

MyOutputFilename Not_this_file
OutputFilename this_file_should_change
# Next line should have value "no change"
OutputFilenameAndSome no change
# Multiple
AnotherConfig AnotherValue
YetAnother config value with multiple spaces
# Flawed
FinalFlaw What if the value has OutputFilename as part of text?

And after running, I got the file cuts_new.txt:

OutputFilename new_output_file.txt
OutputFilename new_output_file.txt
# Next line should have value "no change"
OutputFilename new_output_file.txt
# Multiple
AnotherConfig AnotherValue
YetAnother config value with multiple spaces
# Flawed
OutputFilename new_output_file.txt

Notice the duplicated line near start, due to falsely changing the OutputFilenameAndSome option, and the changed bottom line when comparing to original file.

And finally the file cuts_multiple.txt:

MyOutputFilename Not_this_file
OutputFilename new_output_file.txt
# Next line should have value "no change"
OutputFilenameAndSome no change
# Multiple
AnotherConfig And another one
YetAnother bites the dust
# Flawed
FinalFlaw What if the value has OutputFilename as part of text?

This file has only the intended changes. The latter option should be a better alternative for changing lines in a file, and should be quite efficient as well. A further optimisation, could be to remove already changed option from the change_options dict after doing that line, but then again that could be unneccessary micro optimisation.

The provided solutions reads and writes the file in one go, and only keeps one line of the file in memory (except internal cacheing). In most operating systems, this should be the better option for handling an arbitrarily sized file. (Earlier Windows version could loose some efficiency due to the almost simultaneously read and write to two different places/files at the same time.)


bool IsPrime(unsigned long n){
    unsigned long k;
    for(k = 2; k*k <= n; k++){
        if(n % k == 0){
            return false;
        }
    }
    return true;
}

A couple things off the bat.

bool isPrime(unsigned long n) {
    for (unsigned long k = 2; k*k <= n; k++) {
        if (n % k == 0) {
            return false;
        }
    }

    return true;
}

The general standard is to name functions either camelCase or snake_case.  You used PascalCase, which is generally only used for classes and structs.

It is standard to declare loop variables that are not used outside the loop in the for declaration.  That's one of the advantages of a for loop, that it allows you to do that.

But neither of those would cause performance problems.  This code checks if each number from 2 to \$\sqrt{n}\$ is a factor of n.  But you don't need to check all the numbers.  You only need to check the primes.  And of course, you generate a list of primes, so it's easy enough to save that and check just the primes.

Something like

bool isPrime(unsigned long n, unsigned long *primes) {
    for (size_t k = 0; primes[k]*primes[k] <= n; k++) {
        if (n % primes[k] == 0) {
            return false;
        }
    }

    return true;
}

Back in the calling function, you will need to add some code to handle primes.

Before the loop.

unsigned long *primes = malloc(2 * sizeof *primes);
if (!primes) {
    // panic:  exit, return, or whatever seems reasonable
}
primes[0] = 2;
primes[1] = 3;

size_t length = 2;

Then take

    unsigned long m, l = 2, k = 1;
    scanf("%lu", &m);
    if (m == 1) {
      printf("%d\n", 2);
    } else if(m == 2){
      printf("%d\n", 3);
    }else{
    while(1){

and replace it with

    size_t m;
    scanf("%u", &m);
    if (m > length) {
        unsigned long *temp = realloc(primes, m * sizeof *primes);

        if (!temp) {
            free(primes);
            // panic:  same way as last time
        }

        primes = temp;
    }
    m--;

    unsigned long candidate = 5;
    unsigned long increment = 4;
    while (length <= m) {
         increment = 6 - increment;

This changes the array index to size_t.  This will easily support 10,000, which is the maximum m (what HackerRank calls \$N\$).

This also changes l to a size_t, since it has to be smaller than m and it will index an array.

This expands the primes array as necessary to handle the inputs.

I moved declarations to when they are initialized.

Your k code has some problems:

You do an increment, a multiplication, a subtraction, and an addition every two iterations.
You do two iterations of l per loop iteration.
You have to duplicate code to handle both the same.
You have to loop forever since the exit criterion is hidden.
You have to check two conditions before the loop to handle the first two primes.

This version of the code prepares to do

One iteration per loop iteration.
The exit criterion is in the loop declaration.
This does one subtraction and one addition on every iteration.
The code no longer needs duplicated.
No special cases are needed for the first two primes.
The solution can be printed after the loop, once rather than in four different places.
If some previous test looked for a later prime, we remember that and don't enter the loop at all.

The candidate variable will have the same values as 6*k-1 and 6*k+1.  The increment will alternate between 2 and 4 (6-2=4 and 6-4=2).  So candidate will be 5, 7, 11, 13, 17, ...  Just as previously.

The rest of the loop can be

        if (isPrime(candidate, primes)) {
            primes[length] = candidate;
            length++;
        }

        candidate += increment;
    }

And then

    printf("%lu\n", primes[m]);

If m was originally 1, it will now be 0 and primes[0] is 2.  If m was originally 2, it will now be 1 and primes[1] is 3.  So there's the special cases.

Outside the outer loop, you should

free(primes);

The big performance improvements are

Not recalculating the same primes for each test case.
Not checking for non-prime factors in isPrime.


Ignoring the 'use a different algorithm' approach. (Even though the Sieve of Eratosthenes is better).

There are two very common optimisations you missed in the prime checker.

You can increment by 2, so you skip all the even numbers.
You can return False early to avoid waisted CPU cycles.

There is another less common optimisation.

Going to the square root of n.

There is also a rare algorithm, that goes in steps of 6.
But that's uncommon, and if you need that speed, use the Sieve.

As for your addition_of_primes function,
I would not build up an intermarry list.

One way to do that is:

amount = 1
total = 2
candidate = 3
while amount < b:
    if is_prime(candidate):
        amount += 1
        total += candidate
    candidate += 2

return total

Or if you want this all in one line:

import itertools
return sum(itertools.islice(itertools.ifilter(is_prime, itertools.count(2)), b))

If you add the optimisations to is_prime, you should get:

def is_prime(num):
    if num == 2:
        return True

    if num % 2 == 0:
        return False

    for div in xrange(3, int(num ** 0.5) + 1, 2):
        if num % div == 0:
            return False
    return True


Using a string for storing a password is considered insecure because there is no possibility to delete that string from memory. From the SecureString documentation

  An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created, and it is not possible to predict when the instance will be deleted from computer memory. Because System.String instances are immutable, operations that appear to modify an existing instance actually create a copy of it to manipulate. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.

so it would be better to use a SecureString but unfortunately that isn't an option when using Aes because it doesn't take an SecureString as a parameter. So what other options are there ? Just take a char[] and overwrite its content when the class is disposed.

The CreateSecureSessionTokenAsync() method should ideally return the token along with a random generated salt (maybe as tuple) to be stored in the data store to decrypt it later without the need that the customer will get the salt together with the token.

An implementation of a random salt using a parameterized length can be found in my answer here.


1) I'd start with a better HTML template, you forgot the DOCTYPE and meta tags:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

</body>
</html>

2) Don't use topalign and align HTML attributes. Keep the styles and layout separate, use CSS:

body {
  margin: 15px 0;
  text-align: center;
}

3) In JavaScript it is ussually preferred to put braces on the same line, because the ASI (automatic semicolon insertion) feature can be problematic, consider this buggy example:

return
{
  foo: 'foo'
}

JavaScript will do this:

return; //<--!!!!
{
  foo: 'foo'
}

See the semicolon it added? Now you return undefined, and not an object.

Now, you forgot a bunch of semicolons. Again, ASI can fill them up for you, but I don't recommend you rely on it if you're a beginner, so my advice is always put the semicolons.

5) Check your code in JSHint, this is what I got:

13 warnings
1   Missing semicolon.
5   Missing semicolon.
6   document.write can be a form of eval.
6   Missing semicolon.
8   Missing semicolon.
9   document.write can be a form of eval.
9   Missing semicolon.
13  Missing semicolon.
14  document.write can be a form of eval.
14  Missing semicolon.
16  Missing semicolon.
17  document.write can be a form of eval.
17  Missing semicolon.
One undefined variable
5   randomnumber
6   randomnumber
13  randomnumber
14  randomnumber
One unused variable
1   time

Go one by one, try to fix all those warnings.

6) Avoid document.write, see Why is document.write considered bad practice. In other words, use the DOM.

7) Inline events are bad practice, again, use the DOM, with addEventListener.

8) Using the DOM can be expensive. Try to always add elements all at once. Document fragments help you improve performance, because you don't mess with the DOM on every iteration of the loop.

9) Finally, separate concerns; the single responsibility idea. This is how I would write it taking all those points into consideration:

// Use the DOM to create elements
function makeInput() {
  var input = document.createElement('input');
  input.type = 'checkbox';
  return input;
}

function append(ele, parent) {
  (parent||document.body).appendChild(ele);
}

function makeLights() {
  var i, j;
  var br = document.createElement('br');

  // Use a document frag to improve performance
  var frag = document.createDocumentFragment();

  // No need to reset "j" on every iteration
  for (i=0; i<=32; i+=2) {
    for (j=0; j<=i; j++) append(makeInput(), frag);
    append(br.cloneNode(), frag);
  }

  for (i=30; i>=0; i-=2) {
    for (j=0; j<=i; j++) append(makeInput(), frag);
    append(br.cloneNode(), frag);
  }

  // Append to document all at once
  append(frag);
}

function randomColor() {
  return Math.floor(Math.random() * 2323232);
}

// Use event delegation for best performance
document.body.addEventListener('mouseover', function(e) {
  if (e.target.tagName == 'INPUT') {
     document.bgColor = randomColor();
  }
});

makeLights(); // init

Demo: http://jsbin.com/yiyic/1


We have some magic numbers.  Also, why don't we use modern syntax for our NSNumber objects?

NSNumber *opacityFromValue = @0.3f;
NSNumber *opacityToValue = @0.0f;

CGFloat fadeLoadBarDuration = 0.8;
CGFloat fadeCheckmarkDuration = 1.0;

CGFloat timeCheckmarkOffset = 0.5;

And now use these variables in place of the magic numbers.

As an added bonus, we'll get slightly better performance by not having to instantiate the opacity values twice each.  NSNumber is an immutable object, so it doesn't matter that we pass the same one both times.


Using a dependency container to load a parent/child class

Don't use a private attribute for the database, use a protected one. That way both classes can share the same $_db, and you only need one setDatabase.

As for your code being OO or not, there simply isn't enough code here to make the claim one way or the other.


This code does not compile, and has many bugs. Can you fix the errors in it?

url- = is a syntax error.

I don't recommend calling a variable split when you are using a method split, it's confusing.

You did not use that variable named split.

You did not define a variable message.

print 'r.text' should I suppose be print r.text.

I'm not sure about data = conn.recv(1024), what will happen if a request is longer than 1024 bytes?

This code needs to be debugged, it is not ready for code review. But it seems like a nice idea, and structurally okay, a good start.  I could help you debug it and get it working if you like.


How would you count in the Fibonacci Sequence?

var fib = function(params) {
    var iterations = params;

Why are you copying params into iterations, rather than just naming your parameter iterations?

    var output = [0];

That's not really your output is it? Perhaps there is a better name?

    for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);

Output already contains ints. There is no reason to parseInt it. Why don't you directly push on the array rather then storing it in an int? Furthermore, you don't actually need an array, you only need the last two elements.

    }
        console.log(output[iterations-1]);

Fix the indent here.
    }

fib("4");

Why are you passing a string?


Is it good practice in Java to pass a StringBuffer to a method to get error messages

Since you are dealing with a validation method, I believe you will want to read my question Is it better practice to have void method throw an exception or to have the method return a boolean? and its answers. My point there is that you don't really need to return a boolean, you could also have a void method throw an exception if the validation fails. The exception could then, in your case, contain the errors as its payload. But I think that passing a logger as a parameter isn't a bad practice, just basically a matter of personal preference and to be decided on a case by case basis, much like the question about whether to return a boolean or to throw an exception.

In any case, however, I would never use a StringBuffer as an error logger like in your case. For one, I might be building a web application where the output is rendered in HTML. In that case the StringBuffer would basically need to contain the HTML markup, which would then become a problem once you one day figure out that you need to run your process from the command line as well, and then you get all the HTML markup to mess up the output there. Also, with the StringBuffer you cannot easily get the error count, just whether there were any errors or not. So I would probably create an implementation of some IErrorHandler kind of interface wrapping a List<String> rather than a StringBuffer, as in @dreza's answer.


The code generally looks good to me.  It is clear, complete and working.  The naming and formatting are clear and consistent (although I prefer to read code that does not have the space before each statement-terminating semicolon) but I did see a few things that may help you improve your code.

Consider using {} style initializers

There are a few places where  a Token is constructed, such as this:

Token token (current, next_) ;

However, this might be misconstrued as a function call. Assuming that you're using C++11 or better, it may be worth considering using the {} style for the constructor:

Token token {current, next} ;

This can't be misconstrued as a function call and may be slightly less ambiguous.

Consider alternative usage

The code works well for the use cases you've said you're interested in addressing.  That's good, and it may be all you ever need, but when I first saw the code, I thought it might be useful to be able to use it like this:

std::string const s2 = "55,33,1,7,42";
auto const t4 = BackInsertTokenize <std::vector <int>> (s2, ',') ;

The intent was to create a vector of integers from the const string, but this code doesn't actually compile.  The problem is essentially this line:

*out++ = Token (current, next) ;

That works fine for any Token type that can be constructed from an iterator range like this, but not for a primitive type like int.  One way to address that might be to provide another template that additionally takes an operator to explicitly perform this conversion with the given types.

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Check if email address contains one of many domains from a table, ignoring the subdomain

Looking at your current code first, I noticed the following:

You should use email.split('@').last instead of an opaque numeric index (plus, you'll always get a string this way, whereas using [1] will return nil if the address doesn't contain an "@" to begin with)
You should probably downcase the address you're trying to match (provided the university domains are similarly downcased, of course)
You never need to loop, check a condition, and set a variable + break if that condition is true. The reason you don't need to that is because you have Enumerable#detect to do it for you.
This looks like a Rails project, so it'd probably be faster to either let the database check for you, or only load the column you need, instead of loading every single University record.

For instance, to let the DB check it, you can do this

match = University.where("? LIKE CONCAT('%', domain)", self.email).any?
errors.add(:email, "Sorry, no match found") unless match

Since you're not actually loading any records doing this, I'd imagine it's pretty fast (and case-insensitive, so no need for downcasing)

As for matching things in Ruby, Nat's approach is the most straightforward one, I'd say.

I'd still do it a bit differently, though:

address = self.email.downcase

# only load the domain column values, since those are all we need here
match = University.pluck(:domain).detect { |domain| address.end_with?(domain) }

errors.add(:email, "Sorry, no match found") unless match

Of course, you should still check that the address is a valid email address in its entirety.


Using a separate class in Symfony to handle a list of entities with controller injection

controller injection

There are almost none use cases where injecting the controller is a good practice in my opinion.

controller should be in control, and not to be controlled. By design you should glue all the part inside the controller and give order in a way.
I assume that most of the functionality you need from the controller, are just another services and not functionality of the controller itself. If it is so then it better to inject the Container object and adding the ContainerAwareInterface
Still in the end it would be best to inject all 5-6 separate dependencies, because you won't hide your dependencies and your code would be easier to test.

multiple dependencies

If you start to inject many dependencies to an object most of the times it means you are giving to many responsibilities to that object. In general I would say that after 5 dependencies stop and think if it couldn't be grouped in new objects responsible for some parts of the logic.

Lets have an scenario:

you are working with data that are all in one language, suddenly your client wants to add multilang support.
you pass all the separate dependencies to our ListTable class, lets say repository, authUser, somethingOther ...
now you realize that you need to pass the current language, so you need to add dependency (object or string doesnt matter).

Best solution in this case would be to create a new class to handle all the responsibilities of retrieving the correct data to display.
Data gathering is one of the things that your ListTable should not do, as its main responsibility should be preparing/digesting the data for easy visualization.

On an example:

Class SecureDataProvider implements LocaleAwareInterface
{
   public function __construct(ObjectRepository $repository, User $authentificatedUser, $locale)
   {
    ...
   }
   public function getLatestRecords()
   {
      // checks if authenticated user got access to this operation or whatever
      // call the repository the get the record sorted by createdAt, passing the locale as query parameter to have the results in requested locale
      // ...

      return ArrayCollection($entities);
   }
}

now you would need to pass only this object to your ListTable.

new ProductListTable(new SecureDataProvider($articlesRepository, ..., ...) );

design of your class

As I said and above you need to separate your responsibilities. The listTable tries to do too much.

On another note visualizing a table is the VIEW in the MVC, and the best place to handle it is in the template.

The purpose of your class should be preparing the data, the way how these data would be shown is the point of View layer (or response).1
The data could in the end be in

table or list
graph (headers as labels),
json, xml or whatever other format from API.

That said the name should be probably changed to reflect the aspect of preparing the data and leave out the part what it will be in the end (table).

If you use twig, you probably would want to make macros for handling the different visual representation

A great reading material on OOP design: http://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/


Tarjan's algorithm for Strongly Connected Components without keeping SCC in stack

Brace Usage

It is generally considered best practice to always use braces with control statements (such as "if" and "for" statements). If you are concerned with whitespace, consider that placing the opening brace on the same line as the control statement means that the total increase in code size is only 1 line (for the closing brace). It has the added benefit of causing the compiler to complain if you later delete the statement, without deleting the entire block of code attached to it.

Preincrement vs. Postincrement

While both preincrement (++i) and postincrement (i++) do the same thing in isolation, I generally prefer to read the latter. The latter also happens to behave the way most people expect when refactoring the code (render the value, then increment), whereas the former tends to be a very special case (increment first, then render the value) which can cause errors and confusion during refactoring and maintenance. As such, I would recommend using preincrement operators only in the rare occasions they are actually needed (they're a flag that you need to slow down and read that chunk of code carefully).

Algorithm Behavior

The algorithm's output varies based on the order that the edges are presented to the class. Either the class needs to ensure that its internal edge lists are always in the appropriate order assumed/required by the algorithm, or the algorithm needs to be modified to handle edges in an arbitrary order (which the stack-based algorithm does).

The original question's test vector results in:

0
1,2,3,4
5,6,7
8

Whereas reordering the edges to be:

{4, 8}, {1, 2}, {8, 6}, {2, 5}, {3, 1}, {7, 5}, {4, 1}, {2, 4}, {4, 6}, {5, 6}, {6, 7}, {2, 3}

Results in an output of:

0
1,2,3,4
5,6,7,8

There may be additional deficiencies/broken cases surrounding this particular implementation. I ceased investigation upon finding this problem, but I would strongly suggest extensive verification against a known-working stack-based implementation after taking any corrective actions on your stackless algorithm.

Container Types

As a general rule of thumb, when returning a container, you should return the most-generic container interface type appropriate. It is almost never appropriate to return a concrete container, such as a List<T> or Dictionary<T>. In the case of public List<List<int>> GetStronglyConnectedComponents(), it should probably return ICollection<ICollection<int>> (since knowing how many groups and how many vertices are in each group makes sense enough to not use IEnumerable<T>, but all of the IList<T> functionality seems overkill).

Comments

Comments are far easier to read when they are above the line they are commenting, rather than to the right. Comments on the right of lines tend to contribute to overly-long lines, they tend to not be well-aligned (and come out of alignment upon refactoring), and tend to get lost/pushed off the side of the screen. All of this makes it much more difficult to do a comments-only skim of the code to get the gist of what it's supposed to be doing, prior to analyzing the code proper, or when quickly trying to find the part of the code you need to modify. The only benefit of comments on the right is that they take up less horizontal space -- but the hit to readability, and therefore usefulness, makes this placement unacceptable to me in most cases.

Some of the comments could also use improvement. "If we will ever find cycle" is confusing; it's either an incomplete thought, or placed on the wrong line. "Initialize to current time" is self-evident; it would be more useful to know why initializing to the current time is important (and possibly comment what currentTime is/does). "DFS" I assume means "depth-first search," and if so, should go into the recursive GetStronglyConnectedComponents call (right before the if statement that kicks off the actual depth-first searching), not the root call.

The "var currentDiscoveryTime[...]" comment is also dead code, and should be removed.

Structures

It would be nice from an aesthetic standpoint to, e.g., pass around a single array of a structure containing your working data, rather than three same-sized arrays.

Speed

If you're simply aiming to get to an \$O(1)\$ sidestep of the stack lookup, consider the easier alternative of keeping a secondary data structure (such as your List<bool>) that you can modify to mirror the stack, allowing you \$O(1)\$ insertion and lookup in \$2N\$ space. This would eliminate your need to get clever with edge orderings (which will take time to sort) or subtle algorithm alterations (translating the stack to effectively an array), while getting you the speedup you want. It's not as cool or elegant as the algorithmic gymnastics of doing away with the stack altogether, but it's much more likely to be maintainable, fast, and correct in the future. ;)


Updating a jquery progressbar via button clicks

Not sure if it is helpful, but since we are on codereview, allow me to give it a shot.

there is a progress element available in HTML5 that works very easily and is fairly well supported (http://caniuse.com/progressmeter), except for in IE off course. I would suggest using this in stead of the (heavy) jquery-ui you use now.
When writing js code, avoid global variables at all cost. They take up resources, and some day they will come and haunt you when you accidentally overwrite a variable that you forgot about. Keep your variables in function scope whenever possible.
when you see yourself writing the same code more then once, with just a minor difference in one of the values, try to think of a way to reuse your code. It will decrease the number of bytes, make your code better maintainable, and almost certainly improve the quality of your code.
Be careful with setTimeout. It can be a very useful and powerful tool, but it costs quite some resources. When working with jQuery, try to use their functions in stead. They have been used and tested millions of times, and you are a lot less likely to mess things up when you use them.

With those tips in mind, I tried to rewrite your code.The full version is in the updated fiddle, and the javascript is here:

// changing progressbar when button is clicked
$(".button").click(function () {
    animateProgress(parseInt($(this).data('diff')));
});

// animate progress by a step indicated by diff
function animateProgress(diff) {
    var currValue = $("#progress").val();
    var toValue = currValue + diff;

    toValue = toValue < 0 ? 0 : toValue;
    toValue = toValue > 100 ? 100 : toValue;

    $("#progress").animate({'value': toValue}, 500);
}


Convert sequence of number into display string

1. Separate data representation from actual output, using standard algorithms where possible.

make_ranges below takes input sequence array and returns limits of all ranges found, in two different sequences from, to:

template<typename F, typename T, typename A>
void make_ranges(F& from, T& to, A array)
{
    auto diff = array;
    std::sort(array.begin(), array.end());
    std::adjacent_difference(array.begin(), array.end(), diff.begin());

    std::vector<size_t> idx(array.size());
    std::iota(idx.begin(), idx.end(), 0);
    auto sep = [&diff] (size_t i) { return diff[i] > 1; };
    for(auto p = idx.begin(); p != idx.end();)
    {
        from.push_back(array[*p]);
        p = std::find_if(++p, idx.end(), sep);
        to.push_back(array[*(p - 1)]);
    }
}

2. For most generic use, use a stream for output:

template<typename S, typename I, typename J>
void print_range(S& stream, I i, J j)
{
    stream << *i;
    if (*j != *i)
        stream << "-" << *j;
}

template<typename S, typename F, typename T>
void print_ranges(S& stream, const F& from, const T& to)
{
    auto i = from.begin();
    auto j = to.begin();
    if (i != from.end())
        print_range(stream, i++, j++);
    while (i != from.end())
    {
        stream << ",";
        print_range(stream, i++, j++);
    }
}

3. For convenient use, provide a streaming operator interface:

template<typename S, typename A>
S& operator<<(S& stream, const array_ranges<A>& ranges)
{
    typename std::decay<A>::type from, to;
    make_ranges(from, to, std::get<0>(ranges));
    print_ranges(stream, from, to);
    return stream;
}

where array_ranges is a helper struct holding a sequence and indicating that its ranges should be streamed out instead of the sequence itself. Given a sequence, an array_ranges instance is made easily via helper function ranges:

template<typename A>
struct array_ranges : std::tuple<A> { using std::tuple<A>::tuple; };

template<typename A>
array_ranges<A> ranges(A&& a) { return array_ranges<A>{std::forward<A>(a)}; }

Example

Now the above can be used as

std::vector<int> arr{1,2,3,4,5,7,7,8,8,8,10,15,10,11,12,88,87,86};
std::cout << arr << std::endl;
std::cout << ranges(arr) << std::endl;

See live example.

If you want to print the ranges into a string, just use an std::ostringstream.

Discussion

With the above separation, you can do more advanced tasks like extracting ranges from arbitrary sequences, processing them (e.g. filtering or merging two sets of ranges), and finally printing them.

If you don't need any extra processing, this separation is more costly than direct printing since it stores intermediate results in arrays from, to. Using std::adjacent_difference introduces another intermediate result.

It is possible to save the extra cost of "intermediate results" while keeping the same design by more advanced techniques like expression templates, but this goes way beyond this simple task.

I would personally prefer a clean design to optimal performance for this task. This makes code more readable and maintainable. Also, with a bit more abstraction, you may find that parts of the code above can be reused elsewhere (especially print_ranges, but I don't want to go too far).

Another choice you could follow is to have an std::pair or (better) a dedicated data structure representing one range. A single sequence would then be enough instead of two sequences from, to, but processing such a sequence would be a bit more involved.

Of course, you are free to flat everything into a single call without intermediates if you prefer.


function to generate values of a javascript object

If you keep the naming consistent, you could probably do something like:

function getThemeName(themeName, transparency) {
  var name = "messages:theme.info." + themeName;
  if( transparency ) {
    name += "_with_transparency";
    return translator.get(name, { percentage: transparency });
  } else {
    return translator.get(name);
  }
}


It is equivalent to:
const renderPriceChange = (price) => {
  return (
    <Text style={price > 0 ? styles.rise : styles.drop}>
      <AntDesign
        name={price > 0 ? 'caretup' : 'caretdown'}
        color={price > 0 ? '#03AE9D' : '#fb2c33'}
        size={10}
      />{' '}
      {percentageFormat(item.price_change_percentage_24h)}%
    </Text>
  )
}

You can inline the if...else by using JavaScript's ternary operator a ? b : c


Copy and paste formatting is slow using VBA

This:

If header = True Then: srcrow = 23: Else: srcrow = 24

Would be much better off as an IIf statement:

srcrow = IIf(header, 23, 24)

Also note, this:

If {boolean-expression} = True Then

..is always redundant and can be written as:

If {boolean-expression} Then

With header being a Boolean already, there's no need to compare it to a Boolean literal to obtain a {boolean-expression}!

One of the most important things to do when you have blocks in your code (If...End If, For...Next, While...Wend, Do...Loop, but also Sub...End Sub, etc.), is indentation.

Here's your function, properly indented:

Function formatrow(roww As Long, header As Boolean)

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False

    Dim headerval As String
    Dim sht As Worksheet
    Set sht = ThisWorkbook.Sheets("DEALSHEET")
    Dim sht2 As Worksheet
    Set sht2 = ThisWorkbook.Sheets("Sheet1")
    srcrow = IIf(header, 23, 24)
    LastColumn = sht.Cells(ZROW + 1, sht.Columns.Count).End(xlToLeft).Column

    For x = 2 To LastColumn
        headerval = sht.Cells(ZROW + 1, x).Value
        srccol = srccolbyname(headerval)
        sht2.Cells(srcrow, srccol).Copy 'THIS IS SLOW
        sht.Cells(roww, x).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
                                        SkipBlanks:=False, Transpose:=False
        Application.CutCopyMode = False
    Next x

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False

End Function

Notice how much easier it is to see where the loop starts, where it ends, and what's in its body.

Now sure what ZROW is, it's not declared in the scope of formatrow so I'm assuming it's a module-scoped constant and that other procedures in that module as using it. If only formatrow uses it, it should be scoped to formatrow.

You declared sht and sht2 as Worksheet objects; you should be querying the Worksheets collection, not Sheets (which contains charts and other sheet types).

But then, if these sheets aren't dynamically generated, you shouldn't need to query any worksheet collection and get the objects by their "sheet name" (which the users can change at any time!) - instead, use their "code name": VBA defines a global-scope object for every Excel object (including ThisWorkbook, but also Sheet1 and every sheet in the workbook), so you can use the Properties toolwindow (F4) to set their (Name) property to a meaningful identifier, and then use that identifier in code, so you can delete all these:

Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets("DEALSHEET")
Dim sht2 As Worksheet
Set sht2 = ThisWorkbook.Sheets("Sheet1")

And then do this (assuming the sheet labelled "DEALSHEET" is named DealSheet):

LastColumn = DealSheet.Cells(ZROW + 1, DealSheet.Columns.Count).End(xlToLeft).Column

And this:

headerval = DealSheet.Cells(ZROW + 1, x).Value

And that:

Sheet1.Cells(srcrow, srccol).Copy 'THIS IS SLOW

And so on.

Now, about performance. You need a radically different approach. How would you do it if you were going to do it manually? Would you Copy+Paste one cell at a time, or Copy+Paste the whole row at once?

You want to copy/paste the formats on srcrow from column 2 through LastColumn: do that.

Sheet1.Range(Sheet1.Cells(srcrow, 2), Sheet1.Cells(srcrow, LastColumn)).Copy
DealSheet.Range(DealSheet.Cells(roww, 2), DealSheet.Cells(roww, LastColumn)) _
         .PasteSpecial Paste:=xlPasteFormats, _
                       Operation:=xlNone, _
                       SkipBlanks:=False, _
                       Transpose:=False

No need to loop, no need to lookup column numbers. Unless I missed something. Should be much faster!

I also ran Rubberduck inspections (build 2.0.10, not released yet). A few things to note:

formatrow is implicitly public. Consider specifying an explicit access modifier.
sht, sht2, strng_name and x are poor names. Consider renaming them; avoid disemvoweling, numeric suffixes, underscores, type prefixes, and 1-2 character identifiers.
formatrow is a Function, but its return value is never even assigned so it always returns an implicit Variant/Empty; it should probably be a Sub.
Parameters roww, header, and strng_name are implicitly passed by reference, and can safely be passed by value (ByVal) instead.
Explicit Call syntax is obsolete. Use the implicit call syntax instead (which you've used to call srccolbyname anyway).


In the design module, use ANSI-style port declarations to reduce redundant port lists (refer to IEEE-Std 1800-2017, section 23.2.1 Module header definition):
module ADDER (
  input     a,
  input     b,
  input     c_in,
  output    sum,
  output    c_out
);

In the testbench, use connections-by-name instead of connections-by-order:
ADDER adder (
    .a     (a),
    .b     (b),
    .c_in  (c_in),
    .sum   (sum),
    .c_out (c_out)
);

This involves more typing, but it avoids common connection errors, and it makes the code easier to understand (more self-documenting).  Refer to Std section
23.3.2.2 Connecting module instance ports by name.
I usually find it helpful for debugging to also display the time:
$display($time, " %b + %b + %b = %b%b", a, b, c_in, c_out, sum);


One thing that i'd like to propose is to replace CompletableFuture with home-brewed builder class that wraps CompletableFuture but will have more 'easy to read' interface. It would be something like this:

class FutureBuilder {

/**
 * Wrapped 'completable future' instance
 */
CompletableFuture future;

...
public FutureBuilder execute(Function<...> task) {...}
public FutureBuilder whenComplete(Consumer<Report> handler) {...}
public FutureBuilder whenFail(BiComsumer<Report, Throwable> handler) {...}
...

/**
 * This method should be called at the end to meet interface requirements
 */
public CompletableFuture build() {
      return future;
}
...
}

So, it may be used in next way:

public CompletableFuture<Result> handler(final RunnerJob job) {
   return new FutureBuilder ()
              .execute(bArr -> this.module2.function2(bArr, job))
              .execute(metrics -> this.module3.function3(metrics, job))
              .whenComplete(r-> uilder().setResult(r).build())
              .whenFail((r, e) -> {
                   this.module4.function4(r, job);
                   return builder().setErrorMessage(e.getMessage()).build();
              })
              .build();
}

I hope that is you are looking for.


Stored procedure to swap account holders

Overall, I think your handling of transaction commit/rollback in the try/catch block is reasonable.
Error handling
You may consider:

adding a bit more information to your returning error in the catch block; for instance, you can use RAISERROR to customize your error message with a lot more information. I strongly recommend to read that page on MSDN.

finding a better method than just printing the output to the console if an error occurs; after all, console output is very ephemeral and can get lost easily. Instead, you could log errors to a table in the database, along with some information about how it was called and with what parameters.

Premise
The premise behind the way you wrote this stored procedure is a bit strange. Your goal is to swap the account holders on one account. Your are accomplishing this by requiring both of the account holders' ID and then if an account exists where X is primary and Y is secondary, you swap them.
I think it would make more sense to additionally take in the account number nib as a parameter, and verify that the primary account holder on the account matches what is input, and likewise the secondary also matches, and if they don't, raise a different kind of error stating that the account holders input do not match the account number provided.

You can combine your 2 UPDATE statements into one, since they are both updating the same row in the table.

You also don't need to use your input parameters to make the update, but you can keep it that way if you feel it makes the intention more clear. In my opinion it would be more clear (and possibly less error-prone) to just directly swap the values into one statement. Demo:

declare @Test table (rownum int, ID1 int, ID2 int);
insert into @Test (rownum, ID1, ID2)
  values (1, 42, 99);
update @Test
  set ID1 = ID2,
      ID2 = ID1
  where rownum = 1;
select * from @Test;
/* Result: ***
rownum ID1 ID2
------ --- ---
1      99  42
**************/

Your naming of parameters should reflect what values you are expecting. @tit1 and @tit2 are always used to refer to primeiroTitular and segundoTitular, respectively. Why not just name them that?

The null-checks in your IF EXISTS clause are unnecessary, since your procedure parameters are not nullable, and as such the equals operator necessarily implies that the fields will not be null.

Some line breaks to shorten your long lines helps readability.

Some will disagree, but it is of my personal opinion that using semicolons ; to end statements makes things clearer. This is not required in SQL Server/Transact-SQL, but it is in almost every other database system.

Make sure to pick a name more descriptive than spTeste2 before you commit this into a production database :-)

Reformatted code:
create procedure spTeste2(
    @primeiroTitular bigint = 111,
    @segundoTitular bigint = 222
) as
begin try;
if exists (
        select primeiroTitular, segundoTitular
        from ContasBancarias
        where primeiroTitular = @primeiroTitular
          and segundoTitular = @segundoTitular
    )
    begin
        declare @nib varchar(50) = (
            select nib
            from ContasBancarias
            where primeiroTitular = @primeiroTitular
            and segundoTitular = @segundoTitular
        );

        begin transaction;
            update ContasBancarias
                set primeiroTitular = @segundoTitular,
                    segundoTitular = @primeiroTitular
                where nib = @nib;
        commit transaction;
    end;
else
    begin
        raiserror('Pelo menos um destes titulares não existe, ou não estão nesta ordem', 16, 1);
    end
end try;
begin catch;
    print ERROR_MESSAGE();

    if @@TRANCOUNT > 0
        rollback transaction;
end catch;


Concentrating on the ConditionallyFormatRowsForUrgency method, I see three times rowStyles = new Tuple<int, Tuple<Color, Color, Font>>(rowIndex, ...) so that is something I would move to a common place. In fact, only its last argument -- lets call it style -- changes.

The initial value for style is actually the default for when the two if-statements don't fire. So I would put that initial value as an else to that if-statement.

Last but not least: Tuple<Color, Color, Font> accounts for most of the clutter. By specifying an alias (using Style = Tuple<Color, Color, Font> at the top) it conveys more meaning and makes it all more readable.

The end result would be like this:

using Style = Tuple<Color, Color, Font>;

private void ConditionallyFormatRowsForUrgency(int rowIndex, DateTime dueDate, string currentPriorityValue)
{
    var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;

    Style style;
    if (ToDoUrgency(currentPriorityValue, "High", dueDate, 2))
        style = VisualSettings.HighPriorityStyle;
    else if (ToDoUrgency(currentPriorityValue, "Medium", dueDate, 7))
        style = VisualSettings.MediumPriorityStyle;
    else
        style = new Style(defaultBackColour, Color.Black, VisualSettings.RegularFont);

    var rowStyles = new Tuple<int, Style>(rowIndex, style);

    FormatRowStyle(rowStyles.Item1, rowStyles.Item2.Item1, rowStyles.Item2.Item2, rowStyles.Item2.Item3);
}

You could consider moving defaultBackColor into the else as that is the only place it is relevant.

In response to your latest edits: I think that your ToDoUrgency method is quite short, concise and easy to read. Maybe the length of the if-conditions make you think it is ugly, but there is not much you can do about it.

One important remark: in ConditionallyFormatRowsForUrgency the style variable should never be null, or you'll get a NullReferenceException later on, somewhere else. I therefore strongly recommend that you throw a NotImplementedException in the switch default case and remove the = null from the line Tuple<Color, Color, Font> style = null. Two reasons: if you ever add a new enum member to Urgency and you forget to add the appropriate case to the switch, you'll get an exception right there in your switch instead of in some other method (e.g. FormatRowStyle). If you then do add the case but forget to set the style variable to something valid, you'll get a compiler error stating that style might be used while it has not been assigned a value. This way you ensure that style is never null and that your switch covers all cases.

Further, on more personal preferences: I'd rename ConditionallyFormatRowsForUrgency to something like FormatRowForUrgency. The fact that it is conditional is an implementation detail: you might later on change how the formatting is done and this should not require you to change the name of the method. And it formats only one row, so use singular Row instead of Rows. You could also rename ToDoUrgency to just ToUrgency as that's what it does.

Lastly, your method ConditionallyFormatRowsForUrgency does not care about DateTime dueDate or string currentPriorityValue, yet is asks for them. Your method cares about Urgency urgency so that's what I would put in the parameters. This also makes your testing easier, as you can just put a single Urgency value in the method and see how it works. The conversion from dueDate and currentPriorityValue to an Urgency enumeration member may then be done somewhere else, and tested separately.

private void FormatRowForUrgency(int rowIndex, Urgency urgency)
{ ... }

In regards to the switch-statement: essentially there are four ways to accomplish what you want to do: as a switch-statement, as multiple if-statements, using inheritance, or as an index into a delegate array of functions. Multiple if-statements are probably uglier in this case than a switch-statement, and inheritance would require a complete rewrite of the Urgency enum to a class hierarchy. The index into a delegate array of functions would look like this:

private static readonly Func<int, Tuple<Color, Color, Font>>[] styleDelegates = new Func<int, Tuple<Color, Color, Font>>[]
{
    rowIndex => VisualSettings.HighPriorityStyle,     // assuming ToDo.Urgency.High = 0
    rowIndex => VisualSettings.MediumPriorityStyle,   // assuming ToDo.Urgency.Medium = 1
    rowIndex =>                                       // assuming ToDo.Urgency.Normal = 2
        {
            var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;
            return new Tuple<Color, Color, Font>(defaultBackColour, Color.Black, VisualSettings.RegularFont);
        }
};

private void FormatRowForUrgency(int rowIndex, ToDo.Urgency urgencyLevel)
{
    var rowToStyle = dataGridView1.Rows[rowIndex].DefaultCellStyle;

    Tuple<Color, Color, Font> style = styleDelegates[(int)urgencyLevel](rowIndex);

    FormatRowStyle(rowToStyle, style);
}

However, I would not recommend it. It is very likely that it severly reduces performance. There is just not much you can do about the switch statement and I would not mind seeing it there where it is now. But an alternative might be to move the switch statement altogether into another method, with the added benefit that it is possible to return early out of the switch.

private Tuple<Color, Color, Font> GetStyleByUrgency(int rowIndex, ToDo.Urgency urgencyLevel)
{
    switch (urgencyLevel)
    {
        case ToDo.Urgency.High: return VisualSettings.HighPriorityStyle;
        case ToDo.Urgency.Medium: return VisualSettings.MediumPriorityStyle;
        case ToDo.Urgency.Normal:
            var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;
            return new Tuple<Color, Color, Font>(defaultBackColour, Color.Black, VisualSettings.RegularFont);
        default:
            throw new InvalidOperationException();
    }
}

private void FormatRowForUrgency(int rowIndex, ToDo.Urgency urgencyLevel)
{
    var rowToStyle = dataGridView1.Rows[rowIndex].DefaultCellStyle;

    Tuple<Color, Color, Font> style = GetStyleByUrgency(rowIndex, urgencyLevel);

    FormatRowStyle(rowToStyle, style);
}


Facebook crawler redirect to force displaying own opengraph meta-tags

It would be better to assign $page_path_display this value ("/") from the beginning as all the cases use that as a prefix.
You're missing whitespace in this statement ($expl_path[2]!=""),  it should be $expl_path[2] != "".
In the following code block, you don't need to assign $meta_string as you return it straight away.

    return
    '<meta property="og:title" content="'.$use_title.'" />
    <meta property="fb:app_id" content="'.$fb_app_id.'"/>
    <meta property="fb:admins" content="'.$fb_admins.'"/>
    <meta property="og:type" content="article" />
    <meta property="og:url" content="'.$site_url.'/" />
    <meta property="og:image" content="'.$use_pic.'" />
    <meta property="og:site_name" content="'.$site_url_displayname.'" />
    <meta property="og:description" content="'.$use_text.'" />
    ';

In the following code block, you could just use an if-else instead of a switch

    switch($page_title) {
        case "": case "home":
            echo show_fbmeta_home();
            exit();
        break;
    }

for example:

if ($page_title == "" || $page_title == "home"){
    echo show_fbmeta_home();
    exit();
}

global, you should avoid using globals, because they're bad practice.


I think your solution is already pretty good. It is at worst \$\mathcal{O}(n)\$ in both runtime and memory. You use enumerate instead of iterating over the indicies manually.

The only four things I would comment on are:

In real life code, this being a class would of course  be completely unnecessary (but it seems to be mandatory in this case).
Explicitly returning None at the end. This is always a judgement call between being unnecessarily verbose (since it is returned implicitly anyways) and being more expressive. Since this case is explicitly excluded in the problem description (all inputs have exactly one solution), I would not add it here. If it were an explicit rule to return None in case there was no solution I would, however, include it.
You should add some docstring to the class/method. At least to get in the habit of always doing it.
Python's official style-guide, PEP8, recommends using lower_case for variable, function and method names (but this seems to also be mandatory from the problem description).


Calculate arithmetic expression represented by a string, in Java

If your logic is too complicated, why don't you try to separate the concerns. You may create a Parser that will contains more well-named method to parse handle the characters in your stream. This one can either produce an object that is evaluated to produce your result or it can call methods on another class to evaluate each expression as soon as they are found (like the DOM vs SAX parsers).


Merging cells in multiple columns on multiple sheets

Some notes -
Sub or Function
Functions should be used when something is returned and subs should be used when something happens. In this case they are actually both Subs.

Naming
So I think PIS is the actual name of the sheet, not a variable. But, it's all uppercase and not very descriptive. In this case I would think it's a constant because
Standard VBA naming conventions have camelCase for local variables, UPPER_CASE for constants and PascalCase for other variables and names.

Variables
You did a good job declaring all of your variables, but it's always a good idea to turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.
Names - names are cheap and characters are free. You can use this to your advantage by giving all of your variables descriptive names. For instance - RngB tells me nothing about what that range is supposed to be doing.
Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Select Case
Why do you have a select case given you're basically using it like an IF? It looks pretty messy, to me. You could fix that up with a constant. Personally, I'd pull it out as its own function -
Private Function IsTargetSheet(ByVal sheetName As String) As Boolean
    Const SHEET_NAMES As String = "Med Curr, Med Ren, Med RevRen, Med Prop, Med Renewal Alts A, Med Renewal Alts B, Med Renewal Alts C, Med Prop Other Markets 1A, Med Prop Other Markets 1B, Med Prop Other Markets 1C, Med Prop Other Markets 2A, Med Prop Other Markets 2B, Med Prop Other Markets 2C, Med Prop Other Markets A, Med Prop Other Markets 3B, Med Prop Other Markets 3C"
    If InStr(1, SHEET_NAMES, sheetName) > 0 Then
        IsTargetSheet = True
    Else: IsTargetSheet = False
End Function

And now you just need this in the main sub -
For i = 1 To sheetCount
    sheetName = ActiveWorkbook.Sheets(i).Name
    If IsTargetSheet(sheetName) Then MergeCellsx sheetName
Next i

MergeCellsx
In case you didn't know, a Sub can take an argument the same way as a function -
Sub MergeCells(ByVal sheetName as String)

I see you are targeting columns 2 and 3, 5 and 6, 8 and 9. When you have something like that, it might be better to put those number in a variable or constant so that if they change, you can just change the initial value of the variable. -
Const FIRST_NAME_COLUMN As Long = 2
Const SECOND_NAME_COLUMN As Long = 3

Now every time you type in the columns, you can use the constant which will tell you what the column is supposed to contain.
Also, in this instance, you would probably be better with a long if instead of 15 conditional loops. Maybe even the select case would belong here. When you see repeated code like that, it's an indication you can refactor it.


On the surface the code in your question seems fine, but I can tell you from experience that once this door is cracked just a bit, it will continue to creak open wider over time.

"I'm just checking if we have an ID or category name."
"This just adds a few meta tags."
"It's already 200 lines; 50 more won't matter."

The linked controller, however, is doing way too much work. It should be passing data off to a model class (not the entity manager directly), placing whatever the view needs into the ViewModel, and that's it. Controllers are glue code. As you have it, you'll need to copy all of this code and modify it slightly to expose the CRUD interface in another form.

For the code you posted, I would prefer to separate the actions so each handles one specific use case: all items, items matching a category, and one item (not in the code but you mentioned it). Create a regex route for the last two. The beauty of this is that you don't need to do all the conditional checks--the dispatcher does it for you.

// see miscellaneous tips below
public function init() {
    $this->objectManager = $this->getServiceLocator()
        ->get('Doctrine\ORM\EntityManager');
}

public function allAction() {
    return new ViewModel(array(
        'news' => $this->loadItems(),
        'categoryName' => null,
    ));
}

public function categoryAction() {
    $category = $this->objectManager
        ->getRepository('\News\Entity\Category')
        ->findOneByUrl((string) $this->params('category'));
    if (!$category) {
        return $this->redirect()->toRoute('news');
    }
    return new ViewModel(array(
        'news' => $this->loadItems(array('category' => $category->getId())),
        'categoryName' => $categoryName,
    ));
}

private function loadItems($options = array()) {
    $news = $this->objectManager
        ->getRepository('\News\Entity\Item')
        ->findBy($options, array('created' => 'DESC'));
    $items = array();
    foreach ($news as $item) {
        $buffer = $item->getArrayCopy();
        $buffer['category'] = $item->getCategory()->getName();
        $buffer['user'] = $item->getUser()->getDisplayName();
        $items[] = $buffer;
    }
    return $items;
}

This is about the same length of the original, but it's far less complicated. Each action is easy to follow and clearly lays out what it requires.

Miscellaneous

And here are a few tips after looking at your linked controller and view code:

You are accessing the entity manager in every action (sometimes pulling it from the registry twice in the same method). Do this once by storing it in an instance property in init.
The index and list actions are nearly identical. Refactor these to extract the common code into a new private method. It looks like this applies to some of the other actions, e.g., converting a news item into an array for the view with its associated category and user names.
You can simplify the title-setting with the Elvis operator: $title = categoryName ?: "Список новостей".
Every page should have an H1--even the "all news" index page.
An non-empty array is truthy in PHP. if(count($this->news) != 0): can be shortened to if($this->news):. If you want to be explicit, at least use if(!empty($this->news)):.
If $this->news will be an empty array instead of null or false when there are no items, you don't even need the if since looping over an empty array is a no-op.
You don't need the ; in <?=...?> since it's an expression instead of a statement. You also don't need it for one-line statements in <?php ... ?>, but we still use it to avoid bugs when someone adds a line.


The error message is caused by me misunderstanding the purpose of deleteLater. As implied by the documentation, the member function is only required when deleting the object inside a slot, like HandleFinishedDownload.

  Note: Do not delete the object in the slot connected to the error() or finished() signal. Use deleteLater().

In all other cases, the standard delete keyword should be used. As a result, here is an updated implementation of CancelDownload.

void Downloader::CancelDownload()
{
    if (mCurrentReply != Q_NULLPTR) {
        mCurrentReply->abort();
        delete mCurrentReply; // this is the only altered line
        mCurrentReply = Q_NULLPTR;
    }
}


Removing code smell from Room Booking code

None of this information should be written into your program's source code.  Rather, it should be stored in a configuration file, perhaps in XML, JSON, or YAML format  — or maybe stored in a database instead.  Not only would your code be less repetitive, it would also be more flexible, in that you wouldn't have to rebuild the application just to change trivial things such as product offerings and prices.


From a short review;

The code does not produce exactly your output, the x part is different;
["x", "2020-7-1", "2020-8-1", "2020-9-1"], I assume the code is right
That reduce is fine, it's the best part of the code really
The date part seems complicated the check for the valid date could have been done in a filter, the rest in a map
Consistency is important, you use both the fancy technique dataConvert = [...[dateConvert], ...valueConvert]; and dateConvert.unshift("x"); which could have been dateConvert = ["x", ...dateConvert];, the only good reason for unshift could have been that dateConvert is a const but it isnt
I dont like x as a variable name, it says nothing to me, I would go for o (object)
Similarly when you reduce allTasks you pass arr as the cumulator, but it's not an array, it's an object so you could/should use o there
This [...[dateConvert], ...valueConvert]; is equivalent to [dateConvert, ...valueConvert];, you may want to play around more with the spread operator
get p1 p2 value is a very contemporary comment, it is true today because tasks indeed only contain p1 and p2, but the day that tasks get new or changed, that comment will be worthless, consider something like group all tasks properties
I guess a task is an item, but I would rather see allTasks.reduce((o, task) than allTasks.reduce((arr, item)

If you take all that, I would counter propose this;

function convertData(data){

  let dateConvert = data.filter(o => new Date(o.time)).map(o => {
    const date = new Date(o.time);
    return `${date.getFullYear()}-${ date.getMonth() + 1}-1`;
  });
  dateConvert = ["x", ...dateConvert];

  let allTasks = data.flatMap(x => x.tasks);

  //Group all task properties
   const valueConvert = Object.values(allTasks.reduce((o, task) => {
     o[task.key] = o[task.key] || [task.key];
     o[task.key].push(task.value);
     return o;
   }, {}));

  return [dateConvert, ...valueConvert];
}

const data2 = [
{
    time: "2020-7",
    tasks: [
      {
        key: "p1",
        value: 15
      },
      {
        key: "p2",
        value: 13
      },
    ]
  },
{
    time: "2020-8",
    tasks: [
      {
        key: "p1",
        value: 16
      },
      {
        key: "p2",
        value: 19
      },
    ]
  },
{
    time: "2020-9",
    tasks: [
      {
        key: "p1",
        value: 12
      },
      {
        key: "p2",
        value: 93
      },
    ]
  }
];

console.log(convertData(data2));