You should generally try to avoid global variables (like tableSize). Since they can be used everywhere ("globally"), at the worst case you need to read all of the code to figure out where they come from and how they're used. In this case, tableSize could become a parameter of multTable.

While it will probably work on the compilers you'll come across, void main() isn't strictly guaranteed to work in all C implementations. The standard signature is int main(int argc, char** argv), or possibly int main(void).

Defining multiple variables in a single line, like short i = 1, nbMultipliers;, is generally frowned upon because (a) it can be hard to read, and (b) C made some questionable decisions about the need to repeat qualifiers like const and * on types, making the syntax dangerous.

However, you shouldn't really be defining all of your variables at the top of your functions (this was required in old versions of C, but hasn't been for twenty years). You should define your variables as late as possible.

The signature of question could be simplified to short question(void) -- don't use pointers when you don't have a reason to.

You are calling error incorrectly. You've defined it to take a short, but you're passing it a pointer to a short. It should instead be called like error(nbMultiplier);. The C compiler should tell you this -- are you compiling using warnings? The flags -Wall -Wextra are very useful!

Initializing pointSize prior to reading in is not necessary, and actually possibly harmful to the compiler/a debugger catching your mistakes. Also, NULL is a value for pointers. When you're setting *pointSize, you're setting the value of a short, not a pointer. You probably mean 0 or -1 or some other value - but again, it's simpler to just leave it uninitialized in this case, so that a sanitizer or debugger can catch any accidental uses of uninitialized data.

The format specifier for short is %hd, not %u. Using %u will invoke undefined behavior. Here too, the compiler will emit a warning telling you to fix this.

exit is included in stdlib.h, which you have not #included. It also requires a integer parameter, the exit code to use. Since this is an error, you should use EXIT_FAILURE.

Here is what your program looks like (skipping the body of multTable which we haven't gotten to yet) if you apply all of the above:

#include <stdio.h>
#include <stdlib.h>

short question(void);    // Ask user how many multipliers
void error(short nbUser); // Cherck error
void multTable(short);  // The table

int main(void)
{
    short tableSize = question();
    error(tableSize);

    /* header */
    printf("       |");
    for (short i = 1; i <= tableSize; i++)
    {
        printf("  %3u  |", i);
    }
    printf("\n");

    for (short i = 1; i <= (tableSize + 1); i++)
    {
        printf("========");
    }
    printf("\n");
    /* end header */

    multTable(tableSize); // the table
    return 0;
}

/* Ask user how many multipliers */
short question(void)
{
    short pointSize;
    printf("How long this table should be ? (0 - 50) ");
    scanf("%hd", &pointSize);
    printf("\n");
    return pointSize;
}

void error(short nbUser)
{
    if (nbUser < 0 || nbUser > 50)
    {
        printf("Error : you must enter a number between 0 and 50");
        exit(EXIT_FAILURE);
    }
}

void multTable(short tableSize)
{
......
}

Notice how related question() and error(); you use error() only to evaluate the output of question(), and question()'s output cannot be trusted without invoking error(). Instead of making question() possibly return a bad value, you should make it encapsulate the error detection itself:

short question(void)
{
    short pointSize;
    printf("How long this table should be ? (0 - 50) ");
    scanf("%hd", &pointSize);
    printf("\n");
    if (pointSize < 0 || pointSize > 50)
    {
        printf("Error : you must enter a number between 0 and 50");
        exit(EXIT_FAILURE);
    }
    return pointSize;
}

Also, notice that you have two places that have printfs: both main and multTable. It's good practice to keep each function doing a single understandable thing. main is doing too much in also printing the table header; especially since that table header needs to be changed if you ever change multTable's output format. So, you should move printing the table header into multTable.

In multTable, look carefully at how you're using the line variable. You're only using it to write to line[i], and then immediately read back line[i] -- you're not using it as an array at all! It can simply be replaced with a local short variable.

The resulting multTable will look something like this:

void multTable(short tableSize)
{
    /* header */
    printf("       |");
    for (short i = 1; i <= tableSize; i++)
    {
        printf("  %3u  |", i);
    }
    printf("\n");

    for (short i = 1; i <= (tableSize + 1); i++)
    {
        printf("========");
    }
    printf("\n");
    /* end header */

    for (short j = 1; j <= tableSize; j++)
    {
        printf("  %3u  I", j);
        for (short i = 1; i <= tableSize; i++)
        {
            short product = i * j;
            printf("  %3hd  |", product);
        }
        printf("\n");
        for (short i = 1; i <= (tableSize + 1); i++)
        {
            printf("-------+");
        }
        printf("\n");
    }
}

General comments

First, you should put more care into how you name things.

You should generally avoid abbreviations (unless they are extremely standardized abbreviations). You read all the time, & u dnt gnly rd txtlkths, you read text that looks like this. Don't say nb, say number. Don't say mult, say multiplication.

Functions should generally be named like commands to do something. For example, printMultiplicationTable(). This lets you read code as a sequence of commands, each one saying what it does. Look at how clear and simple the following looks:

int main(void) {
    short tableSize = getTableSize();
    printMultiplicationTable(tableSize);
    return 0;
}

Comments should not state things that are obvious. A comment of // the table adds absolutely nothing to a line that consists of multTable();. Also, you generally don't need /* end .. */ comments. Your text editor or IDE can let you quickly jump to the beginning and end of functions, and "collapse" them. Keeping track of these manually in the code adds very little value but quickly adds a lot of clutter.

You also hardly need to use shorts. They are often dangerously small (real world numbers very quickly get larger than 16,000), and are no longer faster to operate on in modern computers. If you have a very large array of small numbers, then it might be time to use a short instead of an int (though an explicitly sized type, like int16_t, would be even better!)

Your multiplication table accepts input up to 50, but it won't actually work properly for inputs that large. That's because the largest numbers in the resulting table are more than 3 digits wide. Your code should use 4 columns, or you should dynamically adjust the number of columns depending on what's needed for the user's input.

Also, it bears repeating, make sure you compile with compiler warnings on, and address all of the warnings. C is not easy to get right, and C compilers generally give very helpful warnings that catch lots of mistakes that both beginners and veterans make. You should probably use both -Wall and -Wextra if you're using clang or gcc to get all of the warnings turned on.


Leetcode Count of Smaller Numbers After Self solution

The first advice is to remove the class. In python you should use classes when it makes sense to do so, but you don't need to.

Next, your bst_insert has redundant code. root.left = None and root.right = None are already done in your constructor, so you don't need to duplicate them.

The last piece of advice is to use reversed(nums) instead of num[::-1] as the former does not make a copy, which should be faster and use less memory.

Other than that this looks pretty good.


proper structure of classes using interface classes

There no such thing like an interface class (term used in initial version of post). You have interfaces and classes implementing the interfaces.

I don't see any List<Document> in your code, but If you have defined the list as List<IDocument>, you must stick to this definition. You cannot assign it a List<Document>. But you can add Document objects to this list.

Generally two types T<A> and T<B> are not assignment compatible, even if A and B are assignment compatible. An exception is when the in or out keywords are used in generic interfaces. But this can only be done if the generic type occurs exclusively as input or exclusively as output as explained in Variance in C#.NET 4.0 Covariance and Contravariance.

I would convert the list properties Documents and Pages to getter-only properties.

public interface IPortfolio
{
    string FirstName { get; set; }
    string LastName { get; set; }
    string Name { get; set; }
    int Id { get; set; }
    List<IDocument> Documents { get; }
}

And create the class like this

public class Portfolio : IPortfolio
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Name { get; set; }
    public int Id { get; set; }
    public List<IDocument> Documents { get; } = new List<IDocument>();
}

This makes the Documents property read-only. The list itself remains read/write.

var portfolio = new Portfolio();
portfolio.Documents.Add(new Document());


Your board dictionary can be simplified from
board = {1: ' ', 2: ' ', 3: ' ',
         4: ' ', 5: ' ', 6: ' ',
         7: ' ', 8: ' ', 9: ' '}

to a dict comprehension:
board = {n: ' ' for n in range(1, 10)}

Your win_game function can be greatly simplified, from
def win_game(marker, player_id):
    """Function to check for winning combination"""
    if board[1] == marker and board[2] == marker and board[3] == marker or \
            board[4] == marker and board[5] == marker and board[6] == marker or \
            board[7] == marker and board[8] == marker and board[9] == marker or \
            board[1] == marker and board[4] == marker and board[7] == marker or \
            board[2] == marker and board[5] == marker and board[8] == marker or \
            board[3] == marker and board[6] == marker and board[9] == marker or \
            board[1] == marker and board[5] == marker and board[9] == marker or \
            board[3] == marker and board[5] == marker and board[7] == marker:

        print_board()
        time.sleep(1)
        print("Player", player_id, "wins!")
        return True

    else:
        return False

to
def win_game(marker, player_id):
    """Function to check for winning combination"""
    if board[1] == board[2] == board[3] == marker or \
       board[4] == board[5] == board[6] == marker or \
       board[7] == board[8] == board[9] == marker or \
       board[1] == board[4] == board[7] == marker or \
       board[2] == board[5] == board[8] == marker or \
       board[3] == board[6] == board[9] == marker or \
       board[1] == board[5] == board[9] == marker or \
       board[3] == board[5] == board[7] == marker:
       print_board()
       time.sleep(1)
       print("Player", player_id, "wins!")
       return True
    return False

You see, the else statement is not necessary, as the return statement will make the program jump out of the function. Also, as you can probably tell,
a == 1 and b == 1 and c == 1

is the same as
a == b == c === 1

The unnecessary else statement applies to your other functions as well
For get_player_details:
def get_player_details(curr_player):
    """Function to get player identifier and marker"""
    if curr_player == 'A':
        return ['B', 'O']
    else:
        return ['A', 'X']

to
def get_player_details(curr_player):
    """Function to get player identifier and marker"""
    if curr_player == 'A':
        return ['B', 'O']
    return ['A', 'X']

For play_again:
def play_again():
    """Function to check if player wants to play again"""
    print("Do you want to play again?")
    play_again = input()

    if play_again.upper() == 'Y':
        for z in board:
            board[z] = ' '
        return True
    else:
        print("Thanks for playing. See you next time!")
        return False

to
def play_again():
    """Function to check if player wants to play again"""
    print("Do you want to play again?")
    play_again = input()
    if play_again.upper() == 'Y':
        for z in board:
            board[z] = ' '
        return True
    print("Thanks for playing. See you next time!")
    return False

In your print_board function, you can increase the readability of your print statement with a formatted string. Using not instead of == 0 is considered more pythonic:
def print_board():
    """Function to print the board"""
    for i in board:
        print(i, ':', board[i], ' ', end='')
        if i % 3 == 0:
            print()

to
def print_board():
    """Function to print the board"""
    for i in board:
        print(f'{i} : {board[i]}  ', end='')
        if not i % 3:
            print()


Exception handling for HTTP request timer

Generally, you should try and minimize the number of statements in a try block to the minimum possible.

However, in your case, since

URL urlToCheck = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlToCheck.openConnection();
connection.setRequestMethod("GET");

and

connection.connect();
int urlStatus = connection.getResponseCode();

can all throw exceptions, and the rest of the code is relatively minor (5 lines in your version or 4 in mine), I would leave it all as is, in the try block.

I would recommend eliminating stop and writing the timing code like this:

Long start = System.currentTimeMillis();
int urlStatus = connection.getResponseCode();
Long urlCheckTime = System.currentTimeMillis() - start;

This will yield slightly more accurate timing and eliminates a unneeded variable. You can also eliminate urlCheckTime by having the code in the return string but that's a matter of taste.

As for whether to use a blanket IOException or to have individual catch blocks for MalformedUrlException and so on, that is a question that you need to answer. If you want to have more detailed output, you will need the additional catch blocks. If however, you are simply testing to see if the URL is working, then your method is fine.


Python word counter for all files in the current directory

I recommend using pathlib and Path objects instead of os, and you should use a context manager when manipulating files (e.g. with open("file.txt", "r") as file: ...). You also have a lot of repeating code when you're checking extensions, and you keep checking the rest of the if statements even if it's matched an earlier one. And the final else: pass does literally nothing so just remove that.

You could also do something about your nested for loops for sheet, row and cell (you'd typically use zip or itertools.product then) but this is kind of readable and nice so I'm not sure it's worth the conversion.


Binary tree level order traversal algoritm

Depending on number of nodes in your tree, recursive post-order traversal of the tree, might let you run into problems on the stack. If the number of nodes is huge, you might need to consider a non-recursive post-order traversal.

Have a look at http://leetcode.com/2010/10/binary-tree-post-order-traversal.html, which describes multiple solutions, both iterative and non-recursive.

On think to keep in mind is that the non-recursive algorithms use more memory, as it need to push nodes to a stack.

You might also consider doing a post-order tree traversal enumerator, but that might be for another day.


MS CA2202: Object can be disposed more then once

As @amon mentioned, the correct way of referencing IDisposable Objects in C# is the using-statement.

In general you then have the try-catch block around the using statement to catch eventual initialization errors. This means your Code would look somewhat like this:

String fileContent = String.Empty;
_logger.Debug("Debug-String");

try{
   using(FileStream fs = new Filestream(filename, FileMode.Open, FileAccess.ReadWrite,
     FileShare.None, 64 * 1024, FileOptions.SequentialScan){
      fs.Position = 0;
      using (StreamReader sr = new Streamreader(fs, encoding, true){
         fileContent = sr.ReadToEnd();
      }
   }
}
catch (Exception){
   ArchiveFile(filename, archiveConfig.ErrorFolder, category, _logger);
   throw;
}

return fileContent;

This also allows you to declare variables only when used.

Finally a small note on filename... you are using camelCase in all variables but that. Be consistent in your naming schema


any is a primitive, it doesn't loop in R but in C, which is much much faster.

loops in R are quite slow, that's why it's important that you use said vectorized functions if you care about speed (apply functions are still loops however).

A way to speed things up is to use package Rcpp to write code in C++ through R, when you have a slow R function that uses simple loops it's the way to go, it's still not as fast as C but in our case maybe that'll be enough given we don't need to go through all the vector ?

Let's check:

# defines anyx_cpp
cppFunction(
  'bool anyx_cpp(const NumericVector x,const double y) {
     const double n = x.size();
     for (double i = 1; i < n; i++) {
       if (x(i) == y) {
         return(true);
       }
     }
  return false;
  }')

anyx_r <- function(x,y){
  for(x_ in x) if(x_ == y) return(TRUE)
  FALSE
}

vec <- 1:1e7
x <- 5e6
microbenchmark::microbenchmark(
  rloop  = anyx_r(vec,x),
  cpp    = anyx_cpp(vec,x),
  native = any(vec==x)
)

# Unit: milliseconds
#    expr      min        lq      mean   median       uq      max neval
#   rloop 166.5758 171.34355 203.15277 179.9776 198.8560 990.1650   100
#     cpp  39.5462  40.60585  57.84617  41.4594  46.1232 690.1746   100
#  native  36.9900  37.86090  51.80317  38.9640  43.6510 888.3059   100

Almost but not quite ;).

So bottom line, in general you can trust vectorized R functions, even if it might seem they're working too much at first sight.


Add Number to First Number on Each Line of File then Write to Another File - Python

Constants uppercase

A very widespread convention is that constants should be uppercase, so please conform to the standard for readability.

Unused variables

hdrln = 1
llen = 0

The first one is never used, the second one is never used with the original value, so I suggest removing that declaration.

with and iterable interface for files

with is a commonly used to keyword to simplify working with files to take care of automatic closing, also files are iterable so you can just do: for line in file that should simplify your code.

Isolate logic in functions

tfile.write ('{:{sfw}.{sprec}f}{}'.format(float(line[:fw])+add, line[-llen:], sfw=str(fw), sprec='2'))

That should be in its function along with documentation because it is the main part of the program, the logic should be highlighted and explained not hidden inside the boilerplate.


Class that represents a conditional expression

Well, being the class a binary comparator, and being that the enum contains comparison operators, I would suggest to call them BinaryComparator and ComparisonOperator. Unless you have a naming convention or something else that would make those names not usable, obviously.

I would suggest naming classes by what they represent, if possible it should be a name not related to the context (if such names don't make the code less readable or less understandable).


Based on the code you have listed, the answer to both of your questions is: no.

curl_global_init(CURL_GLOBAL_ALL) won't be called only once as you're checking isGlobalInitCalled but not setting it to indicate the initialization shouldn't be done again. curl_global_cleanup() won't be called because you have no matching delete-expression for the destructors to get called (see the memory leaks portion of new expression).

Regarding how to make this work...

For the one-time-initialization, you could eliminate the use of the isGlobalInitCalled variable and just use numberOfCurlProcess instead (in the constructor) like this:

curlWrapper() {
    curlGlobalkey.lock();

    if(numberOfCurlProcess == 0)
    {
        curl_global_init(CURL_GLOBAL_ALL); // this should be called only once in the entire program when a first object using this class.
    }
    numberOfCurlProcess++;

    curlGlobalkey.unlock();

    //globalCurlInit();

    initializeMemoryStruct();
}

For the one-time-cleanup, I'd suggest using smart pointers which "enable automatic, exception-safe, object lifetime management". As to how code using smart pointers could look, that can depend on what the newest version of the C++ standard is that you're able to use. With C++14, I'd use code that instead looked more like:

class Accessor {
public:
    std::unique_ptr<curlWrapper> curl = std::make_unique<curlWrapper>();
};

main() {
    //somewhere in the main
    std::unique_ptr<Accessor> aa = std::make_unique<Accessor>();
    std::unique_ptr<Accessor> bb = std::make_unique<Accessor>();

    thread(aa).doProcess();
    thread(bb).doProcess();
}

There are other ways to solve the second problem too but if you're going to dynamically allocate instances, smart pointers is the way I'd suggest managing memory as they'll take care of calling the instances' destructors for you.


Clone a LinkedList with each node having a next and a random pointer

Not a clone
Your "clone" is not a clone of the original list.  It is a single head node that points to the second node of the original list.  In order to make a real clone, all pointers in the cloned list should point only to other nodes in the cloned list.
Two passes
Your attempt isn't completely wrong.  After creating all the cloned nodes, you just need a second pass where you convert the original node pointers to cloned node pointers using the map you created.


Unit testing with dependency injection and MOQ

There are a number of issues in your code.

Naming. Methods should use verb phrases to denote the action they perform and try to be specific. So your DateList method should become something like GetWorkingDates, or just GetDates if kind of dates is obvious in your case.
Test naming. Do spend some time on composing a name for your unit test method that describes what exactly is being verified. DateListTest2 does not provide any information except that it deals with DateList() method somehow.
Incorrect responsibilities. Let's look at IDropDownDataRepository interface. It is an interface to obtain a list of dates (probably). And this functionality may be used in different places, not just to render this list in the HTML. But instead of returning IEnumerable<DateEntity> or any other type of collection, it returns HttpResponseMessage, which is only useful for HTTP communication. The only class that knows about specifics of how the list of dates should be used - is your DropDownDataController class. And in your case (no special HTTP response or different HTTP codes) - DropDownDataController.DateList method can return IEnumerable<DateEntity> as well.
Do use AsNoTracking() method when you perform read-only queries.
Test expected resulting behavior instead of the way it was done. If your class manages to satisfy all your tests without calling the mocked instance, then either result of the mocked instance call is insignificant, or you should improve tests by adding new test(s) to verify the change in behavior depending on outcome of the call to mocked instance. Your DateListTest1 test currently expose such a problem, as the only thing that it verifies is that controller calls IDropDownDataRepository.DateList() to render the output. Instead, you should setup IDropDownDataRepository.DateList() to return some list, and verify that the return value of the controller method returns the data in expected way. If the class under test does not call the mocked instance - it will fail such a verification anyway. In general the usage of Mock<T>.VerifyAll is not recommended.

As a result you may get something like this:

public interface IDropDownDataRepository
{
    IEnumerable<DateEntity> GetDates();
}

public class DropDownDataRepository : IDropDownDataRepository
{
    //Should be injected as well
    private MyDatabaseEntities db = new MyDatabaseEntities();

    public IEnumerable<DateEntity> GetDates()
    {
        return from date in db.MyProcedure().AsNoTracking()
               select date;
    }
}

public class DropDownDataController : ApiController
{
    private IDropDownDataRepository _dropDownDataRepository;

    public DropDownDataController(IDropDownDataRepository dropDownDataRepository)
    {
        _dropDownDataRepository = dropDownDataRepository;
    }

    [HttpGet]
    public IEnumerable<DateEntity> GetDates()
    {
        try
        {
            return _dropDownDataRepository.GetDates();
        }
        catch
        {
            // I would leave the default error handling which would return 500 error
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
    }
}

public class DropDownDataControllerTest
{
    [TestMethod]
    public void GetDatesShouldReturnDatesFromRepository()
    {
        //Arrange
        var mockRepository = new Mock<IDropDownDataRepository>();
        var dateEntities = new[] { new DateEntity { Date = new DateTime(1990, 1, 1) }, new DateEntity { Date = new DateTime(1990, 1, 1) } };
        mockRepository
            .Setup(x => x.GetDates())
            .Returns(dateEntities);

        DropDownDataController controller = new DropDownDataController(mockRepository.Object);

        //Act
        var response = controller.GetDates();

        //Assert
        Assert.AreEqual(dateEntities, response);
    }
}


How to optimize Karatsuba algorithm (using arraylist and java)

Reduce running time

Maybe you can use subList to prevent new lists that are basically a copy of a part of the input? This saves a lot of autoboxing (which I assume is the bottle neck, if the algorithm is implemented correctly). You could profile your application to see where most time is spend.

For example:  ahigh = a.subList(0,n1);

You can initialize List c with a size, as you know the length it will be.

Use addAll whenever you can, it will use the faster System.arrayCopy internally if possible.


Refer here for the definition of a balanced binary tree. If you don't like having two return values, you can always refactor and write a separate height() function to get the height of a tree. This would allow you to implement it without having to return two values and would improve the readability of your code as well. This is the suggested way to do it.

I would say avoid raising exceptions unless you're certain you know you want to. You should never raise an exception if you don't have to.


Is there something wrong with my remove-duplicates implementation in Scheme?

It's not enough for your code to "work"; it also must work well. In particular, your code materialises the whole stream at the outset, which defeats the purpose of using a stream in the first place.

Instead of checking whether the current element exists in the rest of the stream, check whether the current element has already been seen. Yes, you have to keep track of the seen elements (preferably via a set, but if your Scheme implementation doesn't have that, a list will do in a pinch), but it will mean that your stream will continue to be a stream, rather than just be a glorified list.

Here's an implementation of the concept using lists to track the seen elements (I used SRFI 41 streams instead of SICP streams, since that's what I'm familiar with):

(define (unique-stream str)
  (stream-let recur ((seen '())
                     (str str))
    (if (stream-null? str)
        stream-null
        (let ((item (stream-car str)))
          (if (memv item seen)
              (recur seen (stream-cdr str))
              (stream-cons item (recur (cons item seen) (stream-cdr str))))))))


Here are some tipps:

Try to avoid / minimize the amout of global variables.
Use approved verbs (see Get-Verb) for your functions (the first letter should be uppercase).
Use the Join-Path cmdlet to combine a path.
Use string interpolation

"${app}_pscp-$timestamp.log"

or the format operator

'{0}_pscp-{1:dd-MMM-yyyy HH.mm.ss.fff}.log' -f $app, (Get-Date)

instead of string concatenation.

Also, I would not create a Copy-File nor a Rename-File function. Just invoke Copy-Item and Rename-Item in the main…


I see multiple instances of id="form_input". These attributes need to change to class or each id attribute value should be altered to be unique.
Instead of using
 tags to style your input fields on separate lines, use css.  By setting all of the elements in the form as display:block;, you can eliminate the excess markup -- a cleaner alternative.  CSS should be the first technique to create spacing and layout stylings; when you find yourself creating spaces with the spacebar or with
, try to achieve the same effect with display, margin, padding, etc.
11 reasons why placeholders are problematic -- I can appreciate that you intend to design a clean, minimalist layout, but I don't think I support non-labeled fields and your project should maintain a consistent theme considering that your project may eventually need to employ more forms.
In addition to the previous bullet point about UX, I will urge you to add some client-side validation to your form.  These character limitations will be up to you.  I assume empties.js is doing something that enables the submit button, but I can't see it.  If empties.js is as functionally narrow a file as it's name suggests, you may want to build more robust processes in there.
Rather than sanitizing server-side and unconditionally inserting into the database, you should be catching overtly "bad" submissions and denying access.
If a submitted password contains html markup, that is no concern of yours (no need to sanitize) because you will never, ever be printing that value -- ever.  More clearly: never alter someone's submitted password characters.
You must never, ever present the raw error message to the end user.  See @YCS's hyperlink.  Especially with registration forms, you need to find the correct balance between informing the registrant why the submission was denied, yet not compromising the security of your project.
Finally, login/registration systems are widely available now.  If you are doing this as an educational exercise, then carry on.  If you don't want to reinvent the wheel, just use a pre-existing script from a security-minded author.


Caching that resets itself under certain circumstances: Reduce boiler plate code

This might be a job for @functools.cached_property. It works a lot like @property, except it remembers the value between calls. The value can then be cleared using del in the fit function, or elsewhere if needed.
Unfortunately, the properties can't be deled until they've been set, which means we have to re-add the boiledplate in fit in the form of try: del x; except AttributeError: pass. Maybe that's an improvement since it's at least centralized, but it's still not ideal.
There are workarounds like
def fit(self, data):
    self.intermediate_data_ = ...

    for prop in ["complex_transform1", "complex_transform2"]:
        try:
            delattr(self, prop)
        except AttributeError:
            pass

    return self

Or perhaps something like
def fit(self, data):
    self.intermediate_data_ = ...

    for prop in self.reset_on_fit:
        delattr(self, prop)

    self.reset_on_fit = []
    return self

with the properties looking like
@cached_property
def complex_transform1(self):
    self.reset_on_fit.append("complex_transform1")
    return self.intermediate_data_ / self.parameter / 2

But putting that data into a hardcoded string is not very refactor-friendly. Perhaps we can define a decorator to figure that out for us?
Well, I haven't tested it very thoroughly, but I think we can:
from functools import cached_property, wraps

def resets_on_fit(fn):
    @wraps(fn)
    def wrapper(self):
        self.reset_on_fit.append(fn.__name__)
        return fn(self)

    return wrapper

class MyClass:
    # ...

    def fit(self, data):
        self.intermediate_data_ = data + self.parameter + 2

        for prop in self.reset_on_fit:
            delattr(self, prop)

        self.reset_on_fit = []
        return self

    @cached_property
    @resets_on_fit
    def complex_transform1(self):
        return self.intermediate_data_ / self.parameter / 2


this->threads_.emplace_back(
    std::thread(std::bind(&PoolExecutor::worker, this)));

Creative use of std::bind, but a lambda would have sufficed:

this->threads_.emplace_back(
    std::thread([this] () { this->worker() });

void submit(std::function<void()> func)
{
    this->cv_.notify_all();
}

Why bother waking all worker threads when only a single slice of work was added? std::condition_variable_any::notify_one() is more appropriate.

void stop()
{
    this->stop_ = true;
}

Here, on the other hand, std::condition_variable_any::notify_all() should have been used, wake the threads currently sleeping.

void stop()
{
    this->stop_ = true;
    this->cv_.notify_all()
}

std::shared_lock<std::shared_timed_mutex> lock(this->mu_, std::try_to_lock);
this->cv_.wait_for(lock, 10ms);

This part only works as expected for the first thread, as it actually gets the lock. The second thread fails to obtain the lock.

See the documentation for std::condition_variable_any::wait_for. The lock must be locked before entering wait_for.

That means you can't use std::try_to_lock, but actually need std::lock.

While at it, you should get used to using the optional 3rd parameter on wait to pass in a predicate in order to filter spurious wakes:

std::shared_lock<std::shared_timed_mutex> lock(this->mu_, std::lock);
this->cv_.wait_for(lock, 10ms, [this] () {return this->stop_ || !this->work_queue_.empty());

That predicate is executed before waiting for the first time, so if e.g. this->stop_ is already set by the time lock is aquired, wait() with the predicate returns immediately without requiring another wake up call.

At this point you can do away with the "timed" stuff as well. You no longer need it. You can now also replace your std::condition_variable_any by the simpler std::condition_variable.

In fact, neither do you need the 2nd mutex either:

std::mutex mu_;
std::condition_variable cv_;

...

bool finished()
{
    std::lock_guard<std::mutex> guard(this->mu_);
    return this->working_ == 0 && this->work_queue_.empty();
}

void worker()
{
    while(!this->stop_)
    {
        bool accquired = false;
        {
            std::unique_lock<std::mutex> lock(this->mu_);
            this->cv_.wait(lock, [this] () { return this->stop_ || !this->work_queue_.empty() );
            if(this->stop_) break;
            if(!this->work_queue_.empty())
            {
                func = this->work_queue_.front();
                this->work_queue_.pop();
                accquired = true;
                this->working_++;
            }
        }
        if(accquired)
        {
            func();
            --this->working_;
        }
    }
}

  Q1. Am I using mutex and lock correctly?

No. Even though it might have even worked, you violated the contract by attempting to wait on an unlocked mutex.

  Q2. It is possible to use single mutex in PoolExecutor class?

As seen above, yes.

  Q3. Is there any ways to wait executor until finished?

If by "finished" you mean the executor is ready to be destroyed? That is already the case.

Otherwise if you just mean to wait until the pool runs empty? Well, you do have std::atomic_int working_ in there.

All you really need now, is a second condition variable:

void wait() {
    std::unique_lock<std::mutex> lock(this->mu_);
    this->cv2_.wait(lock, [this] () {
        return ( this->working_ == 0 && this->work_queue_.empty() ) || this->stop_
    });
}

Now update the worker to invoke this->cv2_.notify_all() after decrementing this->working_ and you are done.


Calculate with numbers from different number systems

Main feedback has already been given by @AJNeufeld and this post is not about the performance of your program but rather other aspects.

You should try putting a check before you access an index in an array and slightly change your if block from this,

if (args[0].contains("help")) {

to,

if (args.length == 0 || args[0].contains("help") || args.length < 5) {

as the former will run into ArrayIndexOutOfBoundsException if no argument is passed. Also it would be helpful to call the displayHelp() method in case no argument (args.length == 0) was passed so the user knows the usage of program.

Also, for safely accessing array indexes, you should put another OR condition args.length < 5 which will ensure at least five parameters are passed, else again you may run into ArrayIndexOutOfBoundsException.

These checks should make the program a little more safer.


Function to parse floats optionally followed by %, more strict than parseFloat in javascript

I think it's a bit too much code. If you are already using a regular expression, why not using it to do all the parsing for you?

function parseNumeric(number) {
    var num = number.trim();
    var reOut = /^([-+]?(\d+\.?\d*|\d*\.?\d+))\s*%?$/.exec(num);
    return reOut ? parseFloat(reOut[1]): undefined;
}


Have I coded this small object grouping script Pythonically?

list1 is a bad variable name. What is it actually storing? I know that it is a list, but I don't know what it is being used for.

It looks like this code is a snippet from a bigger block of code, but at least in this context, list1 is never being read. You should make sure the value is used later or remove the variable.

a is also a bad name. A single letter variable name is rarely a good variable name.

Comments:

for a in rows:
    date_time = a[12] #gets date_time

#strips date_time with regex to match the proper pattern format
#sample date_time from db "2014-07-07 11:10:18.867024-04"
    date_time = re.match(r'^.*?\.', date_time).group(0)

Your comments should start at the same indentation level as the code. What you have now could make someone reading your code think there are two different blocks.

Most of your comments are saying what the code does. This is generally an indication that you need to make your code more descriptive. You can achieve this with better variable names and extracting chunks of code into well-named sub-functions. Comments are better suited at describing why something is being done.

if a == rows[-1]:
    source.append(a[11])
    list1.append(source)

else:
    if epoch - old_epoch < 60:
        source.append(a[11])

    else:
        list1.append(source)
        source = []
        source.append(a[11])

You don't need the extra line after the if/else blocks.

source = []
source.append(a[11])

is the same as

source = [a[11]]

pattern has a constant value, you can initialize it before the loop instead to resetting the value for every row.

if epoch - old_epoch < 60:

60 is a magic number. What does it mean? If it were to change, you would have to find all the places 60 appears and check if it means the same thing as this context. If it has a name, you can just change the value once.


Filtering parent and children elements of list of dictionaries

If your actual program has the products list is a constant global variable, declare it as PRODUCTS (uppercase global constants)
Using list(filter(lambda can be removed by a simple comprehension. A list comprehension is the preferred method of iterating over lists as per PEP-0202
Instead of returning False in get_by_id, return a None, as that is more user intuitive.

Check the following:

def get_by_id(product_id):
    """Return a product from the list with given id, or None if not found"""
    return next((p for p in PRODUCTS if p["id"] == product_id), None)

There is no extra list being created in-memory. The generator expression returns the first value (if any) or defaults to the None. Check docs for the next function.

For the get_by_product, you can have 2 snippets. One will remove the given product from list if product.parent_id exists, and another will search for child products.

def get_by_product(product):
    if product["parent_id"] is not None:
        return [p for p in PRODUCTS if p != product]
    return [p for p in PRODUCTS if p['parent_id'] == product['id']]


Returning index of nth occurrence of a substring

There's no need to split the original string or slice away at the string, you can just use the built in indexOf, keeping track of how many times you've looked for the substring. As a personal preference, I'd also use smaller, not as bombastic, variables names.

Also, there's absolutely no need to include jQuery in this - the $(document).ready is redundant.

function GetSubstringIndex(str, substring, n) {
    var times = 0, index = null;

    while (times < n && index !== -1) {
        index = str.indexOf(substring, index+1);
        times++;
    }

    return index;
}


There are a few issues with your code I've modified it below. Some of the changes I made:

cache your jQuery objects
reword your slideMessage condition so that it is more readable
parameterize the animations and pull them out into methods of their own
move your initialization code so that it is all together

Updated JsFiddle

$(function () {
    var $message = $('#message'),
        $tab = $('#tab');
    var speed = 300;

    function animateMessage(to) {
        // don't want to animate them right now
        // rather: animate them when this function I'll return is called
        return function () {
            return $message.animate({
                marginTop: to
            }, speed);
        };
    }

    function animateTab(to) {
        return function () {
            return $tab.animate({
                top: to
            }, speed);
        };
    }

    //little helper method to queue animations
    function queue(immediate) {
        var rest = [].splice.call(arguments, 1);
        if (immediate) {
            $.when(immediate()).then(function () {
                queue.apply(window, rest);
            });
        }
    }

    function slideMessage() {
        var tabVisible = $message.css('marginTop') !== '0px';

        if (tabVisible) {
            queue(animateTab('-160px'),
                animateMessage('0px'));
        } else {
            queue(animateMessage('-40px'),
                animateTab('0px'));
        }
    }

    //Hide message if user has javascript
    $message.css('marginTop', '-40px');
    slideMessage();

    $('#message .close, #tab').click(function() {
        slideMessage();
    });
});

In response to the comments:

This is very similar to the code you initially put up. I derived it again on a gist using the code you put in your question here (slightly different from the code in the fiddle): https://gist.github.com/3060013/6a4de29001f845c625e2f907752562c7abf9dd85

Clone that repository to see the full history.

while your code does work, it has a couple of inefficiencies and the slideMessage has too much going on.

every time you call $('...'), jQuery needs to do some work in the background to figure out what you mean in the string.  You can instead cache these items and not need to depend on retrieving them repeatedly being fast. In this case it doesn't make much of a difference, but eventually it will cause your page to be slower.
There is too much extra junk in the way to make it apparent what slideMessage is doing. A good rule of thumb is to wait a week, then if you cannot glance at a statement and know that it is both in the right place in the function and what it is doing then something is too complex. While your code is probably sensible to you right now I am willing to stake the claim that in a few weeks/months when you go to add some other functionality you would waste some time trying to figure out what this is doing.

Caching a jQuery object is an expression for introducing a variable that holds the result of the $('...') function and its related forms.
Perhaps you shouldn't? I'm not 100% on this yet. I think this part of the code can be further cleaned up. I'm still leaning against combining them. I think something that represents this pseudocode would be best, but I'm not sure how to do that best:

if tabVisible
    slide tab out then slide message in
else
    do the opposite of what I did to switch them back

That is to say, I don't think the else block should specify the logic of how to do the opposite.


Design dilemma: extensibility vs simplicity

In my opinion, a better approach (along similar lines) is to avoid abstract base classes and instead use generic "policy" classes. You informally define an interface for each behaviour, and mix them into the class as template parameters. This avoids the need for dynamic memory allocation, and removes the overhead of virtual function calls; everything is resolved at compile time. Your example could be something like this:

#include <iostream>

// Flying styles must have interfaces compatible with this
// struct FlyStyle
// {
//    void Fly() const;
// };

struct FlyHigh
{
  void Fly() const
  {
    std::cout << "Fly high!" << std::endl;
  }
};

struct NoFly
{
  void Fly() const
  {
    std::cout << "No fly!" << std::endl;
  }
};

// Speaking styles must have interfaces compatible with this
// struct SpeakStyle
// {
//     void Speak() const;
// };

struct SpeakLoud
{
  void Speak() const
  {
    std::cout << "Speak LAUD!!!!" << std::endl;
  }
};

struct NoSpeak
{
  void Speak() const
  {
    std::cout << "No speaking!" << std::endl;
  }
};

template <class FlyStyle, class SpeakStyle>
class SuperBird
{
  public:
    void Fly() const
    {
      flystyle.Fly();
    }
    void Speak() const
    {
      speakstyle.Speak();
    }
  private:
    FlyStyle flystyle;
    SpeakStyle speakstyle;
};

typedef SuperBird<FlyHigh, SpeakLoud> Eagle;
typedef SuperBird<NoFly, NoSpeak> Penguin;

int main()
{
  Eagle eagle;
  eagle.Fly();
  eagle.Speak();

  Penguin penguin;
  penguin.Fly();
  penguin.Speak();
}


Do without the ternary expressions: because a ternary expression is very good for initializing one variable, but is much less good for initializing two variables.

// Declared but not initialized (to null), in order to guarantee that
// they are each initialized in the subsequent if statements.
Player firstPlayer;
Player secondPlayer;

if (player_1.Active.CurrentSpeed > player_2.Active.CurrentSpeed)
{
    firstPlayer = player_1;
    secondPlayer = player_2;
}
else if (player_1.Active.CurrentSpeed < player_2.Active.CurrentSpeed)
{
    firstPlayer = player_2;
    secondPlayer = player_1;
}
else
{
    //Randomize who goes first
    ... etc ...
}


Basic/beginner interactive program in Python

Ok here we go.

Style

You should get acquainted with the official python coding style, which is PEP8.
I notice especially naming violations with your global variables, which should follow the rules of functions: lowercase with underscore separation.

If-elsing

Perhaps it's just me, but I find heavily usage of if/elif/else messy.

Python does not support the typical switchstatement that could fit here, but there is an idiom that resembles it in python by using a dictionary of functions.

for example:

options = {1 : sleep,
           2 : work,
           3 : outdoors,
}
options[entries]()

this will require you to create an additional sleep function that can be executed to print the text We are such stuff as dreams are made on

This technique however lacks the break system that is available in switch statements, but you don't seem to need that in your code.

Additionally this scales really easily, all you got to do is add a new method, nicely encapsulated, and add it to the dictionary.

Multiple end points

Your code seems to have multiple end points. At the end of your start() function you print done. But also in your work() function you print it and terminate the program manually. It is cleaner to have a smooth main function, with multiple options (may it be function calls), when the function calls return, you simply print done only there and the program stops.

Main function

It is a good habit to use a main function, perhaps even better to rename your start to main and use the following construct:

def main():
    # Your main code

if __name__ == "__main__":
    main()

Goodluck!


Printing multiple different shapes on the same line

It really is that simple.  Your idea of putting everything into one puts() call would be an improvement, because I/O calls are relatively expensive.  Not that it really matters in this exercise.  It's just a good habit.

The second shape should be a little bit wider. =)

Note that a return 0; at the end of main() is automatically implied, as a special case.

#include <stdio.h>

int main() {

    puts("*********        ***          *           *\n"
         "*       *      *     *       ***         * *\n"
         "*       *     *       *     *****       *   *\n"
         "*       *     *       *       *        *     *\n"
         "*       *     *       *       *       *       *\n"
         "*       *     *       *       *        *     *\n"
         "*       *     *       *       *         *   *\n"
         "*       *      *     *        *          * *\n"
         "*********        ***          *           *");

    return 0;

}


Editing system files in Linux (as root) with GUI and CLI text editors #2 (final)

Self-review

comments

Comments are very important to future readers, they speed up the comprehension of the whole code. I think I messed up at least one comment, (others pending review):

original:

# let's take a closer look at the first argument, the editor

suggested:

# store the first argument, the editor name

combine what can be combined

By combining simple pieces of code, we make it easier to read.

original:

# store an editor alias, if there is any
editor_alias=$( alias "$editor_name" 2> /dev/null )

# remove that alias for now
if [ -n "$editor_alias" ]; then
    unalias "$editor_name"
fi

suggested:

# store an editor alias; and if there is any, remove it for now
if editor_alias=$( alias "$editor_name" 2> /dev/null ); then
    unalias "$editor_name"
fi

implement code workaround into the function

My previous solution does not do any checks for code and also, by doing this we get rid of that alien alias.

original:

# VS Code specific workaround to work under root
alias sucode="sudo mkdir -p /root/.vscode && sudo code -w --user-data-dir=/root/.vscode"

suggested:

# run the editor with one-time SUDO_EDITOR set-up
if [ "$editor_name" = code ]; then
    # code specific workaround
    sudo mkdir -p /root/.vscode &&
    sudo code -w --user-data-dir=/root/.vscode "$@"
else
    # main command generic
    SUDO_EDITOR="$editor_path $wait_option" sudoedit "$@"
fi

avoid generating editors aliases for which editor is not installed

My previous solution is generating all editor aliases, no matter if such program is installed on the system, this could have been unpleasant to users.

original:

for cli_editor in $sudoedit__cli_editor_list; do
    alias su$cli_editor="sudoedit_enhanced_run $cli_editor ''"
done
for gui_editor in $sudoedit__gui_editor_list; do
    alias su$gui_editor="sudoedit_enhanced_run $gui_editor -w"
done

suggested:

for cli_editor in $sudoedit__cli_editor_list; do
    if command -v "$cli_editor" > /dev/null 2>&1; then
        alias su$cli_editor="sudoedit_enhanced_run $cli_editor ''"
    fi
done
for gui_editor in $sudoedit__gui_editor_list; do
    if command -v "$gui_editor" > /dev/null 2>&1; then
        alias su$gui_editor="sudoedit_enhanced_run $gui_editor -w"
    fi
done


Convertors converting unconverted objects

Avoid long one-liners:

This:

if ((int)value == 1) { return new SolidColorBrush(Color.FromArgb(255, 34, 34, 34)); }

Should be:

if ((int)value == 1)
{
    return new SolidColorBrush(Color.FromArgb(255, 34, 34, 34));
}

Typically one-liner if-statements are-so because they're short and can't be justified to take up 3 lines for something so small.

Avoid 'else' one-liners:

This is a clutter:

if (condition) { return val1; }
else { return val2; }

This isn't as big of a clutter, just space-consuming:

if (condition)
{
    return val1;
}
else
{
    return val2;
}

Acceptable alternatives:

I would do the following for maximum readability:

return condition ? val1 : val2;

Making use of the ternary operator and being the most maintainable/readable method.

In cases where you're not able to keep it one line, something like you had above is perfectly acceptable:

if (condition) { return val1; }
// Do something...?
return val2;

One-way converters:

I would consider the following situation before throwing an NotImplementedException().

public interface IOneWayValueConverter
{
    object Convert(object value, Type targetType, object parameter, string language);
}

// Optionally Adding "TwoWay" to the name (or some other similar naming method).
public interface IValueConverter : IOneWayValueConverter
{
    object ConvertBack(object value, Type targetType, object parameter, string language);
}

If this isn't an option (for any number of reasons) then it would seem the only acceptable answer to this situation would be throwing a NotImplementedException() as you stated.


Some immediate improvement ideas are possible at first glance:

Avoid duplicated code: defaultTimeZone() appears twice. It's easy to factor that out by changing the branching logic: keep checking the requirements (preferences != null, the preference value not null, and so on) until you find a usable value and return. To handle all other (failure) execution paths, use a single return at the end of the method
Use the .isEmpty() method to check if a string is empty. This is better than !"".equals(value), which means literally "is this value the same as """. Using isEmpty is natural.
The variable named timeZone suggests it's an instance of TimeZone. That's misleading, I would rename it to something else to clarify.

Applying the above:

protected TimeZone resolveTimeZone() {
    IUserPreferences preferences = userProfileService.getCurrentUserPreferences();
    if (preferences != null) {
        String timeZoneText = preferences.getPreferredTimeZone();
        if (timeZoneText != null && !timeZoneText.isEmpty()) {
            return TimeZone.getTimeZone(timeZoneText);
        }
    }
    return defaultTimeZone();
}

On closer look, there are a few more things I don't really like:

The defaultTimeZone method sticks out a little from other getter calls in the posted code: getCurrentUserPreferences, getPreferredTimeZone, getDefaultLocale, ... Perhaps it would be better to be consistent with those and rename the method to getDefaultTimeZone
Calling Calendar.getInstance is costly. If the default timezone will not change during the lifetime of the application, then it would be better to initialize it once during startup, and reuse it afterwards.
The name resolveTimeZone is a bit vague. What does it mean, "resolve", really? Looking at the implementation, it's not as clear as it can be.

I would recommend to split the method like this:

protected TimeZone getTimeZone() {
    TimeZone preferredTimeZone = getPreferredTimeZone();
    if (preferredTimeZone != null) {
        return preferredTimeZone;
    }
    return defaultTimeZone();
}

private TimeZone getPreferredTimeZone() {
    IUserPreferences preferences = userProfileService.getCurrentUserPreferences();
    if (preferences != null) {
        String timeZoneText = preferences.getPreferredTimeZone();
        if (timeZoneText != null && !timeZoneText.isEmpty()) {
            return TimeZone.getTimeZone(timeZoneText);
        }
    }
    return null;
}

Here, the names and implementations of the methods are more natural:

getTimeZone: looking at the implementation it's perfectly clear what's going on: use the preferred timezone if possible, otherwise the default. Nice and simple.
getPreferredTimeZone: from the method name, it comes natural that the method tries to figure out a timezone from the user configuration and return null otherwise.

Alas, this does have the drawback of an extra if condition compared to the original. However, the cost of the extra call should be negligible in practice. This may be a matter of taste. I think the value of clarity in the design outweighs the cost of that extra if (unless performance is absolutely critical, of course).


Welcome to CodeReview! This isn't great code, but that doesn't mean that this is a bad question. I think that you've come to the right place.

Recursion

    if color == "":
        print("No skipping!")
        print(check(input("Enter Name Here>>> ")))

This uses recursion when it shouldn't. In other words, check is calling itself needlessly, and if the user tries to "skip" enough times, you'll get a stack overflow. Instead of doing this, just loop until you have valid input.

Fake delays

    print("Calculating...")
    sleep(2.5)

Few things bother me more than when a user interface lies to me. This output suggests that it takes 2.5 seconds for a calculation to be done, but that simply isn't so. Don't lie to your users - just show the results.

sleep(100) is actively harmful - the user needs to Ctrl+C to kill the program; otherwise it sits there preventing the user from getting their shell terminal back. This should just be deleted.

Don't repeat yourself

There are many places in the program that are expressed in a repetitive manner, especially user input (the "no skipping" mechanism), the call to count, and the additions to get total. I suggest the following:

def input_without_skip(prompt: str) -> str:
    while True:
        result = input(f'{prompt}>>>')
        if result:
            return result
        print('No skipping!')

def is_master() -> bool:
    return input_without_skip('Enter Name Here') == 'Hercules'

def get_counts():
    for question, prompt, chars in (
        (     'What is your favorite color?',   'fav_color', 'g'),
        (          'What is your dream car?',     'fav_car', 'g'),
        (            'What team are you on?',   'team_name', 'g'),
        (         'Who is your best friend?', 'best_friend', 'g'),
        (        'What color is your shirt?', 'shirt_color', 'g'),
        (                   'You got clout?', 'clout_level', 'y10'),
        ('Do you think you passed the test?',     'passed?', 'y')
    ):
        print(question)
        answer = input_without_skip(prompt)
        yield sum(answer.count(c) for c in chars)

def main():
    if is_master():
        print('Welcome home, master.')
        return

    print("Let's find some data!")
    total = sum(get_counts())

    if total > 1:
        print("passed")
    else:
        print("failed")
    print("Congrats on your result!")

if __name__ == '__main__':
    main()


Here's a crack at a bit of code.  It's probably worth mentioning though that I don't think your code could even compile or if it does your missing variables i.e. itoy_tmp5...

Either way, like Robert said I looked for some patterns that seemed to be repeating and started from there.  I extracted the first part to a method and then extracted again etc etc

Here's the code anyway if it helps.

    private string[] GetPossibleNames(string toyName)
    {
        return new []
            {
                toyName,
                HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace("&#228;", "&auml;"),
                toyName.Replace("\u00a0", " "),
                HttpUtility.HtmlDecode(toyName),
                HttpUtility.HtmlDecode(toyName.Replace("\u00a0", " "))
            };
    }

    private bool IsToyFor<T>(Table<T> table, string[] possibleToyNames, Func<T,string> getName)
    {
        return table.Any(p => possibleToyNames.Contains(getName(p)));
    }

    private bool HasInterestingToy(string[] possibleToyNames)
    {
        return IsToyFor(db.tblDoll, possibleToyNames, p => p.doll_name) ||
               IsToyFor(db.tblDoll, possibleToyNames, p => p.car_name);
               //Do the same as for Car and Doll, do it for Plane and Boat too
    }

    public JsonResult ValidateAll(string toys)
    {
        Dictionary<string, object> res = new Dictionary<string, object>();
        var resultCheck = new List<string>();

        string[] lines = toys.Split(new [] {"\n"}, StringSplitOptions.RemoveEmptyEntries);

        foreach (string line in lines)
        {
            string[] possibleToyNames = GetPossibleNames(line.Trim());

            if (HasInterestingToy(possibleToyNames)) resultCheck.Add("1");
        }

        res.Add("ok", resultCheck);
        return Json(res, JsonRequestBehavior.AllowGet);
    }


is there a shorter and a faster way than below to reverse a string?

Sure,

new StringBuilder(string).reverse().toString()

is generally used. Here is code to reverse a string that's also quite nice and that might even be faster in some situations.

As to your code:

naming: avoid short variable names: c and s could be index and letter.
c = c - 1 is often written as c--.
you shouldn't just write your code in main, but in a function so that you can easily test it. And some unit test can never hurt.
your code throws a StringIndexOutOfBoundsException for the empty string.

  is this code efficient?

No, not really. I profiled it, and the result is:

name                    per call (mean, ns)     per call (median, ns)     95th percentile (ns)     total (ms)     runs
reverseCharToString     897                     892                       816                      5.7408         8000000
reverseBuilder          132                     132                       101                      0.8448         8000000
reverseArray            126                     125                       95                       0.8064         8000000

Where reverseCharToString is your code, reverseBuilder is the code I pasted above, and reverseArray is the code I linked to. The main reason for this is that you are creating a lot of new objects.


Duplicated code

In order to remove duplicated code, the key is to identify the parts that are identical/different from one place to another. In your case, you could add a filter parameter to your all function (which would then deserve to be named differently).

You could write something like :

def get_result(self, beginFilter=None):
    labels_list = []
    for index in self.result:
        for key, value in index.items():
            if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter)):
                names = value
                labels_list.append(names)
                collection = set(labels_list)
    return collection

def brickyard(self):
    return self.get_result('BYD')

def schoolhouse(self):
    return self.get_result('SCH')

def spa(self):
    return self.get_result('Spa')

As a side-note, I had not given enough thought before writing the code above but if I had to re-do it from the beginning, I'd choose '' as a default value because it wouldn't need a special handling (all strings start with '' as far as I can tell).

Simplifying code

All your name variables were useless. Your names variable is not really useful neither. Also, labels_list could be named labels.

Finally, your conversion from list of labels to set of labels could be done only once at the very end of the function.

def get_result(self, beginFilter=None):
    labels = []
    for index in self.result:
        for key, value in index.items():
            if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter)):
                labels.append(value)
    return set(labels)

Now, it looks clearer that labels could be a set directly instead of converting it afterward.

def get_result(self, beginFilter=None):
    labels = set()
    for index in self.result:
        for key, value in index.items():
            if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter)):
                labels.add(value)
    return labels

You could also write this as a single set comprehension. Set comprehension is a convenient way to define set (you also have list comprehension and dict comprehension and even something called generator expression but this is out of scope at the moment).

It usually goes like this

my_list = [func(x) for x in my_iterable]  # list comprehension
my_set = {func(x) for x in my_iterable}  # set comprehension
my_dict = { my_key(x): my_val(x) for x in my_iterable}  # dict comprehension

In all 3 cases, one could add an optional filtering part so you could write something like:

my_set = {func(x) for x in my_iterable if some_property(x)}

Finally, you can also add more nested iterations. In your case, we could write (but some people would consider that this is going too far):

def get_result(self, beginFilter=None):
    return { value
        for index in self.result
        for key, value in index.items()
        if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter))}

Back to where we came from

Now that I understand better the point of your code, we can try to clean up the get_result function. The filtering can actually be moved out of the function.

def all(self):
    return { value
        for index in self.result
        for key, value in index.items()
        if 'accountLabelType' in key}

def brickyard(self):
    return {v for v in self.all() if v.startswith('BYD')}

def schoolhouse(self):
    return {v for v in self.all() if v.startswith('SCH')}

def spa(self):
    return {v for v in self.all() if v.startswith('Spa')}

or with a helper function :

def all(self):
    return { value
        for index in self.result
        for key, value in index.items()
        if 'accountLabelType' in key}

def filter(self, begin):
    return {v for v in self.all() if v.startwith(begin)}

def brickyard(self):
    return self.filter('BYD')

def schoolhouse(self):
    return self.filter('SCH')

def spa(self):
    return self.filter('Spa')

More

In order not to call all multiple times, one could imagine saving the result.


Custom error page with information tokens implementation

First of all I'd consider if hashing is required. Think that:

It's longer to type and impossible to remember.
If user is calling technical support by phone then he will have hard time to spell it out (especially if not native speaker).
It has not any benefit over a simpler short number.
You're computing a MD5 hash (128 bits, 32 bytes) then converting to hex string (64 characters) then removing the first 26. Are you sure you do not introduce collisions in your hash?!

You already have an ID then you might want to simply return that ID (eventually you may add a check-digit to prevent simple mistakes). This will also simplify your code because you do not need an UPDATE to store the calculated hash (check digit may simply be recomputed). Hashing here is (IMO) just overthinking (if you want to obfuscate the ID simply return its hexadecimal value).

You're using long (mapped to bigint). Do you plan to have more than 2^32 errors in your log? 16 Gb just to store the IDs...it's unlikely, don't consider just the number itself but disk space used for each row which has also a very long string).

You're logging stack trace but you're ignoring exception message and exception types which are probably more important than the stack.

You're logging the exception as-is but think about MethodInvocationException, AggregateException, TypeLoadException (just to mention few) where content of InnerException (or InnerExceptions) is much more important than its wrapper. You have a nice Exception.GetBaseException() to get the root cause of the current exception.

I don't know how you throw your own exceptions but often I use Exception.Data to provide more context and useful details. It may be not your case but don't forget about it.

You hard-coded 404 HTTP status code, why don't you use HttpStatusCode.NotFound?

DatabaseLogger.InsertLog() (fix your calling code because it's DatabaseLog) is a missed opportunity of generalization. I'd not go with complex architectures, factories and abstractions (but a simple IoC container might do well here), the fact that storage is in a database is a detail.

Also class should be sealed (currently you do not have extension points and it's not supposed to be a base class):

sealed Logger {
    public int Write(Exception exception) {
        var timestamp = DateTime.UtcNow;
        var content = TranslateExceptionToText(exception);

        // Code to write to DB storage...
    }

    private static string TranslateExceptionToText(Exception exception)
        => exception.GetBaseException().ToString();
}

Notes:

TranslateExceptionToText() is pretty naive, better logic should be used.
I moved responsibility to extract useful information from your error handler to the logger class but you may consider to introduce a 3rd class for this when logic is more complex.
Move SQL code to private const string fields, it's easier to find and edit keeping your code cleaner.
Do not use AddWithValue(). It has some, not obvious, drawbacks. It's not always a bad choice but I think it's easier to stop using it than determining each time if its usage is good or not.
Logging may fail and you dot have any error handling! What's your recovery policy in this case?
Strings for SQL code are not (do not use) interpolated strings. Drop $.
Strings for SQL code are not (do not use) verbatim strings. Drop @.

Application_Error might be simplified:

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastException();
    HttpContextException.Current.ClearError();

    if (IsPageNotFoundException(exception))
        RedirectToNotFound();
    else
        RedirectToError(Logger.Default.Write(exception));
}

Implementation of IsPageNotFoundException(), RedirectToNotFound() and RedirectToError() should be clear but let's write IsPageNotFoundException():

private static bool IsPageNotFoundException(Exception exception)
{
    if (exception is HttpException httpException)
        return httpException.GetHttpCode() == (int)HttpStatusCode.NotFound;

    return false;
}


Basically, what you need is a Cartesian product of 7 sequences, each containing a 0 and a 1. Eric Lippert has an interesting article about doing just that using LINQ (note: I think you could make his code more efficient using immutable collections). If you use his method, your code could look something like:
var product = CartesianProduct(Enumerable.Repeat(new[] { 0, 1 }, games.Count));

foreach (var indexes in product)
{
    if (indexes.Sum() < 4)
    {
        winningOdds += indexes
            .Select((index, game) => games[game].Odds[index])
            .Aggregate((x, y) => x * y);
    }
}


Finding the average of each row in a CSV file

Firstly, note that you are not closing the file after opening it. A Better way to read from a file would be to use the with statement. Read What is the python “with” statement designed for? to know more about the with statement.

The code would be,

with open("data.csv") as filename:
    # Code Follows

Other things to note here are

The mode of the open statement is 'r' by default and hence, you don't need to explicitly mention it.
Use a meaningful variable name like filename. This is to help your future self from not asking What is the f?

Now coming to the core of the problem. You can use the fileobject directly to iterate over the lines, You do not need to read the entire file into a list. This is helpful for large files. The code will be

for line in filename:
     # Code follows

The line line2 = line.replace("\n", "") is quite inadequate as there might be other whitespace like a trailing space or a \r. To solve all these issues, you can use str.strip.

stripped_line = line.strip()

Again, Note the name of the variable. Coming to this code block

line2 = line2.split(",")
Nlines = []
for i in line2:
    i = float(i)
    Nlines.append(i)
sums = sum(Nlines)

You can solve this issue using split and a generator expression.

stripped_line  = stripped_line .split(',')
line_sum = sum(float(i) for i in stripped_line)

Alternatively you can use map

line_sum = sum(map(float,stripped_line))

(You can use literal_eval to directly do sum(literal_eval(stripped_line)), But the string functions are the right (and preffered way))

Hence the complete code will be reduced to (excluding the data creation part)

def line_averages():
    with open("test.csv", "r") as filename:
        avLines= []
        for line in filename:
            stripped_line  = line.strip()
            stripped_line  = stripped_line.split(',')
            line_sum = sum(float(i) for i in stripped_line )
            avLines.append(line_sum/len(stripped_line ))
        return avLines

Code Golfing the solution, We can use a List Comprehension. Read this to kow more about the list comprehensions.

def line_averages():
    with open("test.csv", "r") as filename:
        lines = [[float(i) for i in line.strip().split(',')] for line in filename]
        return [sum(i)/len(i) for i in lines]


For the overall program structure, I suggest:

Using fileinput instead of explicitly using sys.argv[1].  Your program would automatically switch between sys.stdin and the named file.
Breaking out the redaction logic into its own function, because each line is a self-contained problem with well-defined inputs and outputs.

To perform the redaction, I suggest using regular expressions, since this is just a pattern-matching problem.  You've used the re module already, so you might as well go all the way.

import fileinput
import re

def redact(original, target):
    matched = False
    def replacement(m):
        matched = True
        s = list(m.string)
        for g in range(1, 1 + len(m.groups())):
            for i in range(m.start(g), m.end(g)):
                s[i] = ' ' if s[i] == ' ' else '_'
        return ''.join(s)

    # Replace contiguous spaces with one space
    original = re.sub(r"\s+", " ", original)
    pattern = re.compile(
        '^(.*?)' +
        '( .*?|.*? )'.join(re.escape(c) for c in target.split(' ')) +
        '(.*?)$'
    )
    result = pattern.sub(replacement, original)
    return 'I cannot fix history' if matched else result

if __name__ == '__main__':
    for line in fileinput.input():
        line = line.strip()
        if not line:
            continue
        print(redact(*line.split(';', 1)))


Since you only want lines starting with BLAH, filter the lines before parsing the CSV. I think the profiler is misleading you by attributing the time spent parsing CSV to the line for row in reader in your code.

with open(file, 'rt', newline='', encoding='utf-8') as f:
    filtered = (line for line in f if line.startswith('BLAH'))
    reader = csv.reader(filtered, delimiter='\t')
    for row in reader:
        files_found_lines.append(row[0:9])


Transferring data for a given month from one sheet to another

Sub month()

Dim month As String

Something isn't right, one of these two has the wrong name. Procedure names should start with a verb, they do something. If you can name that something, then you can name the procedure. If you can't name that something, then your procedure is doing too many things and needs to be broken down into something that can be named.

So we're getting the month name for some user input - if that's always going to be in English, then there's no need to hard-code that in a Select Case block.

Public Function ToMonthName(ByVal value As Integer) As String
    On Error GoTo CleanFail 'remove if runtime error 5 should bubble up to caller instead

    Dim result As String
    result = MonthName(value)

CleanExit:
    ToMonthName = result
    Exit Function
CleanFail:
    result = vbNullString
    Resume CleanExit
End Function

So, now we have the month name (or an empty string), that month procedure can actually start focusing on its task.

It's confusing that every code paths execute the died: label. There's no error handling - seeing that line label I was expecting to see On Error GoTo died somewhere.

So two things are happening here. First we're iterating dataWS and populating three arrays in parallel - there's a design smell right here: you have 3 data structures that are "in sync", when there should really be only one.

Make a small class module, and expose the 3 properties you're interested in:

Option Explicit
Private Type TModel
    CostCenter As String
    Description As String
    Amount As Single
End Type

Private this As TModel

Public Property Get CostCenter() As String
    CostCenter = this.CostCenter
End Property

Public Property Let CostCenter(ByVal value As String)
    this.CostCenter = value
End Property

Public Property Get Description() As String
    Description = this.Description
End Property

Public Property Let Description(ByVal value as String)
    this.Description = value
End Property

Public Property Get Amount() As Single
    Amount = this.Amount
End Property

Public Property Let Amount(ByVal value As Single)
    this.Amount = value
End Property

Now you can store instances of this class, which encapsulates the data you're interested in. This:

Do While .Cells(start + i, 1) <> "" 'loop through column A while there is a month present (not blank)

    ccArray(i) = .Cells(start + i, 11).Value 'store cost center
    amountArray(i) = .Cells(start + i, 13).Value 'store amount
    descriptArray(i) = .Cells(start + i, 9).Value 'store description

    i = i + 1

Loop

Becomes this:

Dim data As Collection
Set data = New Collection

Dim item As DataModel 'assuming class name was "DataModel"

Do While .Cells(start + i, 1) <> vbNullString 'loop through column A while there is a month present (not blank)

    Set item = New DataModel
    item.CostCenter = .Cells(start + i, 11).Value
    item.Amount = .Cells(start + i, 13).Value
    item.Description = .Cells(start + i, 9).Value

    data.Add item
    i = i + 1

Loop

And now if the body of that loop was extracted into its own function...

Private Function ReadModel(ByVal source As Range) As DataModel
    Dim result As New DataModel
    result.CostCenter = source.Cells(1, 11).Value
    result.Amount = source.Cells(1, 13).Value
    result.Description = source.Cells(1, 9).Value
    Set ReadModel = result
End Function

You could also define an Enum to get rid of the magic values there:

Private Enum ColumnPosition
    DescriptionColumn = 9
    CostCenterColumn = 11
    AmountColumn = 13
End Enum

And then use them to enhance readability here:

Private Function ReadModel(ByVal source As Range) As DataModel
    Dim result As New DataModel
    result.CostCenter = source.Cells(1, CostCenterColumn).Value
    result.Amount = source.Cells(1, AmountColumn).Value
    result.Description = source.Cells(1, DescriptionColumn).Value
    Set ReadModel = result
End Function

The calling code will now look like this:

Dim data As Collection
Set data = New Collection

Do While .Cells(start + i, 1) <> vbNullString 'loop through column A while there is a month present (not blank)

    data.Add ReadModel(.Range("A" & start + i).EntireRow)
    i = i + 1

Loop

And now if you ever need to read more values, that code doesn't even need to change - you can simply modify the DataModel accordingly, and the function that reads a row's values into an instance. And this loop and collection should go into its own function, too.

The number of items in the collection would be simply data.Count.

Next the loop that consumes this data, could be a For Each loop:

Dim item As DataModel
For Each item In data
    '...
Next

Again, this should be in its own procedure. On Error Resume Next shouldn't need to be there. What errors are being thrown under the carpet? They should be handled.


The program is difficult to read because all code is in the main()
function. As an example, one has to jump to the end of the program in
order to understand how the “get a positive integer from the user” loop
works.

It is generally better to separate the I/O from the computation, and
have dedicated functions for a single purpose. In your example, the overall
structure could for example look like this:

static int readPositiveInteger(String prompt) throws IOException {
    // ...
}

static boolean[] openDoors(int numOfDoors) {
    // ...
}

static void printOpenDoors(boolean[] doors) {
    // ...
}

public static void main(String[] args) throws IOException {

    int numOfDoors = readPositiveInteger("Enter the number of doors: ");
    boolean[] doors = openDoors(numOfDoors);
    printOpenDoors(doors);
}

More remarks:

The naming convention for Java classes is upper camelcase, in your case
HundredDoors.
The boolean hasNum should be a local variable in main().
boolean variables are by default initialized to false, the explicit
initialization in a loop is not needed.
You create a new Scanner instance for each attempt to read a positive
integer. A single instance is sufficient if you read lines from standard
input with nextLine().
The message “Please enter an integer” should be “Please enter a positive
integer" since that is what you need and check for.
Array indices start at zero whereas the door numbers start at one.
If you allocate one additional boolean element for the doors array then
the door number can be used as array index directly, instead of adding/subtracting
one at various places. That makes the code better understandable.
The output can be written directly to standard output instead of
concatenating it to a string first.

Putting it all together, the program could look like this:

import java.io.IOException;
import java.util.Scanner;

public class HundredDoors {

    static int readPositiveInteger(String prompt) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int i = 0;
        do {
            System.out.print(prompt);
            try {
                i = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e){
                i = 0;
            }
            if (i <= 0) {
                System.out.println("Please enter a positive integer!");
            }
        } while (i <= 0);
        return i;
    }

    static boolean[] openDoors(int numOfDoors) {
        boolean[] doors = new boolean[numOfDoors + 1];
        for (int index = 1; index <= numOfDoors; index++) {
            for (int door = index; door <= numOfDoors; door += index) {
                doors[door] = !doors[door];
            }
        }
        return doors;
    }

    static void printOpenDoors(boolean[] doors) {
        System.out.println("Doors still opened:");
        int count = 0;
        for (int door = 1; door < doors.length; door++) {
            if (doors[door]) {
                if (count == 10) {
                    System.out.println();
                    count = 0;
                }
                count += 1;
                System.out.print(door + " ");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {

        int numOfDoors = readPositiveInteger("Please enter the number of doors: ");
        boolean[] doors = openDoors(numOfDoors);
        printOpenDoors(doors);
    }
}


Best practice and alternatives for string manipulation with an emphasis on readability

In C#, you could use the built-in string.Format instead:

string parameterizedUrl = "page.aspx?id={0}&ref={1}";
return string.Format(parameterizedUrl, id, referrer);

I haven't profiled it, but I think it would at worst be not any less efficient than your double Replace() call.


Leetcode 102: Binary tree level-order traversal in Swift

Simplifying your code

Let's start here:

let capacity = nodes.reduce([Int]()) {
    if $0.contains($1.0) == false {
        return $0 + [$1.0]
    }
    return $0
}.count

The test

if $0.contains($1.0) == false

is shorter (and – in my opinion – better) written as

if !$0.contains($1.0)

Each invocation of the closure creates a new array. In such cases it is more efficient to use reduce(into:) with a closure that updates the array:

let capacity = nodes.reduce(into: [Int]()) {
    if !$0.contains($1.0) {
        $0.append($1.0)
    }
}.count

But what this code actually does is to determine the number of distinct levels in the nodes array. That is simpler and more efficiently done with a set:

let capacity = Set(nodes.map { $0.0 }).count

Here

return nodes.reduce([[Int]](repeating: [], count: capacity), {
    var tmp = $0
    tmp[$1.0].append($1.1)
    return tmp
})

a new nested array is created with each invocation of the closure. Again, this can be improved with reduce(into:), so that the first function becomes

func levelOrder(_ root: TreeNode?) -> [[Int]] {
    guard let root = root else {
        return []
    }
    let nodes = recursiveVisit(root)
    let capacity = Set(nodes.map { $0.0 }).count
    return nodes.reduce(into: [[Int]](repeating: [], count: capacity), {
        $0[$1.0].append($1.1)
    })
}

I have only minor suggestions for the second function:

var nodes = [(Int, Int)]()
nodes.append((0, node.val))

can be combined to

var nodes = [(0, node.val)]

The results of the recursive calls can be appended to the nodes array directly:

nodes += recursiveVisit(node.left).map {
    return ($0.0 + 1, $0.1)
}
nodes += recursiveVisit(node.right).map {
    return ($0.0 + 1, $0.1)
}

And if you use tuple labels then the code becomes better readable (and almost self-documenting):

func recursiveVisit(_ node: TreeNode?) -> [(level: Int, value: Int)] {

    guard let node = node else {
        return []
    }
    var nodes = [(level: 0, value: node.val)]
    nodes += recursiveVisit(node.left).map {
        return (level: $0.level + 1, value: $0.value)
    }
    nodes += recursiveVisit(node.right).map {
        return (level: $0.level + 1, value: $0.value)
    }
    return nodes
}

This can be used in the first function as well. As an alternative, define a custom struct with “level” and “label” members.

Alternative #1 – A nested function

It is not necessary to create an array of (level, value) tuples first. You can add a value to the sublist on the current level, or append a new level while traversing the tree recursively. With a nested function you don't even have to pass the array around:

func levelOrder(_ root: TreeNode?) -> [[Int]] {
    var levels: [[Int]] = []

    func recursiveVisit(_ node: TreeNode?, level: Int) {
        guard let node = node else {
            return
        }
        if level < levels.count {
            levels[level].append(node.val)
        } else {
            levels.append([node.val])
        }
        recursiveVisit(node.left, level: level + 1)
        recursiveVisit(node.right, level: level + 1)
    }

    recursiveVisit(root, level: 0)
    return levels
}

Alternative #2 – Iteration instead of recursion

The referenced Java solution solves the task with iteration, and a list containing all nodes on the current level. Of course that can be done in Swift as well. Here is an example of a quite compact implementation:

func levelOrder(_ root: TreeNode?) -> [[Int]] {
    guard let root = root else {
        return []
    }

    var wrapList: [[Int]] = []
    var queue = [root] // First level

    while !queue.isEmpty {
        // All values of nodes on the current level:
        wrapList.append(queue.map { $0.val })
        // Replace queue by list of all nodes on the next level:
        queue = queue.flatMap { [$0.left, $0.right ] }.compactMap { $0 }
    }

    return wrapList
}


Give function get file extension for you

You can use PHP inbuilt function. Inbuilt functions are the fastest.

$ext = pathinfo($filename, PATHINFO_EXTENSION);


Aside from the issue of setIntervals resolution/accuracy there's a lot of room for improvement in your angular.

angular.module('app', []);

"app" isn't a good name for your module "fruitjs.timer" would be better as it is more descriptive and has a much lower chance of naming clashes.

app.controller('main', function($scope, $interval) {

Again "main" isn't a great name for your controller "timerController" would be more explicit.

You should also utilise angular's support for safe minification:

app.controller('main', ['$scope', '$interval', function($scope, $interval) {
    // code
}]);

Notice that the second parameter is now an array declaring the names of the services/modules you require and finally your controller function (this is the recommended way).

More bad naming clickme, foo, startfun - none of these names mean anything.

$scope.status isn't the status at all - it's the potential action.

You don't need the clickme variable (which should at least be camel cased to clickMe). You have 2 potential actions "Start" and "Stop" - you don't need the additional boolean to track what state you're currently in.

Use either 2 or 4 spaces for your indentation - don't mix and match.

You don't change the label after you stop the timer.

Code with above changes

var app = angular.module('fruitjs.timer', []);
app.controller('timerController', [ '$scope', '$interval', function($scope, $interval) {
    var interval, incrementTimer, actions;
    actions = { start: "Start", stop: "Stop" };

    $scope.timer = 0;
    $scope.action = actions.start;

    incrementTimer = function() {
        $scope.timer += 1;
    };

    $scope.toggle = function() {
        if ($scope.action === actions.start) {
            $scope.action = actions.stop;
            interval = $interval(incrementTimer, 1000);

        } else if ($scope.action === actions.stop) {
            $scope.action = actions.start;
            $interval.cancel(interval);
        }
    };

    $scope.reset = function () {
        $interval.cancel(interval);
        $scope.timer = 0;
        $scope.action = actions.start;
    };
}]);

All you need to do now is solve the problem of keeping time accurately :)


Keep reading Command-line until you get the word END

takes (integers) numbers from Command-line and keeps reading the
  terminal until it gets a word END.

For example,

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    sum := int64(0)
    s := bufio.NewScanner(os.Stdin)
    s.Split(bufio.ScanWords)
    for s.Scan() {
        word := s.Text()
        num, err := strconv.ParseInt(word, 10, 64)
        if err != nil {
            if strings.ToUpper(word) == "END" {
                break
            }
            fmt.Fprintln(os.Stderr, err)
            continue
        }
        sum += num
    }
    if err := s.Err(); err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    fmt.Println("Sum of all numbers:", sum)
}

Terminal:

12 24
36
6
6
  END
Sum of all numbers: 84


Implementing the observer pattern for a stock exchange scenario

Make immutable class members const

If you have a member of a class that is set once at construction time, but will never change, then make it const. For example, in Stock:

class Stock {
  const std::string name;
  ...
  public:
  Stock(..., std::string stock_name, ...): name(stock_name) {
    ...
  }

And once it is const, you can safely make name public and remove get_name().

Avoid circular references

Your stock exchanges contain stocks, but stocks also refer to stock exchanges. This circular reference is unnecessary and might give you problems; for example you had to add forward references to class Stock_Observer and class Stock in stock_exchange.hpp. Conceptually, a stock is not tied to a specific stock exchange, so just remove the member variable Stock::se.

Of course, the problem is now how to notify observers when the stock price changes. One way to handle that is to allow one to set a callback function in a Stock, for example:

#include <functional>

class Stock {
  std::function<void(Stock &)> price_changed_callback;
  double price;
  ...
  public:
  void set_price_changed_callback(std::function<void(Stock &)> callback) {
    price_changed_callback = callback;
  }

  void set_price(double p) {
    price = p;
    if (price_changed_callback)
      price_changed_callback(*this);
  }
  ...
}

Then the stock exchange calls set_price_changed_callback() when it registers the stock, and sets it to something like its notify_observers() function.
If you want to have a Stock be part of multiple exchanges, then you'd better look for a library that handles more complex callback registration for you, like libsigc++.

Another option would be to move set_price() to the stock exchange itself.

Think carefully about ownership

In your code, stock exchanges have pointers to stocks, and stocks have a pointer to a stock exchange. But what if a stock goes out of scope before a stock exchange, or vice versa? It's not a problem in your simple main(), but once your code grows the chance you will make a mistake will increase. It's best to use the right tools to control ownership.

One possibility is to use shared_ptr<>. Make it so you can only create a shared_ptr to a Stock:

class Stock {
  private:
  Stock() { ... }

  public:
  static std::shared_ptr<Stock> make_stock(args) {
    return std::make_shared<Stock>(args);
  }
}

And have Stock_Exchange keep a map of shared_ptrs:

class Stock_Exchange {
  std::unordered_map<std::string, std::shared_ptr<Stock>> registered_stocks;
  ...
}

Alternatively, if you'd only ever have stocks associated with a single exchange, you could have Stock_Exchange take direct ownership:

class Stock_Exchange {
  std::unordered_map<std::string, Stock> registered_stocks;
  ...
  public:
  register_stock(std::string name, double price) {
    register_stocks.emplace(std::make_pair(name, Stock(name, price));
  }
}

Of course, if you go that route there is little point in having a class Stock anymore.

Use references when iterating over a container where possible

In this part of your code:

for(auto o : stock_observers[stock_name])
{
    o->notify(stock_name);
}

You are actually making a copy of each observer. It is almost always better to use a reference when iterating through a container:

for(auto &o : stock_observers[stock_name])
{
    o->notify(stock_name);
}


First, a couple Typescript notes:

I assume you cannot change the data format, if you can, I would highly recommend renaming the enum property. enum is a keyword in Typescript.
OrderStateEnum should be represented as an actual enum. I'd also consider dropping the Enum suffix.

enum OrderStateEnum {
  RECEIVED = 'RECEIVED',
  PAID = 'PAID',
  UNPAID = 'UNPAID',
  CUSTOMER_NOTIFIED = 'CUSTOMER_NOTIFIED',
  FINISHED = 'FINISHED'
}

Avoid default exports - see Typescript Deep Dive

You are correct, Ramda can help simplify this code.

pluckStateEnum is equivalent to R.prop('enum')
ordersByState can have the nesting level reduced, additionally, checking if the intersection of two arrays is empty can be better represented with R.any(R.contains(R.__, arr1), arr2). I also use chain to flatten the array while getting properties.

const ordersByState = states => orders.filter(R.pipe(
  R.prop('orderStates'),
  R.chain(R.prop('enum')),
  R.any(R.contains(R.__, states))
))

With this change, the function becomes much easier to read. See the repl.

For completeness, here is how I would implement this function:

function group(orders, orderListing) {
  const ordersByState = states => orders.filter(R.pipe(
    R.prop('orderStates'),
    R.chain(R.prop('enum')), // you might know this as flatMap
    R.any(R.contains(R.__, states))
  ))

  return orderListing.map(listing => ({
    id: listing.id,
    orders: ordersByState(listing.orderStateEnums).map(R.prop('id')),
  }))
}


Android - handle navigation to multi activities from list view

What do you see as the advantage of your approach? Why not just:

servicesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             showActivity(ServicesActivity.class);
        }
    });

without the constants and the switch converting them to their respective classes? What value do you feel this additional abstraction layer adds to the code?

(If you got rid of it, you'd only need showActivity implemented as follows:

private void showActivity(Class mActivity) {
    Intent intent = new Intent(MainActivity.this, mActivity);
    startActivity(intent);
}

)

A few other remarks:

By convention, names of methods in Java should start with lower-case (so, showActivity and navigateTo - just like startActivity and setOnClickListener).
Parameter names shouldn't start with "m". There is a - controversial - naming convention that prefixes class members (or fields) with "m". I personally think it's iffy, but some people do that. This convention at least has some logic behind it though, whereas prefixing a parameter with "m" makes no sense.
As of now you can pass any class to this method, which isn't as type safe as it could be. If you made it generic, you could narrow it down to Activity subclasses, making it more typesafe:

private <T extends Activity> void showActivity(Class<T> activity) {
    Intent intent = new Intent(MainActivity.this, activity);
    startActivity(intent);
}

Now you can't call eg. showActivity(Integer.class).
Other than removing the "m" prefix from the parameter name, I wouldn't also keep it named "activity". It's an Activity class, not an Activity (instance object) itself. I'd rename it to activityClass.


Regular expressions - match only specified string length

Ref. http://www.regular-expressions.info/anchors.html

  Anchors are a different breed. They do not match any character at all. Instead, they match a position before, after, or between characters. They can be used to "anchor" the regex match at a certain position. The caret ^ matches the position before the first character in the string. Applying ^a to abc matches a. ^b does not match abc at all, because the b cannot be matched right after the start of the string, matched by ^. See below for the inside view of the regex engine.

  Similarly, $ matches right after the last character in the string. c$
  matches c in abc, while a$ does not match at all.

With anchors you may skip length test entirely.

So:

import re
str = raw_input("input in form 'aA1' please >")
check = re.compile("^[a-z][A-Z][0-9]$")
validate = check.match(str)
if validate:
    print "Correct string"
else:
    print "Incorrect string"