Why? Why use a Queue to implement a stack? A Queue, by definition, (Computer Science Definition, not Java interface) is a FIFO device. A Stack, by definition, is a LIFO device. They are significant opposites of each other. Doing it this way is .... silly.

Also, it is not using the features of a FIFO queue to do the work, it is using the features of a Collection (add, addAll, Iterable). The only methods you should be calling on the queue are add, and remove.

A native array with a size would be a much, much better implementation, and would have \$O(1)\$ add and remove complexity, with occasional \$O(n)\$ if a resize is needed.

Also, your code is buggy, three things:

You 'cheat' and use poll() for the pop, and poll() returns null if the queue is empty, but, you do not 'guard' against the null being used as a push(null) value. Thus, there is no way to test whether the stack is empty reliably.
You do not implement peek()
You leak the monitor. By using synchronized methods, you let other people control your locking system. If people want to lock their code on something, they may use your stack, and then your synchronization is not contained.

I don't like this question of yours. To me it looks like a step backwards compared to your other recent questions.

Edit: About Locking

Consider some user of your class, they want a stack that is thread safe.... and they need to coordinate between some threads.

They need a convenient object to synchronize on. STACK is there... so they use it.

Note, I would never normally write code like the following.... but, the following code will never finish... Even though, at face value, it looks fine? You understand now?

private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(10);

private static final StackUsingQueue<File> STACK = new StackUsingQueue<File>();

private static final void myMethodProcessesFilesInParallel(File dir) {

    // this method processes Files in a folder.
    // only allow one folder to be processed at any one time. Synchronize on something:
    synchronized(STACK) {
        List<File> files = dir.listFiles();
        final AtomicInteger counter = files.size();

        for (final File file : files) {
            THREAD_POOL.submit(new Runnable() {
                public void run() {
                    // STACK is thread-safe. pop() is good!
                    try {
                        File file = STACK.pop();
                        System.out.println(file.length());
                    } finally {
                        synchronized(counter) {
                            counter.decrementAndGet();
                            counter.notifyAll();
                        }
                    }
                }
            });
        }

        synchronized (counter) {
            while (counter.get() > 0) {
                counter.wait();
            }
        }
    }
}


First a light review:

You've got a bug, I think. Your map_type_to_class sets a feed_type_id variable, but your case statement is looking at a stream_type_id variable that I don't see anywhere.

Second, don't use so many return statements. It's Ruby; returns are implicit. So this you don't need returns in if...else or case branches you have in your question. In idomatic Ruby, you only see return if someone specifically wants to exit a method early (and even that's rare with well-factored code).

Lastly, this bit is redundant

tweet_urls = self.where(:feed_id => feed_id.to_i)
if tweet_urls.empty?
  return []
else
  return tweet_urls
end

Which, to all intents and purposes is the same as simply:

self.where(:feed_id => feed_id.to_i)

It's implicitly returned, and it's array-like, so there's no need to do anything special. It's either empty or it's not. If you want something that's truly an Array instance (and not just duck-typed), you can append a .to_a.

Anyway, what you're looking for is the constantize method for strings. What you've got is a fairly simple has_many relationship, you just want something like a string item_type column on your Feed model that contains the class name (as a string) instead of your current numeric ID.

From there it's a matter of implementing a polymorphic has_many (Rails already has a polymorphic option for belongs_to but that's a to-one association).

You could simply do

def Feed
  def items
    klass = item_type.constantize
    klass.where(feed_id: id)
  end
end

(yes that could just be one line).

You won't have all the fancy collection methods, caching, and other nice stuff Rails provides for regular associations, but you can add that if you want or simply make do without it (I recommend the latter unless you find it to be bigger hassle).

So in your FeedsController (or wherever), you're looking at something like

def show
  feed = Feed.find(params[:id])
  render json: feed.items
end

That should work as a super-minimal implementation. The point is really just that you store the class name, which you can then turn from a string into a class name constant with constantize.

Alternatively, you could use Rails' built-in associations, but there's more setup involved and it's not as clean to look at. Again, you'll want an item_type string column.

def Feed
  has_many :webpages # the class name Webpage is implicit
  has_many :pictures
  has_many :twitters # yuck, not a good name, but it'll imply the Twitter class

  def items
    association = item_type.underscore.pluralize # convert a class name to an association name
    send(associtation) # call the association method (e.g. `webpages`)
  end
end

The main advantage is that the items method is just a shortcut that provides the correct association object, so you have all the usual convenience methods. So you can do something like this for a webpage-type feed

Feed.find(some_id).items.create(params[:url])

Of course, the major issue is that it's not clear what's going on. Is items a collection of Picture? Of Webpage? If you just blindly try to create a Picture record from params meant for a webpage, things get messy.

So I'd stick to the first version, where items isn't an opaque alias for an association, and instead work a bit harder when adding new records and such.


std::string_view
Firstly, there seems to be some misusages of string_view. string_view is non-owning, and is a view to an allocated char array (such as string).
The usage
template <typename Resource>
class MissingResource : public std::exception {
    std::string_view fileName{};
    std::string_view msg{};

public:
    [...]
    template <typename T>
    void initMsg() {
        msg = "Failed loading resource: "
              "{ Type: "    + std::string(typeid(Resource).name()) + ", "
              "File name: " + fileName.data()                      + " }";
    }
    [...]
};

Is dangerous, since after calling initMsg(), msg will point to an destroyed object (the right hand string is temporary).
Better change it to be an owning string in this case: std::string_view msg => std::string msg. I assume you already have it like this, otherwise it would provide the output which you gave in the description.
Secondly, the other member variable std::string_view fileName does not seem necessary. Since you create the error message for msg with fileName and do not use alone, we can skip it, right?
General design of MissingResource
Applying the changes above, we have:
template <typename Resource>
class MissingResource : public std::exception {
    std::string msg{};

public:
    MissingResource() = default;
    MissingResource(std::string_view fileName)
    {
        initMsg<Resource>();
    }

    template <typename T>
    void initMsg(std::string_view fileName) {
        msg = "Failed loading resource: "
              "{ Type: "    + std::string(typeid(Resource).name()) + ", "
              "File name: " + fileName.data()                      + " }";
    }

    virtual const char* what() const noexcept override {
        return msg.data();
    }
};

initMsg is currently a public method, but from what I see, it's only used locally in the constructor. If this is the case, it should rather be a private method - you want to keep the public API for the class as simple and small as possible.
Another improvement would be to be able to create msg in the constructor list - so that it does not have to be created twice. We can do this by making the initMsg a static method.
Let's remove the extra unnecessary template for initMsg as well - the entire class already holds the template argument.
And note that virtual + override is unnecessary. If you mark a method as overrided, it is implicitly virtual. Remove virtual for unnecessary noise.
We now have something like this:
template <typename Resource>
class MissingResource : public std::exception {
    std::string msg{};

    static std::string initMsg(std::string_view fileName) {
        return "Failed loading resource: "
              "{ Type: "    + std::string(typeid(Resource).name()) + ", "
              "File name: " + fileName.data()                      + " }";
    }

public:
    MissingResource() = default;
    MissingResource(std::string_view fileName) : msg{initMsg<Resource>()}
    {}

    const char* what() const noexcept override {
        return msg.data();
    }
};

ResourceHolder
Since this review is already long, I will just point out one thing in ResourceHolder, namely in insert. We can avoid separating declaration from initialization for bool loaded (and make it const!) by encapsulating the logic into a separate method. This might be a bit preferential, but it is good practice to avoid separating declaration and initialization.
Something like this:
private:
    bool fromFile(std::string_view fileName, Args&&... args)
    {
    if constexpr (std::is_same<Resource, sf::Music>()) {
            return resPtr->openFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);
        }
    else {
            return resPtr->loadFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);
    }

public:
    template <typename... Args>
    void insert(const Key& key, std::string_view fileName, Args&&... args) {
        auto resPtr = std::make_unique<Resource>();

        const bool loaded = fromFile(fileName, std::forward<Args>(args)...)

        /** Called here */
        if (!loaded) {
            throw MissingResource<Resource>(fileName);
        }
        resources.emplace(key, std::move(resPtr));
    }


Using Span and Memory to read UTF8 from a socket

I have no experience with Span<T> or Memory<T> so the following is just some general considerations on coding etc.

In FakeNetworkStreamRead(...): why have a internal limit of 5 bytes? Why not let the length of the Span<T> argument determine the maximum bytes to read?

Why are you using a Memory<T> as buffer, when reading from the stream?:

Memory<byte> byteMemory = new byte[3];

Why not just a Span, because you only use it as a such and not holding or collecting any data in it:

Span<byte> byteSpan = new byte[3];

IMO you should change the do {} while(...) loop to a while (...) loop, because, if the stream is empty you do a "lot" of work in the first round trip for no reason:

  int read = 0;

  while ((read = FakeNetworkStreamRead(byteSpan)) > 0)
  {
    ...
  }

With the above in mind I've tried to refactor your code to:

static int FakeNetworkStreamRead(Span<byte> span)
{
  int stop = Math.Min(_position + span.Length, _data.Length);
  int i = 0;

  for (; _position < stop; i++, _position++)
  {
    span[i] = _data[_position];
  }

  return i;
}

static void Main(string[] args)
{
  Span<byte> byteSpan = new byte[3];
  Memory<char> charMemory = new char[1024];

  var charMemoryPos = 0;
  var decoder = Encoding.UTF8.GetDecoder();
  int read = 0;

  while ((read = FakeNetworkStreamRead(byteSpan)) > 0)
  {
    Console.WriteLine($"Read {read} bytes");

    // pass the sliced part of the memory I want to parse, and the part
    // of the char buffer where I want to write
    decoder.Convert(byteSpan.Slice(0, read),
                    charMemory.Slice(charMemoryPos).Span,
                    false, out int bytesUsed, out int charsUsed, out bool completed);

    // update offsets and counts
    charMemoryPos += charsUsed;
  }

  Console.WriteLine(new string(charMemory.Slice(0, charMemoryPos).Span));
}

In order to flush the decoder state, the do {} while(...) loop is useful anyway:

static void Main(string[] args)
{
  int bufferLength = 3;
  Span<byte> byteSpan = new byte[bufferLength];
  Memory<char> charMemory = new char[1024];

  var charMemoryPos = 0;
  var decoder = Encoding.UTF8.GetDecoder();
  int read = 0;

  do
  {
    read = FakeNetworkStreamRead(byteSpan);

    decoder.Convert(byteSpan.Slice(0, read),
                    charMemory.Slice(charMemoryPos).Span,
                    read == 0, out int bytesUsed, out int charsUsed, out bool completed);

    Console.WriteLine($"Read {read} bytes -> Used: {bytesUsed} -> Completed: {completed} -> CharUsed: {charsUsed} -> {decoder.FallbackBuffer.Remaining}");

    charMemoryPos += charsUsed;
  } while (read > 0) ;

  Console.WriteLine(new string(charMemory.Slice(0, charMemoryPos).Span);
}

Here the read == 0 argument to decoder.Convert(...) becomes true at the end of the stream, which will flush the state and clears the internal buffer of decoder


Can this custom Test:Unit assert be replaced/refactored? Am I missing test cases?

You have adequate test coverage for integers, and probably this will extend to floating points as well (although you really should test those as well, IMO). However you should also test for objects. Also, try a couple combinations of objects, numbers, and strings to be really sure that your assertion is correct.

If you only need to test for integer arrays, you should make it clear that the assert only works for them and its behavior with other arrays is undefined. In that case maybe you should change the name to assert_same_items_integer or something similar for clarity.


Integer not Double

Double is not a reasonable type because checking if a number is big does not work with Doubles, you should use Integer

First class functions

Using a list is not a clean procedure, it does not work for very big numbers and it is slow for big numbers.

It is better to pass in a validation function:

numberCheck :: (Integer -> Bool) -> String -> IO ()
numberCheck predicate text = do
  num <- askUser ("Is it " ++ text ++ "? ")

  if predicate num
    then putStrLn "Yes"
    else putStrLn "No"

Usage is:

main = do
  hSetBuffering stdout NoBuffering
  putStrLn "Welcome to Numbers!"

  numberCheck odd "odd"
  numberCheck (\x -> x `mod` 18 == 0) "multiple of 18"
  numberCheck (> 100) "big (bigger than 100)"


It will make sense to use OOP in your implementation.
You can model the crypt as a Crypt class,
there gate and lever can be attributes,
and entrance, lever_room can be methods.

Transforming your implementation is quite easy, follow this pattern:

class Crypt(object):
    def __init__(self):
        self.gate = False
        self.lever = False

    def entrance(self):
        while True:
            choice = raw_input('> ')

            if choice == 'west':
                self.guard_shack()
            elif choice == 'east':
                self.lever_rm()
            elif choice == 'north' and not self.gate:
                print "The gate is still closed and locked."
                self.entrance()
            elif choice == 'north' and self.gate:
                self.fountain_rm()
            else:
                self.entrance()

# ...

def main():
    crypt = Crypt()
    crypt.welcome()
    crypt.entrance()

To learn more about classes and OOP in Python,
I recommend the official tutorial.

It's not a good practice to run code in the global namespace,
because if you try to import this module from another module,
all that code will be executed immediately.

The right way to do this in Python is to add this conditional:

if __name__ == '__main__':
    main()

This condition will only be true when the file is executed as a Python script.

Don't use the == operator to check the value of boolean variables and expressions like this:

elif choice == 'north' and gate == False:
    print "The gate is still closed and locked."
    entrance()
elif choice == 'north' and gate == True:
    fountain_rm()

Instead of x == True you can use the boolean variable directly,
in case of x != False you should use not x, for example:

elif choice == 'north' and not gate:
    print "The gate is still closed and locked."
    entrance()
elif choice == 'north' and gate:
    fountain_rm()

This looks like a bug:

else:
    entrance(gate)

Because in your declaration the entrance method doesn't take any parameters.


Version 3

Consider the case of a sequence of 00 00 00 02. This sequence will pass the first 3 if conditions and fail at the 4th one. But what does this tell you ? It tells you that instead of increasing i by 1 it should be increased by 4.

This idea converted to code could look like this

for (int i = 0; i < frame.length - 4; i++) {

    if (frame[i] != 0) {
        continue;
    }

    i++;
    if (frame[i] != 0) {
        continue;
    }

    i++;
    if (frame[i] > 1) {
        continue;
    }

    if (frame[i] == 1) {
        // found marker 00 00 01
        // do work here

        continue;
    }

    i++;
    if (frame[i] == 1) {
        // found marker 00 00 00 01
        // do work here
    }
}

which isn't easy to read/understand at first glance, so a big comment about why the increasing of i is done like this would be in order.


If you can only change a bool once, and the entire purpose of a loop is to set the bool, then you should just exit the loop after the bool gets changed.  There's no point in looping more than you need to, and you also don't have to worry about the bool getting switched back.  So you can write your example like this:

bool SomeMethod()
{
    foreach(var obj in objs)
    {
        if(!obj.Method())
        {
            return false;
        }
    }
    return true;
}

You can use Enumerable.All() for this logic:

bool SomeMethod()
{
    return objs.All(x => x.Method());
}

An alternative to if(!x) y = x; in your situation is y = y && x;


Parsing CSV data

First, let me point out that what you are doing is not proper CSV parsing. Recommended reading: How to parse CSV data with Ruby. Carving up CSV files manually is not often ideal, as it can lead to mistakes, such as what I will explain below.

Using a well established library is most often a better choice. This also holds true of other types of data files, such as XML and JSON. Those libraries help improve consistency and reduce bugs.

Once you've chosen a library to use, read further into how to use that library effectively. You mentioned that you are pretty new, so I will leave that here as something to study when you feel ready to tackle it. =)

Bugs

Your code "works" for your simple use case, but only because you are comparing identical CSV files, rather than because the CSV files contain the same data. What your code is doing is splitting up a string (the characters from your CSV files) into lines, and comparing those. If the lines are identical, but are not in the same order, then you start getting incorrect results. For demonstration, you can try this:

sample_data1 = \
'Kanye,West
Jay,Z
Chance,TheRapper
Two,Chains'

sample_data2 = \
'Jay,Z
Kanye,West
Two,Chains
Chance,TheRapper'

# open an array for each list of names
people = Array.new
people1 = Array.new

# load each list into a variable
first_list = sample_data1
second_list = sample_data2

# rest of the code stays the same

I would expect the result to be the same either way (if it was working correctly), however this is what I get back:

Kanye West
Jay Z

Interesting. Let's see why this is happening, by adding some print and puts instructions in your each_line statements. (note that I converted from curly brackets to do...end syntax since it makes it simpler for statements which aren't one-liners)

puts '- first_list'
first_list.each_line do |line|
    fields = line.split('\n')
    print fields
    people.push(fields)
    puts
end

Did the same thing to second_list. Here is what the console shows now. I added the comments to show you what is happening.

- first_list
["Kanye,West\n"]
["Jay,Z\n"]
["Chance,TheRapper\n"] # has newline
["Two,Chains"] # no newline
- second_list
["Jay,Z\n"]
["Kanye,West\n"]
["Two,Chains\n"] # has newline
["Chance,TheRapper"] # no newline

The issue that is causing those errors is as follows. In Ruby, single-quoted strings and double-quoted strings do not work the same way.

When you use single-quoted strings, they are string literals, so '\n' is not the newline escape character; rather it is a backslash character and the lowercase letter n. If you want to be able to use backslash escaping, you need to use double-quoted string "\n" instead. (this also holds true of things like string interpolation)

You will also notice that you have an array of arrays (or 2D array), which is fine if that's what you need, but I suspect that's possibly not what you expected.

The reason each value is an array is because you are splitting them in a loop with each_line, and then "splitting" (incorrectly due to single quote) each line again with .split('\n') and pushing that into the array.

Implementing the above fixes:

Splitting on "\n" after the file is read, not while iterating;
Using double-quotes to look for newline characters rather than string literals of '\n';
Pushing split strings into the destination array, rather than into sub-arrays/

# open an array for each list of names
people = Array.new
people1 = Array.new

# load each list into a variable
first_list = File.open("namelist.csv", "r").split("\n")
second_list = File.open("namecomplist.csv", "r").split("\n")

# split the file up by line and push
# the contents of the line to an array
# each element is delineated by the new line
# character "\n"
first_list.each do |line|
    people.push(line)
end

# split the second file up by line and push
# the contents of the line to an array
second_list.each do |line|
    people1.push(line)
end

This now functions "correctly", at least to the extent you want to compare for the same lines of comma-separated characters. Note that this is still a naive solution, because if there were spaces or other unexpected characters between the commas and words, it would also not work correctly.

Review

With the nasty bug out of the way, here are some things I would do to improve your code.

First, I would suggest to make a method to read the CSV file. Flambino's answer goes into more detail on that matter, so I will just post a naive implementation that works OK. I recommend to heed Flambino's advice on this file-reading matter.

# Converts a CSV raw character string into
# an array of newline-separated strings.
def load_list_from_csv(csv_file_raw_str)
  list = csv_file_raw_str.split("\n")
end

Then we can just update this:

# load each list into a variable
first_list = load_list_from_csv(sample_data1)
second_list = load_list_from_csv(sample_data2)

Or in your case...

# load each list into a variable
first_list = load_list_from_csv("namelist.csv", "r")
second_list = load_list_from_csv("namecomplist.csv", "r")

While we're at it, let's make a method to compare the 2 files. Basically just combining a few bits of code into one method. By the way, the operation you are making on those data sets is called an intersection.

Here is a working code example on repl.it showing the changes:

sample_data1 = \
'Kanye,West
Jay,Z
Chance,TheRapper
Two,Chains'

sample_data2 = \
'Jay,Z
Kanye,West
Two,Chains
Chance,TheRapper'

# Converts a CSV raw character string into
# an array of newline-separated strings.
def load_list_from_csv(csv_file_raw_str)
  list = csv_file_raw_str.split("\n")
end

# Intersect two arrays to return identical strings/lines
def intersect_csv_names_lists(file1, file2)
  people1 = load_list_from_csv(file1)
  people2 = load_list_from_csv(file2)
  [people1 & people2].join("\n")
end

# Replace commas with spaces in a string
def format_replace_commas_with_spaces(arr)
  arr.gsub(',', ' ')
end

# Print the matching data and substitute a comma
# for a space for formatting purposes.
# The result should be the names of the people
# who are on both lists.
puts format_replace_commas_with_spaces(intersect_csv_names_lists(sample_data1, sample_data2))

Output:

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

 Kanye West
 Jay Z
 Chance TheRapper
 Two Chains
=> nil


There is a race condition in your code. When you call t.start() the thread doesn't start immediately which means that it's possible to have a thread waiting to execute but the current thread can call notifyall before the new thread has a chance to increment the counter. This can be fixed by doing the increment in the constructor instead of in run.

On another note, FILE_LIST.add is not safe to call from multiple threads. All the rest around that is safe. So, the for loop can be reduced to:

for (File temp : listOfFiles) {
    if (temp.isFile()) {
        synchronized (FILE_LIST) {
            FILE_LIST.add(temp.getAbsolutePath());
        }
    } else if (temp.isDirectory()) {
        Thread t = new Thread(new MyThreadA(temp.getPath()));
        t.start();
    }
}

When waiting on an object there is the (documented) possibility of a spurious wakeup, which means that the thread woke up without anyone calling notify.

The way to deal with that is to wait in a loop:

synchronized (FILE_LIST) {
    while(ATOMIC_COUNTER.get() > 0)
        FILE_LIST.wait();
}

The condition is inside the synchronized to avoid a race condition (not the one detailed above though).


Performance aspects regarding file access

In your getMaleNames($custom) function you first load the /names/male.json contents, then look at $custom and use this one if not empty: so in the latter case you spent time reading file while it's useless. You'd instead look at $custom first, then at file if needed.
Obviously the same applies to getFemaleNames().

In the other hand, when you call one of your static functions you create a new Gender instance, so invoking both of the get...Names() functions, which ends with reading two files for each external call as soon as they don't provide non empty $custom argument.
It could be far more efficient to create a unique instance once, then use its contents.
As a first thought this might be achieved by looking at the Gender instance from the static functions, and create it only when it doesn't exist yet. But look also at the strategy part below.

Compacting code

There are several places where this can be done.

The best example is in the already cited get...Names() functions: they can be simply factorized like this (also includes the change suggested about files):

protected function getNames($gender, $custom) {
  if (is_array($custom[$gender])) {
    foreach ($custom[$gender] as $name) {
      $names[] = strtolower($name);
    }
  }
  $names =
    json_decode(file_get_contents(__DIR__ . '/names/' . $gender . '.json'));
  return $names;
}

Another example is that, even if you want to keep separate functions available for the external calls (though guess() only is probably enough), you can simplify the two is...() functions, like this one (same for isFemale()):

public static function isMale($name, $default = 'm', $unknown = 'm', $custom = []) {
  return self::guess($name, $default, $unknown, $custom) === 'm';
}

Finally the getName() function can be simplified like this:

protected function getName($name) {
  return strtolower(explode(' ', $name)[0]);
}

Strategy

Analyzing what your class is made for, it appears that creating an instance is not required. The only data which needs to be saved between two external calls is the content of the /names/...json files (and only if we retain the first change I proposed above!).

So you might:

keep properties $maleNames and $femaleNames only, and make them static.
also make the protected functions static.
move all the logics currently in __construct() to guess() (working with simple variables rather than properties).
and not have __construct() at all.

Additionally observe that, in the current __construct() logics:

the affectation to $this->gender is never used further
getName() can be called only once and is very simple, so the function can be abandoned in profit of direct comptuting
the if/else sequence can be replaced by directs returns

So it ends with this full code simplified version:

Class Gender{
  protected static $maleNames;
  protected static $femaleNames;
  public static function guess($name, $default = 'm', $unknown = 'm', $custom = []){
    if (!self::$maleNames) {
      self::$maleNames = self::getNames('male');
    }
    if (!self::$femaleNames) {
      self::$femaleNames = self::getNames('female');
    }
    $name = strtolower(explode(' ', $name)[0];
    $isMale = in_array($name, self::$maleNames);
    $isFemale = in_array($name, self::$femaleNames);
    if ($isMale && !isFemale) {
      return 'm';
    }
    if (!$isMale && isFemale) {
      return 'f';
    }
    if ($isMale && isFemale) {
      return $default;
    }
    return $unknown;
  }
  public static function isMale($name, $default = 'm', $unknown = 'm', $custom = []) {
    return self::guess($name, $default, $unknown, $custom) === 'm';
  }
  public static function isFemale($name, $default = 'm', $unknown = 'm', $custom = []) {
    return self::guess($name, $default, $unknown, $custom) === 'f';
  }
  protected static function getNames($gender, $custom) {
    if (is_array($custom[$gender])) {
      foreach ($custom[$gender] as $name) {
        $names[] = strtolower($name);
      }
    }
    $names =
      json_decode(file_get_contents(__DIR__ . '/names/' . $gender . '.json'));
    return $names;
  }
}


Check out Rustfmt.
There's a Clippy warning for zero_one_knapsack: explicit lifetimes given in parameter types where they could be elided.
Don't prefix every parameter with p. There's no naming conflict and it adds confusion to everyone that tries to use the API. Especially for variables like padded_weight, where "padded" is another English word!
Introduce a key method to DRY up Ord / PartialEq / Hash implementations.
A leading _ means that item is unused but must be present for some reason; don't call your methods that. Switch to words since identifiers can't start with numbers
Start iteration in zero_one_knapsack_items at 0. This simplifies the logic and shows that take_while can be removed.
This also leads to using iter and enumerate instead of operating on a range.
In turn, this leads to removing the need for indexing into items.
Remove the result temporary variable. It doesn't introduce a useful name and doesn't need to occur in a different temporal location.
There is a filter_map that does two operations in one, but I like the separation of filter and map here. You almost want a scan_map.
There's no need to specify type on collect; it's inferred from the return type of the function.
I'm not a fan of the truncated variable names. Computers don't care about long names, but humans do care about short names. This is especially true when there are overlapping meanings for prefixes like inc (included or inclusive).
Prefer iterating on a slice instead of on a range of numbers. If you need the number, use enumerate; this avoids out-of-bounds checking on each index operation.
Implement Default for your type if there's an appropriate value.
Import Ord and max to make that code a bit cleaner to read.

use std::cmp::{Ord, max};

#[derive(Debug, Clone)]
struct Item {
    value: usize,
    weight: usize,
}

impl Item {
    fn new(value: usize, weight: usize) -> Item {
        Item {
            value: value,
            weight: weight,
        }
    }
}

#[derive(Debug, Clone)]
struct Info {
    ks_value: usize,
    added_weight: usize,
    included: bool,
}

impl Info {
    fn new(ks_value: usize, added_weight: usize, included: bool) -> Info {
        Info {
            ks_value: ks_value,
            added_weight: added_weight,
            included: included,
        }
    }

    fn key(&self) -> usize {
        self.ks_value
    }
}

impl Ord for Info {
    fn cmp(&self, other: &Info) -> std::cmp::Ordering {
        self.key().cmp(&other.key())
    }
}

impl PartialOrd for Info {
    fn partial_cmp(&self, other: &Info) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Info {
    fn eq(&self, other: &Info) -> bool {
        self.key() == other.key()
    }
}

impl Eq for Info {}

impl Default for Info {
    fn default() -> Info {
        Info::new(0, 0, false)
    }
}

fn zero_one_knapsack_items<'a>(items: &'a [Item],
                               max_weight: usize,
                               subproblems: &[Vec<Info>]) -> Vec<&'a Item>
{
    items.iter().enumerate()
        .rev()
        .scan(max_weight, |w, (i, item)| {
            let subproblem = &subproblems[i+1][*w];
            *w -= subproblem.added_weight;
            Some((item, subproblem.included))
        })
        .filter(|&(_, included)| included)
        .map(|(item, _)| item)
        .collect()
}

fn zero_one_knapsack(items: &[Item], max_weight: usize) -> Vec<&Item> {
    let mut subproblems = vec![vec![Info::default(); max_weight + 1]; items.len() + 1];

    for (i, item) in items.iter().enumerate() {
        for w in 0..max_weight + 1 {
            let w_i = item.weight;
            let exclusive_cost = subproblems[i][w].ks_value;
            subproblems[i + 1][w] = if w < w_i {
                Info::new(exclusive_cost, 0, false)
            } else {
                let inclusive_cost = subproblems[i][w - w_i].ks_value + item.value;
                max(Info::new(exclusive_cost, 0, false),
                    Info::new(inclusive_cost, w_i, true))
            }
        }
    }

    zero_one_knapsack_items(items, max_weight, &subproblems)
}

fn main() {
    let items = [Item::new(92, 23),  // 1
                 Item::new(57, 31),  // 1
                 Item::new(49, 29),  // 1
                 Item::new(68, 44),  // 1
                 Item::new(60, 53),  // 0
                 Item::new(43, 38),  // 1
                 Item::new(67, 63),  // 0
                 Item::new(84, 85),  // 0
                 Item::new(87, 89),  // 0
                 Item::new(72, 82)]; // 0

    for i in zero_one_knapsack(&items, 165) {
        println!("{:?}", i);
    }
}


Race car with falling objects that make the car go back to its initial position game

indentation

A little bit of whitespace goes a long way in giving your code a visual structure. This makes the code more readable:

#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_color.h>
#include <allegro5/allegro_ttf.h>
#include <iostream>

ALLEGRO_DISPLAY *display;
ALLEGRO_EVENT ev;
ALLEGRO_EVENT_QUEUE *eventqueue;
ALLEGRO_TIMER *timer;
ALLEGRO_BITMAP *car;
ALLEGRO_BITMAP *object;

float FPS = 60.0;
int width = 800;
int height = 600;
int objectX = 810;
int objectY = 610;
int objectYStep = 5;
int playerPosX = width / 2;
int playerPosY = 510;
int playerStep = 10;
bool isOpen = true;

void moveObject(){
    objectY = objectY + objectYStep;
}

void movePlayerRight(){
    playerPosX = playerPosX + playerStep;
}

void movePlayerLeft(){
    playerPosX = playerPosX - playerStep;
}

bool objectOutOfBounds(){
    return objectX > width || objectY > height;
}

bool intersects(ALLEGRO_BITMAP *objecte, ALLEGRO_BITMAP *cars, int objecteX, int objecteY, int carsX, int carsY){
    int objecteW = al_get_bitmap_width(objecte);
    int objecteH = al_get_bitmap_height(objecte);
    int careW = al_get_bitmap_width(cars);
    int careH = al_get_bitmap_height(cars);
    return objecteX<careW + carsX && objecteX + objecteW>carsX && objecteY<careH + carsY && objecteX + objecteH>carsY;
}

int main(){
    al_init();
    if (!al_init()){
        std::cout << "Failed to initialize allegro5." << std::endl;
    }
    al_init_image_addon();
    if (!al_init_image_addon()){
        std::cout << "Failed to initialize image." << std::endl;
    }
    display = al_create_display(width, height);
    if (!display){
        std::cout << "Failed to create display." << std::endl;
    }
    al_install_keyboard();
    if (!al_install_keyboard()){
        std::cout << "Failed to install keyboard." << std::endl;
    }

    eventqueue = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);
    car = al_load_bitmap("racecar.png");
    object = al_load_bitmap("brickonn.jpg");

    al_register_event_source(eventqueue, al_get_display_event_source(display));
    al_register_event_source(eventqueue, al_get_keyboard_event_source());
    al_register_event_source(eventqueue, al_get_timer_event_source(timer));

    while (isOpen){
        al_clear_to_color(al_map_rgb(255, 255, 0));
        ALLEGRO_EVENT event;
        al_wait_for_event(eventqueue, &event);
        al_start_timer(timer);
        if (objectOutOfBounds()){
            objectX = rand() % width;
            objectY = 0;
            objectYStep = objectYStep + 1;
        }
        if (event.type == ALLEGRO_EVENT_TIMER){
            moveObject();
        }
        if (event.keyboard.keycode == ALLEGRO_KEY_LEFT){
            movePlayerLeft();
        }
        else if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT){
            movePlayerRight();
        }
        if (intersects(object, car, objectX, objectY, playerPosX, playerPosY)){
            std::cout << "CRASH!" << std::endl;
            playerPosX = width / 2;
        }
        al_draw_bitmap(car, playerPosX, playerPosY, 0);
        al_draw_bitmap(object, objectX, objectY, 0);
        al_flip_display();
    }

    al_flip_display();
    al_rest(10);
}

Pick a coding style and consistently use it. Prefer a coding style that's common or "standard" in your language. It greatly helps when getting help from people. If your code is easy to digest, it's more likely somebody will do so.

comments

There are no comments. That's a problem. Add some comments to your code to explain what's going on.

more functions

  I stopped putting everything in the main function

That's a good idea. You can go even further. Look at the first part of your main() function. If you had to put a comment over it, it'd probably look like that:

// initialisation
al_init();
if (!al_init()){
    std::cout << "Failed to initialize allegro5." << std::endl;
}
al_init_image_addon();
if (!al_init_image_addon()){
    std::cout << "Failed to initialize image." << std::endl;
}
display = al_create_display(width, height);
if (!display){
    std::cout << "Failed to create display." << std::endl;
}
al_install_keyboard();
if (!al_install_keyboard()){
    std::cout << "Failed to install keyboard." << std::endl;
}

eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / FPS);
car = al_load_bitmap("racecar.png");
object = al_load_bitmap("brickonn.jpg");

al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_timer_event_source(timer));

Instead, put all this code in a function and only invoke initialise() from main(). This takes away the gory details when reading the code at first glance. Ok, there's an initialisation going on. Am I interested in that? Yes -> dive into the function, No -> go ahead with main


Rethrowing exception just as an information

Especially if you expect these exceptions to occur (relatively) often, I think that using exceptions is a bad idea here. Exceptions should not be used for regular flow of control, this applies to Java as well. Creating and throwing exceptions is among the most costly operations there is in many programming languages.

One comment especially that caught my attention was: "Now I have to make some specific calculations, but sth wrong happend and I do know what to do with it in this place..." If you know what to do with it, then why are you throwing an exception? If you look in the dictionary an exception is:

  special case, departure, freak, anomaly, inconsistency, deviation, quirk, oddity, peculiarity, irregularity" (+ exclusion, omission, objection).

Is your case really an anomaly? (Doesn't sound like it but I can't make this decision for you)

Instead, consider creating a CalculationResult class, which can be returned from your methods. The class can contain your solved variable (possibly among other things). Then when a method has returned a CalculationResult to it's caller, you can read the CalculationResult and decide what to do with it.


Is this the optimal way to write "find these IDs in a list of objects" using linq?

Use a Dictionary<int, Organization> to look up organizations by their IDs quickly.

Your code will then look like this: OrganizationIdList.Select(id => organizations[id])....

Given your clarification in the comments that your are getting organizations from a database, you should let the database do the hard work for you. The code will depend upon the ORM you're using, but a relatively SQL-agnostic version of the query will look like this:

SELECT organization_id, division, name FROM organizations WHERE organization_id IN (?)

or this:

SELECT organization_id, division, name FROM organizations JOIN user_organizations
USING (organization_id) WHERE user_id = ?


Detect strings that consist of some a's followed by some b's

So:

// Note: str is a string.
//       containing "a"
//       So length = 1

while (str[i] == 'a' && i < str.length()) {
    i++;
}
// First Loop
//     str[0] == 'a' && 0 < 1
//     true && true
//     true
//       So we enter the loop body and increment i to 1.
// Second Loop
//     str[1]  // access beyond the end of the string.
//             // thus undefined behavior.

If we swap the test around

while (i < str.length() && str[i] == 'a') {
    i++;
}
// First Loop
//     0 < 1 && str[0] == 'a'
//     true && true
//     true
//       So we enter the loop body and increment i to 1.
// Second Loop
//     1 < 1  &&  // The left hand side of the test is false
//                // && is shortcut operator so the right hand
//                // side is not evaluated and the loop exited.


Ruby method that is validating the payload received

Inline conditionals would make this a bit cleaner:

def disbursements
  @invoice = Invoice.find(params[:id])

  @invoice.errors[:invoice_id] << 'invoice_id can not be blank' if @invoice.invoice_id.nil?
  @invoice.errors[:trips] << 'Funds can not be disbursed yet.' if Time.now.utc <= @invoice.trips.first
  @invoice.errors[:cancelled] << 'This invoice was already been cancelled.' if @invoice.cancelled
  @invoice.errors[:service_rendered] << 'This invoice has already been disbursed.' if @invoice.service_rendered

  return render json: @invoice.errors, status: :unprocessable_entity if @invoice.errors.any?
  ...
end

We can slim the method down and save a lot of space that way.

I removed the utc_time variable because it was only used once.


If a program fails for some reason then it should

Write a diagnostic message to standard error (not standard output),
so that it can not be mistaken for normal output, e.g. when
the program runs in a pipe. strerror(errno) gives you an error
message string corresponding to the last error, e.g.
"No such file or directory" or "Permission denied".
Terminate with a non-zero status code. You can use predefined
exit codes from <sysexits.h> if that is available on your system,
or make up your own.

Combining this with the "Avoiding deep nesting" advice from
Caridorc's answer, the overall structure would be

int main(int argc, char *argv[]) {

    if (argc != 2) {
        fprintf(stderr, "Usage: hex [file]\n");
        exit(EX_USAGE);
    }

    FILE *in = fopen(argv[1], "rb");
    if (in == NULL) {
        fprintf(stderr, "Cannot not open %s: %s\n", argv[1], strerror(errno));
        exit(EX_NOINPUT);
    }

    // ... print hex dump ...

    fclose(in);

    exit(EXIT_SUCCESS); // EXIT_SUCCESS == 0
}

Your variable names are too short and non-descriptive.

i is the current offset into the file. The correct type for
a file offset is off_t.
br is the amount of bytes read. The correct type would
be size_t (which is what fread() returns, so this avoids
a warning when compiling on a 64-bit architecture).
l is a line buffer.

j is OK as a iteration variable, but the scope should be limited to the
for-loop.

The main loop would then start like this:

off_t offset = 0;
size_t bytesRead;
char line[16];

while ((bytesRead = fread(&line, 1, 16, in)) > 0){
    printf("%08llx ", offset);
    offset += bytesRead;
    for (size_t j = 0; j < bytesRead; j++){
        printf("%02x ", line[j]);
    }

I don't know why you want to print a NUL-byte as ??, therefore
I have removed that part.

The padding can be done by printing an empty string
with a field width:

    printf("%*.s", 3*(16 - (int)bytesRead), "");

The remaining part of the main loop is OK, only that I would
generally use more space, at least around parentheses and keywords:

    for (int j = 0; j < bytesRead; j++) {
        if (line[j] > 31 && line[j] < 127) {
            printf("%c", line[j]);
        } else {
            printf(".");
        }
    }
    printf("\n");
}


A few small points:

public class HashTable<T, TU>

Use more mnemonic names, like TKey, TValue here.

public class HashTable<T, TU>

The name indicates how the class is implemented; name it after what it does logically. This is a map, or a dictionary, or a key-value store, or whatever you want to call it.  That it is a hash table is a mechanism; name classes after their semantics.

public class HashTable<T, TU>

I would expect a map to implement appropriate generic interfaces IDictionary, IEnumerable, ICollection, and so on.

private int _fillFactor = 3;

Why 3? Explain to the reader what is going on here.

_items = new LinkedList<Tuple<T, TU>>[4];

Why 4?

throw new Exception("Duplicate key, cannot insert.");

Throw more specific exceptions.

        if (_items[pos] == null)
        {
            _items[pos] = new LinkedList<Tuple<T, TU>>();
        }
        if (_items[pos].Any(x=>x.Item1.Equals(key)))
        {

That could be an else if.

        if (NeedToGrow())
        {
            GrowAndReHash();
        }

You never call NeedToGrow and GrowAndRehash separately, which indicates to me that they are the same thing. You could make one method called GrowAndRehashIfNecessary().

public TU Get(T key)
public void Add(T key, TU value)

You might also implement an indexer.

var newItems = new LinkedList<Tuple<T, TU>>[_items.Length * 2];

The number of array slots will always be a power of two, and therefore you are taking the bottom n bits of the hash as your hash key.  Depending on how the data is distributed and the quality of the hash codes given to you, that might lead to a fair number of collisions. You'd want to try this out on real data and see how it goes.

public void Add(T key, TU value)
public void Remove(T key)

Add resizes and rehashes if the table gets too full, but Remove does not resize and rehash if the table gets too empty. Apparently you have made the implicit and undocumented design decision that many adds are more likely than many removes, and that in the case where many removes happen, it is OK to waste memory.  Was that decision intentional, or an accident?

Finally, consider studying the implementation of the Dictionary type; the .NET sources are available and the dictionary hash table implementation is entertaining reading. You get a sense of how feature-complete and robust these things really have to be to be a workhorse of the base class libraries.


Your code doesn't run as written. It needs a function definition.
Your design needs work. Suppose the current page is 30 and the list of pages says "... 20 [30] 40 ..." as in your example. How do I get to page 29 or page 31? It doesn't look as if these page numbers will ever appear in the list.

The more usual design is to always show a small number of pages at the beginning and end, and a small number of pages adjacent to the current page. So that the list of pages would look more like "1 2 3 ... 28 29 [30] 31 32 ... 78 79 80".
The expression

int(float(count_all+(items_on_page-1))/float(items_on_page))

is unnecessarily complex. You can use Python's floor division operator (//) to achieve the same thing without converting to floats and back again:

(count_all + items_on_page - 1) // items_on_page

Your variables are poorly and unsystematically named. count_all, for example. All what? Or countpagesstr, which sounds like it might be a string, but is in fact a list. You use underscores in some cases (count_all) but not in others (countpages).
It is easiest conceptually to separate the two steps of deciding which page numbers to show and showing them in order with ellipses.

In the code below I build the set of the page numbers from the first three pages, the five pages around the current page, and the last three pages. I use Python's sets so that I can take this union without having to worry about duplicate page numbers.

def abbreviated_pages(n, page):
    """
    Return a string containing the list of numbers from 1 to `n`, with
    `page` indicated, and abbreviated with ellipses if too long.

    >>> abbreviated_pages(5, 3)
    '1 2 [3] 4 5'
    >>> abbreviated_pages(10, 10)
    '1 2 3 4 5 6 7 8 9 [10]'
    >>> abbreviated_pages(20, 1)
    '[1] 2 3 ... 18 19 20'
    >>> abbreviated_pages(80, 30)
    '1 2 3 ... 28 29 [30] 31 32 ... 78 79 80'
    """
    assert(0 < n)
    assert(0 < page <= n)

    # Build set of pages to display
    if n <= 10:
        pages = set(range(1, n + 1))
    else:
        pages = (set(range(1, 4))
                 | set(range(max(1, page - 2), min(page + 3, n + 1)))
                 | set(range(n - 2, n + 1)))

    # Display pages in order with ellipses
    def display():
        last_page = 0
        for p in sorted(pages):
            if p != last_page + 1: yield '...'
            yield ('[{0}]' if p == page else '{0}').format(p)
            last_page = p

    return ' '.join(display())


What you have there is actually just a fancy assignment operation. The closure there plays no role. And if you would need to set another placemark, you would have to repeat the code or wrap in one more function.

IMHO, it would be much more pragmatic to use a lot simpler approach:

var createPlacemark = function (point, placemark) {
        point.setLatitude(100);
        point.setLongitude(-100);
        placemark.setGeometry(point);
        return placemark;
    },
    myPlacemark = createPlacemark(ge.createPoint(''), ge.createPlacemark(''));

This way you get reusable routine with a clear name. And if goal of this all was to prevent external sources from adding placemarks, just warp it all in the standard:

(function () {

}());

The bottom line is: you were over-thinking it.


Nice initiative on a lightweight MVC framework!

Note wanted to add more reference links, but it won't allow me to do more thanb 2

Config

Pass the default controller setting to the function

or

Pass all routing related settings to the __constructor. and use them as class attributes

Loader class

The setup isn't all that bad. Nice and lightweight. A few things, i would do different;

Seperations of conserns (One of the SOLID principles). Let the loader just load an return the instances.

Don't bind the loaded elements directly to controller in you class, so in future you could also use it for different cases then just the controller class.
Don't render the views in a loader. Make a render class or such. If you way of rendering changes, you would have to change the loader. Which ultimately don't make sense.

Make APP_PATH and LIBRARY settable within the loader, and call them differently

A loader class attribute for each load path
Default the attributes to APP_PATH and LIBRARY
Getter and Setter for load paths
Now you would be able to integrate different paths / modules etc. Making it more flexible

Autoloader for library classes

By registering the loader as php autoloader you can just instantiate a class.
If not yet loaded into mem, it will be sent to the autoloader.
There you resolve the path it should be on and instantiate.

Security

The big thing in this form of autoloading is the concern for input. Make sure all input is either given by the application itself or validate it.

Validate user strings that will be autoloaded (eg. controller names)
You can do this by first doing a realpath() check on the computed path. And make sure the realpath() is within the locations you would expect.
This prevenst users from entering stuff like '......\uploads\mayhackscript' which would be executed otherwise.

This is a real danger.

General remarks

Take a look at te following;

SOLID principles
PSR-2 coding standards; note, it extends PSR-1 which extends PSR-0

Good luck on your project!


The user inputs are the gross income and number of dependents. The program calculates the income tax based on the inputs and the tax law

Only import what you need from java util not the whole package.
Move constants to member level and make static, or pass in these parameters to your program.
Use a money package for calculations involving money.


Searching purchase records, with or without a vendor criterion

The simplest refactor would be:

# this is the base query
requests = PurchaseRequest.includes(:purchase_order)
             .where(:created_at => @date_start..@date_end)
             .where(:total_cost => @cost_beginning..@cost_end)

# then we add additional conditions if required
requests =
  unless @vendor == "0" # if vendor, get specific purchase request
    request.where("purchaseorder.VendorRef_ListID = ?", @vendor)
  end

If you find that you do certain queries often, the it's probably a chance to use scopes.  You may already know about scopes, but if not, check out Mastering ActiveRecord and Arel.

class PurchaseRequest < ActiveRecord::Base
  has_one :purchase_order

  # requests within a certain data
  scope :date_between, ->(date_range) {
    where(:created_at => date_range)
  }

  # requests with a certain cost range
  scope :cost_between, ->(date_range) {
    where(:total_cost => date_range)
  }

  # find request for a specific vendor
  scope :for_vendor, ->(vendor) {
    # this scope does an inner join to purchase_order and adds
    # a condition that the PurchaseOrder must belong to a specific
    # vendor.  That is, only requests matching the vendor are returned
    joins(:purchase_order).merge( PurchaseOrder.for_vendor(vendor) )
  }
end

class PurchaseOrder < ActiveRecord::Base
  # purchase orders belonging to a specific vendor
  scope :for_vendor, ->(vendor) {
    where(:VendorRef_ListID => vendor)
  }
end

So with scopes added, you can now refactor your code like so:

# this is the base query
requests = PurchaseRequest.includes(:purchase_order)
             .date_between(@date_start..@date_end)
             .cost_between(@cost_beginning..@cost_end)

# if vendor, get specific request
requests = request.for_vendor(@vendor) unless @vendor == "0"


Three identical AJAX button handlers in three views

I was able to get rid of the duplicate code by using event delegation.  I changed my event listener to:

$('#taglist').on('click', '.remove-tag-button', function () {
    $.ajax({
      type: "POST",
      data: {id: <%= @item.id %>, tag: $(this).data("tag-name")},
      url: "/remove_tag"
    });
  });


Given the nature of the snippet, I'll just overlook the fact that you're using inline JS on your elements, and your script is entirely in the global namespace. Normally I'd recommend using something like addEventListener for your click events, and enclose your code in an IIFE.

Now to get that big elephant in the room, timers in JS are inaccurate. The delay in timers only guarantee minimum time until execution, but not exact time of execution. Your time will drift. What I would suggest is to take the time during page load. Then on set intervals, you get the current time, subtract the current time from the start time to get the time elapsed, and from that, compute your hours, minutes and seconds.

Now for the rendering, it doesn't matter how often you actually print to the page as long as you are using the time elapsed. Also, I would suggest putting the reference to the DOM element in a variable outside the interval. That way, you won't be fetching the element from the DOM every time (which is slow).

Your padding logic is also repeated. You could just put that in a function and call it when needed. You can use slice with a negative index to slice from the right. Also, since we're operating in milliseconds (because of Date.now()), and there's some division, your numbers will have decimals. To eliminate them, you can use | 0 to clip them off. It's somewhat the same as Math.floor.

Given that review, your code should look something like:

var startTime = Date.now();
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var container = document.getElementById('timer');

function stopTimer() {
    clearInterval(timer);
}

function pad(n){
  return ('00' + n).slice(-2);
}

var timer = setInterval(function(){
  var currentTime = Date.now();
  var difference = currentTime - startTime;

  var hours = pad((difference / hour) | 0);
  var minutes = pad(((difference % hour) / minute) | 0);
  var seconds = pad(((difference % minute) / second) | 0);

  container.innerHTML = hours + ':' + minutes + ':' + seconds;

// This only represents time between renders. Actual time rendered is based
// on the elapsed time calculated above.
}, 250);

<button type="button" onclick="stopTimer()">Stop</button>


Fast counting of interactions between groups given users interactions and groups assignments

Re-formulating the problem into a matrix multiplication one speeds up the algorithm very much.

Algebra:

Create a matrix G of n_groups x n_users such that every column is a group mask, that is, all users (columns) that belong to that group (row) are flagged are 1 and 0 otherwise. If Y is the matrix of interactions, then the interactions between every pair of groups can be obtained by the following equation:

$$I = GYG^T$$

Code:

The code is:

import numpy as np
from numpy import dot

def test3(y, c):

    N = len(c)
    C = len(set(c))
    noty = np.mod(y+1,2)

    # create C group masks of 1 (if user is belongs to group) and 0.
    G = np.zeros((C,N))
    for group in range(C):
        G[group] = [1 if c_== group else 0 for c_ in c]

    # Groups (src) * interaction_matrix * Groups_transposed (dst)
    # Every row of Groups matrix is the mask of a group
    return dot(dot(G,y),G.T), dot(dot(G,noty),G.T)

1000 loops, best of 3: 810 µs per loop


OK, after reading you're using a struct because maps use more memory, and that you posted this question here because you're new to go, let's dive in to this a bit more.
Do maps use more memory
The short answer is yes. However, things are a bit more complex than that. In essence, a map is a hash table, so of course, a map of type map[string]int will internally store all the strings, the buckets, hashes, data tables, etc... Whereas a struct is just a block of memory where fields point to an offset within that memory, it's pretty much the most efficient way to group values.
That said, while a map with 5 keys does use more memory than a struct with 5 fields of type int, the difference on modern systems is quite negligible. There are a number of other factors to consider when it comes to choosing the type.
Runtime memory management
Once again, this may seem like a point where maps look like a terrible option, but it's just some background so you understand how maps, WRT memory management, work. Consider this:
foo := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
}

What happens here is that the runtime will allocate memory to hold the three strings, and the three values. The strings are passed through a hashing function, all memory required to store this map, the hashes, and its three values is allocated and assigned. Easy. Now compare this to:
bar := map[string]int{}
// some code
bar["one"] = 1
// more core
bar["two"] = 2
// etc...
bar["three"] = 3

In this scenario, the runtime creates an empty map and assigns it to bar. Some memory is allocated for the internal structures the map needs, but each time we assign a new key, the memory required to store the data for this map grows, and the runtime potentially has to reallocate memory, move stuff around, etc... this definitely is less efficient. We can, however, initialise a map with a certain size. I often do this if I know the map I'm populating will eventually hold at least 10, and at most 15 values. I'll just use make and specify the max size:
foobar := make(map[string]int, 3) // guarantees no realloc while adding the first 3 values

Another area where maps put some added strain on the runtime is when it comes to garbage collection. Remember: we need to allocate memory for the value, hash/buckets (map internals), and key, so doing something like:
delete(foo, "two")

affects 3 objects the runtime is having to manage. That's the reality of maps. The go implementation is fairly optimised, but if you run a heavy application that were to rely solely on maps, your pprof data after a while might show that the runtime is spending a lot of time on its GC cycles as a result.
The latter is not really something you should be taken into consideration when comparing maps to structs, however. Structs don't support deleting fields to begin with. I just mentioned this for completeness sake. While it looks like a downside, you could equally argue that having the ability to delete keys from a map is a feature you might want to have. Indeed, sometimes you need to be able to do that.
Restrictions of a Struct
So far, we've established structs are more memory efficient, generally easier on the GC cycles (discounting nested structs, interfaces, embedding, etc...). They do have their limitations, however. The thing discussed earlier about memory management (adding more keys to a map causing reallocation) aren't an issue here. The memory is allocated all at once, and is nicely padded. On the flip side: the memory is allocated all at once. Even if I only were to need one field, a struct is an all or nothing type.
Dynamic access
Maps can use strings, ints, and really any comparable type. A struct has fields. This means the data contained stored in a map is a lot easier to access dynamically:
// given foo from earlier
func get(k string) (int, error) {
    v, ok := foo[k]
    if !ok {
        return 0, fmt.Errorf("key '%s' not found", k)
    }
    return v, nil
}

Whereas using a string to fetch the field of a struct requires a lot more code. The easiest way would be a receiver function on the struct type (method)
// assuming the chrinfo type from your code
func (c chrinfo) get(k string) (int, error) {
    switch k {
    case "Size0_50", "size0_50": // accounting for capitalisation
        return c.Size0_50, nil
    case "Size50_100", "size50_100":
        return c.Size50_100, nil
    case "Size100_1000", "size100_1000":
        return c.Size100_1000, nil
    case "Size1000_10000", "size1000_10000":
        return c.Size1000_10000, nil
    case "Size10000", "size10000":
        return c.Size10000, nil
    }
    return 0, fmt.Errorf("field '%s' doesn't exist", k)
}

This function will need to be updated for each field you add, and although capitalisation is something you may want to take into account, it's cumbersome. Typo's can lead to vague bug reports that cost hours to replicate, only to conclude there was no bug in the code you were looking at, but the person filing the issue didn't bother to check whether or not their input was correct...
Reflection
So obviously, one may conclude that using reflection at least takes away the burden of having to maintain this type of getter function. However, let's circle back to your original reason for not using a map: memory consumption.
Compared to the runtime cost reflection incurs, the memory overhead of a map is laughable. It's akin to hopping on a plane to the arctic to cool a can of coke, instead of using an ice-cube, because using a freezer to freeze ice is wasting electricity, all the while burning literally tons of kerosine to fly your beverage around the globe instead.
Reflection is crazy expensive. It uses a hell of a lot of CPU cycles, and if you look into the source code every time you access something through reflection, you'll allocate the reflect types, like the reflect.Value type, which contains a reflect.rtype. These are just 2 structs you're allocating just to get access to a single field:
type Value struct {
    // typ holds the type of the value represented by a Value.
    typ *rtype

    // Pointer-valued data or, if flagIndir is set, pointer to data.
    // Valid when either flagIndir is set or typ.pointers() is true.
    ptr unsafe.Pointer

    // flag holds metadata about the value.
    // The lowest bits are flag bits:
    //  - flagStickyRO: obtained via unexported not embedded field, so read-only
    //  - flagEmbedRO: obtained via unexported embedded field, so read-only
    //  - flagIndir: val holds a pointer to the data
    //  - flagAddr: v.CanAddr is true (implies flagIndir)
    //  - flagMethod: v is a method value.
    // The next five bits give the Kind of the value.
    // This repeats typ.Kind() except for method values.
    // The remaining 23+ bits give a method number for method values.
    // If flag.kind() != Func, code can assume that flagMethod is unset.
    // If ifaceIndir(typ), code can assume that flagIndir is set.
    flag

    // A method value represents a curried method invocation
    // like r.Read for some receiver r. The typ+val+flag bits describe
    // the receiver r, but the flag's Kind bits say Func (methods are
    // functions), and the top bits of the flag give the method number
    // in r's type's method table.
}

type rtype struct {
    size       uintptr
    ptrdata    uintptr // number of bytes in the type that can contain pointers
    hash       uint32  // hash of type; avoids computation in hash tables
    tflag      tflag   // extra type information flags
    align      uint8   // alignment of variable with this type
    fieldAlign uint8   // alignment of struct field with this type
    kind       uint8   // enumeration for C
    // function for comparing objects of this type
    // (ptr to object A, ptr to object B) -> ==?
    equal     func(unsafe.Pointer, unsafe.Pointer) bool
    gcdata    *byte   // garbage collection data
    str       nameOff // string form
    ptrToThis typeOff // type for pointer to this type, may be zero
}

I'm not going to walk through the entirety of the reflect package, although you may want to take some time to do that yourself, just to see what using reflection actually implies. For now, let me assure you this:
Using reflection uses tons of CPU cycles and memory

So the question you had was: is there a better way? I'd say the answer to that is a resounding yes. A map will do just fine, in fact. The slightly higher memory consumption is nothing compared to the overhead you're creating using reflection.
I touched on tags in my comment, which is something you can look into, but I wouldn't recommend it for this particular use-case (seeing as tags require reflection, too). You could use the combination of a map/struct as a field lookup table, like the one I mentioned. Assuming these calls don't happen concurrently, you can create a map statically (as in: as a field of a type, or a global variable if there is no other option), and do something like this:
var (
    mychr  crinfo          // your struct
    lookup map[string]*int // lookup map
)

func init() {
    lookup = map[string]*int{
        "Size0_50":       &mych.Size0_50,
        "Size50_100":     &mych.Size50_100,
        "Size100_1000":   &mych.Size100_1000,
        "Size1000_10000": &mych.Size1000_10000,
        "Size10000":      &mych.Size10000,
    }
}

Then, to increment the corresponding field, it's quite simple:
func inc(k string) {
    if ptr, ok := lookup[k]; ok {
        *ptr += 1
    }
}

The map contains pointers to each corresponding field, if the field exists, we increment its value. Job done.


Python3 conditionally moving files and string formatting

Since this looks like a script that might get onto some production server at some point, I'm going to give some recommendations from that point of view and how I'd do it if I were to implement this for my employer.
In this review I'll mostly focus on the project structure, requests, exceptions and credentials management. I'll first paste the code that I came up with and then I'm going to explain in detail why did I do most of the changes.
# config.py

from getpass import getpass
import time

TIMESTAMP_SRC = time.strftime("%Y%m%d")
TIMESTAMP_DST = time.strftime("%Y%m%d-%H:%M:%S")

DST = "/home/user2/script_logs/"
SRC = "/home/user2/.working_scripts/hpe_out/"
FILE_NAME = "hpeCriticalAlert"
OUTFILE = f"{SRC}/{FILE_NAME}.{TIMESTAMP_SRC}.csv"

BASE_URL = "https://synergy.example.com/rest"
USERNAME = "administrator"
PASSWORD = getpass("Input your password: ")

# EMAIL CONFIG
SMTP_SERVER = 'smtp.example.com'

FROM = 'hpe-dashboard@example.com'
TO = ['user1@example.com', 'user2@example.com']
SUBJECT = 'HTML OneView'

EMAIL_TEMPLATE = """\

     Dear Team,

     Please Find the Report!

     {}

    Kind regards.

    Synergy Global Dashboard.

"""

# main.py

import os
import shutil
import smtplib
from email.message import EmailMessage

import pandas as pd

pd.set_option('expand_frame_repr', True)
import requests

from .config import (
    BASE_URL,
    DST,
    OUTFILE,
    PASSWORD,
    SRC,
    TIMESTAMP_DST,
    USERNAME,
    SUBJECT,
    FROM,
    TO,
    EMAIL_TEMPLATE,
    SMTP_SERVER,
)

class FileMoveFailure(Exception):
    pass

class SynergyRequestFailure(Exception):
    pass

class SessionIdRetrievalFailure(SynergyRequestFailure):
    pass

class ResourceAlertsRetrievalFailure(SynergyRequestFailure):
    pass

def move_csv_files():
    for csv_file in os.listdir(SRC):
        if csv_file.endswith(".csv") and os.path.isfile(os.path.join(SRC, csv_file)):
            try:
                shutil.move(
                    os.path.join(f"{SRC}/{csv_file}"),
                    f"{DST}/{csv_file}-{TIMESTAMP_DST}.log"
                )
            except OSError as os_error:
                raise FileMoveFailure(
                    f'Moving file {csv_file} has failed: {os_error}'
                )

def get_session_id(session):
    try:
        response = session.post(
            url=f"{BASE_URL}/login-sessions",
            headers={
                "accept": "application/json",
                "content-type": "application/json",
                "x-api-version": "120",
            },
            json={
                "userName": USERNAME,
                "password": PASSWORD
            },
            verify=False
        )
    except requests.exceptions.RequestException as req_exception:
        # you should also get this logged somewhere, or at least
        # printed depending on your use case
        raise SessionIdRetrievalFailure(
            f"Could not get session id: {req_exception}"
        )

    json_response = response.json()
    if not json_response.get("sessionID"):
        # always assume the worse and do sanity checks & validations
        # on fetched data
        raise KeyError("Could not fetch session id")

    return json_response["sessionID"]

def get_resource_alerts_response(session, session_id):
    try:
        return session.get(
            url=f"{BASE_URL}/resource-alerts",
            headers={
                "accept": "application/json",
                "content-type": "text/csv",
                "x-api-version": "2",
                "auth": session_id,
            },
            verify=False,
            stream=True
        )
    except requests.exceptions.RequestException as req_exception:
        # you should also get this logged somewhere, or at least
        # printed depending on your use case
        raise ResourceAlertsRetrievalFailure(
            f"Could not fetch resource alerts: {req_exception}"
        )

def resource_alerts_to_df(resource_alerts_response):
    with open(OUTFILE, 'wb') as f:
        for chunk in resource_alerts_response.iter_content(chunk_size=1024):
            f.write(chunk)
    return pd.read_csv(OUTFILE)

def send_email(df):
    server = smtplib.SMTP(SMTP_SERVER)
    msg = EmailMessage()

    msg['Subject'], msg['From'], msg['To'] = SUBJECT, FROM, TO
    msg.set_content("Text version of your html template")
    msg.add_alternative(
        EMAIL_TEMPLATE.format(df.to_html(index=False)),
        subtype='html'
    )

    server.send_message(msg)

def main():
    move_csv_files()

    session = requests.Session()
    session_id = get_session_id(session)

    resource_alerts_response = get_resource_alerts_response(session, session_id)
    df = resource_alerts_to_df(resource_alerts_response)

    send_email(df)

if __name__ == '__main__':
    main()

config.py
The first major thing that I did was to split apart the configuration data from the main script. This will make your life easier when it comes to modifying the values since they're altogether.
Another very important and sensitive thing to notice is the PASSWORD field. Do NOT, EVER, expose credentials in plain text. There are so many cases where this happened at big companies and resulted in loss of millions of $$ due to hackers exploiting this...
There are multiple ways of avoiding this. None is perfect but it's definitely better than storing passwords in plain-text:

Ask for user's input;
Store them as ENV VARIABLES;
Use some secrets management tool like Ansible Vault

This config file doesn't necessarily have to be a .py file. It can be a yaml, ini, .env, json file. I made it like this for convenience.
main.py
Honestly, when I first saw your script, I remembered how I used to write code when I started programming. It's messy, you understand it at the moment of writing and it kinda does the job you need. But when it comes to maintaining it, it's really, really tedious and frustrating: all those useless comments, unused imports, no spacing, nothing... You wouldn't even know where to start next time you have to add some new feature. Because of this you'd probably need to completely rewrite it.
Improvements brought by my implementation:

code is definitely easier to read and understand, even if I haven't added any docstrings.
it's a lot easier to modify any part of the code since it's now broken into smaller pieces. You can read more about the SRP principle here. I honestly could've done better on this one but for a first review, it'll do.

What is still to be improved (by you)

add some logging
add docstrings / type hints
chose better names for your variables (SRC, DST and so on aren't to descriptive)
create tests to ensure your code works (I haven't really tested my implementation but it should give you an overall idea)

1. Imports
As you can see I don't have any unused imports and it's really easy to recognise stdlib modules, 3rd party modules and local modules because of the grouping:
# stdlib
import os
import shutil
import smtplib
from email.message import EmailMessage

# 3rd party modules
import pandas as pd

pd.set_option('expand_frame_repr', True)
import requests

# local config
from .config import (
    BASE_URL,
    DST,
    OUTFILE,
    PASSWORD,
    SRC,
    TIMESTAMP_DST,
    USERNAME,
    SUBJECT,
    FROM,
    TO,
    EMAIL_TEMPLATE,
    SMTP_SERVER,
)

2. Exceptions
I've seen people creating a new exceptions.py file where they create custom exceptions for different use-cases. I just let them in main.py. Having your own subclasses lets you treat distinct exception cases separately. (such as the difference between not having permissions to run a report, and the report execution failing).
3. CSV files
Since you only want to move the .csv files to a specific location it's not necessary to build a list and iterate against it again to move each file. Instead, do it in one run and also raise an exception if something happens:
4. Requests
It's always a good practice to catch any specific exception that might be raised. I've only handled the generic RequestException which is going to catch any request exception but you might want to treat some exceptions separately: Connection errors, timeout errors, etc.
Also, always make sure the data you receive is what you expect. I've seen cases where certain APIs where changed by some provider without announcing us (the developers) or without stating in their documentation otherwise. This usually breaks everything and takes some time figuring out what the root cause is.
5. Others
I think the rest of it is pretty straight forward. I'm not saying my solution is perfect but it's a better starting point.
Enjoy! :)


More concise and/or idiomatic max subarray in Clojure?

Great answer from Jean Niklas L'Orange on the Clojure Google Group:

(defn max-subarray [A]
   (let [pos+ (fn [sum x] (if (neg? sum) x (+ sum x)))
         ending-heres (reductions pos+ 0 A)]
     (reduce max ending-heres)))


How to replace the given email address with a value in a given input?

Performance wise using string concatination (output += ) inside a loop isn't the best choice because for each output +=  a new string is created because strings are immutable. Using a StringBuilder would be the way to go. But instead of returning a string, you could return an IEnumerable<string> which would make the code more flexible.

Passing an IEnumerable<string> as method parameter holding the not wanted domains will make the code open for needed changes.

Passing an IEnumerable<string> as method parameter holding the tokens would enable the method to only do one thing.

Because the method is public you should have proper parameter validation.

Using a little bit of Linq would compact the code a lot.

Instead of hardcoding "SOMETEXT" you could pass an optional parameter.

Implementing the mentioned changes using string as return-type would lead to
public static string RemovePersonalInfo(string input)
{
    if (input == null) { throw new NullReferenceException(nameof(input)); }
    if (string.IsNullOrWhiteSpace(input)) { return input; }

    return RemovePersonalInfo(input.Split(new char[] { ' ', '\t', '\r', '\n' }), new string[] { "@gmail.com", "@yahoo.com" });

}
private static string RemovePersonalInfo(IEnumerable<string> tokens, IEnumerable<string> domains, string replacement = "SOMETEXT")
{
    return string.Join(" ", tokens.Select(token => (domains.Any(domain => token.Contains(domain)) ? replacement : token)));
}

and could be called like before.


I like that you use an immutable map.  However I don't like the name map: you should give it a more descriptive name and it should be capitalized since it is a constant.  You should also declare the type of map as LinkedHashMap: it is important here since you do use the ordering property.  You can define map as private static final Map<String, Integer> map = new LinkedHashMap<String, Integer>() {{ this.put(x, y); ... }}.

Your api should probably return an error on invalid roman numeral instead of: // calling representationOf() makes sure that "IIIII" becomes "V".

In method of (string to int), I think you don't have to use a StringBuilder and to invert it.  You can easily modify your algorithm to work forward and just use toCharArray.  You could use the Java 8 "functional" (Stream) features here instead of a for-loop.  I like functional programming since it makes for shorter and more readable code, but they really messed things up in Java 8 and I couldn't find an easy solution.  I could do it in Scala, but in Java 8 it would end up being longer than your code and completely unreadable.


Helper method to find VisualChildren of multiple Types

SRP

Your current soulution violates the Single Responsibility Principle because it does two things:

it enumerates all children and
it checks if a child is of the specified type

This can and should be splitted into two methods that you can implements as  extensions.

The Children extension will only know how to get all children, nothing more. This means I removed the type checking and I reduced nesting by inverting the first condition.

public static IEnumerable<UIElement> Children(this DependencyObject dependencyObj)
{
    if (dependencyObj == null)
    {
        yield break;
    }

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObj); i++)
    {
        var child = VisualTreeHelper.GetChild(dependencyObj, i);
        if (child != null)
        {
            yield return child as UIElement;
        }

        foreach (var childOfChild in child.Children())
        {
            yield return childOfChild;
        }
    }
}

The second extension OfTypes will be your filter. Here I changed the order of the parameters and decorated the last one with params which will allow you to easier specify the types without having to create an extra list for them.

public static IEnumerable<UIElement> OfTypes(this IEnumerable<UIElement> uiElements, params Type[] types)
{
    return uiElements.Where(x => types.Contains(x.GetType()));
}

Example:

var result = currentView.Children().OfTypes(
    typeof(CheckBox),
    typeof(RadioButton),
    typeof(TextBox)
);

The separation of those two concerns allows you to reuse the Children extension for other purposes should you need it somewhere else.

FindVisualChildrenOfMultipleTypes

By using extensions like the two I've just suggested, you can get rid of the very long method name because you splitted it in multiple parts.


Counting rows in a CSV file that correspond to a database row, each with a million records

Your inner loop appears to be unnecessary. Why not create a lookup:

var knownAccountNumbers = new HashSet<string>(
    dataStructure.Tables["AccountData"].Rows
        .Cast<DataRow>()
        .Select(row => row[0].ToString()));

Now your loop is simply:

foreach (DataRow row in dt.Rows)
{
    var accountNumber = row[0].ToString().Replace("\"", "");
    row[12] = knownAccountNumbers.Contains(accountNumber) ? "Y" : "N";
}

I think I remember reading once that the memory usage of a HashSet is 12 bytes per entry + size of the entry. So you're looking at 12MB + 1,000,000 * (2 * accountNumber.Length). So basically nothing in the grand scheme of things. However, you are gaining constant time lookups which should be a huge benefit to this kind of work.

You should take more care when naming things. Don't abbreviate e.g. acctNum -> accountNumber.


Best practice instantiating generic delegates and accessing property getters

As my answer on Stack Overflow states, there is a solution which allows you to create a getter delegate for any type, so the entire switch block can be dropped. Personally, I find that the cleanest solution. The only overhead of this approach is the cast from object to the specific type where necessary. (For a getter this would happen only once on the return value.) I'm guessing if you would benchmark this, the result would be negligible.

When you are certain that the only types required are those specified, or that no new types are expected very often, you could still opt to use your current approach. I would apply a few changes however:

Use PropertyInfo.GetGetMethod() to retrieve your MethodInfo for the getter.
Use the type of PropertyType directly to determine which CreatePropertyGetter to call instead of the name of the type.
Use Func<K, T> instead of MyMethod.
Use a Dictionary holding anonymous functions which create the correct delegate for the specified type of the key. This can replace the switch statement.

The last point is possible as follows:

Dictionary<Type, Func<PropertyInfo, object>> getterCreators =
    new Dictionary<Type, Func<PropertyInfo, object>>
    {
        { typeof(string), p => CreatePropertyGetter<T, string>(p) },
        { typeof(DateTime), p => CreatePropertyGetter<T, DateTime>(p) },
        { typeof(decimal), p => CreatePropertyGetter<T, decimal>(p) }
    };

Ofcourse you still have to cast from object to the desired type.

UPDATE:

As Timwi pointed out in the comments, p => CreatePropertyGetter<T, ...>(p) can be further reduced to: CreatePropertyGetter<T, ...>.


Converting a list to an array when list has quotes and embedded comma

I could get rid of your startQuote variable, I reduced the number of i CONTAINS '"' comparasions by 1.

array function convertRow(required string lstRow) {
    var arResult = [];
    var arTemp = ListToArray(arguments.lstRow, ',', true);
    var quoteMode = false;

    for (var i in arTemp) {
        var containsQuote = i CONTAINS '"';
        if (containsQuote && not quoteMode) {
            ArrayAppend(arResult, replace(i, '"', ''));
            quoteMode = true;
        }
        else if (quoteMode){
            arResult[ArrayLen(arResult)] &= "," & replace(i, '"', '');
            quoteMode = not containsQuote;
        }
        else{
            ArrayAppend(arResult, i);
        }
    }

    writedump(lstRow);
    writedump(arResult);

    return arResult;
}


Python text based game room to room movement

Overall I don't think the code is that bad, considering what is the purpose; but if you want to expand your game I think the greatest issue is the data structure.
It'd be very easy to misplace some room or call it in a different way if you have to repeat yourself every time, so I suggest you to use a class to represent a Room:
class Room:
    name: str
    north: 'Room'
    east: 'Room'
    south: 'Room'
    west: 'Room'

    def __init__(self, name, north=None, east=None, south=None, west=None):
        self.name = name
        self.north = north
        self.east = east
        self.west = west
        self.south = south

        if north:
            north.south = self
        if east:
            east.west = self
        if south:
            south.north = self
        if west:
            west.east = self

    def go_to(self, direction):
        if direction in ['north','east','south','west']:
            return getattr(self, direction)
        else:
            return None

    def __str__(self):
        return self.name

I'm using types because is very helpful to find out problems before it's too late, in Python if you have a recursive type (like Room) you need to use the quotes, but it just a syntactic notation.
By default a room does not have any north,east,south,west Room (hence the =None) but the important thing that happens in the __init__ is that when you add a room it automatically set the opposite direction. So if a room goes to another by east, the other room does the opposite by west. Thus we are reducing errors in directions. If this will not be the case for some room, you will be able to override that using another class (SelfLockingRoom that closes all the other directions when you enter, for example).
The __str__ method is just to handle the display of the room to the room itself; at one point you could have more than just the name to display.
I'm adding also a go_to method, it is the room responsibility to decide where to go given the direction; in the future you could have a TrapRoom that extends Room and in case of direction "East" will do nasty things, for example. The getattr is just to avoid having to write if direction=='north': return self.north but it would be the same and maybe even clearer.
Actually, if the game develops further, you may need more complex rules to decide what do to given a direction so probably you will need a House class:
class House:
    current_room: Room
    rooms: list[Room]  # at the moment is not used but could be in the future?

    def __init__(self, current_room: Room, rooms: list[Room]):
        self.current_room = current_room
        self.rooms = rooms

    def go_to(self, direction):
        if next_room := self.current_room.go_to(direction):
            self.current_room = next_room
        return next_room

At the moment is not very useful, but I think it's going to be.
To initialize the house you just create the rooms:
house_rooms = [cellar := Room('Cellar'), library := Room('Library'), dining_room := Room('Dining Room'),
               gallery := Room('Gallery'), bedroom := Room('Bedroom', east=cellar),
               dungeon := Room('Dungeon', east=gallery),
               kitchen := Room('Kitchen', north=dining_room),
               great_hall := Room('Great Hall', south=bedroom, north=dungeon, west=library, east=kitchen)]

house = House(current_room=great_hall, rooms=house_rooms)

(As you can see I'm not repeating names or directions)
The game loop is OK, we can collect some helpful methods, just in case you want to expand them in the future:
def prompt(text: str):
    print(text)

def ask(text: str) -> str:
    return input(text).strip()

and this would be your game loop (I'm always lowering the direction so you can write East east or EAST).
commands = {
    "directions": ['north', 'south', 'east', 'west'],
    "quit": ['q', 'quit']
}

def game_loop():
    prompt(f"\nYou are in the {house.current_room}")
    command = ask('\nWhat direction do you want to go? ').lower()
    if command in commands["directions"]:
        if not house.go_to(command):
            prompt("You can't go that way.")
    elif command in commands["quit"]:
        return False
    else:
        prompt("I don't understand that command.")
    return True

if __name__ == '__main__':
    while game_loop():
        pass


In this case, you take an action depending on class type of bean, so I would recommend you to implement a Visitor Pattern, because it is not god practice to use instanceof and because Visitor Pattern lets you growth your code without coupling.

My answer is more complex than previous, but it will give you more flexibility. What if you want to do more things than setNameForEntity? or what if you wnat to implement more concrete classes? Visitor Pattern will suite this needs.

Now, here comes how I would do the refactor. First, create an abstract class (or an interface) as base class for beans, like AgentPostResponseBean and ImportAgentPostResponseBean. This base class have a method accept(Visitor visitor).

public abstract class AbstractResponseBean{
    public abstract void accept(Visitor visitor, AccountEntity entity);
}

If your ResponseBeans already inherit from an existing abstract class or they implement an existing interface, simply add the accept method to that class/interface.

Then, implement visit method on each concrete class, as follows

public void accept(Visitor visitor, AccountEntity entity){
    visitor.visit(this, entity);
}

Finally, create a Visitor class, that accept the visit of each concrete ResponseBeans class you are interested in. For example:

public class Visitor{

    private String getFillName(AccountEntity entity){
        String chineseName = entity.getChineseName();
        String firstName = entity.getFirstName();
        return StringUtils.isBlank(chineseName) ? firstName : chineseName;
    }

    public void visit(AgentPostResponseBean respBean, AccountEntity entity){

        if (StringUtils.equals(respBean.getParentId(), entityId)) {
            respBean.setParentName(getFillName);
        }
        if (StringUtils.equals(respBean.getPosterId(), entityId)) {
            respBean.setPosterName(getFillName);
        }
    }

    public void visit(ImportAgentPostResponseBean respBean, AccountEntity entity){

        if (StringUtils.equals(respBean.getParentId(), entityId)) {
            respBean.setParentName(getFillName);
        }
        if (StringUtils.equals(respBean.getPosterId(), entityId)) {
            respBean.setPosterName(getFillName);
        }
    }
}

Of course, visitor's private method getFillName would be better implemented in AccountEntity. This way, your code will be refactored as follows:

List<AccountEntity> fillNameAccounts = agentDao.getAgentListByIds(accountIdList);
Visitor visitor = //get instance from some factory or singleton or app context ...

for (T bean : results)
{
    for (AccountEntity entity : fillNameAccounts)
    {
        bean.visit(visitor, entity);
    }
}


Printing Colored, CLId Unicode Chess Board - follow-up

This is some nice polished code. I have just a few remarks.

When initializing ELEMENTS, the piece names get pasted in twice.
Perhaps you'd like to loop over them,
adding a black and a white variant to the dict?
You might even associate the proper unicode code point
with each enum member, rather than calling auto().

        [(Color.BLACK, Piece.PAWN) for _ in range(8)],

You have nice helpers everywhere.
Except for the two lines about pawns.
Maybe you'd like a get_pawns(color) function?

Instead of enumerating row and then doing this:

        piece = ELEMENTS.get(piece)

consider running enumerate over map(ELEMENTS.get, row).


The if statement can be reduced to just:

[[ ${#line} >= 8 && ${#line} <= 63 && $((++validLines)) > 0 ]]
    && echo $line >> $outputfile || ((deletedlines++))

We use bash's [[ ... ]] shell keyword to collate our conditions together. Helpfully, [[ ... ]] supports the use of >= and <=.

[[ <something-to-test> ]] && <one-command-if-test-is-true> || <one-command-if-test-is-false> is quite a useful (IMHO!) construct in bash for implementing a if-then-else logic. The only thing to note is that you can only specify one command each for both branches.

As such, we can 'inline' our increment of validLines and do an always true comparison to simplify our if branching, namely to either (&&) output the line to the output file, or (||) increment our deletedLines. Otherwise, it gets slightly longer due to the required use of { ... } compound command:

[[ ${#line} >= 8 && ${#line} <= 63 ]]
    && { ((validLines++)); echo $line >> $outputfile; } || ((deletedlines++))

Now onto the other parts...

fileToClean should be set as fileToClean="$1" in case the filename has spaces inside.
Multi-line echo can be done as such:

[ ! -f "$fileToClean" ] && cat<<M && exit -1

Oh noes,
We have a multi-line error message
Telling user that the file is not a regular file.

M

Your way of checking the elapsed time should be done outside your script, using the time command. time can generate more (and probably more accurate) statistics about the 'performance' of your script and is readily available, hence the suggestion as opposed to manually calculating the value(s) yourself. :)

Now do you really need to do this in bash? Here's an awk one-liner (split into three for readability):

awk '{sub(/^[ ]+/,"");sub(/[ ]+$/,"")};
    length()>=8&&length()<=63{v++;print > "'"$outputfile"'" };
    END{print "Valid lines:",v"\nInvalid lines:",NR-v}' "$fileToClean"

Trim line.
If length matches, count the line and print to "$outputfile".
At the end, print the summary for valid/invalid lines.


As insertion sort is an O(n2) algorithm, there's not much point to optimizing it.  For any input that is large enough for you to care about the performance, you would want to pick a sorting algorithm with better bounds.  Quicksort, for example, is usually closer to O(n log n).

That said, I'll point out some style issues:

You should never omit optional braces, as you've done for the inner for-loop.  Think of it this way: anytime you omit braces, you're a contributing factor to a future coding accident.  (Apple learned this lesson the hard way; their new swift language requires braces.)
Variables can usually be named better than "temp".  Renaming temp to elementToInsert, for example, would make your code self-documenting.


Discarded sums
You calculate these sums:
sum(case when s.type = 'in' then s.quantity else 0 end) as 'in',
sum(case when s.type = 'out' then s.quantity else 0 end) as 'out'

but then reduce them to a 0/1 here:
if(coalesce(x.in - x.out, 0) = 0, 0, 1) as quantity,

This means that a sum is not appropriate at all. This should be refactored to an if exists, where the predicate compares s.type to in/out and checks that s.quantity > 0.


C# class that handle MySQL db connection

What's the point of dbConnection? As it stands now it is a barely-there wrapper around MySqlConnection with a built-in connection string(!) and some odd behavior when you call openConnection(). You claim this works, are you sure -- because why wouldn't conn.Close(); throw an exception if there isn't an open connection?

Why do you always open a transaction? Why is your connection string hard-coded?

This code:

doesn't follow capitalization standards,
doesn't use a using statement to encapsulate classes that implement IDisposable (which should also be used when dealing with MySqlCommand and MySqlDataReader etc.),
has bad variable names like readerSql, usernameMySql,...


Input/character validation on an input-element

Whatever you do DON'T MODIFY Object.prototype

Modifying Object.prototype is one of the worst things you can do in JavaScript

Quoting MDN:

  Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every    browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

What should I do?

Preferably create a function:

function Validate(element, regex) {
    // code
}

but if you want to extend an element use Element.prototype, preferable with Object.defineProperty:

Object.defineProperty(Element.prototype, 'validate', {
    value: function(regex) {
        // code
    }
});

The bonus of using this is you can instead of getters and setters which are pretty cool too.

Avoid empty ifs

Here you have:

if (c.match(regex) || allowed.indexOf(e.which) >= 0) {
    //Do nothing
} else {
    e.preventDefault();
}

instead, use a NOT (!):

if (!(c.match(regex) || allowed.indexOf(e.which) >= 0))
    e.preventDefault();

the best way to write this specific condition would be:

if(!c.match(regex) || allowed.indexOf(e.which) < 0)

Use clear variable names

As much as I love code-golf (writing short code), this is not it. Make sure your variable names are clear.

I don't know what the c variable does so I can't suggest an alternative name, this also makes it more confusing to me on the workings of your code.

Use Regex literals not strings

Your example shows:

"[0-9A-Fa-f]"

That's a string, not a Regex, use Regex literals (to avoid escaping also):

/[0-9A-Fa-f]/