First of all, it's great that you've used type signatures. So let's have a look at the contents of your functions.

Use divMod instead of div and mod

In toDigits, you both div and mod x by 10. However, there's a function that combines them both: divMod. With that in mind, we can write

toDigits :: Integer -> [Integer]
toDigits x
    | x <= 0       = []
    | divBy10 < 10 = [divBy10, remainder]
    | otherwise    = toDigits divBy10 ++ [remainder]
    where (divBy10, remainder) = x `divMod` 10

Avoid left-recursion on ++

However, your function is currently non-optimal. If you use x ++ [y] repeatedly, you end up with \$\mathcal O(n^2) \$ instead of \$\mathcal O(n) \$, as ++ is \$\mathcal O(n) \$ (where \$n\$ denotes the length of the first list).

It's easier to write toDigitsRev:

toDigitsRev :: Integer -> [Integer]
toDigitsRev x = case x `divMod` 10 of
                  (0, 0) -> []
                  (0, m) -> [m]
                  (d, m) -> m : toDigitsRev d

The case is just a matter of preference, you can continue to use your guards. Note that we now use (:), which is alwas \$\mathcal O(1) \$. Our toDigits is now only

toDigits :: Integer -> [Integer]
toDigits = reverse . toDigitsRev

Use simpler patterns where possible

Your patterns in doubleEveryOther are a little bit contrived. If we look closely, we can see that we always return the input, except for the two-element case. Let's reorder the patterns first to see that:

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther xs = reverse $ doubleEveryOther' (reverse xs)
    where   doubleEveryOther' (x:y:xs) = [x, y*2] ++ doubleEveryOther' xs
            doubleEveryOther' []       = []
            doubleEveryOther' (x:[])   = [x]
            doubleEveryOther' (x:y:[]) = [x, y*2]

Now the first pattern handles both (x:y:xs) and (x:y:[]), so we can get rid of the last pattern:

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther xs = reverse $ doubleEveryOther' (reverse xs)
    where   doubleEveryOther' (x:y:xs) = [x, y*2] ++ doubleEveryOther' xs
            doubleEveryOther' []       = []
            doubleEveryOther' (x:[])   = [x]

In our empty and single-element pattern we return our input, so we can combine both variants into a single pattern:

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther xs = reverse $ doubleEveryOther' (reverse xs)
    where   doubleEveryOther' (x:y:xs) = x : y*2 : doubleEveryOther' xs
            doubleEveryOther' xs       = xs

Also, it's common to use short names for workers, so let's call the worker go:

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = reverse . go . reverse
    where   go (x:y:xs) = x : y*2 : go xs
            go xs       = xs

The point-free definition of doubleEveryOther is a matter of preference.

Other remarks

sumDigits and validate are fine, although I'd write them as follows

sumDigits :: [Integer] -> Integer
sumDigits  = sum . map (sum . toDigits)

validate :: Integer -> Bool
validate x = checksum == 0
  where
    checksum = sumDigits (doubleEveryOther $ toDigits x) `mod` 10

That's only a matter of personal preference, though. The compiler will change map f $ map g to map (f . g) automatically, so your variant of sumDigits didn't traverse the list twice.


From a CodeIgniter point of view, this is fine but CI isn't really MVC. in MVC proper, the controller would be doing very little (See: https://stackoverflow.com/questions/13813046/how-is-mvc-supposed-to-work-in-codeigniter ). However in CodeIgniter's implementation you still want to strive for "Fat model, thin controller", which you're doing for the most part. This will give you far greater reusability as the logic isn't tied to a specific controller. I'd argue that most of the things in the $data array are actually stateful or display logic (e.g. which panel to display) so don't belong in the controller.

MVC strives for a high separation of concerns with reusable components and although CodeIgniter goes against this philosophy slightly, you can still work around it. Keep your views and models reusable.


Macro to distribute data within the sheets based on tabs name

Use any method that make a "directly-interation" with worksheet like copy, paste, range.value = something (...) intensifies the runtime of the code. To solve this you need to create an array to store the SourceSh.Rows(r) values. Before the loop change spreadsheet you parse all values stored in the array to cells using the method that I will show in the example. When the loop change spreadsheet you clear the array.

With that I think that you will have at least 65% better performance.

I created an example comparing runtime of the array method with the single value method,
to 20k cells. See the difference?

[

Sub Compare()

Dim arr() As Variant
Dim max As Long
Dim start As Double

start = Timer

max = 20000
ReDim arr(max)

Application.ScreenUpdating = False

'Using the array method

For i = 1 To max

    arr(i) = i

Next i

Sheets("Planilha1").Range("A1:A" & UBound(arr) + 1) = WorksheetFunction.Transpose(arr)
Debug.Print "Array method in seconds: " & Round(Timer - start, 2)

'Parsing single values method

start = Timer

For i = 1 To UBound(arr)

    Sheets("Planilha1").Range("A1:A" & UBound(arr) + 1) = i

Next i

Debug.Print "Value method in seconds: " & Round(Timer - start, 2)

Application.ScreenUpdating = True

End Sub


Fail-safe remote API operations for managing customers and billing

Do you have access to the customer API? If so, I think the deletion of the Paypal account should be handled by it.

If you do not have access to it, it seems the most important call is the Paypal one, so you should first make sure that one succeeds. Once it does, you can delete the customer account. But no matter how you delete it, there will be some time, even if only a few seconds, when the customer account will be without a Paypal account. The customer API needs to handle this situation gracefully.

To make sure the customer account gets eventually deleted, I would add this account to some table and have a cron job process it every X seconds. The cron job should delete all the account in that table. It means that if deletion fails, it will try again a few seconds later, so it's safe to assume the account will eventually get deleted.


HackerRank Array left rotation using Swift

I am not a swift programmer so i will not be able to give you exact advice on how to improve the quality of your code but rather the algorithm you used to solve this challenge and nitpicks i have with your solution.

Firstly lets look at the question itself.

It asks you to print out the new array. why are you creating it and turning it back into a string?

That considered, you can simply perform 2 for loops

1 for loop up until the "break" where the array has overflown, and a second for loop for the rest of the untouched array.

therfor we can simply print out the elements at location

d to n

and then the elements from

0 to d

This will shorten your code considerably and make it run a whole lot faster because no extra variables are needed and you arent doing array manipilation, its just a way to iterate over an array


You could create a helper routine getStarImage:forRating: and use that to set up each star:

let fullStarImage:  UIImage = UIImage(named: "starFull.png")!
let halfStarImage:  UIImage = UIImage(named: "starHalf.png")!
let emptyStarImage: UIImage = UIImage(named: "starEmpty.png")!

func getStarImage(starNumber: Double, forRating rating: Double) -> UIImage {
    if rating >= starNumber {
        return fullStarImage
    } else if rating + 0.5 == starNumber {
        return halfStarImage
    } else {
        return emptyStarImage
    }
}

if let ourRating = object?["OurRating"] as? Double {
    cell?.star1.image = getStarImage(1, forRating: ourRating)
    cell?.star2.image = getStarImage(2, forRating: ourRating)
    cell?.star3.image = getStarImage(3, forRating: ourRating)
    cell?.star4.image = getStarImage(4, forRating: ourRating)
    cell?.star5.image = getStarImage(5, forRating: ourRating)
}

If the last part looks a bit redundant, you could do it in a loop.  This probably isn't worth it for 5 items, but it demonstrates what you can do in Swift:

for (index, imageView) in [cell?.star1, cell?.star2, cell?.star3, cell?.star4, cell?.star5].enumerate() {
    imageView?.image = getStarImage(index + 1, forRating: ourRating)
}


Code in patched Cygwin for calculating path to command interpreter

You're allocating too much memory:

unsigned int total = nchars + 1 + sizeof cmdname + 1;

You only need 1 terminating null at the end of the string.  This is already accounted for in the size of cmdname (since you declare it as a string initialized []).  You can simply allocate:

unsigned int total = nchars + 1 + sizeof cmdname;

Or, if you add the "\" onto cmdname you could do:

char cmdname[] = "\\cmd.exe";
unsigned int total = nchars + sizeof cmdname;


Whitespace formatting

Apply a linter that will give you PEP8 suggestions. Among other things, it will suggest the following:

import os,gc,queue

There should be spaces after those commas. It'll also suggest that there be one line per import.

class add_line:

should be

class AddLine:

and have a couple of newlines before it.

else :

shouldn't have a space before the colon.

f-strings

"https://ejje.weblio.jp/content/"+ w_list[1]

can be

f'https://ejje.weblio.jp/content/{w_list[1]}'

Falsiness

if len(fetched_text)== 0:

can be

if not fetched_text:

Don't repeat yourself

            li_ = list(map(lambda x:x.contents[0], fetched_text))
            li_.insert(0,w_list[0])
            self.put_queue(li_)

appears twice. Put it in a function or restructure your if blocks.

File iteration

with open(path) as f:
    while True:
        lines = f.readline()
        if not lines:
            break

First of all, your variable name is confusing. This isn't lines, it's line.

Also: just change your iteration to

with open(path) as f:
    for line in f:

As for this:

with open(path_w, mode='a') as f:
    # ...
    f.close()

Get rid of the close; the file is already closed at the end of the with.

main

You do check __name__, but you don't give all of that code function scope. You should move it into a main function. Otherwise, every one of those variables will be visible from other functions.


Im not going to comment on the implementation of the calculator (there are more well versed people out there) but I will comment on the coding style;

Return early (or in this case throw early)

I much prefer (I think most people do) to return or throw early to avoid more brackets and indentation.

So I would change the body of calc() to look like;

if($this->x == 0 && $this->z == 0){
    throw new \Exception('Operations with 0 not allowed!');
}

switch($this->y){
    case '+':
    return ($this->x + $this->z);
    break;

    case '-':
    return ($this->x - $this->z);
    break;

    case '/':
    return ($this->x / $this->z);
    break;

    case '*':
    return ($this->x * $this->z);
    break;

    default:
    throw new \Exception('Unknown operator');
    break;

}

Let Exceptions bubble up

If this is a calculator the excepted return is a number, not a string so doing the whole try catch and returning the $e->getMessage() is probably not what the developer expects to happen.

Variables In The Constructor

There is a lot of resources out there that suggest this is the correct way to pass data to a class.

To me variables passed to a constructor should be other classes this class depends on, the reason is so we don't have to add more manual definitions when using dependency injection (this is not true in every instance).

but here are some arguments why in this particular instance I wouldn't pass data to the constructor

For dependency injection you are going to have to define where those variables are
You will have to instantiate a new Calculator(x, y, z) every time you want to use it which seems wasteful as you return the values and not store them for another class to use


Find Common Denominator for 2 Fractions with JavaScript - Simplify & Improve

Here's my attempt to help you.

As a general rule, keep everything as general as you can and don't split your code into different cases unless you have to. From the if (factor >1) part, I knew things could be improved
At the end, the denominators will be the Least Common Multiple of the two initial fractions.
Then, you just need to multiply the numerators by the same amount used to multiply the denominators

Here's the corresponding code.

// Finds the highest common factor of 2 numbers
function highestCommonFactor(a, b) {
    if (b == 0) {
        return a;
    }
    return highestCommonFactor(b, a%b);
}
function leastCommonMultiple(a,b) {
    return a*b/(highestCommonFactor(a,b));
}

// Input fractions to add ////////////////////////////////
// Fraction 1 = 2/6
var fraction1Numerator = 2;
var fraction1Denominator = 6;

// Fraction 2 = 1/2
var fraction2Numerator = 1;
var fraction2Denominator = 2;
////////////////////////////////////////////////////////////////

// Find the highest common factor of both denominators
var commonMultiple = leastCommonMultiple(fraction1Denominator, fraction2Denominator);

fraction1Numerator   *= (commonMultiple / fraction1Denominator);
fraction2Numerator   *= (commonMultiple / fraction2Denominator);

// Display solution
document.getElementById("divSolution").innerText = fraction1Numerator + "/" + commonMultiple + " + " + fraction2Numerator + "/" + commonMultiple;


Method names in Java are usually camelCase as well as variable names. So,

WriteToXSL.WriteTo should be WriteToXSL.writeTo,
WebElement Element should be WebElement element,
Testgoal should be testgoal.

WriteToXSL and WriteToPDF aren't the best class names. The Java Language Specification, Java SE 7 Edition, 6.1 Declarations says the following:

  Class and Interface Type Names

  Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed
  case with the first letter of each word capitalized.

I would call them XslWriter and PdfWriter. (See also #3 here.)

Also related: Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions
element is a String here:

WriteToXSL.WriteTo(Testgoal, "NOK", element.toString());

Calling toString() on a String is not too useful, you could remove that. Actually, I'd rename the variable to emptyViewText to describe its exact content.
As far as I see driver.findElements() never returns null, so you could remove the null check here:

List<WebElement> allSearchResults = driver
              .findElements(By
                           .xpath("//*[contains(@class, 'teaser-list')]/li/article/div[2]/h3"));
//Check if xpath contains any WebElements, if not check if no results message is displayed
if(allSearchResults == null || allSearchResults.size() < 1 ){

The allSearchResults.size() < 1 condition could be changed to allSearchResults.isEmpty().
Comments on the closing curly braces are unnecessary and rather disturbing. Modern IDEs could show blocks.

    }// close if
}// close for loop

[“// …” comments at end of code block after } - good or bad?][4]
You could avoid the flag here with a return statement:

boolean resultsFound = false;
for (WebElement Element: allSearchResults) {
    if (Element.getText().contains(title)) {
        WriteToXSL.WriteTo(Testgoal, "NOK", "");
        WriteToPDF.addRow(Testgoal, "NOK", "");
        resultsFound = true;
        break;
    }
}
if (resultsFound == false) {
    WriteToXSL.WriteTo(Testgoal, "OK", "");
    WriteToPDF.addRow(Testgoal, "OK", "");
}

Consider this:

for (WebElement Element: allSearchResults) {
    if (Element.getText().contains(title)) {
        WriteToXSL.WriteTo(Testgoal, "NOK", "");
        WriteToPDF.addRow(Testgoal, "NOK", "");
        return;
    }
}
WriteToXSL.WriteTo(Testgoal, "OK", "");
WriteToPDF.addRow(Testgoal, "OK", "");

Actually, I would restructure the code to remove the duplicated XSL/PDF writing calls. I have changed them with two exceptions:

public static void checkAbsentSearchResult(String title, String testGoal) throws IOException {
    try {
        doCheckAbsentSearchResult(title, testGoal);
        WriteToXSL.WriteTo(testGoal, "OK", "");
        WriteToPDF.addRow(testGoal, "OK", "");
    } catch (Exception e) {
        WriteToXSL.WriteTo(testGoal, "NOK", e.toString());
        WriteToPDF.addRow(testGoal, "NOK", "");
    }
}

public static void doCheckAbsentSearchResult(String title, String testGoal) throws IOException {
    final List<WebElement> allSearchResults = driver.findElements(By
            .xpath("//*[contains(@class, 'teaser-list')]/li/article/div[2]/h3"));
    // Check if xpath contains any WebElements, if not check if no
    // results message is displayed
    if (allSearchResults.isEmpty()) {
        final String emptyViewText = driver.findElement(By.xpath("//div[@class='view-empty']")).getText();
        if (!emptyViewText.contains("no results found")) {
            throw new RuntimeException(emptyViewText);
        }
    } else {
        for (final WebElement searchResultElement: allSearchResults) {
            if (searchResultElement.getText().contains(title)) {
                throw new RuntimeException("");
            }
        }
    }
}

Note that it changes the output a little bit when there is an error. I guess it could be fine for a report.


Assuming these are all AR models with appropriate associations, I'd create a method on Site that iterates over a site instance's Blogs, Questions and Videos and collects their tags.  Something like this maybe:

def get_site_tags
  tags = []
  self.blogs.each do |blog|
    (tags <<  blog.tags)
  end
  self.questions.each do |question|
    (tags <<  question.tags)
  end
  self.videos.each do |video|
    (tags <<  video.tags)
  end
  tags.flatten!
end

Would this work for you or am I missing something?


Consider using iterator instead of for-looping. That will get rid of your index manipulation (decrement if element is removed).

Iterator iterator = mList.iterator();
while(iterator.hasNext()){
   Element e = iterator.next();
   if(shouldRemove(e)){
       iterator.remove();
   }
}

Is there a performance requirement that necessitate implementation of such algorithm? In most cases, implementing conventional interfaces make code readable and modular and you'll probably benefit from performance increase should the way Android perform filtering is optimised further down the road, without doing anything.

In any case, what makes you think that this implementation is faster? Your reliance on copying ArrayLists may prove wasteful if the unfiltered list is exceptionally large.


Some quick remarks:

DemoGraphic isn't a compound word so there shouldn't be a capital letter in the middle. However, Barcaccount is so it should be called BarcAccount. Same for Sridentifier, Updatedate, Aridentifier.

Use meaningful variable names. I have no idea what ar is, or sr.

UpdateEmailTable(IEnumerable<StudentEmail> students) and then var studentEmails = students.ToList(); Use properly named and typed parameters. Your method requires a List<StudentEmail> studentEmails (or perhaps ICollection<StudentEmail> studentEmails), write it like that and make the calling code to pass the correct argument.

This method is peppered with Console.WriteLine. This means it mixes business logic and UI. Bad idea. At least change this to use a logging system, and then configure that so it outputs to the command line.

You say this takes three hours, which suggests either a massive volume of data or particularly slow code (or perhaps your tables are not correctly indexed?). Perhaps implementing logic that uses SqlBulkInsert could solve the performance issue. Perhaps take the incoming data and store it in a table, and then apply one or two SQL queries to update the data in BarcDemoGraphicEmail.


Review

The calculator requires a very specific syntax and depends on whitespace delimiters. As a consumer it is really easy to make a mistake in using the calculator.
I would expect a basic calculator to include parentheses parsing as well as the basic operators +-/*.
You split the input in a series of string tokens List<string> equationList. String is hard to work with once you start extending the calculator. Invest in a custom class Token that has at least a Value (string) and a Type (Operator, Operand, Parenthesis, Whitespace, ..)
Method PunktVorStrich return the same list as provided in the parameters. It could be made void if you allow the provided list to get changed in the method body.
I would not perform the multiplication/division evaluation in the preprocessor. It should be done in a later phase.

Limitations

You have created a preprocessor function that transforms any input string into one that only uses addition and subtraction.

"1 + 1 * 3"

comes out as

"1 + 3"

Since the expression still remains to be evaluated, you'd have to go over the expression again, this time only dealing with the basic operators. I would not use a function like PunktVorStrich in the preprocessing phase, I would include it in the expression evaluator. This would gain performance, by only iterating the expression once.

By the way, how would you evaluate this expression? There is no consensus in math.

"2 / 3 * 4"

If you want to extend your calculator, you'll notice it would get harder to maintain the evaluator, since you have a fixed format <number><whitespace><operator>.. and evaluate left to right. As you noticed, a simple multiplication and division already are special cases to this left to right scanner. The following simple expressions can currently not be parsed.

"1+1"
"(1 + 1) + 1"

Expression Tree Evaluator

What you could do, is tokenize the input, build an expression tree and evaluate the tree. For instance "(1 + 1) + 1" could have a syntax tree:

//             add
//     add          1
//  1       1

You should read more about evaluating expressions using lexers and parsers. Try refactoring the simple evaluator with only +-/* to this structure.


Your ringbuffer has a compile time size, so it would be appropriate to make it a template class rather than simply passing it as an argument to the constructor. You never plan to change it anyway?

template<size_t bufSize>
class CircularBuffer

That leads to the next point. You use a std::unique_ptr<int[]> There is something in C++ that is much better than this std::array. With the size of the buffer a compile time template argument of the class you can easily use it

template<size_t bufSize>
class CircularBuffer {
    std::array<int, bufSize> buf;
    std::size_t head;
    std::size_t tail;
    bool full_v;

    ...
};

Note that this increases the size of the class object considerably, as the std::array is directly inlined in the class.

The other members of this class are always the same after construction so you should use static member initialization:

template<size_t bufSize>
class CircularBuffer {
    std::array<int, bufSize> buf;
    std::size_t head{ 0 };
    std::size_t tail{ 0 };
    bool full_v{ false };

    ...
};

Note that this completely removes the need to define a constructor at all. The compiler generated default constructor will do just fine.

Resetting the buffer should not change the data stored in it as it is not read anyway so just leave it alone

void CircularBuffer::reset()
{
    head = 0;
    tail = 0;
    full_v = false;
}

Can tail ever be larger than head? If not why are you checking it.


Simple Producer-consumer implementation in Python

Actually, the initial producer-consumer scheme is over-complicated and has the following issues:

Using 2 separate threading.Semaphore objects:
One of them is used for producer (remaining_space), another - for consumer (fill_count). Though they won't be convenient here (as I'll describe below), but for your future potential cases, a better naming would be self.producer_counter and self.consumer_counter.What those 2 semaphors (as internal counters) do is just emulating limitation of the capacity of a resource (the resource is deque in our case)
How it starts and flows:

On running the producer starts appending random items in a loop of 100 iterations:

    ...
    for _ in range(self.times):
        self.queue.append(random.randint(0, 100))

on each iteration the producer thread will acquire self.remaining_space.acquire() decrementing the internal counter. When producer's counter is zero (0) the producer thread will block until the consumer thread calls self.remaining_space.release() thus increasing the producer's counter by 1 and letting the producer thread to proceed.Such a "dragging" of acquire/release in multiple places can be just replaced with well-known queue.Queue, which is FIFO queue that already uses deque under the hood and already provides the needed locking mechanism and timeout logic.

  The queue module implements multi-producer, multi-consumer queues.
  It is especially useful in threaded programming when information must
  be exchanged safely between multiple threads. The Queue class in
  this module implements all the required locking semantics.

...

class queue.Queue(maxsize=0)

  Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the
  queue. Insertion will block once this size has been reached, until
  queue items are consumed. If maxsize is less than or equal to zero,
  the queue size is infinite.

So maxsize already gives us a limited capacity.

Namings:
A better names for a numeric constants in our new scheme would be:

MAX_QSIZE = 10  # max queue size
BUF_SIZE = 100  # total number of iterations/items to process

"Tricky" passing of TIMES constant:
It's not good to pass total number of processed items to Consumer constructor:

class Consumer:
    def __init__(self, queue, times=TIMES):
    ...

that allows compromising and specifying improper number of items to process.Consider the following case:

TIMES = 100
...
    producer = Producer(queue)
    producer_thread = threading.Thread(target=producer.run)
    consumer = Consumer(queue, times=50)
    consumer_thread = threading.Thread(target=consumer.run)

this will point the consumer to consume less items than the queue contains, eventually having the queue with dangled items.If you run that case you'll have the pipeline blocked/hanged. To avoid that we need to ensure the consumer has gotten and processed all items in the queue:

class Consumer:
    def __init__(self, queue):
        self.queue = queue

    def run(self):
        while not self.queue.empty():
            item = self.queue.get()
            self.queue.task_done()
            print(item)

To enrich the queue communication we can incorporate queue.task_done() and queue.join() (the final version will incorporate them).

The final concise version:

from queue import Queue
import random
import threading

MAX_QSIZE = 10  # max queue size
BUF_SIZE = 100  # total number of iterations/items to process

class Producer:
    def __init__(self, queue, buf_size=BUF_SIZE):
        self.queue = queue
        self.buf_size = buf_size

    def run(self):
        for _ in range(self.buf_size):
            self.queue.put(random.randint(0, 100))

class Consumer:
    def __init__(self, queue):
        self.queue = queue

    def run(self):
        while not self.queue.empty():
            item = self.queue.get()
            self.queue.task_done()
            print(item)

def main():
    q = Queue(maxsize=MAX_QSIZE)

    producer = Producer(q)
    producer_thread = threading.Thread(target=producer.run)

    consumer = Consumer(q)
    consumer_thread = threading.Thread(target=consumer.run)

    producer_thread.start()
    consumer_thread.start()

    producer_thread.join()
    consumer_thread.join()
    q.join()

if __name__ == "__main__":
    main()


Manage connection without 'using' statement

I can understand why you want to remove the clutter from your code - but sharing the instance of MySqlConnection isn't a good idea. As soon as multiple threads are trying to use the connection at the same time, things are going to go wrong.

The connections are already pooled for you (See here) so you creating and disposing IDbConnections is cheap and easy.

I think you should create a connection factory:

public interface IConnectionFactory
{
    IDbConnection GetOpenConnection();
}

public class ConnectionFactory : IConnectionFactory
{
    private static readonly string connectionString =
        ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

    public IDbConnection GetOpenConnection()
    {
        // Is there an overload to automatically open the connection?
        var connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}

Then your base repository can do:

public abstract class BaseRepository
{
    protected readonly IConnectionFactory connectionFactory;

    public BaseRepository(IConnectionFactory connectionFactory)
    {
        this.connectionFactory = connectionFactory;
    }
}

Then all of your actual repositories can do:

public class MyTableRepository : BaseRepository
{
    public MyTableRepository(IConnectionFactory connectionFactory) : base(connectionFactory) {}

    public List<MyTable> GetAllMyTable()
    {
        using (var connection = connectionFactory.GetOpenConnection())
        {
            return connection.Query("SELECT * FROM MyTable").ToList();
        }
    }
}

I realise it doesn't save you much over the original code other than centralising the connection string...

A more advanced idea would be add an Execute method to your base repo but I don't think it would add much...

protected T Execute<T>(Func<IDbConnection, T> query)
{
    using (var connection = connectionFactory.GetOpenConnection())
    {
        return query(connection);
    }
}


Factory to construct a FineTime out of many kinds of objects

Overloading!

public static FineTime getFineTime(Long o){
    if(o == null){ return null; }
    return new FineTime(o);
}

public static FineTime getFineTime(Integer o){
    if(o == null){ return null; }
    return new FineTime(o);
}

public static FineTime getFineTime(FineTime o){
    return o;
}

public static FineTime getFineTime(Date o){
    if(o == null){ return null; }
    try {
        return DateConverter.dateToFineTime(o);
    } catch (IllegalArgumentException iae) {
        //Try another converter
        LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(Date) failed", iae);
        return null;
    }
}

public static FineTime getFineTime(String date){
    if(date == null){ return null; }
    //TAI
    try {
        return _stfFormatTai.parse(date);
    } catch (IllegalArgumentException iae) {
        //Try another converter
        LOGGER.log(Level.FINE, "_stfFormatTai.parse(String) failed", iae);
    }
    //UTC
    try {
        return _stfFormatUtc.parse(date);
    } catch (IllegalArgumentException iae) {
        //Try another converter
        LOGGER.log(Level.FINE, "_stfFormatUtc.parse(String) failed", iae);
    }
    //dd-MMM-yyyy HH:mm:ss
    try {
        return DateConverter.dateToFineTime(_sdfFormat1.parse(date));
    } catch (ParseException pe) {
        //Try another converter
        LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat1.parse(String) failed", pe);
    } catch (IllegalArgumentException iae) {
        //Try another converter
        LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat1.parse(String) failed", iae);
    }
    //dd-MM-yyyy HH:mm:ss
    try {
        return DateConverter.dateToFineTime(_sdfFormat2.parse(date));
    } catch (ParseException pe) {
        //Try another coverter
        LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat2.parse(String) failed", pe);
    } catch (IllegalArgumentException iae) {
        //Try another converter
        LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat2.parse(String) failed", iae);
    }
    return null;
}

And a default implementation

public static FineTime getFineTime(Object o){
    LOGGER.info("Could not convert " + StringUtil.asString(o) + " to FineTime");
    //No converter found, return 'null'
    return null;
}

And gone are most of your troubles.

The problem in this case, however, is that you do need to know what type your object has. You cannot "just" insert an object and get a value out. To do so anyway seems to imply bad design.

If you wanted to go that direction anyway, consider making a map of Class, Converter of sorts.

Something else you could do is leave the method you have right now as is, and just wrap your String and Date conversions in a separate function. That would significantly simplify the method as well, boiling down to "if integer, finetime via integer, if long, finetime via long, if string, finetime via string, if date, finetime via date, else log error and return null".


Partial Maven clean install after Git pull

Take a cleaner approach if you can

The current approach is basically a dirty hack to work around Maven's inability to do incremental builds.
I recommend to start looking into another more modern build system that is able to re-build just what needs to be rebuilt.
Such as Gradle.

Always double-quote variables in arguments

As a rule of thumb, always put double-quotes around variables used as arguments. For example in all these places, there should be double-quotes around the variables:

read -a GIT_DIFF_OUTPUT_ARY <<< $GIT_DIFF_OUTPUT
...

GIT_DIFF_OUTPUT="$(git diff --name-status HEAD@{1} ${CURRENT_BRANCH})"
...

IFS='/' read -ra SPLIT <<< $i
...

GIT_DIFF_OUTPUT_ARY_ROOT_PATH+=($path)
...

for val in ${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}
...

cd $val
...

Avoid performance pitfalls

For each path in the diff,
the script builds the array GIT_DIFF_OUTPUT_ARY_ROOT_PATH with the first two path segments,
and keeps the elements unique by not adding a value if it's already in the array.
As the size of the array grows, this becomes increasingly inefficient,
as this is quadratic time complexity.

I believe the paths printed by git diff is sorted by default.
You can take advantage of that:
track the previous element,
and only add a new value when it's different from the previous.
You will achieve better performance and without using the containsElement function.

Use the exit code directly in conditional expressions

Instead of this:

containsElement "$path" "${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}"
if [[ $? != 0 ]]
then
    #Add the path since it was not found
    GIT_DIFF_OUTPUT_ARY_ROOT_PATH+=($path)
fi

You could use the exit code of the function directly in a conditional:

if ! containsElement "$path" "${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}"
then
    #Add the path since it was not found
    GIT_DIFF_OUTPUT_ARY_ROOT_PATH+=($path)
fi

Get current Git branch name using native Git commands

Instead of this:

CURRENT_BRANCH="$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')"

This is a better, native way:

CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"

Use native Bash to get string length

This line tries to check the length of a variable:

if [[ "$(echo -n $i | wc -m)" != 1 ]]

Although -m is used, the possible values will not be multibyte,
so the solution is equivalent to using -c.
In this case, a better solution exists with native Bash:

if [[ ${#i} != 1 ]]

Use better variable names

i is good for simple counters. It's not a good name for anything else.

What is FORWARD? path_separator or pathsep would have been better.


Can this be written more concise and aligned with the Functional Reactive Programming paradigm?

Two months late, but I will try to answer nevertheless. ;-)

Since your rand already makes sure the numbers will be valid indices for your fruits, you don't have to use so many if cases. The rest looks OK to me, but I made some annotations in the source.

import Random
import Mouse
-- Sometimes empty lines can improve readability.

data Fruit = Apple | Orange | Banana | Melon | Guava

-- For module global declarations, it is often helpful to
-- explicitly annotate the types.
fruits : [Fruit]
fruits = [Apple, Orange, Banana, Melon, Guava]

-- especially for functions :)
fruit : Int -> Fruit
fruit n = head <| drop n fruits

rand : Signal Int
rand = Random.range 0 ((length fruits) - 1) Mouse.clicks

-- exercise: Try to figure and annotate the remaining types. ;-)
fruitText = toForm <~ (asText <~ (fruit <~ rand))

time = lift (inSeconds . fst) (timestamp (fps 40))

scene dy form = collage 300 300 [move (0, 100 * cos dy) form]

main = lift2 scene time fruitText

btw: share-elm.com is a bit easier for showing elm code to someone than making him copy paste to elm-lang.org/try.
See: http://share-elm.com/sprout/52567327e4b0d6a98b1531c7


Project Euler #2 - Sum of even Fibonacci numbers to 4,000,000

I'm also kind of a Clojure newbie (I've been messing with it off and on for about two years), so take my comments with a grain of salt.

In the loop in fib, I would separate each binding pair with commas, like this:

(loop [i n, cur 1, next 1] ; etc.

Clojure treats commas as whitespace, so you can use them anywhere you can use a space. It can make binding vectors and map literals with everything on one line a lot easier to read.

It looks like your function fibs is just making an infinite lazy sequence of Fibonacci numbers by mapping fib over a range. You can actually write a function to do this directly; see http://clojuredocs.org/clojure_core/clojure.core/lazy-seq (the second example). I don't know how the performance compares, but it's short and a good way to learn about making your own lazy sequences.

I think your solution function is good, but https://stackoverflow.com/questions/3153396/clojure-reduce-vs-apply says there might be a tiny performance advantage to using reduce instead, like this:

(reduce + (filter even? (fibs-until 4000000)))

The hard-coded limit in solution makes me uncomfortable somehow. The rest of your code is very nicely packaged out into separate, reusable functions, so it feels a little odd to see solution not. Maybe pass the limit as an argument, and then write

(println (solution 4000000))

Otherwise your code looks good to me. It's very clean and easy to read.

You might also be interested in type hinting and the memoize function if you're working through Project Euler; they can help improve performance, especially on mathematical code. For example, if you know the argument to fib will always fit in a Java long (64 bits), you can write fib like this:

(defn fib [^long n]  ;etc

This gives the compiler a type hint that lets it avoid reflection, and can improve performance.

You can pass memoize a referentially transparent function (one that always returns the same value given the same arguments), and it will return a new version of the function that caches results. For example, say you'd written a naive Fibonacci like this:

(defn fib [n]
  (if (< n 2)
    1
    (+ (fib (- n 1)) (fib (- n 2)))))

Then you could send that function to memoize, and you'd get a new version that would save its previous results. Since that naive function keeps recalculating the same cases, you'd get a performance boost by turning those repeat calls into map lookups.

I hope some of my comments were helpful, and have fun with Clojure; it rekindled my interest in programming.


Swapping two integer numbers with no temporary variable

You make assumptions which may not be true. Why do you believe that
int tmp = a;
a = b;
b = tmp;

actually is compiled down to using an actual variable? It is likely just a register used on the CPU.
Have you inspected it?
Further, why do you assume that:
a ^= b ^= a ^= b;

uses fewer registers than a swap?
Really, what you should do is:
#include <algorithm>
#include <iostream>

int main() {

    int a = 20;
    int b = 66;

    // before swapping
    std::cout << a  << ' ' << b  << '\n';

    // swap
    std::swap(a,b);

    // after swapping
    std::cout << a << ' ' << b << '\n';

}

Which is also a reminder that having the a ^= b ^= a ^= b; 'naked' in your code is not good practice. Something like that should be embedded in a function, not directly in the main method.
Update - assembler output
For the code:
int a = 20;
int b = 66;

int t = a;
a = b;
b = t;

return a;

you get the assembler output:
movl    $20, -12(%rbp)
movl    $66, -8(%rbp)
movl    -12(%rbp), %eax
movl    %eax, -4(%rbp)
movl    -8(%rbp), %eax
movl    %eax, -12(%rbp)
movl    -4(%rbp), %eax
movl    %eax, -8(%rbp)
movl    -12(%rbp), %eax
popq    %rbp

For the code:
int a = 20;
int b = 66;

a ^= b ^= a ^= b;

return a;

you get
movl    $20, -8(%rbp)
movl    $66, -4(%rbp)
movl    -4(%rbp), %eax
xorl    %eax, -8(%rbp)
movl    -8(%rbp), %eax
xorl    %eax, -4(%rbp)
movl    -4(%rbp), %eax
xorl    %eax, -8(%rbp)
movl    -8(%rbp), %eax
popq    %rbp

What does that show?

It shows that both systems run in 12 instructions, including the copy to the stack (%rbp)
that both systems use the single register %eax
both systems use the stack as a temp store for the result (the XOR reuses -8 and -4 offsets in the stack, the tmp uses -12(%rbp)

Net result? Both systems use less than 16 bytes of the stack, they both use 1 register in addition to the stack, and they both have the same number of instructions.
I know which one is more readable....
Of course, with the above code, if I add -O2 to the optimization, I get the assembler:
movl    $66, %eax
ret

which, as you can imagine, is fast.


How to handle same code parts in Factory Method?

Currently your factories instantiate the new objects and then fill in all of their properties with the right values. You could split instantiation from property value assignment. Your StoneHouseCreator could instantiate a StoneHouse, use a HousePopulator that populates the values that all objects of type House have in common, and then the StoneHouseCreator could populate the rest of the values that are exclusive to a StoneHouse. That same HousePopulator could also be used by your WoodenHouseCreator, which would then proceed to populate the WoodenHouse-specific properties.

Actually, there are two ways of doing this. Either you keep it as it was originally (i.e. using inheritance), give your base class a PopulatorMethod(...) that populates the properties of a House, and call base.PopulatorMethod(...) from your override of PopulatorMethod(...) in the child classes. Or you drop the inheritance between your factories completely, you make your FactoryMethod() implementations accept instances of WoodenHouseInfo or StoneHouseInfo depending on the implementing class, and have them use a HousePopulator as you have done.

If you go down the second route, you don't need an abstract parent class, although an interface would be nice, and you can move the HousePopulator = new HousePopulator() assignment to the individual factory classes.

If you want to philosophise about this at a higher level, these are the problems that we run into because of inheritance. Factories, that is the logical separation of object use from object creation, are more naturally suited to cases where you use composition over inheritance. If you are interested more in this, I would recommend reading this excellent article on the topic.


Simple tkinter GUI that uses a popup menu class

Fixing the bug

First of all, I would like to address an issue you did not ask about. It is related to the situation where the user tries to copy without selecting any text. That is exactly the scenario I faced. This situation triggers an exception:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
  File "/home/begueradj/Desktop/popupkopy.py", line 26, in text_copy
    text = self.textbox_text.get("sel.first", "sel.last")
  File "/usr/lib/python3.5/tkinter/__init__.py", line 3095, in get
    return self.tk.call(self._w, 'get', index1, index2)
_tkinter.TclError: text doesn't contain any characters tagged with "sel"

To fix this issue, simply check if the user selected a text and then allow him to perform the copy action. This is something you can express within the body of text_copy() function as follows:

def text_copy(self, event=None):
    if self.textbox_text.tag_ranges("sel"):
        self.clipboard_clear()
        text = self.textbox_text.get("sel.first", "sel.last")
        self.clipboard_append(text)

Good decision?

  But my code started to look a little messy so I decided to move all
  the popup related methods and variables to its own class. And also
  decided to write it that I can reuse my popup class for other projects
  in the future that will require a popup menu.

A part of the software design, consists in identifying entities (objects/classes) of the problem you are trying to resolve. Thinking of the popup men as a class in itself is a right decision.

Discussing the implementation from the OOP perspective

Inside the Popup() class, you can get rid of this declaration self.textbox_text = '' as it is useless (never used, unlike what you may think) and a bit confusing. If you remove that variable, your program will still function correctly.
I say self.textbox_text = '' is useless because what you actually are using in all Popup() functions is rather the attribute you added to the instance of Popup() inside MyTestApp() when you coded: self.popup.textbox_text = self.data_textbox. That is also why it is confusing.
The remark 2 above means also that MyTestApp() and Popup() classes are not compliant with the OOP philosophy because the first one must not be responsible of "expanding" the list of attributes of the second one. Objects have rather a state (Python attributes, in our case) and a behavior defined through an interface (not the interface in the strict OOP concepts) consisting of a set of methods and functions. The communication between objects occurs through their interfaces (functions/methods). And that is exactly why I am telling you this line: self.popup.textbox_text = self.data_textbox does not comply with the OOP philosophy.
How to fix the issue highlighted via the remark 3 above? Well, by just respecting the principles: a MyTestApp() instance must communicate with a Popup() instance (self.popup, in your case) through methods. I mean, you must find a way to communicate self.data_textbox to self.popup object through a suitable method. This is too easy and clean as you will see in the improved version below.

Few other remarks

The previous section, especially the remark 4 above, responds fully to your questions. However, I would like to add few improvements suggestions to your code which I think you need to take in consideration as they are the widely respected standard. I will list some of them briefly:

Avoid wildcard imports. This is not what I recommend, but what PEP 8 asks us to do:

  Wildcard imports (from  import *) should be avoided, as they
  make it unclear which names are present in the namespace, confusing
  both readers and many automated tools. There is one defensible use
  case for a wildcard import, which is to republish an internal
  interface as part of a public API (for example, overwriting a pure
  Python implementation of an interface with the definitions from an
  optional accelerator module and exactly which definitions will be
  overwritten isn't known in advance).

  When republishing names this way, the guidelines below regarding
  public and internal interfaces still apply.

What does this mean in practice? It simply means you should remove these 2 lines: from tkinter import Tk, ttk, Frame, FALSE, Text, Button, \
    Scrollbar, Entry, END, INSERT and from tkinter import Frame, Entry, END, INSERT and be content with import tkinter as tk. This way you avoid useless imports you never used, but also you avoid repetition of the imports and, more importantly, in case you need to create a custom class/widget having the same name of one of the tkinter's classes, you will not face names clashes issues.

Choose the right names: while this rule sounds easy to understand, not lot of us respect it even if it is too important for the development process. In my solution below, I renamed several of your variables.
Last but not the least, follow Tkinter best practices.

Improved version

Taking in consideration all what is mentioned through the above sections, I came up with this improved version of your code (which surely can be subject to further improvements):

main.py:

from tkinter import ttk
import tkinter as tk
from popup import RightClickMenu

class MyTestApp(tk.Frame):
   def __init__(self, parent):
       self.master = parent
       tk.Frame.__init__(self, self.master)
       self.configure_gui()
       self.create_widgets()
       self.bind_right_click_menu_to_typing_area()

   def configure_gui(self):
       self.master.title('MY Test App')

   def create_widgets(self):
       self.create_text_area()
       self.create_exit_button()

   def create_text_area(self):
       self.text_area = tk.Text(self.master, borderwidth=2, relief='sunken')
       self.text_area.config(height=30, width=80)
       self.text_area.grid(row=0, column=0, sticky="new")

   def create_exit_button(self):
       self.exit_btn = ttk.Button(self.master, text='Exit', command=self.exit_application)
       self.exit_btn.grid(row=1, column=0, sticky='W', pady=15)

   def bind_right_click_menu_to_typing_area(self):
       self.popup = RightClickMenu(self.master, self.text_area)
       self.text_area.bind("<Button-3>", self.popup.popup_text)

   def exit_application(self):
       self.master.destroy()

def main():
   root = tk.Tk()
   MyTestApp(root)
   root.mainloop()

if __name__ == '__main__':
   main()

popup.py:

import tkinter as tk

class RightClickMenu(tk.Frame):
   def __init__(self, parent, text_area):
       self.master = parent
       tk.Frame.__init__(self, self.master)
       self.text_area = text_area
       self.create_widgets()

   def create_widgets(self):
       self.create_right_click_menu()

   def create_right_click_menu(self):
       self.right_click_menu = tk.Menu(self.master, tearoff=0, relief='sunken')
       self.right_click_menu.add_command(label="Copy", command=self.copy_text)
       self.right_click_menu.add_separator()
       self.right_click_menu.add_command(label="Paste", command=self.paste_text)
       self.right_click_menu.add_separator()
       self.right_click_menu.add_command(label="Clear", command=self.clear_text)

   def popup_text(self, event):
       self.right_click_menu.post(event.x_root, event.y_root)

   def copy_text(self):
       if self.text_area.tag_ranges("sel"):
           text = self.text_area.get("sel.first", "sel.last")
           self.clipboard_append(text)

   def paste_text(self):
       self.text_area.insert(tk.INSERT, self.clipboard_get())

   def clear_text(self):
       self.text_area.delete(1.0, tk.END)


To be honest, if it weren't for the hint in the first line (define (primes-up-to-about n)), I'd have no idea that this was an implementation of the Sieve of Eratosthenes.

The main problem, I think, is that names like table, clear!, and next-marked-from are all too low-level, not much better than the bytevector primitives, and devoid of contextual meaning.

To start, I think you should be able to rearrange the definitions.

  (define bytelen (+ (arithmetic-shift n -4) 1))
  (define primes-table (make-bytevector bytelen 255))
  (define bitlen (arithmetic-shift len 3))

Instead of clear!, try a more meaningful name like mark-as-composite!.

To complete the abstraction of the bytevector as a sieve, you would also need a helper function (define (next-prime-above n) …) that combines your next-marked-from and index->value.

(reverse rv) seems suspiciously expensive.  I think you should be able to build the list of primes in ascending order using smarter recursion.


Program finds the first almost matching string in a list - Advent Of Code 2018 Day 2 Part 2

There isn't a whole lot of code here, so I'll just point out what I see top-to-bottom. I'll note though that I'm exceedingly tired and don't fully understand what the problem you're solving is, so I'll just be commenting on aspects of language usage:

Your file starts as (require 'clojure.set). Every Clojure file should start with a call to the ns macro that creates a namespace matching your file's position under the source file of the project. If this file was at PROJECTFOLDER/src/subfolder/my_file.clj, the file should start with

(ns subfolder.my-file)

This allows your file to be properly included by other files.

You have a call to require also though. This can neatly be added to the ns call:

(ns subfolder.my-file
  (:require [clojure.set]))

You aren't even taking advantage of the require though; you can call clojure.set/intersection even without the require. With the require, you can write set/intersection. That's not as nice as it could be though. If you use :as, you can shorten the uses further:

(ns subfolder.my-file
  (:require [clojure.set :as s])) ; Aliasing the set namespace as s

(s/intersection ...) ; Works!

(def not-empty? (complement empty?))

You seem to already be familiar with functional languages. Do you know Haskell? While it's certainly OK to write this function like this, as a complement of another, after a lot of messing around, I've found it's better to just write it out fully in most cases:

(defn not-empty? [coll]
  (not (empty? coll)))

Why? Because now when you ctrl+q it in a good IDE, you get a nice documentation summary that includes the parameter names. For a case like this, most people will immediately know what not-empty? does. For more complicated cases though, you may find that writing out the full defn leads to easier to understand code and generated documentation. Remember the mantra: "code is read more often than it's written". Don't make code harder to understand just to save a few keystrokes.

Really though, do you need this at all? (not (empty? coll)) is arguably just as readable as (not-empty? coll). You also only use it once, and can simply reverse the bodies of the if where it's used. I remember reading that negations (not) should be avoided when possible, as they're slightly hard to comprehend. Even if you did want to have the if bodies in that particular order, you could use (if-not (empty? coll)...) instead.

Nice idiomatic naming though. Your use of dash-naming and ? suffixes are completely appropriate here and idiomatic.

(def input-lines (line-seq (clojure.java.io/reader "input.in")))

Nothing overly wrong here. Of course, hard coding the file path right inside the def isn't necessarily ideal, but for a toy program like this, it's understandable.

This makes your program impossible to test on my end though, as I have no clue what data you're using. I'm unable to run your program, so I'll simply be "translating" between concepts that should be equivalent.

Your IIFE (Immediately invoked function expression; a term from Javascript) is a little odd here. I can't say I've ever seen code like this. This has a few downsides:

Lisp writers can get a little off-put by seeing ((. Often, two opening brackets beside each other either means some fancy is going on, or you have a bug waiting to be run. In this case, it's the former, but it doesn't look ideal.
This entire chunk of code has no name associated with it at all! You have the entire main part of your program top-level as a self-calling anonymous function call. This gives no hints as to what this chunk of code is doing
Having top level expressions that do a lot of work is a problem when developing with a REPL. When I load this into IntelliJ, every time I reload the file, the whole thing runs! Ideally, you should be manually invoking code from the file instead of having the code in the file run when the file is simply loaded.

I would, at the very least, change this to:

(defn main-routine [ids seen-patterns]
  (when (empty? ids)
    (throw (Exception. "Didn't find match")))

  (let [[next-id & other-ids] ids
        match-patterns (get-match-patterns next-id)
        matches (s/intersection match-patterns seen-patterns)]
    (if (not-empty? matches)
      (prn (apply str (filter #(not= \* %) (first matches))))
      (recur other-ids (apply conj seen-patterns match-patterns)))))

(defn main []
  (main-routine input-lines #{}))

Now you have a little more control regarding when your program actually executes.

While straight recursion is usually fine, Clojure has loop that makes ""recursion"" simpler in some cases. Your code looks like it could be rewritten as:

(defn main-routine [ids seen-patterns]
  (loop [[next-id & other-ids] ids]
    (if next-id ; next-id will be nil if ids is empty
      (let [match-patterns (get-match-patterns next-id)
            matches (s/intersection match-patterns seen-patterns)]
        (if (not-empty? matches)
          (prn (apply str (filter #(not= \* %) (first matches))))
          (recur other-ids (apply conj seen-patterns match-patterns))))

      ; This should be a more specific exception.
      ; It also might just be appropriate to return nil, indicating failure.
      (throw (Exception. "Didn't find match")))))

The gain in this scenario isn't huge though, if there's any at all. I just wanted to point out the existence of loop since I often see it ignored, even though it's exceedingly helpful when doing complicated, multi-accumulator reductions.

This is very good code though, especially for someone new to the language. Except for your lack of ns (and even that isn't necessary here), everything I saw is mostly nitpicking. I look forward to seeing more review requests from you.


Movie search layout tweaks with cookie persistence

This seems a bit simpler (in terms of code repeating)

var Layout = {
    'Poster': {
        href: 'css/list.css'
    },
        'Description': {
        href: 'css/desc.css'
    }
};

function setLink(file, pathFix) {
    $('link:first').attr('href', pathFix + file);
}

$(function () {
    var currentPathFix = '',
        initialLayout = $.cookie("Layout");
    if (window.location.href.indexOf('/search/') >= 0) {
        currentPathFix = '../';
    }
    setLink(Layout( initialLayout ), currentPathFix );
    $.each(Layout, function (key, item) {
        $('.' + key).click(function () {
            setLink(item.href, currentPathFix);
            $.cookie("Movie_Layout", key, {
                expires: 365,
                path: '/media/search',
                secure: true
            });
            $('.content-genre, .searchresults').hide().delay(75).fadeIn(275);
            window.scrollTo(0, 0);
        });
    });
});


A program that uses three methods to reverse and print an array

Let's review your code line by line
string getnums = Console.ReadLine();

The name getnums is not really a good name for a string variable. When you name a variable please try to use noun(s) (w/o adjective). Methods should start with verbs.

int getnum = Convert.ToInt32(getnums);

This is quite error-prone. What if the user types three? Your application will crash with a FormatException.
Please prefer int.TryParse and remember that all input is evil (until proven otherwise).

int[] array1 = new int[getnum];

Yet again array1 is not really a good name. Someone who reads your code will not know what was your intent with this variable. Try to write code that is understandable for others as well.
This is quite error-prone again, because getnum can contain negative number. The array allocation attempt might result in a OverflowException.
Consider to use ArrayPool if you try to allocate an quite big array.

static int[] GenerateNum(int getnums, int[] arrayy)

The arrayy is really a bad name here, you are using Hungarian notation which should be avoided.
You don't need to pass getnums because you can get the Length of the array.
With the current implementation the PopulateArray might be a better name.
Depending on your design the responsibility to allocate memory can be moved over here as well.

for (int index = 0; index < getnums; index++)

Feel free to use array.Length instead of getnums

arrayy[index] = index;

If you design your application in the way that this method should allocate the memory as well then you could rewrite this whole method with the following command:
return Enumerable.Range(0, getnums).ToArray();

int[] RevArray(int[] arrayy)

As it was stated by others as well abbreviation does not add anything here. On the contrary it might make confusion because it could mean other things as well not just reserve, like reveal, revive, review, revisit, etc...

for (int index = 0; index < (arrayy.Length)/2; index++)

The Array class defines a Reverse method, which can do the whole in-place replacement on your behalf without reinventing the wheel.
Here you are using the Length property which is good. I suspect that this code is based on this SO answer. I strongly encourage you to add there a comment where you mention the source of your code.


Remove all duplicated elements in a single list

All in all it looks OK to me. I would maybe call the variables something else:

list -> root
tmp -> currentValue
start -> result
etc.

In the ListNode class it's common practice in C# to name public members in CamelCase:

public class ListNode
{
    public int Value;
    public ListNode Next;
    public ListNode(int x)
    {
         val = x;
         next = null;
    }
}

I think that the null-conditional operator is unnecessary in the outer loop.

My own version would look something like:

public static ListNode RemoveDuplicates(ListNode root)
{
  ListNode current = root;
  ListNode result = null;
  ListNode prev = null;

  while (current != null)
  {
    bool singleFound = true;

    while (current?.val == current?.next?.val)
    {
      current = current.next;
      singleFound = false;
    }

    if (singleFound)
    {
      if (result == null)
      {
        result = prev = current;
      }
      else
      {
        prev.next = current;
        prev = prev.next;
      }
    }

    current = current?.next;

    if (singleFound && prev != null)
      prev.next = null;
  }

  return result;
}

Some other considerations:

The name is maybe ambiguous:

My first thought was that it should remove all but one entry per value:

{ 1, 1, 2, 3, 4, 5, 5, 7, 7 } -> { 1, 2, 3, 4, 5, 7 }

Normally I would prefer that a static method/function would leave the argument list untouched, but you actually operate on the nodes in the list directly and return a new ListNode as root of the resulting list. So the original list is in an indefinite state
when the function returns.

My own implementation modified to handle that:

public static ListNode RemoveDuplicates(ListNode root)
{
  ListNode current = root;
  ListNode result = null;
  ListNode prev = null;

  while (current != null)
  {
    bool singleFound = true;

    while (current?.val == current?.next?.val)
    {
      current = current.next;
      singleFound = false;
    }

    if (singleFound)
    {
      if (result == null)
      {
        result = prev = new ListNode(current.val);
      }
      else
      {
        prev.next = new ListNode(current.val);
        prev = prev.next;
      }
    }

    current = current?.next;
  }

  return result;
}

If you had a class like:

public class SortedLinkedList
{
  public void DeleteDuplicates()
  {
    ...
  }
}

I would on the other hand expect DeleteDuplicates() to operate on the current instance.


Calculating relay operating times, according to IEC 60255

You need not declare # -*- coding: utf-8 -*- in Python 3: UTF-8 is the default.

Writing I = np.logspace(…) inside your curve_equation function is bad practice, because it hard-codes certain x-values for your plot.  In fact, your plot is wrong, because the calculations are for \$I_s\$ values ranging from 102 A to 105 A (due to the inner I = np.logspace(np.log10(Is), 5, 1e2)), but your plot's x axis is labelled as if the values ranged from 101 A to 105 A (due to the outer I = np.logspace(1, 5, 1e2)).  Specifically, four of the curves should intersect at 1 kA, 10 s.

I also find the way in which the curves are specified very cumbersome.  You have five magic strings ("SIT", "VIT", etc.) which you search for in curve_types.  Then, you retrieve the k, alpha, and beta parameters by using the corresponding index.  Printing an error message and returning None is an inappropriate error-handling mechanism; you should raise or propagate an exception for such a fatal error.

I'd rather specify the parameters the other way: each curve should be defined as a \$(k, \alpha, \beta)\$ tuple.  To do that, I would use namedtuples.  I'd go a bit further and make each namedtuple smart enough to know what its own \$td(I)\$ function looks like, when \$T\$ and \$I_s\$ are specified.

from collections import namedtuple
import numpy as np
import matplotlib.pyplot as plt

class IEC_Curve(namedtuple('IEC_Curve', 'name k alpha beta')):
    def td(self, T, Is):
        """
        The td(I) function for a given IEC curve, time dial setting, and
        current setting.
        """
        return lambda I: self.k * T / self.beta / ((I / Is)**self.alpha - 1)

SIT = IEC_Curve('SIT', k=0.14, alpha=0.02, beta=2.97)   # Standard inverse / A
VIT = IEC_Curve('VIT', k=13.5, alpha=1, beta=1.5)       # Very inverse / B
LTI = IEC_Curve('LTI', k=120, alpha=2, beta=13.33)      # Long time inverse / B
EIT = IEC_Curve('EIT', k=80, alpha=2, beta=0.808)       # Extremely inverse / C
UIT = IEC_Curve('UIT', k=315.2, alpha=2.5, beta=1)      # Ultra inverse

I = np.logspace(2, 5, 1e2)
for curve in (SIT, VIT, LTI, EIT, UIT):
    plt.loglog(I, curve.td(T=1, Is=1e2)(I), label=curve.name)
plt.xlabel("Current [A]")
plt.ylabel("Time [s]")
plt.title("IEC Time/current curves")
plt.grid()
plt.legend()
plt.show()

Note that td is a method that returns a function.  To calculate values of \$td\$ with fixed \$T\$, fixed \$I_s\$, and swept \$I\$:

UIT.td(T=1, Is=1e2)(I=np.logspace(2, 5, 1e2))

To calculate a value of \$td\$ for a given \$T\$, \$I_s\$, and \$I\$:

UIT.td(T=1, Is=1e2)(I=1e2)

(This happens to cause a ZeroDivisionError, which manifests itself as a RuntimeWarning: divide by zero encountered in divide at the beginning of the sweep.)

In case you feel intimidated by my use of inheritance of namedtuple, you could use a manually written constructor instead:

class IEC_Curve:
    def __init__(self, name, k, alpha, beta):
        self.name = name
        self.k = k
        self.alpha = alpha
        self.beta = beta

    def td(self, T, Is):
        return lambda I: self.k * T / self.beta / ((I / Is)**self.alpha - 1)

One difference is that namedtuples are immutable, whereas the members here are mutable.


I think this is a bit over engineered. Let's talk our way through the problem.

By definition we know the highest pandigital number is 987654321.
We need to loop through each odd number between 1 and 987654321.
We need to test each number as a prime.
Here's a nice optimised isPrime function from here.

function isPrime(number) {
  var start = 2;
  while (start <= Math.sqrt(number)) {
    if (number % start++ < 1) return false;
  }
  return number > 1;
}

If it is prime we need to test each number is pandigital. We should only need to loop once. If we make a set of the digits in a number, then the length of the set will be equal to the total count of digits in the number.

function isPandigital(number) {
   var numStr = number.toString(),
     digits = [];

   for (var digit in numStr) {

     if (numStr.hasOwnProperty(digit) && digits.indexOf(digit) === -1)
        digits.push(digit);
   }

   return digits.length === numStr.length;
}

Then you just need to write the loop:

var pandigitalPrimes = [];

for (var n = 1; n <= 987654321; n+=2) {
  if (isPrime(n) && isPandigital(n)) pandigitalPrimes.push(n);
}

Now it's your job to optimise these ideas so that this process doesn't take absolutely forever.


A min-max pair would be slightly better represented using a Range.  In fact, starting with Ruby 1.9, rand can accept a range.

The loop can be written a bit more succinctly.

The pretty-printing function should also be written in one line instead.

lower_case is a more conventional naming convention.  An explicit return is not necessary, as the code returns the last value anyway.

def get_random_numbers(range, count=1)
  array = []
  while array.length < count
    n = rand(range)
    array.push(n) unless array.include?(n)
  end
  array
end

def pretty_print(array)
  puts array.join("\t")
end

pretty_print(get_random_numbers(1..49, 6)


Espresso tests that check if Snackbar is displayed and if there is an internet connection

Test#1 looks good, but I would add a case with blank text "_____" too.
Test#2 looks good, but I would name as userGetsErrorWhenSearchingInvalidRestaurant()
Test#3 needs attention. You verify only that an internet connection is good but you don't test user interaction. There are 2 options:

Left 'as is' but rename test method to `isConnectedOrConnectingReturnsTrueWhenInternetIsAvailable()
Add user interaction to make sure the data from internet was loaded successfully.


Is dynamically generating routes from Model enum safe?

Place.send(params[:category])

Using raw user data with send is very dangerous, as it allows the user to call any method (params[:category] could be "delete_all" for example).
Using raw user data with responsd_to? can also be problematic, as this method exposes inner details of the class.

Instead, compare the user data against Place.post_types. It will look like this: (Untested)

 if  Place.post_types.has_key? params[:category]
   @places = Place.where(post_types: params[:category]).order(:created_at).limit(10)
 end

Also, dynamically creating a string for a regex is unreliable:

Regexp.new( Place.post_types.keys.join("|") )

It will break if a key contains any special characters, for example.

Instead of using a regex, test the data against Place.post_types.

EDIT: Actually, it seems this contraint is unneeded as it's tested in the controller.


When working with DateTime it's usually a good idea to not use a hardcoded DateTime.Now. This makes testing such methods very difficult because you cannot mock it so you have to write very tricky tests all with Now. You allso cannot easily switch to UtcNow etc. and you have to know which now it uses internally.

A much better solution would be to use another parameter like DateTime referenceDate. This way you can use any combinations of the two values and create more predictable and easier to understand tests.

Additionally I'd make this method static because it does not access any class fields etc.

Oh, I also need to add that you use excelent variable names! This is exactly how it should be done! ;-)


It's kind of secure, but it uses older algorithms.

Although Benjamin correctly identifies 3DES, I would not call 3 key triple DES "broken". It still delivers a security of about 112 bits which nobody sane will try and break.

There is a chance that somebody would try and break your password though, and the shown password is clearly not random enough as it only contains 12 lowercase characters from a 26 character alphabet, which translates in 4.7 * 12 = 56 bits of entropy (each fully random letter delivers about 4.7 bits of entropy, 5.7 if upper and lowercase are randomly mixed). It may be that the relatively high number of iterations (99,999 iterations) will save you, but you're only supplying the 3DES key with half the entropy it requires to obtain the 112 bit security, so that's not enough.

The derivation method is probably secure, but it likely also performs too many operations which may just benefit an adversary. You are much better off with a more modern key derivation method such as Argon2. Likewise, we generally try and use authenticated encryption nowadays instead of the underlying CBC mode encryption. Problem is that there is no such prebuild solution directly available from the Java API, so you'd have to implement a copy of a protocol yourself or use a good library. Fernet would e.g. give you a more modern format.

You may want to include a version number to your encrypted messages so you can upgrade your algorithms or iteration count / salt size (etc.) at a later date. That way you can recognize older ciphertext, decrypt it, re-encrypt it with the newer protocol or keys and finally securely erase the old ciphertext. Or you could add additional encryption by encrypting it again using a different key derived from the password (a bit harder to do and to decrypt, but certainly possible).

SHA-1 has been broken, but not enough for it to become a problem for PBE. Of course you should still try and avoid old algorithms such as 3DES and SHA-1 and replace them with new ones such as AES and SHA-256.

Oh, almost forgot. Triple DES has a block size of 64 bits / 8 bytes, which is deemed pretty small nowadays. You could lose some confidentiality when encrypting large files with it in CBC mode because blocks may start to repeat (you might lose much more confidentiality with other modes of operation).

The idea of the password consisting of characters is that you can clear a char array, while you cannot do the same thing for a String. If you supply the password as a string then you lose this ability.

Do you know that there is a CipherInputStream and CipherOutputStream that can be put in front of a FileInputStream or FileOutputStream?


I would improve the following things:

implement a "crawler" class that will store the "driver" instance as a variable and will also have a better separation of concerns - a separate method to log in, a separate method to get friends etc
stop using time.sleep() for waits with selenium - hardcoded time delays are seriously unreliable - use Explicit Waits instead
stop using XPaths - they are the least readable and the least reliable - use the fastest "by id" or the more concise "by css selector" locators

Improved code:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class FacebookCrawler:
    LOGIN_URL = 'https://www.facebook.com/login.php?login_attempt=1&lwv=111'

    def __init__(self, login, password):
        chrome_options = webdriver.ChromeOptions()
        prefs = {"profile.default_content_setting_values.notifications": 2}
        chrome_options.add_experimental_option("prefs", prefs)

        self.driver = webdriver.Chrome(chrome_options=chrome_options)
        self.wait = WebDriverWait(self.driver, 10)

        self.login(login, password)

    def login(self, login, password):
        self.driver.get(self.LOGIN_URL)

        # wait for the login page to load
        self.wait.until(EC.visibility_of_element_located((By.ID, "email")))

        self.driver.find_element_by_id('email').send_keys(login)
        self.driver.find_element_by_id('pass').send_keys(password)
        self.driver.find_element_by_id('loginbutton').click()

        # wait for the main page to load
        self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a#findFriendsNav")))

    def _get_friends_list(self):
        return self.driver.find_elements_by_css_selector(".friendBrowserNameTitle > a")

    def get_friends(self):
        # navigate to "friends" page
        self.driver.find_element_by_css_selector("a#findFriendsNav").click()

        # continuous scroll until no more new friends loaded
        num_of_loaded_friends = len(self._get_friends_list())
        while True:
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            try:
                self.wait.until(lambda driver: len(self._get_friends_list()) > num_of_loaded_friends)
                num_of_loaded_friends = len(self._get_friends_list())
            except TimeoutException:
                break  # no more friends loaded

        return [friend.text for friend in self._get_friends_list()]

if __name__ == '__main__':
    crawler = FacebookCrawler(login='login', password='password')

    for friend in crawler.get_friends():
        print(friend)

(not tested)


Perhaps,

for val in dict1.itervalues():
    if val in dict2:
       list_needed.append([val,dict2[val]])

This is similar to

list_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2]

My preference would be to make [val,v] a tuple - i.e (val,v) which is an immutable D.S and hence would be faster than a list. But it may not count for much.


Take a limited number of items from a potentially infinite generator

I would write it as:

function* take(n, generator) {
  let values = generator();

  let i = 0;
  while (i++ < n) {
    yield values.next().value;
  }
}

this seems to match the intent more closely though its mostly a matter of personal preference.

Update

You can also add the take method as an extension to the generator so you could call it like generator().take(3). See this SO answer if you are interested in that approach.


Optimizations for this user-account HTML structure?

"Saeed Neamati" should probably be the heading (h1) of the section (instead of span).

Don’t forget the alt attribute for the img.

The .notifications should be a sectioning element, probably section, maybe aside. Then the notification count could be the heading.

The .menu should be enclosed by a nav, as it’s the navigation for that section.

Result:

Saeed Neamati

Current User

2

First Notification

Second Notification

Change your password

Subscription settings

Payments

Depending on your implementation, the .menu resp. the .notifications may be the main content for that section. In that case, the corresponding sectioning element should be removed.


A random relative prime number based on the modulus

What is m.bitLength, and how often do you get a <= 0 or an gcd-1?

Why do you think creating an object in the loop could be bad? Performance? Memory wise?

An object is ready for garbage collection as soon as it is unreachable and out of scope.

So the second object, if the first one fits the condition, will hide the first one - the first one is out of scope, and unreachable.

For a cheap object like a BigInteger, you may worry if you produce millions and millions of Objects in one second, over and over again. Maybe then, if you experience a performance problem, you can measure and find out, where it happens.


AFAIK, you won't get client-side validation of VG2, but otherwise I can't see that it shouldn't work. (There is probably a client-side event and a method you could call to duplicate the behavior for the client)


VBA code that compares 2 sheets from different systems

You turn off ScreenUpdating and Calculation and never turn them back on. Make sure you do that.

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

You have your variables but the names can be improved. Variable names that describe what your code is doing will make it easier when you or whomever inherits the workbook after you has to edit it later. Declare them just before you use them, ws4 is not used anywhere and can be removed.

    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet
    Dim i As Long, j As Long, iCol As Long, iRow As Long, sl1 as Long, sl2 as Long

You're looping through rows and looking at columns using magic numbers (1, 2, 3, 17, 24) that have some meaning. I've no clue why any of them are important. Give a descriptive constant that tells you what it's there for.

Best I can discern you don't want something else done. Remove it.

If ... Then
    'SomeCode
Else
End If

Much cleaner. No "guessing" if an Else was forgotten

If ... Then
    'SomeCode
End If

You check for certain criteria before populating. Create a function for that and allow that to be your check.

If Trim(ws1.Cells(i, 1).Value2) = Trim(ws2.Cells(j, 1).Value2) Then
    If Trim(ws1.Cells(i, 17).Value2) <> Trim(ws2.Cells(j, 24).Value2) Then 'this is the criteria so if different.

Becomes. You now focus on providing what's needed for the function to return it's Boolean (True/False) instead of how it's doing it.

If IsDataValidForPopulation(primarySheet, primarySheetRow, secondarySheet, secondarySheetRow) Then

Below is the body of the function. Trim was replaced with Trim$ to avoid
an implicit conversion.

Private Function IsDataValidForPopulation(ByVal primarySheet As Worksheet, ByVal primarySheetRow As Long, ByVal secondarySheet As Worksheet, secondarySheetRow As Long) As Boolean
    Const PRIMARY_SHEET_CRITERIA_COLUMN As Long = 17
    Const SECONDARY_SHEET_CRITERIA_COLUMN As Long = 24

    If Trim$(primarySheet.Cells(primarySheetRow, 1).Value2) = Trim$(secondarySheet.Cells(secondarySheetRow, 1).Value2) Then
        If Trim$(primarySheet.Cells(primarySheetRow, PRIMARY_SHEET_CRITERIA_COLUMN).Value2) <> Trim$(secondarySheet.Cells(secondarySheetRow, SECONDARY_SHEET_CRITERIA_COLUMN).Value2) Then
            IsDataValidForPopulation = True
        End If
    End If
End Function

Your population is next. The name PopulateData describes what's being done, the parameters populationSheet, populationRow, and populationColumn also self document. You were incrementing iCol several times iCol = iCol + 1 and then set it back at the end. That's been replaced and eliminates the vertical scrolling. Note: the ByRef on populationRow. This allows the incrementation done at the end to be seen by the caller and continue offsetting to the next row.

Private Sub PopulateData(ByVal primarySheet As Worksheet, ByVal primarySheetRow As Long, ByVal secondarySheet As Worksheet, ByVal secondarySheetRow As Long, ByVal populationSheet As Worksheet, ByRef populationRow As Long, ByVal populationColumn As Long)
    'Describe your magic numbers. Rename them appropriately
    Const FIRST_NUMBER As Long = 1
    Const SECOND_NUMBER As Long = 2
    Const THIRD_NUMBER As Long = 3
    Const FORTH_NUMBER As Long = 17
    Const FIFTH_NUMBER As Long = 24
    With populationSheet
        .Cells(populationRow, populationColumn).Value2 = primarySheet.Cells(primarySheetRow, FIRST_NUMBER).Value2
        .Cells(populationRow, populationColumn + 1).Value2 = primarySheet.Cells(primarySheetRow, SECOND_NUMBER).Value2
        .Cells(populationRow, populationColumn + 2).Value2 = primarySheet.Cells(primarySheetRow, THIRD_NUMBER).Value2
        .Cells(populationRow, populationColumn + 3).Value2 = primarySheet.Cells(primarySheetRow, FORTH_NUMBER).Value2
        .Cells(populationRow, populationColumn + 4).Value2 = secondarySheet.Cells(secondarySheetRow, FIFTH_NUMBER).Value2
    End With

    populationRow = populationRow + 1
End Sub

You had Set ws3 = ActiveWorkbook.Sheets("NINO Differences")' this will be a different sheet as I change the criteria which meant you'd need to change the code. Through refactoring and using the parameter populationSheet you now mandate that whoever calls this Sub needs to supply the required sheets.

Private Sub NINODifferences(ByVal primarySheet As Worksheet, ByVal secondarySheet As Worksheet, ByVal populationSheet As Worksheet)

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim primarySheetLastRow As Long
    primarySheetLastRow = primarySheet.Cells(primarySheet.Rows.Count, 1).End(xlUp).Row

    Dim secondarySheetLastRow As Long
    secondarySheetLastRow = secondarySheet.Cells(secondarySheet.Rows.Count, 1).End(xlUp).Row

    Const populationColumn As Long = 1
    Dim populationRow As Long
    populationRow = 2

    Dim primarySheetRow As Long
    Dim secondarySheetRow As Long
    For primarySheetRow = 1 To primarySheetLastRow
        For secondarySheetRow = 1 To secondarySheetLastRow
            If IsDataValidForPopulation(primarySheet, primarySheetRow, secondarySheet, secondarySheetRow) Then
                PopulateData primarySheet, primarySheetRow, secondarySheet, secondarySheetRow, populationSheet, populationRow, populationColumn
            End If
        Next secondarySheetRow
    Next primarySheetRow

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

You now have the option to create something like what follows to provide the sheets you need it run on. Note: I suggest renaming the Worksheets.CodeName member do be descriptive and use that in place of ActiveWorkbook.Sheets("SheetA") since you're using the name displayed on the sheet tab. If that get's changed you'll have to change your code.

Public Sub Test()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Set ws1 = ActiveWorkbook.Sheets("SheetA") 'Use the Worksheet.CodeName member

    Set ws2 = ActiveWorkbook.Sheets("SheetB")
    NINODifferences ws1, ws2, ActiveWorkbook.Sheets("NINO Differences")
    NINODifferences ws1, ws2, ActiveWorkbook.Sheets("FOO Differences")
    NINODifferences ws1, ws2, ActiveWorkbook.Sheets("BAR Differences")
    NINODifferences ws1, ws2, ActiveWorkbook.Sheets("DUK Differences")
    '...
    NINODifferences ws1, ws2, ActiveWorkbook.Sheets("ZZZ Differences")
End Sub


Getting matching items in lists based on nullable properties

Let's start refactoring!

foreach (Product p2 in productList1)
{
    Product match = productList2.FirstOrDefault(p =>
    {
        string pId = p.Id1.NullIfEmptyOrWhiteSpace() ??
                     p.Id2.NullIfEmptyOrWhiteSpace();

        string p2Id = p2.Id1.NullIfEmptyOrWhiteSpace() ??
                      p2.Id2.NullIfEmptyOrWhiteSpace();

        if (pId == null || p2Id == null)
            return false;

        return pId.Equals(p2Id);
    });

    // do stuff with match
}

p2Id does not depend on p, so let's move it out of the lambda.

foreach (Product p2 in productList1)
{
    string p2Id = p2.Id1.NullIfEmptyOrWhiteSpace() ??
                  p2.Id2.NullIfEmptyOrWhiteSpace();

    Product match = productList2.FirstOrDefault(p =>
    {
        string pId = p.Id1.NullIfEmptyOrWhiteSpace() ??
                     p.Id2.NullIfEmptyOrWhiteSpace();

        if (pId == null || p2Id == null)
            return false;

        return pId.Equals(p2Id);
    });

    // do stuff with match
}

Now let's define a method on Product to remove the repetition. I called it GetKey, but there's probably a better name.

public string GetKey()
{
    return this.Id1.NullIfEmptyOrWhiteSpace() ?? this.Id2.NullIfEmptyOrWhiteSpace();
}

foreach (Product p2 in productList1)
{
    string p2Id = p2.GetKey();

    Product match = productList2.FirstOrDefault(p =>
    {
        string pId = p.GetKey();

        if (pId == null || p2Id == null)
            return false;

        return pId.Equals(p2Id);
    });

    // do stuff with match
}

It looks like you actually want to call IsNullOrWhiteSpace in NullIfEmptyOrWhiteSpace, so let's fix that.

public static string NullIfEmptyOrWhiteSpace(this string value)
{
    return string.IsNullOrWhiteSpace(value) ? null : value;
}

Actually, we don't need to go through productList2 if p2Id is null.

foreach (Product p2 in productList1)
{
    string p2Id = p2.GetKey();
    if (p2Id == null)
    {
        continue;
    }

    Product match = productList2.FirstOrDefault(p =>
    {
        string pId = p.GetKey();

        if (pId == null)
            return false;

        return pId.Equals(p2Id);
    });

    // do stuff with match
}

Given that we only use p2 for its key, we can rewrite this as

foreach (var key in productList1.Select(product => product.GetKey()).Where(key => key != null))
{
    Product match = productList2.FirstOrDefault(p =>
    {
        string pId = p.GetKey();

        if (pId == null)
            return false;

        return pId.Equals(key);
    });

    // do stuff with match
}

Now let's use a dictionary to replace the call to productList2.FirstOrDefault.

var firstProductWithKey = new Dictionary<string, Product>();
foreach (var product in productList2)
{
    var key = product.GetKey();
    if (key != null && !firstProductWithKey.ContainsKey(key))
    {
        firstProductWithKey.Add(key, product);
    }
}

if (!firstProductWithKey.Any())
{
    return;
}

foreach (var key in productList1.Select(product => product.GetKey()).Where(key => key != null))
{
    Product match;
    if (firstProductWithKey.TryGetValue(key, out match))
    {
        // do stuff with match
    }
}

So what have we gained? Hopefully the intention of the code is a bit clearer, but there's also a performance benefit.

Let's say that the lists have \$n\$ and \$m\$ elements respectively, and that there are no keys common to the two lists.

In the original code, we're evaluating each key in the first list \$m\$ times, and each key in the second list \$n\$ times. So \$2nm\$ keys in total.

In the refactored version, we evaluate each key in the first list once, and each key in the second list once, for \$n + m\$ keys. We're performing much less work, and generating much less garbage for the GC.


Finding odd and even digits from an integer

Try to avoid using using namespace std.
<cmath> is not utilized anywhere, so just remove it unless you end up adding associated code.
Avoid giving variables single-letter names (unless they're simple loop counters, which is okay to do).  Although it may save some typing, it will instead make them appear meaningless as there is no context.  Comments can be added, but they're not a good substitute for actual variable names.  If a variable needs a comment, chances are it hasn't been given a good name.
To help increase readability and maintainability:

Have one variable per line.  This also helps in case comments need to be added.

long a;
long s=0;
long s1=0;

Separate operators and operands with whitespace so that the two can be identified.

long a;
long s = 0;
long s1 = 0;

Separate code lines based on purpose, also so that readers can focus on certain parts.

cout<<" Odd numbers ranged array"<<endl;

for(i=0; i<n; i++)
    cout<<d[i]<<" ";

cout<<endl;

Keep variables as close in scope as possible instead of listed together.  This could also help determine if a variable is no longer being used.

cout << "Write a number: " << endl;
long a; // move this here
cin >> a;

std::endl also flushes the stream, which is slower.  If you want just a newline, use "\n":

cout << "Write a number: \n";

This:

c=nl[i];
nl[i]=nl[j];
nl[j]=c;

can be done more concisely with std::swap:

std::swap(n1[i], n1[j]);

Consider making this program more modular (using functions).  Keeping everything in main() could make it hard for yourself and others to read and maintain the code.  It is also not clear, just from looking at it, that this program is written to fulfill those five tasks.  It could just be one task if the reader weren't otherwise aware of them.

This can be done any way you'd like, but the most likely solution could be to have one function for each of those tasks (while giving them appropriate names).  They could then be called from main(), and you could also get the user input from main() (this could, for instance, allow you to terminate the program right away if invalid input is given).


Decoupling with a self-descriptive mediator function

Odd question,

arguments.callee is considered obsolete, it's use will trigger an error in strict mode
On top you use moduleOne, but you pass module1 in the array in your exports call
You did not provide the source for exports
You have both missing & unnecessary semicolons ( jshint.com )
This

var a = arguments,
    l = a.length;
    c = a.callee;

should be

var a = arguments,
    l = a.length, //<- Comma here
    c = a.callee;

Traditionally the private things go on top, with a return/export at the bottom, still I like your way better
I'm assuming your exposed part of the facade is just a show case of what you can do and you will not actually decide which function to call based on parameter count and type.

All in all, I find this introduces complexity while not providing very much in return. Personally, I would hold off on modules until I really need them. And then, use require.js.


You are trying to parse HTML with regexes, which is widely considered to be a bad idea. For example, all these tags would have equivalent link text and target URL:

Link Text

Link Text

   Link Text

Link Text

Link Text

A line-based parser will fail here, and a regex-based parser will be very difficult to write correctly. So please use an existing HTML parser. The result will be fast and elegant, but as I don't use Ruby I can't give examples.

Let's move on to coding style. You are using multiple naming styles: beginning_time and newLine. Whatever you do, be consistent, although I'd recommend snake_case for variable names.

Some of your variable names contain abbreviations where none are necessary: quote_character is probably better than qtMark, descStart would probably be better described as description_start.

You used many variables to make your regexes appear more modular, but they are not. Your regexes will become more readable if you write them down directly rather than assembling them. You could also specify them outside of your loops:

href_regex = /href="([^"]+)"/

Points to note here:

[^"]+ is generally preferable over .*?
The /m option was highly unnecessary, because you process your input line by line. So there is no way that your . could ever match a newline in your original regex.

In your regexes, you used #{…} interpolation a lot. Strangely you didn't do any of that when assembling other strings, instead using less readable concatenation. E.g. we could rewrite

mainEntry = "original-url=\"" + source +
"\", dest-url=\"" + dest + "\""

as

main_entry = "original-url=\"#{source}\", dest-url=\"#{dest}\""

This is still pretty unreadable because of those pesky escapes – using the alternate %Q() literal syntax we could simplify this to:

main_entry = %Q(original-url="#{source}", dest-url="#{dest}")

… and ditto in the similar cases.

A snippet like

words = desc.split(' ')
words.each { |word| occur[word] += 1 }

could be improved in two ways:

get rid of the unnecessary variables. The code is already sufficiently self-documenting with the word parameter to the block
rename occur to something sensible like word_count

You declare your source variable outside of the each_line loop. It would be better to declare your variables as close to their point of usage as possible. Furthermore, you initialize them with the empty string. I (as a Ruby newbie) would probably initialize them to nil instead. This has the further advantage that we can remove those line.include? "some string" tests which do not even guarantee that the regex will match. The  String#[Regex, capture] method returns either the string matched by that capture group, or nil – which is exactly what we want.

Don't re-open a file all the time inside a tight loop, this is quite expensive. Open the file once, write to it multiple times. This will probably remove your main performance bottleneck.

If we stuff all this advice into your code, we might end up with the following refactoring:

start_time = Time.now

file_count = 1

File.open("firstOut.txt", 'w') do |out1|
    File.open("secondOut.txt", 'w') do |out2|
        for file_name in Dir["allParts/*.dat"] do
            puts "#{file_name}#:#{file_count}"
            file_count++

            File.open(file_name, "r") do |file|
                file.each_line do |line|
                    source      = line[/#URL:(.*?)\n/, 1]
                    destination = line[/')   + 2
                        description_end   = line.rindex('') - 1
                        description = line[description_start .. description_end]
                        if (description != nil && description != "")
                            out1.write(%Q(#{main_entry}, desc="#{desc}"\n\n))
                            description.split(' ').each do |word|
                                word_count[word] += 1
                            end
                        else
                            out1.write(%Q(#{main_entry}\n\n))
                        end

                        word_count.each do |word, count|
                            out2.write(%Q(#{main_entry}, word="#{word}", count=#{count}\n\n))
                        end
                    end
                end
            end
        end
    end
end

puts "Time elapsed #{Time.now - start_time} seconds"

Note that this can be improved further – the high level of indentation suggests we should extract some parts as separate functions. I further want to reiterate that I'm not a proficient Rubyist, so there might be some egregious oversights in the above code.


Generally, try to think about the problem before brute-forcing it.

Is there an easy way to sum all the multiples of 3 below \$N\$? Of course there is.
First we note that the largest multiple of 3 is \$3 * \lfloor\frac{N}{3}\rfloor\$ and the sum of all the multiples is then \$3 * 1 + 3 * 2 + ... 3 * \lfloor\frac{N}{3}\rfloor\$. Factor out the 3 and you get \$3 * (1 + 2 + 3 + ... \lfloor\frac{N}{3}\rfloor)\$. Now we use Gauss's trick for summing the natural numbers to get a nice easy formula for the sum: \$3*x*\frac{x+1}{2}\$, where \$x\$ is \$\lfloor\frac{N}{3}\rfloor\$.

Similarly, we can get the sum for the multiples of 5, and add the results together. However, we then have a bunch of duplicates (namely multiples of 15)
which we can also calculate in a similar manner and then subtract to get the final result.

This approach completely eliminates any and all looping, and so will be super quick.

Now, let's discuss your code. Here's a list of suggestions:

If you are prompting the user, provide some helpful hints as to what you are expecting as input.
Having hardcoded bounds such as yours is unintuitive. Have your sum be a long or even long long (depending on the desired platform) and you will not run into issues with integer inputs, which are guaranteed by scanf(%d). This will also cut down on the indentation, increasing readability.
Variable names are important. While it is pretty easy to see that i, k are the bounds, and j, l are counter variables after reading the code, it would be even easier to understand with lower_bound, upper_bound and i, j for the counters (per standard practices).
Consider generalizing the problem to create a function that will be reusable elsewhere.