Performing multiple substring replacements on a string

Your Algorithm is a little bit too abstract to provide a one size fits all solution.

What does it mean, when a string contains "something" or "something else"?
Are they completely different strings like "I know (something)" and "He gave me (something else)"? Or are there similarities like:
"Peter knows (something)" and "Joe knows (something else)". So "knows" would be the keyword after which your phrase occurs. "Contains" is somehow a little bit unprecise.

If it is relativly easy to extract the substring you need -perhaps with a regular expression- you could use a HashMap to provide the correct converter with a simple call with the phrase as the key.

public class Converters {

  HashMap<String, Converter> converters=new HashMap<String, Converter>();

  public Converters(){
      // Fill Hashmap here
  }

  public Converter getConverterFor(String phrase){
      if (!converters.containsKey(phrase)) throw new NoConverterFoundException();
      return converters(phrase);
  }

}

Converter is here an interface, which all of your converters have to implement.
This solution provides easy maintenance - a new Converter needs only one new entry in the HashMap. And no unreadable if-else-whattheeckyouwantelse-blocks anymore.

But this is only one possible solution. A better solution requires more information on your phrases.


Naming conventions:

You should follow the C# design guidelines and use PascalCase for public members, class names and methods. camelCase is for private members.

Give your members and methods meaningful names. Names like con or com don't mean anything, except for you. Try using sqlConnection and sqlCommand instead.

Method names should indicate what they do and/or return. So a method name like getFromDatabase is bad practice. What are you getting from the database? Instead, use GetUsers, GetRecords or GetData. Try to be specific, only use general names like the last example if there's no other way.

This also applies to the other methods, use Open or OpenConnection instead of openConnect. (same for Close)

String.Format:

Don't concatenate all sorts of variables with string constants. Use the String.Format method. Place the format and add your values as arguments. This results in cleaner code that is easier to read and maintain. Example, change this:

string conString = "server="+serverName+";User Id="+uid+";database="+dbName+"";

to:

var connectionString = String.Format("server={0};User Id={1};database={2}", server, userID, database);

Constructor + overloading:

Your constructor contains the values you use for the connectionstring. Don't place these values here as it makes the use of the constructor very limited. Create a separate method that will create the connection and call this method from the constructor. The default values you are using can be placed in a settings file or make them private constant fields:

private const string Server = "localhost";
private const string Database = "airline_db";
private const string UserID = "root";

Also, create another constructor that takes parameters so you can create a connection with other values. Combined you can overload the constructor and put all the logic in one. This looks clean and makes maintaining your code a lot easier. Example (classname is DatabaseConnector):

public DatabaseConnector() : this(Server, UserID, Database)
{
    //This will call the other constructor with the const values
}

public DatabaseConnector(string server, string userID, string database)
{
    mySqlConnection = CreateConnection(server, userID, database);
}

private MySqlConnection CreateConnection(string server, string userID, string database)
{
    var connectionString = String.Format("server={0};User Id={1};database={2}", server, userID, database);
    return new MySqlConnection(connectionString);
}

Methods:

comText is something I don't understand. It is a void method but doesn't do anything important enough to be a separate method. Let it return a MySqlCommand instead. Rewritten:

public MySqlCommand InitSqlCommand(string query)
{
    var mySqlCommand = new MySqlCommand(query, mySqlConnection);
    return mySqlCommand;
}

Your DataTable and DataSet variables should be scoped inside the methods. There's no reason they should be global in the class. This way you can rewrite your getFromDatabase to following:

public DataTable GetData(string query)
{
    var dataTable = new DataTable();
    var dataSet = new DataSet();
    var dataAdapter = new MySqlDataAdapter { SelectCommand = InitSqlCommand(query) };

    dataAdapter.Fill(dataSet);
    dataTable = dataSet.Tables[0];
    return dataTable;
}

Things you'll also see changed is, the use of:

an object initializer for initializing members
the var keyword, this looks cleaner and you let the compiler do the job

Your Open and Close method should be private. The change in state should be determined by the class itself. Otherwise you can close the connection and try executing some command.

Dispose:

When using instances that handle unmanaged resources sucha as streams, connections, ... you have to dispose them. Otherwise they will not be claimed by the garbage collector. There are two ways to do this:

Manually call the Dispose() method:

private void Finalize()
{
    if (mySqlConnection != null && mySqlConnection.State == ConnectionState.Closed)
        mySqlConnection.Dispose();
}

Use the using statement when using the commands.

More reading:

IDisposable.Dispose Method
using Statement (C# Reference)
Naming Guidelines
Object and Collection Initializers


Subclassed Python Counter for a more visually user-friendly __str__() method, for anagrams

1. Review

There is no docstring. What kind of object is a LetterCounter?
The Python style guide recommends restricting lines to 79 characters. If you did this, then we wouldn't have to scroll the code horizontally to read it.
The Python style guide recommends naming constants (like superscript_digits) using ALL_CAPITALS. It's not compulsory to follow this guide but it makes it easier to collaborate with other Python programmers.
Instead of:

superscript_digits = ''.join(['\u2070','\u00b9','\u00b2','\u00b3','\u2074','\u2075','\u2076','\u2077','\u2078','\u2079'])

add an encoding declaration to the start of the source code:

# -*- coding: utf-8 -*-

and write:

SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹"

The function int_to_superscript is short, and only called once, so it would make sense to inline it at its single point of use.
There is no need for the call to list in sorted(list(self.items())): sorted accepts an iterable.
Referring to tuple elements by index, for example x[0] and x[1], makes it hard for the reader to understand what the elements are. It is clearer to use tuple unpacking to assign meaningful names to the elements. So instead of:

value_count = sorted(list(self.items()))
return ' '.join( '{}{}'.format(x[0], LetterCounter.int_to_superscript(x[1])) for x in value_count )

write something like:

return " ".join("{}{}".format(key, str(count).translate(SUPERSCRIPT_TRANS))
                for key, count in sorted(self.items())

or, if you are happy to use formatted string literals:

return " ".join(f"{key}{str(count).translate(SUPERSCRIPT_TRANS)}"
                for key, count in sorted(self.items()))

2. Revised code

# -*- coding: utf-8 -*-

from collections import Counter

# Code point mapping from digits to superscript digits.
SUPERSCRIPT_TRANS = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")

class LetterCounter(Counter):
    """Subclass of Counter with readable string conversion using sorted
    ordering of keys and superscript digits for counts.

    >>> print(LetterCounter("HELLOWORLD"))
    D¹ E¹ H¹ L³ O² R¹ W¹

    """
    def __str__(self):
        return " ".join(f"{key}{str(count).translate(SUPERSCRIPT_TRANS)}"
                        for key, count in sorted(self.items()))

3. Answers to questions

If you want a mapping with sorted views of its keys and items, then you need the sortedcontainers package, which has the SortedItemsView that you are looking for. (The package has no SortedCounter, but it is not difficult to write one by subclassing SortedDict.)
It is rarely a good idea to leave dead code (like the subscripts in your example). The problem is that dead code does not get tested, and so as the live code changes it is easy to forget to make corresponding changes to the dead code, so that when you come to try to resurrect the dead code you find that it is broken.
The pickling protocol uses its own special methods like __getstate__, not __repr__.
There are situations in which it's useful for eval(repr(o)) to return an object similar to o, but otherwise you are free to redefine __repr__ however you like.


Python implementation of stack to return minimum in O(1) time

The minimum gets updated after a push but not after a pop, causing getMinimum to return the wrong value:

>>> stack = Stack()
>>> stack.push(2)
>>> stack.push(1)
>>> stack.getMinimum()
1 # correct
>>> stack.pop()
1
>>> stack.getMinimum()
1 # wrong: the only item in the stack now is the number 2


First, unless the work module is about force times distance in a physics simulator, it is a terribly over-generic name! What does the name work communicate to someone who is sitting down with your application for the first time? Name modules after what they do and be as specific as possible but not more so.

Second, if you're only exposing a single method in that module just return that method directly, no need for an object.

Next, won't your scrolling handlers depend on a specific structure being present already? You might want to make it explicit. I can't really make a recommendation how without understanding better how you plan to use this (I'm really confused what work.buildHTMLTable(url) could possibly do).

As for where key navigation should go, it really is all about naming. So if you view the arrow key navigation to be a part of the grid scrolling then yes, it should be in the module that sets that up, otherwise it should not be.

Finally, What if you have two grids on the same page? seems like you're trying to apply a lot of stuff globally? Perhaps your modules can accept the grid you want to modify as a parameter?


A few other methods I would suggest implementing:

get;
setdefault;
has_key (if supporting 2.x); and
__repr__/__str__.

There is an edge case on hashable collections (tuple, frozenset):

>>> d = FriendlyDict()
>>> d[(1, 2)] = "foo"
>>> d[1]
'foo'
>>> d[frozenset(("bar", "baz"))] = 3
>>> d["bar"]
3

Also equality comparisons might be a problem - should two FriendlyDicts be considered equal if all (most?) of their keys are "close enough" and have the same values?

In terms of additional features, consider whether numerical keys should be matched with some tolerance - dictionaries not handling floats particularly well could be one reason to use this class. Also, a missing letter within a string key might be something to pick up (e.g. d["parameer"]).


Find abstraction for classes which represent tables with differnt amount of colums (based on DataTables)

I can think of trying something like this.

interface ICount
{
  int count();
}

class CountOne : ICount { int count() { return 1; }}
class CountTwo : ICount { int count() { return 2; }}

abstract class IFooTable<T> where T : ICount, new()
{
  int count() { return (new T()).count(); }
}

class FooTable<T> : IFooTable<T>
{
  void AddRow(params object[] values) {
    assert(values.length = this.count());
    ...
  }
}

class OneTable : FooTable<CountOne> { }
class TwoTable : FooTable<CountTwo> { }

But honestly I would just expect the add function to take a row. This is not something where I'd use generics, instead I'd just use mutable data structures that have constraint checks. I'm way more concerned with column names matching especially when a params statement doesn't make sure they're in the right order.

class FooTable
{
  List<string> columns;
  List<DataRow> rows;

  void AddRow(DataRow row)
  {
    assert(column names for the row match the expected values);
    rows.add(row);
  }
}

Alternatively, you could mix both approaches. Using the generics to ensure the number of columns and then adding a DataRow at a time to enforce column names match up.


Validating an input string against some enum fields

I would pass a TestEnum instead of a String to your method, forcing the exception handling to be outside the method. I don't see why you are using Strings at all actually (although I suspect that this is only a small part of your code, and that you have your reasons for needing this).

I would do some refactoring and use EnumSet, which could make your code something like this: (untested code, but I believe it should work)

public static void main(String[] args) {
    String enumName = "h3";
    EnumSet<TestEnum> except = EnumSet.of(TestEnum.h1, TestEnum.h2, TestEnum.h3);

    boolean valid;
    try {
       valid = !except.contains(TestEnum.valueOf(enumName));
    } catch (IllegalArgumentException e) { valid = false; }
    System.out.println(valid ? "valid" : "invalid");
}

Note that I have gotten rid of your entire method here as I think that when you use EnumSet like this, you don't need the method. But of course you can put the relevant parts of the above code into a method.


Python doesn't have private anything but we still have a need to separate inners of a class from the public interface.

By convention, attributes or methods whose name starts with a single underscore are considered internals of the class and, thus, not part of the public API. There is no mechanism in place to restrict their access, so user that know what they are doing can still use them; but if anything goes wrong, it will most likely be their fault, not yours.

Also, in the context of versionned libraries, internals are not subject to backward compatibility and can change without notice on a new release.

But instead of methods as getter or setters, we prefer properties that allows the same kind of flexibility (read-only vs. read-write) with the simplicity of attributes access.

Appart from that, I would add either __str__ or __repr__ (or both) as methods in your class to simplify printing accounts:

class BankAccount:
    def __init__(self, name, balance=0.00):
        self.name = name
        self._balance = balance

    def deposit(self, amount):
        """make a deposit"""
        self._balance += amount

    def withdraw(self, amount):
        """make a withdraw"""
        if amount > self._balance:
            raise ValueError("insufficient funds")
        self._balance -= amount

    @property
    def balance(self):
        """check the balance"""
        return self._balance

    def __repr__(self):
        return '{0.__class__.__name__}(name={0.name}, balance={0.balance})'.format(self)

    def __str__(self):
        return 'Bank account of {}, current balance: {}'.format(self.name, self.balance)

Example usage being:

customer1 = BankAccount('Alex')
print(repr(customer1))
customer1.deposit(100)
customer1.withdraw(30)
print(customer1)
customer2 = BankAccount('Sam', 200)
print(customer2.balance)

As regard to the "one class per file" rule, it may make sense in languages where a file does not bear much meaning.

But in python a file is a module. It is perfectly fine and expected to put related entities in them as they define a namespace.

Beside, where would you put simple functions and constants using a "one class per file" approach? As class attribute of some sort of "namespace" class? Yuck! Module already serve this purpose, don't reinvent the wheel.


Solving a variation of the "Partition Problem"

I don't see a partition problem here. What the task suggests is a representation of a given number in the form of \$\Sigma a_n3^n\$ where \$a_n \in \{-1,0,1\}\$. I highly recommend proving to (or at least convincing) yourself that every number has such representation. Then you may want to see how few first numbers are represented:

    1                   1
    2                  -1  1
    3                   0  1
    4                   1  1
    5                  -1 -1  1
    6                   0 -1  1
    7                   1 -1  1
    8                  -1  0  1
    9                   0  0  1
    10                  1  0  1
    11                 -1  1  1
    12                  0  1  1
    13                  1  1  1
    14                 -1 -1 -1  1

(first column is for 1, second for 3, third for 9, etc) and figure out the rule of sequencing the coefficients for each power of 3 (think reminders). The actual coding becomes straightforward.


Regex to first match, then replace found matches

Regex.Matches returns a MatchCollection which contains Matches which captures the index and length of each match. So as such you won't have to fire up the regex engine again because you can do something like this:

string toSearchInside; // The actual string I'm going to be replacing within
List<string> searchStrings; // The list of words to look for via regex

string pattern = @"([:@?]{0})";
string replacement;

foreach (string toMatch in searchStrings)
{
    var regex = new Regex(
                            string.Format(pattern, toMatch),
                            RegexOptions.IgnoreCase
                            );
    var matches = regex.Matches(toSearchInside);

    if (matches.Count == 0)
        continue;

    replacement = CreateReplacement(toMatch);

    // in case the replacement is of a different length we replace from
    // from back to front to keep the match indices correct
    foreach (var match in matches.Cast<Match>().Reverse())
    {
        toSearchInside = toSearchInside.Replace(match.Index, match.Length, replacement);
    }
}

Unfortunately the .NET framework doesn't come with a positional Replace so we have to create one which I did as an extension method:

public static string Replace(this string s, int index, int length, string replacement)
{
    var builder = new StringBuilder();
    builder.Append(s.Substring(0,index));
    builder.Append(replacement);
    builder.Append(s.Substring(index + length));
    return builder.ToString();
}

If you do this often and the match patterns don't change you could consider two things:

Pre-compile the regular expressions
Pre-create the replacements


MS Access query complexity on finding duplicates

You'll have to take this with a huge grain of salt, because the following advice is for generic, standards-abiding SQL - which Access is not.
In regular SQL, this is as simple as:
select dupes.id1, ST1.nam
from (
    select id1
    from ST1
    group by id1
    having count(*) > 1
) dupes
join ST1 on ST1.id1 = dupes.ST1
order by dupes.id1;

Another way to do it without a join at all is a partition (window) function that adds a count column within each group. Unfortunately, the Access idea of a partition diverges significantly from the rest of reality, so this probably isn't possible for you. Regardless, for what it's worth, it would look like
select id1, nam
from (
    select id1, nam,
           count(*) over (partition by id1) as n
    from ST1
)
where n > 1
order by id1;

If at all possible, consider moving away from Access. It introduces more problems than it solves.


swap would be is a nice general purpose swap routine. Notice that in your code you always call it with pos equal to 0. You should either drop this redundant parameter, or make swap even more general purpose by not assuming the semantics of the parameters, e.g.:

void swap(char * ptr1, char * prt2) {
    char ch = *ptr1;
    *ptr1 = * ptr2;
    *ptr2 = ch;
}

In this version, ptr1 and ptr2 do not have to belong to the same array.
recursive_mirror decrements length twice, and the first decrement has a side effect. The (non-existent) purpose of this side effect takes an effort to understand. A direct

  swap(arr, 0, length - 1);
  recursive_mirror(arr + 1, length - 2);

seems more readable).
The base case test can be if (length < 2).

Nitpick: your base case tests fails miserably on a negative length. However, from the very beginning we know that length shall not be negative, so declaring it as an unsigned seems more prudent. At least the intention is documented.


What is the best way to code an array that has same keys as another array's values

Here is the answer:

I delete the keys from the args array, and I create a new array from combining both headers and args:

$argsVal = [ array('filter' => FILTER_VALIDATE_REGEXP,'options' => array('regexp' => '/^[a-zA-Z0-9_:.()\/]*$/'), ),
               array('filter' => FILTER_CALLBACK,'options' => "validateDate", ), FILTER_VALIDATE_FLOAT, ];

$args = array_combine($headers,$argsVal);


Display progress bar to show async request status using jQuery

Realizing that you are trying to make reusable code, I figured I would share my methodology, as I believe it will extend your structure here.

I like to wrap everything into an object with functions appropriate to AJAX, and I added in your .overlay components:

var ajax = {
        showProgressBar:function($overlay){
            var $doc = $(document),
                $win = $(window);

            $overlay
                .css({
                    height:$doc.height(),
                    width:$doc.width(),
                    display:'block'
                })
                .find('.progress')
                .css({
                    top:($win.height() / 2),
                    left:($win.width() / 2)
                });
        },
        hideProgressBar:function($overlay){
            $overlay.hide();
        },
        abortActive:function(){
            var self = this;

            if(($.active > 0) && (self.active !== undefined)){
                self.active.abort();
            }
        },
        clearActive:function(){
            this.active = undefined;
        },
        send:function($type,$url,$data,$success,$error,$abort){
            var self = this,
                $overlay = $('.overlay'),
                $beforeSend = ($abort ? function(){
                    self.abortActive();
                    self.showProgressBar($overlay);
                } : function(){
                    self.showProgressBar($overlay);
                }),
                $complete = ($abort ? function(){
                    self.clearActive();
                    self.hideProgressBar($overlay);
                } : function(){
                    self.hideProgressBar($overlay);
                }),
                curFunc = $.ajax({
                    type:$type,
                    url:$url,
                    data:$data,
                    beforeSend:$beforeSend
                }).success($success).error($error).complete($complete);

            this.active = ($abort ? curFunc : self.active);
        }
    };

And then it is called with an example of something like this:

ajax.send(
    'POST',
    'requires/submitSomething.php',
    {
        id:$someId,
        type:$someType
    },
    function(data){
        alert('Successful! The response message was: '+data.message);
    },
    function(data){
        alert('Error! The response message was: '+data.message);
    },
    false
);

This is obviously super generic, but should do the trick. A quick explanation:

the beforeSend setting will fire a callback function prior to sending the AJAX, which is where you want to load your progress gif
the complete setting will fire a callback function once everything else completes, including the success / error functions, so it is where you want to hide the progress gif
in the success / error functions, you can include the response data and manipulate as you wish
the use of this in the send function refers to the object parent, hence able to see the other functions rather than referring to them by name
the ajax call is assigned to a variable to allow for aborting the call mid-stream before starting another (if another action overrides it, for example) ... the reason for the use of this rather than self is because we need to assign it to the object rather than just reference the existing objects within it
the function creation is based on the boolean you pass in for $abort, to determine if your AJAX call should stop all current AJAX calls or have it run in parallel (depending on your usage)

And a few small tweaks I made to your existing jQuery code to optimize:

cached $(document), $(window), and $('.overlay') as they are used more than once in the functions
consolidated your .show() function into the previous CSS statement (as the default is to basically perform a .css({display:'block'}) statement ... if you have overridden this with a custom function, you can return as needed)
chained the calls to $('.overlay') and $('.progress'), as they were both based on $(this)

This function should give you a good starting point, and you can modify as needed if you need additional parameters. The only additional parameter I advise against is the use of dataType; for some reason, everyone using json likes to include dataType in their AJAX call (which is an intelligent guess, not a true marker) instead of doing it right. Don't be "that guy", put your appropriate header declaration in the files you are loading via AJAX and it will be bulletproof.

Hope this helped.


Adding several text parts to one file in sequence

Here we go, I would create some "util" namespace to write some helper code:

./util/index.js

const bPromise = require('bluebird');

const fs = require('fs');

const readFile = bPromise.promisify(fs.readFile);

const appendFile = bPromise.promisify(fs.appendFile);

const createWS = filename => {
    var writer = fs.createWriteStream(filename, {defaultEncoding: 'utf8', flags : 'a'});
    return {
        write : bPromise.promisify(writer.write.bind(writer))
    }
}

module.exports = {
    readFile,
    appendFile,
    createWS
}

Thanks to bluebird we can convert functions with callback functions into functions that returns a resolved or rejected Promise with the result value. So that is what it's done in "./util/index.js".

In your main file:

var { readFile, appendFile, createWS} = require('./util');

var filename = "content.txt";
var writer = createWS(filename);
var xyz = ['x', 'y', 'z'];

// (1) Read 'head.txt'
readFile('head.txt', 'utf8')
.then( head => appendFile(filename, head))
.then( ()=>{
    // Head appended
    var a = '...';
    var b = '...';
    var ab = a + b;
    return appendFile(filename, ab);
})
.then( ()=>{
    // ab appended
    //return xyz.reduce((a, b)=> a.then( ()=> writer.write('...' + b + '...') ), Promise.resolve(null) )
    // or just
    return writer.write(xyz.map(el=>'...' + el + '...').join(''));
})
.then( ()=>{
    return writer.write(xyz.map(el=>'...' + el + '...').join(''));
})
.then( ()=>{
    return readFile('footer.txt', 'utf8')
        .then( footer => writer.write(footer))
})
.then( ()=>{})
.catch(console.error.bind(console));

Now looks very nice and it's clear. There's no need (Like in your code) to execute synchronous functions.

Check the ES5 code.

./util/index.js

var bPromise = require('bluebird');

var fs = require('fs');

var readFile = bPromise.promisify(fs.readFile);

var appendFile = bPromise.promisify(fs.appendFile);

var createWS = function createWS(filename) {
    var writer = fs.createWriteStream(filename, { defaultEncoding: 'utf8', flags: 'a' });
    return {
        write: bPromise.promisify(writer.write.bind(writer))
    };
};

module.exports = {
    readFile: readFile,
    appendFile: appendFile,
    createWS: createWS
};

index.js

var _require = require('./util');

var readFile = _require.readFile;
var appendFile = _require.appendFile;
var createWS = _require.createWS;

var filename = "content.txt";
var writer = createWS(filename);
var xyz = ['x', 'y', 'z'];

// (1) Read 'head.txt'
readFile('head.txt', 'utf8').then(function (head) {
    return appendFile(filename, head);
}).then(function () {
    // Head appended
    var a = '...';
    var b = '...';
    var ab = a + b;
    return appendFile(filename, ab);
}).then(function () {
    // ab appended
    //return xyz.reduce((a, b)=> a.then( ()=> writer.write('...' + b + '...') ), Promise.resolve(null) )
    // or just
    return writer.write(xyz.map(function (el) {
        return '...' + el + '...';
    }).join(''));
}).then(function () {
    return writer.write(xyz.map(function (el) {
        return '...' + el + '...';
    }).join(''));
}).then(function () {
    return readFile('footer.txt', 'utf8').then(function (footer) {
        return writer.write(footer);
    });
}).then(function () {}).catch(console.error.bind(console));


Designing a dynamic array of Memory Streams

You might need to create a class handler that would handle the PdfDocument and MemoryStream, which will make things easier to handle and disposed as well. Then, you can just adjust the handler to your application requirements. here is an example :

public class PdfDocumentManager
{
    // Use Dictionary to keep both PdfDocument and MemoryStream paired.
    // Also, this means, you'll only save unique PdfDocuments and work on them.
    // if you want to save a PdfDocument multiple times (say different copy of the original copy)
    // use List<KeyValuePair<PdfDocument, MemoryStream>> instead.
    private readonly Dictionary<PdfDocument, MemoryStream> _storage = new Dictionary<PdfDocument, MemoryStream>();

    public PdfDocumentManager() { }

    public void Add(PdfDocument document)
    {
        // don't forget to validate

        _storage.Add(document, ToMemoryStream(document));
    }

    public void AddRange(IEnumerable<PdfDocument> documents)
    {
        foreach(var document in documents)
        {
            // validate each document before adding it.
            Add(document);
        }
    }

    public void Remove(PdfDocument document)
    {
        // code to remove the saved stream.
        // choose MemoryStream or PdfDocument or Both if you want.
    }

    private MemoryStream ToMemoryStream(PdfDocument document)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            document.Save(stream);
            return stream;
        }
    }

    private PdfDocument ToPDFDocument(MemoryStream stream)
    {
        // code to convert back to memory stream.
        // just search the values to return its key.
        // if there is no match, then create a new PdfDocument along with MemoryStream, then return it back.
    }

    public IEnumerable<PdfDocument> GetAvailableDocuments()
    {
        return _storage.Keys;
    }

    public IEnumerable<MemoryStream> GetAvailableStreams()
    {
        return _storage.Values;
    }

}

simple add usage :

// initiate
var pdfManager = new PdfDocumentManager();

// add single document
pdfManager.Add(new PdfDocument(testParametersToDesignUniquePDF1));
pdfManager.Add(new PdfDocument(testParametersToDesignUniquePDF2));

// add multiple PdfDocument
var pdfDocumentList = new List<PdfDocument>
{
    new PdfDocument(testParametersToDesignUniquePDF1),
    new PdfDocument(testParametersToDesignUniquePDF2)
}

pdfManager.AddRange(pdfDocumentList);

The methods in this class are just for demonstration purpose only. You can bind the idea to your actual needs. With this handler, you can even make it a singleton class or make _storage static to have only one storage for the duration of the application ..etc. You can also move some related conditions inside the class to validate the documents (for instance, if you check if that document existed or not ..etc). This would give you also an easier way to handle the disposable objects.


It's too bad your template engine doesn't support conditions. What about this?

def marked_active_post(orig_posts, active_index):
    posts_view = orig_posts.deepcopy()
    posts_view[active_index]['active?'] = True
    return posts_view

That means n+1 copies instead of 2, but no need to optimize it until it proves to be slow.


Initially, I thought I would need to synchronize everywhere, but in the end, I didn't use any. Is this code still usable from multiple threads?

No. When one thread sets

private ScheduledFuture future;

other may not see it in

    public void waitChoke() throws InterruptedException, ExecutionException {
        if(future == null || future.isDone() || future.isCancelled())
            return;
        future.get();
    }

Making future volatile would help. However, there's another problem with it changing before the test and future.get(). Here, a local variable would help.

  As a side question- ScheduledExecutorService seemed like the best way to delay without forcing a block unless something needs to wait, but it asks for a Runnable, which I don't seem to really utilize. Is this poor design?

I guess, it's fine but you've overcomplicated it. Do you need EndThrottle#throttle? Do you need EndThrottle at all?

Why not just this?

future = executor.schedule(new Runnable(), 5, TimeUnit.SECONDS);

Overall, it doesn't look bad, but concerning thread-safety, there may be more problems.


Pascal Triangle c# code space complexity

As I think greybeard was trying to say, unless you are know that memory consumption/allocation costs are a serious concern, then this code is fine from a memory point of view. The space-complexity is the same as the output (quadratic in A), so you can't do better than that.

There a couple of small things to be said:

as GreyBeard says, A is completely meaningless, and should really have a lowerCamelCase name as a parameter (e.g. dimension, size?); generate ought to be GeneratePascalTriangle or something meaningful (public -> UpperCamelCase) (msdn reference)
currenctRowLength should be currentRowLength, and should only be defined inside the for loop (i.e. where it is assigned); I like that this is its own variable.
you are using a while loop over j, when a for could be more readable (simply because people are used to reading for-loops), and doesn't leak j into the outer scope.
List<List<int>> is a pretty horrid type to be returning: much better to have IReadOnlyList<IReadOnlyList<T>> if the return value is meant to be immutable (which is assignable from List<List<T>> or T[][]).
I'd be inclined to initialise previousRow to null, rather than an empty list: it isn't read until i == 2; assigning it to a 'meaningful' value is defensive and only can work to obscure bugs in the rest of the code.

Mindless Performance Musing

If memory usage/allocations/GC hammering is a real concern, then you can improve matters by not using resizing lists. You havn't given us any idea of what the code is actually meant to do, so it's a bit hard to suggest an alternative, but you could either use arrays (which obvious are non-dynamic) or you can preserve the signature by creating lists with a given initial capacity with the .ctor(int) overload. Note that this will give a performance benefit, but change the time-complexity (which is also quadratic in A).

Code

Putting all of that together (and using arrays instead of lists, because mindless performance is fun, and I don't think it harms the readability here much):

/// <summary>
/// Generates a pascal triangle with the given number of rows
/// </summary>
public static IReadOnlyList<IReadOnlyList<int>> GeneratePascalTriangle(int numberOfRows)
{
    int[][] result = new int[numberOfRows][];

    int[] previousRow = null;
    for (int i = 0; i < numberOfRows; i++)
    {
        int currentRowLength = i + 1;

        int[] row = new int[currentRowLength];
        result[i] = row;

        // start and end
        row[0] = 1;
        row[currentRowLength - 1] = 1;

        // middle
        for (int j = 1; j < currentRowLength - 1; j++)
        {
            row[j] = previousRow[j] + previousRow[j - 1];
        }

        previousRow = row;
    }

    return result;
}


PHP: multilingual Time::since() static class

I've not coded any PHP in last five years but if I'm right the following is the same:

$tokens = array (
    31536000 => array('msgid1' => "Last visit: %d year ago",
        'msgid2' => "Last visit: %d years ago"),
    2592000 => array('msgid1' => "Last visit: %d month ago",
        'msgid2' => "Last visit: %d months ago"),
    604800 => array('msgid1' => "Last visit: %d week ago",
        'msgid2' => "Last visit: %d weeks ago"),
    86400 => array('msgid1' => "Last visit: %d day ago",
        'msgid2' => "Last visit: %d days ago"),
    3600 => array('msgid1' => "Last visit: %d hour ago",
        'msgid2' => "Last visit: %d hours ago"),
    60 => array('msgid1' => "Last visit: %d minute ago",
        'msgid2' => "Last visit: %d minutes ago"),
    1 => array('msgid1' => "Last visit: %d second ago",
        'msgid2' => "Last visit: %d seconds ago")
);

foreach ($tokens as $unit => $data) {
    if ($time < $unit) {
        continue;
    }
    $numberOfUnits = floor($time / $unit);

    $formatString = ngettext($data['msgid1'], $data['msgid2'], $numberOfUnits);
    return sprintf($formatString, $numberOfUnits);
}

I think you should handle 0 too. Currently it prints nothing for this input.


Number to words in left to right direction

This code:

int i,j;
j=0;
while(no>0){
    i = no%10;
    no /= 10;
    word[j] = words[i];
    j++;
}
for(int k= word.length;k>0;k--)
{
    System.out.println(word[k-1]+" ");
}

can be drastically simplified to:

String numbers = String.valueOf(no);
for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}

Or you may save save the user input as String (but make sure it only contains digits). You will have something like this:

 String numbers = br.readLine();
 for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}


Let's remove all if/else checks:

Set direction to 1 or -1 based on the button class and multiply it by ZOOM_OFFSET
Use Math.max, Math.min to constrain zoom value in the range
Use .toggleClass('.foo', condition) to disable the buttons conditionally
Set the attribute just once, in the end: no need to treat the absence of the attribute specially, just use a fallback parseInt(foo) || MIN_ZOOM

And fix some inconsistencies:

Use camelCase names for normal variables, which is a standard JavaScript convention
Use single or double quotes for strings consistently
Prefer .text(foo) over .html(foo) in case of a simple text without HTML tags

$('.schedule-zoom .zoom-btn:not(.disable)').click(function() {
  var direction = $(this).hasClass('zoom-in') ? 1 : -1;
  var container = $('.fixed-container');

  var zoom = parseInt(container.attr('zoom')) || MIN_ZOOM;
  zoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + direction * ZOOM_OFFSET));

  container.attr('zoom', zoom).text(zoom);
  $('.schedule-zoom .zoom-in').toggleClass('disable', zoom == MAX_ZOOM);
  $('.schedule-zoom .zoom-out').toggleClass('disable', zoom == MIN_ZOOM);
});


Prints each letter of a string in different colors

Don't worry about performance.

You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.

Your function is too long.

This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.

Switch statements are ugly.

I don't mean that they are never appropriate, but ConsoleColor is an enum, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.

Don't initialize variables until you need them.

With few exceptions, modern languages are very good about optimizing variable allocation. Putting char log = str[i] inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.

Other tips...

You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.

On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.


Your sentiment is indeed correct, this code is much longer than it needs to be and can be shortened 10x while retaining the same functionality.

You are doing 4 things in a single function!

Asking for input
Generating a password
Printing
Writing to a file.

A function should do 1 thing only.

Let's say we want to generate a password:

def generate_password():
    numbers = (str(random.randint(10, 99)) for _ in range(4))
    letters = (random.choice(string.letters) for _ in range(4))
    return ''.join(numbers) + ''.join(letters)

This function is shorter than yours not only because it does not care about Input/Output, but also because it uses loops (Generator expressions here) to do the same thing many times.

You may call this function in a user-interface that handles input and output like:

print(raw_input("Username ") + " " + raw_input("Surname ") + ": " + generate_password())

Of course you may want to make the interface nicer or make it handle files, but the backbone is here.


Improvements and advice for my Cache class

Something you might consider is switching it to be a static class instead of a singleton.  The caching system itself is already performing the singleton process.

To add functionality, if you change it to a static class you can add helpers to extend caching directly onto the object(s) itself like myDictionary.Cache() and myDictionary.LoadFromCache().

Reflection frequently gets used where it shouldn't.  However, you could decorate the functionality to auto-infer the "namespace.class.variablename" which removes magic stings entirely and makes the extended functionality more fluent.  I hope this helps.


Using a popup to display messages to the user

A few ideas:

Your three javascript functions could easily be combined into one with some simple arguments, like headerText, statusMessage, statusType.
In your description you list some success text, but this isn't in the javascript, so I guess this is set in the code-behind. I consolidate how the text is set. If you choose to use javascript, you could simplify things by changing the asp:Label to a span.
It might be nicer to put the style information in the CSS file and then in the javascript just toggle which classes apply.

Here's an example of how it might look:

CSS

#NewCustomerSubmitStatusPopup.successPopup
{
  background-color: white;
  border-color: #9cc3f7; /* width, pattern added to main CSS block */
}

#NewCustomerSubmitStatusPopup.successPopup h1, #NewCustomerSubmitStatusPopup.successPopup span
{
  color: #9cc3f7;
}

#NewCustomerSubmitStatusPopup.errorPopup
{
  background-color: #F7DFDE;
  border-color: #BD494A;
}

#NewCustomerSubmitStatusPopup.errorPopup h1, #NewCustomerSubmitStatusPopup.errorPopup span
{
  color: #BD494A;
}

javascript

function ShowSubmitPopUp(headingText, statusMessage, statusType)
{
    $('#NewCustomerMask').show("slow");
    $('#NewCustomerSubmitStatusPopUp').show("slow");

    var popupClass = (statusType == 'error' ? 'errorPopup' : 'successPopup');
    $('#NewCustomerSubmitStatusPopUp').attr('class', popupClass);
    $('#NewCustomerSubmitStatusPopUp h1').html(headingText);
    $('#NewCustomerSubmitStatusPopUp span').html(statusMessage);
}


1 It would be more natural to have a field size instead of tail:

struct queue {
    int array[MAX];
    int head;
    int tail;
};

2 If you had size field, checking whether the queue is empty or
full would be a simple one-liner.

    if((p->tail == MAX-1 && p->head == 0 ) || (p->head == p->tail+1)) {
        printf("\nQUEUE IS FULL!!   ");
        return;
    }

3 It's not cool to print from algorithms unless debugging.

int DEQUEUE(struct queue* p) {
    if(p->head == p->tail) {
        printf("\nQUEUE IS EMPTY!!");
        return -1;
    }

4 Can make the output of this more pretty.

void SHOWQUEUE(struct queue* p) {
    ...
}

5 The convention is not to prepend malloc with a type.

Q = (struct queue*) malloc(sizeof (struct queue));

Instead, do this

Q = malloc(sizeof(struct queue));

6 Don't do this:

Q->head = 1;
Q->tail = 1;

Instead, you should write the function that initializes your queue.

7 Above, it's funny that you start indexing from 1.

Summa summarum

You could consider something like the following:

queue.h:

#ifndef QUEUE_H
#define QUEUE_H

#include <stdbool.h>
#include <stdlib.h>

#define CAPACITY 10

typedef struct queue {
    int storage[CAPACITY];
    size_t head;
    size_t size;
} queue;

void queue_init(queue* q);
bool queue_enqueue(queue* q, int element);
int  queue_dequeue(queue* q);
void queue_print(queue* q);

#endif

queue.c

#include "queue.h"
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>

void queue_init(queue* q)
{
    if (!q)
    {
        return;
    }

    q->head = 0;
    q->size = 0;
}

bool queue_enqueue(queue* q, int element)
{
    if (!q || q->size == CAPACITY)
    {
        return false;
    }

    q->storage[(q->head + q->size++) % CAPACITY] = element;
    return true;
}

int queue_dequeue(queue* q)
{
    if (!q || q->size == 0)
    {
        return 0;
    }

    int ret = q->storage[q->head];
    q->head = (q->head + 1) % CAPACITY;
    q->size--;
    return ret;
}

void queue_print(queue* q)
{
    if (!q)
    {
        printf("null");
        return;
    }

    printf("[");

    for (size_t i = 0, index = q->head; i < q->size; ++i)
    {
        printf("%d", q->storage[index]);

        if (i < q->size - 1)
        {
            printf(", ");
        }

        index = (index + 1) % CAPACITY;
    }

    printf("]");
}

main.c:

#include "queue.h"
#include <stdio.h>

int main() {
    queue q;
    queue_init(&q);

    for (int i = 0; i < 5; ++i)
    {
        queue_enqueue(&q, i);
    }

    for (int i = 0; i < 10; ++i)
    {
        queue_print(&q);
        puts("");
        queue_enqueue(&q, queue_dequeue(&q));
    }

    return 0;
}

Hope that helps.


I would get rid of foreach and use for. I have found (and read about) a huge performance difference between the 2 (EDIT, but not always, see below).

Example (untested code):

int c  = listBcBook.Count;

for (int i = 0; i < c; i++)
{
    BCBook bcBook = listBcBook[i];

    BookHistoryDto historyDto = new BookHistoryFacade().FindHistoryByBookIdByPriority(bcBook.id.ToString(CultureInfo.CurrentCulture));
    if (historyDto != null && historyDto.HistoryId > 0)
    {
        bcBook.Priority = historyDto.Priority;
        listPriorityBcBooks.Add(bcBook);
    }
    else
    {
        listNonPriorityBcBooks.Add(bcBook);
    }
}

EDIT: I just read that the performance difference isn't always there because in some cases, the compiler will optimize your foreach loops into for loops. Here is a good read over on SO: https://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c.

In your case, because you're using a List, directly using for should be faster.


You don't need to escape slashes for grep, you can simplify to:

tarfile=$(curl -s https://sv.wordpress.org/ | grep -ioE "https://sv.wordpress.org/wordpress-[0-9].[0-9].[0-9]-sv_SE.tar.gz")

curl and wget are too similar tools. Consider using only one of them, to reduce the number of dependencies of your script.

Instead of this:

wget $tarfile -O senaste_wp.tar.gz
tar xvfz senaste_wp.tar.gz -C ./
rm senaste_wp.tar.gz

You can pipe directly to tar, without needing a temporary file, like this:

curl $tarfile | tar xvz

Lastly, your script is not using anything Bash specific, so you could change the shebang line to !#/bin/sh.


Python code to check if an array has a sequence (1,3,4)

By PEP 8, doesSeqAppear should be does_seq_appear. You used the right naming convention for your unit tests, though. Personally, I would prefer def contains_seq(arr, seq=[1, 3, 4]).

Your arr_len < 3 test is superfluous and should therefore be eliminated. Don't write a special case when the regular case works correctly and just as quickly.

Your all(isinstance(item, int) for item in int_arr) check was not specified in the problem, and is therefore harmful. The question does not say that doesSeqAppear([3.1, 1, 3, 4]) should return False, nor does it say that it should fail with an exception. In fact, by my interpretation, it does contain the magic sequence and should therefore return True. In any case, you have wasted a complete iteration of the list just to perform a check that wasn't asked for.

Checking isinstance(int_arr, list) is un-Pythonic, since duck-typing is the norm in Python. In any case, the code would likely fail naturally if it is not a list.

After cutting all that excess, you should drop the # Loop through elements comment as well.


Dealing with a command line argument (path) with spaces

I think it's fine, although my preference would be readdir over glob. (I know someone made the exact opposite suggestion on your original post, and that's alright.) I can't really articulate why, but I've never liked glob very much---I guess it just seems too magical to me. Some people would argue "why write three lines of code when you can write one?" or "readdir isn't good because you have to filter out dots" or "readdir isn't good because you have to remember to prepend the directory". OK, so put a tiny wrapper around it in your standard library or use read_dir from File::Slurp. Anyway, moving on...

I did want to comment on your comment:

  Dealing with paths with spaces is done by:

my $folder = $ARGV[0];
$folder =~ s|\\|/|g;
$folder =~ s|/$||;

That code doesn't actually do anything related to handling paths with spaces. All it does is take the first command line argument to your script, replacing backslashes with forward slashes and stripping off the trailing slash. It's also unnecessary, since Perl on Windows can deal with either forward or backward slashes in paths. I would also assume that Windows is not giving you a directory path with a trailing slash on it, but I don't have access to a Windows box to confirm that.

Since you are on Windows, the shebang/hashbang line is redundant and can be removed:

#!/usr/bin/perl

Other than that, I think the rest of the code looks pretty good, but I guess it would be strange if I didn't think so, considering that I wrote some of it. When it comes to glob vs. readdir, it's mostly a matter of personal preference, although there's a good thread on Stack Overflow that examines the differences. Read it for yourself and see what you think.


using (var client = new SmtpClient())
   {
      await client.ConnectAsync("smtp.WebSiteLive.net", 587, SecureSocketOptions.None);
      client.AuthenticationMechanisms.Remove("XOAUTH2"); // Must be removed for Gmail SMTP
      await client.AuthenticateAsync(_options.Option1, _options.Option2);
      ...
      await client.DisconnectAsync(true);
    }

Look at how much work you're doing per message. If you reuse the client, you save setup and teardown time on every message after the first one.

If you reuse the client then you'll need to handle errors and be prepared to close it, open a new one, and continue where you left off; so there is a speed-complexity trade-off.


I see a number of things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Sanitize user input better

The date check could be a little more robust.  In particular, verifying that the month is in the range of 1 to 12 is particularly important because that number is later used as an index into a vector.  If I enter the nonsensical date 40/40/1940 the errorCheck routine currently accepts it as valid and the program later crashes.  If I enter just 40/40, the program also crashes.

Simplify your code

Right now the code includes this line:

while((startDay==endDay)!=1)

It would be more straightforward to simply write this:

while(startDay != endDay)

This would only require the addition of an operator!= to the Date.

Don't complicate the code

The code currently contains this structure declaration:

typedef struct Date{
    // stuff
}Date;

First, the typedef is neither needed nor useful.  This isn't C.  Second, it would make sense to declare it as a class rather than as a struct.

class Date {
    // stuff
};

Use const where practical

The operator== member function of Date does not alter the underlying object and therefore should be declared const.

bool operator==(const Date& rhs) const;

Make your classes do more work!

The current Date class is a very lazy thing, leaving all of the work to separate functions.  I'd make it do much more of the work. For instance, I reimplemented your algorithm but did most of the work in class operators.  Here's an excerpt of that code:

int operator-(Date end, Date start) {
    bool swapped{false};
    if (end < start) {
        std::swap(start, end);
        swapped = true;
    }
    int diff = 0;
    for ( ; start != end; ++start) {
        ++diff;
    }
    return swapped ? -diff : diff;
}

int main() {
    Date start, end;

    std::cout << "Enter start date in format DD MM YYYY\n";
    std::cin >> start;
    std::cout << "Enter ending date in format DD MM YYYY\n";
    std::cin >> end;
    std::cout << end-start << "\n";
}

Consider the cost of object creation

The code currently contains this function:

int DaysInMonth(int month, int year)
{
    vector<int> days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if(isLeapYear(year)) days[1] = 29;
    return days[month-1];
}

This is computationally much more costly than it should be because it requires the creation and destruction of a std::vector on every invocation.  Those numbers don't change, so that first line could instead look like this:

static constexpr int days[12]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

In the case of a leap year, alter the returned value instead of the array itself.

Omit return 0

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

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Replace nested property for an interview

Neither of your solutions handles the type of the replacement correctly. For instance "bar.baz.foo:111222" replaces foo:333444 with foo:"111222" where I would expect it to result in foo:111222.
Further they can handle if the replacement is an array, but not if it is an object due to the use of split(':'). You should use str.indexOf(':') together with str.substr() instead:
function replaceInObj(obj, str) {
  let splitIndex = str.indexOf(':');
  let [path, replacement] = [str.substr(0, splitIndex), str.substr(splitIndex + 1)];
  let sections = path.split('.');
  let sub = obj;
  for (var i = 0; i < sections.length - 1; i++) {
    sub = sub[sections[i]];
  }

  sub[sections[i]] = JSON.parse(replacement);
  return obj;
}

Here JSON.parse() is used to interpret the value to the correct type. I don't know if the JSON api is considered as "third-party" in this context.

There is a more "quick and dirty" approach using eval:
function replaceInObj(obj, str) {
  let splitIndex = str.indexOf(':');
  let [path, replacement] = [str.substr(0, splitIndex), str.substr(splitIndex + 1)];
  eval("obj." + path + "=" + replacement);
  return obj;
}

Some test cases:

  let testObj = {
    bar: {
      baz: {
        foo: 333444,
        foo2: 674654
      },
      boo: {
        faa: 11
      }
    },
    fee: 333
  };

    let replacements = [
      "bar.baz.foo:111222",
      "bar.baz.foo:\"05-31-2020\"",
      "bar.baz.foo:false",
      "bar.baz.foo:\"abcdefg\"",
      "bar.baz.foo:[111222, 21341234, 234243]",
      "bar.baz.foo:{ \"aaa\": 1234, \"bbb\": \"hello world\" }"
    ];

    for (let replacement of replacements) {
      let result = replaceInObj(testObj, replacement);
      console.log(result.bar.baz.foo);
    }

function replaceInObj(obj, str) {
  let splitIndex = str.indexOf(':');
  let [path, replacement] = [str.substr(0, splitIndex), str.substr(splitIndex + 1)];
  eval("obj." + path + "=" + replacement);
  return obj;
}


Z-Algorithm for pattern matching in strings

Bugs

In your original compute_z(), you fail to return z.
In your refactored solution, g() has an undefined variable i.
The correct z-values for 'abaab' are [5, 0, 1, 2, 0], not [6, 0, 1, 2, 0].

Questions containing non-working code would normally be closed on Code Review, but since @jonrsharpe has already posted an answer, I'll let it slide.  Since the refactored solution is unreviewable in its current state, I'll examine only the original compute_z().

Reverse engineering

I was, admittedly, unfamiliar with the Z Algorithm.  I stared at compute_z(), befuddled by the cryptically named variables i, k, L, R, and by the purpose of the each if- and else-branch.  Frankly, my experience was closer to reverse-engineering than reading the code.

I came to the realization that I could strip the code down to the following and still get the same result.

def naive_z(string):
    n = len(string)
    z = [n]

    for i in xrange(1, n):
        L = R = i
        while (R < n and string[R - L] == string[R]): R += 1
        z.append(R - L)
    return z

I therefore surmised that the rest of the code served as some kind of optimization, in particular, if (z[k] < R-i): z.append(z[k]).

I also wondered about the R -= 1 statements.  I figured out that there was a loop invariant: at the bottom of the for-loop, string[L : R + 1] was the longest common prefix.

At that point, I decided to give up and start educating myself about the Z Algorithm. ☺

In the end, I decided that the algorithm is complex enough that it wouldn't be reasonable to assume that the underlying principles would be self-evident just by reading the code.  So, I learned something new today.

Observations

Your implementation appears to be a direct translation of the C code at http://codeforces.com/blog/entry/3107.

Superficial criticisms first: you have a few PEP 8 violations.  Notably, the first level of indentation is only 3 spaces, which in Python is a big deal.  The variables L and R violate capitalization conventions, though arguably L is more readable than l.  You also have a few C-isms, such as parentheses around the if-conditions.

Rather than appending one element at a time to z, you should pre-allocate an n-element list at the beginning.  Otherwise, the array might need to be reallocated as it grows.

You miss out on some optimizations due to a botched inequality.  if (z[k] < R-i) should be if z[i] <= R - i.

The R -= 1 statements are awkward, and should be eliminated.  In languages where strings are indexed starting from 0, it would be more idiomatic to use inclusive-exclusive bounds.  In other words, R should point just past the end of the match, such that string[L:R] is the longest matching prefix.

The concern that prompted you to write this question is probably the repetition of the while loops.  It is indeed possible to restructure the code such that the loop only appears once.

def compute_z(string):
    n = len(string)
    z = [0] * n

    zbox_l, zbox_r, z[0] = 0, 0, n
    for i in xrange(1, n):
        if i < zbox_r:              # i is within a zbox
            k = i - zbox_l
            if z[k] < zbox_r - i:
                z[i] = z[k]         # Full optimization
                continue
            zbox_l = i              # Partial optimization
        else:
            zbox_l = zbox_r = i     # Match from scratch
        while zbox_r < n and string[zbox_r - zbox_l] == string[zbox_r]:
            zbox_r += 1
        z[i] = zbox_r - zbox_l
    return z


Usage of a C library in a C++ project (std::string char array conversion)

If mkd_string accepts a const char*, then you are better off using a std::string and its method c_str() to pass the value to the function. Otherwise your solution is correct.
Yes. See this answer for the why. Or build this code (tested with g++ -std=c++0x, gcc version 4.6):

#include <iostream>
int main()
{
    if (NULL == nullptr)
        std::cout << "NULL == nullptr\n";
}

Declare the variable immediately before using it, possibly also defining it. This reduces its scope to the minimum, helps the reader/maintainer of the code understanding what the variable is for, and avoids terrible errors deriving from forgetting to initialize variables. (This should also provide you with some guideline for the question about re-using the same variable twice in the same block.)


You should put the lock statements before the try{}finally.

For example if the thread is interrupted before your interruptible acquire then lockInterruptibly will throw and the finally will try to unlock a non-locked lock (which will throw a IllegalMonitorStateException).

There is no need for the signalAll in the acquire methods, as nothing happens that may require a waiting thread to awake (all that were waiting will still need to wait).

Similarly you only need a signal() call in the release to signal a single waiting thread to awake.

Only the first issue is a true bug the other 2 are performance issues (and invalidate the fairness)


Bit-reversal permutation bug
Keeping both a normal counter and the "reversed counter" is the right idea, but this implementation isn't quite right. For example, it might result in a sequence such as 0, 4, 2, 6, 1, 3, 5, 7 while the correct one is 0, 4, 2, 6, 1, 5, 3, 7.
A   B
000 000
100 100
010 010
110 110
001 001
011 101 <<<
101 011 <<<
111 111

There are various ways to do this without that bug, but some of them rely on instructions that are unlikely to be efficient (or even exist) on microcontrollers, such as leading zero count and shift-by-variable. I don't know what you can make work, and make efficient, since I don't know your microcontroller. Perhaps a recursive implementation of the bit-reversal permutation is better, but maybe not, given the often high cost of recursion on microcontrollers. I can only recommend trying some options, I don't know how they will work out in your specific case.
Also, see at the bottom for algorithmic changes.
Periodic test in the inner loop
By that I mean the condition of this if statement:

if (i % even_to_odd == 0) {
    to_even = 2 * i;
    current_rotation = complex_init(1, 0);
}

While it is the case that a remainder operation with a power of two on the right hand side can be efficient, that only applies when the compiler knows it's dealing with a power of two. Hypothetically, a compiler could detect this case, but there is not much hope for that happening. GCC 10 compiling for x64 (I realize you're not targeting that, but that's not really the point, it's about the compilers ability to reason above the set of values even_to_odd could have and how to use that information) makes this for example:
    mov     eax, ecx
    xor     edx, edx
    div     ebx
    test    edx, edx
    jne     .L41

That's not good, and it would be worse on a microcontroller. Since you know that even_to_odd is a power of two, you could write the condition like this: (i & (even_to_odd - 1)) == 0. If GCC 10 cannot do this automatically, it is not likely that the various vendor-specific compilers for some microcontrollers can do it either, as they are usually weaker in that regard.
Benchmarking note

Seems to be 20-40% faster on my desktop than the recursive version I wrote

By all means test it on your desktop, but when option B is faster than option A on a desktop, that is no guarantee at all that that will still be true on the microcontroller. Even between different desktops there is no such guarantee, if they have processors with a different micro-architecture, for example AMD Zen vs Intel Skylake. Benchmarking the code on your desktop can easily trick you into making decisions that are bad for the microcontroller.
Algorithmic changes
The Stockham FFT avoids an explicit bit-reversal permutation, removing the need to implement it efficiently. On the other hand, it accesses memory in a different way and needs temporary work-space. Maybe it's good for your application, or maybe not, I'm not sure.


Elastic Beanstalk configuration using ebextensions container_commands combining leader_only and test

It turns out there is an environment variable called EB_IS_COMMAND_LEADER which can be used in a test. See e.g. this post on AWS forums.
So, the two container commands from the OP can be replaced by this:
container_commands:
  0100_execute_command_on_leader_only_but_never_on_worker:
    command: foo bar
    test: '[[ $ENV_NAME != "worker" && $EB_IS_COMMAND_LEADER == "true" ]]'

I believe this environment variable is only available during deployment, although I could not find any documentation.
NOTE: The original question was aimed at Amazon Linux AMI (AL1), which is now deprecated. In the new Amazon Linux 2 we can use shell scripts in .platform/hooks/ as an alternative to container_commands. The EB_IS_COMMAND_LEADER variable can be used there as well.


Json.NET has a very useful JsonConverter which you can use to add a custom JsonConverter. Which what you actually need.
So, you can do something like this :
public class CandlestickConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Candlestick);
    }

    public override object ReadJson(JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer)
    {
        if(reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        var candle = ( existingValue as Candlestick ?? new Candlestick() );

        var array = JArray.Load(reader);

        candle.OpenTime = array.ElementAtOrDefault(0)?.ToObject<long>(serializer) ?? 0;
        candle.Open = array.ElementAtOrDefault(1)?.ToObject<double>(serializer) ?? 0;
        candle.High = array.ElementAtOrDefault(2)?.ToObject<double>(serializer) ?? 0;
        candle.Low = array.ElementAtOrDefault(3)?.ToObject<double>(serializer) ?? 0;
        candle.Close = array.ElementAtOrDefault(4)?.ToObject<double>(serializer) ?? 0;
        candle.Volume = array.ElementAtOrDefault(5)?.ToObject<double>(serializer) ?? 0;
        candle.CloseTime = array.ElementAtOrDefault(6)?.ToObject<long>(serializer) ?? 0;
        candle.QuoteAssetVolume = array.ElementAtOrDefault(7)?.ToObject<double>(serializer) ?? 0;
        candle.NumberOfTrades = array.ElementAtOrDefault(8)?.ToObject<long>(serializer) ?? 0;
        candle.TakerBuyBaseAssetVolume = array.ElementAtOrDefault(9)?.ToObject<double>(serializer) ?? 0;
        candle.TakerBuyQuoteAssetVolume = array.ElementAtOrDefault(10)?.ToObject<double>(serializer) ?? 0;

        return candle;
    }

    public override void WriteJson(JsonWriter writer , object value , JsonSerializer serializer)
    {
        var candle = (Candlestick) value;
        serializer.Serialize(writer ,
            new[]
            {
                candle.OpenTime,
                candle.Open,
                candle.High,
                candle.Low,
                candle.Close,
                candle.Volume,
                candle.CloseTime,
                candle.QuoteAssetVolume,
                candle.NumberOfTrades,
                candle.TakerBuyBaseAssetVolume,
                candle.TakerBuyQuoteAssetVolume
            });
    }
}

Now, using this custom converter you can use the JsonConverter attribute on the class like this :
[JsonConverter(typeof(CandlestickConverter))]
public class Candlestick
{
    ...
}

Now you can do this directly :
var candles = JsonConvert.DeserializeObject<List<Candlestick>>(jsonObject);

So, you don't need to use extensions, you only need to do a custom converter which is the proper way to handle Json serialization when using Json.NET.


All arithmetic operator functions (+, -, *, /, %) coded only using bitwise operators in C

Don't forget

int mod ( int dividend, int divisor )
{
    return subtract ( dividend, multiply ( divide ( dividend, divisor ), divisor ) );
}

This seems the long way around.  Your divide_recursive calculates the remainder, but you forget it and then recalculate it.

Instead, consider

int mod( int dividend, int divisor )
{
    int remainder = 0;
    divide_recursive(abs(dividend), abs(divisor), multiply(sizeof(int), 8), 0, &remainder);
    return dividend < 0 ? add(~remainder, 1) : remainder;
}

That requires changing divide_recursive to take a pointer instead:

int divide_recursive( int dividend, int divisor, int size, int quotient, int *remainder )
{
    if ( !size ) return quotient;
    int position = subtract( size, 1 );
    *remainder <<= 1;
    *remainder |= ( dividend >> position ) & 1;
    if ( *remainder >= divisor ) {
        *remainder = subtract( *remainder, divisor );
        quotient |= 1 << position;
    }

    return divide_recursive( dividend, divisor, position, quotient, remainder );
}

And we need to change divide to call it correctly:

int divide( int dividend, int divisor )
{
    int remainder = 0;
    int quotient = divide_recursive( abs( dividend ), abs ( divisor ),
                                      multiply( sizeof(int), 8 ), 0, &remainder );

    return ( dividend ^ divisor ) < 0 ? add ( ~quotient, 1 ) : quotient;
}

Too cute?

int abs ( int integer )
{
    int const mask = integer >> subtract ( multiply ( sizeof(int), 8 ), 1 );
    return add ( integer, mask ) ^ mask;
}

This also seems more complicated than necessary.  Why not just say

int abs(int value)
{
    return (value > 0) ? value : add(~value, 1);
}

Why use three functions and two bitwise operations where a conditional chance of one function call is enough?

Testing

How do you know that your implementation is correct?  The correct way is to write unit tests, but at minimum you need to compare your bitwise operations to the built-in operations.  I wrote the following function to make sure that I was doing the math right (particularly when dealing with negative numbers):

void display_remainder(int dividend, int divisor) {
    printf("%d%%%d=%d=%d\n", dividend, divisor, mod(dividend, divisor), dividend % divisor);
}

This is not the pinnacle of coding practices, but it easily lets me see that my revised version is giving the same results as the built-in.  A better, more persistent solution would be unit tests like

CU_ASSERT(-2%-3 == mod(-2, -3));

or possibly better (albeit harder to write):

CU_ASSERT(-2 == mod(-2, -3));

But either way, what's important is that you compare your results to known good results.  If you publish your tests when you ask for a review, it makes it easier for us to test changes we want to propose and to suggest additional tests that show problems in the original code.


Processing a company list in which every element is an employee list

Yes, you can simplify this. Let's break down the algorithm needed for this:

Chain all employees into one stream
Chunk this stream into 1000 employees

For each chunk get the salaries

Distribute the salaries back again into the different companies

The first part can be done using itertools.chain.from_iterable. The second one can use e.g. this grouper recipe. And the final part can be easily done with itertools.islice if we keep everything before as generators.

from itertools import chain, islice

def grouper(iterable, n):
    it = iter(iterable)
    return iter(lambda: tuple(islice(it, n)), ())

def get_salaries(employees):
    respone = requests.post(url, json={"input": employees})
    return parse_respone(respone)

def employee_salaries_per_company(company_employees):
    all_employees = chain.from_iterable(company_employees)
    salaries = chain.from_iterable(get_salaries(employees)
                                   for employees in grouper(all_employees, 1000))
    return [list(islice(salaries, n)) for n in map(len, company_employees)]

Note that in english the plural of employee is employees and not emploices; and the plural of salary is salaries and not salarices.


Hash calculation for array of long values in C#

You could use XOR to combine hashes which is much faster than your calculation:

int hash = 0;
for(int i = 0; i < array.Length; i++)
    hash ^= array[i].GetHashCode();
return hash;


Closing the database connection in the finally will cause an exception if the Open () call throws an exception, so you better close the connection  immediately after you opened it in the try block.

To overcome this problem in a clean way you should let the using block handle it to close the database connection.

Method's should be named using a verb or verb phrase. So better name it e.g IsDatabaseServerAlive ().

Otherwise it looks ok for me.


You can generalize what you want and create a simple function which returns yes if the key is present in your dict, otherwise returns None:

def key_exists(foo, key):
    """
    foo -> dictionary
    key -> lookup key
    Return foo if key exists in foo. Otherwise, return None
    """
    return 'yes' if key in foo else None

print(key_exists({'a': 'b'}, 'a'))
print(key_exists({'a': 'b'}, 'c'))
print(key_exists({}, 'c'))

The output for the above:

yes
None
None

If you, however, don't need a special message if the key is being found in the dict, and want to return a default value if it isn't found, you can do:

def key_exists(foo, key):
    """
    foo -> dictionary
    key -> lookup key
    Return foo if key exists in foo. Otherwise, return None
    """
    return foo.get(key, None)

The output for the above:

b
None
None

PS: Note that above (as Graipher mentioned) it's enough to directly return foo.get(key) as None is the default value anyway.

You usually want to use dict.get(key[, default]) when you need to assign default values. When get() is called, Python checks if the specified key exists in the dict. If it does, then get() returns the value of that key (which is not exactly what you want). If the key does not exist, then get() returns the value specified in the second argument to get(). That being said, you should go with the first solution

Apart from that, you should also know that doing 'key' in dict is faster than any other method. The time to find a key using this method is \$O(1)\$ whereas calling keys would generate a list and be \$O(n)\$


ActiveRecord model for upvotes and downvotes

Here's a 2-part answer: First, a direct answer to your question, and then an alternative approach to the whole thing.

DRYing the current implementation
Firstly, I'd make sure that every "item" has_one :rating. Right now, you're doing a lot of manual record creation, and Rating has to leave all of its attributes accessible to mass-assignment. It'd also be nicer to simply say question.upvote or answer.upvote directly, instead of "manually" calling the Rating.up method and having to supply both user and item.

That can be done, provided you can store the current user somewhere that's accessible to the models. But let's keep it a little simpler and just go for a syntax like question.upvote(user)

To DRY out the "vote-enabled" models, try this:

# in app/concerns/votable.rb
require 'active_support/concern'

module Votable
  extend ActiveSupport::Concern

  included do
    has_one :rating, :as => :item
  end

  module ClassMethods
    def upvote(user)
      # Build the Rating record if it's missing
      build_rating if rating.nil?
      # Pass the user on
      rating.upvote user
    end

    def downvote(user)
      build_rating if rating.nil?
      rating.downvote user
    end
  end
end

Then, in a record that users can vote on, include that concern:

class Question < ActiveRecord::Base
  include Votable
  # ...
end

class Answer < ActiveRecord::Base
  include Votable
  # ...
end

Now the Question and Answer records will automatically build their own Rating record, if they don't have one already, and then pass the upvote/downvote calls on to that rating record.

As for Rating itself, here's what I'd do (I've changed the attribute names a little, but you can of course keep using yours):

class Rating < ActiveRecord::Base
  belongs_to :item, :polymorphic => true
  # Serialize stuff as straight-up Array
  serialize :upvoters, Array
  serialize :downvoters, Array
  # Create arrays after record initialization, so they're not nil on new records
  after_initialize :initialize_voters
  # Update the "owner's" rating cache after every save
  after_save :update_item

  # Note: No attr_accessible at all; it's not needed.

  # I'll skip the comments, as this should all be very easily readable.

  def upvote(user)
    if upvoted_by?(user)
      decrement :rating
      remove_upvoter(user)
    elsif downvoted_by?(user)
      increment :rating, 2
      add_upvoter user
      remove_downvoter user
    else
      increment :rating
      add_upvoter user
    end
    save
  end

  def downvote(user)
    if downvoted_by?(user)
      increment :rating
      remove_downvoter user
    elsif upvoted_by?(user)
      decrement :rating, 2
      remove_upvoter user
      add_downvoter user
    else
      decrement :rating
      add_downvoter user
    end
    save
  end

  def upvoted_by?(user)
    upvoters.include? user.id
  end

  def downvoted_by?(user)
    downvoters.include? user.id
  end

  private

    def add_upvoter(user)
      upvoters << user.id
    end

    def add_downvoter(user)
      downvoters << user.id
    end

    def remove_upvoter(user)
      upvoters.delete user.id
    end

    def remove_downvoter(user)
      downvoters.delete user.id
    end

    def initialize_voters
      upvoters ||= []
      downvoters ||= []
    end

    def update_item
      if item.present?
        item.update_attribute :rating_value, rating
      end
    end

end

And that's pretty much it. Now you can do Question.find(23).upvote(current_user) or whatever, and it should work out.

Going straight to the database
Alternatively, I'd suggest using "raw" database queries instead of models with serialized attributes and all that. All you really need is a simple table. It doesn't need an id column or a model-layer abstraction. All it needs to is have 4 columns: user_id, vote, item_type, and item_id. You can skip ActiveRecord models and such, since all you need to do is check for a certain user/item combo.

Make user_id, item_id and item_type the primary key (or add a uniqueness constraint) and you can do the entire logic in SQL (at least MySQL). If, for instance, user 23 votes on answer 42, it'd look like this:

INSERT INTO `votes` (`user_id`, `item_id`, `item_type`, `vote`)
VALUES (23, 42, "Answer", X)
ON DUPLICATE KEY UPDATE `vote`=IF(`vote`=X, 0, X);

where X is 1 for an upvote, or -1 for a downvote. That's actually all the upvote/downvote logic in one query.

Right after that, update the total rating for the post:

UPDATE `answers`
SET `rating_value`=(
  SELECT IFNULL(SUM(`vote`), 0)
  FROM `votes`
  WHERE `item_id`=42 AND `item_type`= "Answer"
)
WHERE id=42;

From time to time, you may want to do some clean-up to keep the table a little leaner (i.e. delete rows where the vote is zero, or when an associated item is deleted), but otherwise you should have a pretty robust solution with none of the overhead of Rails and ActiveRecord. And it can all be abstracted into a mixin like the concern above, and you can easily add the upvoted_by?(user)/downvoted_by?(user) methods there too with some simple SQL:

SELECT * FROM `votes` WHERE `vote`<>0 AND `user_id`=23 AND `item_id`=42 AND `item_type`="Answer";


Find the length of a frequency-change cycle (Advent of Code 2018)

I'm not convinced that your algorithm is very different, but since it'll take me more than a comment to outline it, I figured I might as well do a quick code review.

I've also done some name switching -- in general I tried to keep my comments referring to the same named functions as yours, but if you see an unfamiliar name you can reference my sample solution. I probably used the name I gave in it.

Small things

input

Splitting input into a bunch of different functions is good, but there are some changes I'd make.

I would rewrite removeLeadingPlus as a more general function that isn't partial (I'm pretty sure your implementation errors on the empty string -- not that it matters that much since read will error on an empty string too)

removeLeadingPlus :: String -> String
removeLeadingPlus ('+':s) = s
removeLeadingPlus s = s

Note that both cleanNumbers and toNum can be defined without the helper variable strs/string as so

cleanNumbers = map removeLeadingPlus
toNum = map read

I also think that

toNum (cleanNumbers (splitNumbers contents))

is a bit hard on the eyes (though if you're coming from Lisp, I'd understand your inclination). You've correctly identified that input can be realized as the composition of a few functions, so why not define it as such?

input :: String -> [Integer]
input = toNum . cleanNumbers . lines
    where
        cleanNumbers = map removeLeadingPlus
        toNum = map read
        removeLeadingPlus ('+':s) = s
        removeLeadingPlus s = s

And we can go one step further. Now that we've realized that toNum and cleanNumbers are both just maps, we can redefine input as

input :: String -> [Integer]
input = map (read . removeLeadingPlus) . lines
    where
        removeLeadingPlus ('+':s) = s
        removeLeadingPlus s = s

Maybe this looks less clean to you. I think that

input = map (read . removeLeadingPlus) . lines

and

input contents = map (read . removeLeadingPlus) $ lines contents

are both fine and pretty readable.

accumulate

I like this function and I think it's a better approach to obtaining the frequencies (your inefficiency is still in duplicate). However, accumulate looks suspiciously similar to a function in Prelude.

accumulate takes in a list of integers and returns all of the prefix sums of them. So it is essentially foldl of every prefix of the input list.

You might be familiar with scanl which is a combinator that does this.

*DayOnePartTwo> accumulate [1,2,3,4]
[1,3,6,10]
*DayOnePartTwo> scanl (+) 0 [1,2,3]4
[0,1,3,6,10]

It even gives us the desired starting value of 0 (which you presently hardcode into duplicate).

So we can write a much shorter definition of accumulate as

accumulate :: [Integer] -> [Integer]
accumulate = scanl (+) 0

I also think a better name is freqs since I think accumulate is vague.

firstCyclicDuplicate

This can also be realized as the composition of a bunch of functions

firstCyclicDuplicate :: [Integer] -> Maybe Integer
firstCyclicDuplicate = duplicate . accumulate . cycle

Again, up to personal preference.

duplicate

I would rename this to firstDuplicate to be consistent with firstCyclicDuplicate.

Indentation

I'm not a Haskell pro, but your indentation seems a bit off and my syntax highlighting agrees with it (it doesn't highlight the function declarations when they're indented). I would keep everything top level unindented. Also my personal preference is indenting by two spaces, so that's what I've done in my sample solution.

Imports

Your imports are unnecessary as far as I can tell (my code compiles without them). If you thought you needed the imports for the types, I think they're in Prelude.

Use of Maybe in duplicate

I like the use of Maybe here and I suggested the same to dagda1, but I realize now that its use, while stylistically good, is somewhat pointless.

Since you're operating on an infinite list of frequencies, your code will run forever (or until the stack blows). Even though you have

        dup [] _ = Nothing

you'll never pattern match an empty list since you're running this function on an infinite one.

Stylistically, I think using Maybe is better than having a partial function, but I just wanted to point out that having pure functions doesn't necessarily save you from an infinite loop.

Efficiency

Your implementation is, for all intents and purposes, the same algorithm as dagda1's in the other post.

They chose to accumulate the frequencies inside of their function to find the duplicate, whereas you've decoupled the two. Due to laziness I would argue the approaches are the same.

Again, the inefficiency comes down to the use of lists over sets in duplicate. This is a great problem to demonstrate why elem is something you should be wary of using and why linked lists make poor sets.

Your issue is in your duplicate lookup

            if elem x visited

as elem is an O(n) operation. You can read the Efficiency section on my answer to the other post for a bit more details.

The solution is the same, and I'll copy paste my response for convenience.

Introducing Data.Set

Data.Set provides unordered sets with O(log n) lookup and insert time. Yeah, it's O(log n), but the total runtime for me when I checked the implementation was less than a second.

I'm including a sample implementation of day 1 below that I've tested and confirmed on my inputs if you want to compare. Here are some pointers if you want to fix it yourself

You can keep your code mostly the same (although I'd recommend making the style changes I suggested)
You will want to use two functions from Data.Set: member and insert.
Your only need to change duplicate, specifically your use of data structure (see section header, hint hint)

Sample solution

module DayOnePartTwo where

import Data.Set (Set)
import qualified Data.Set as S

inputFileName = "input.txt"

input :: String -> [Integer]
input = map (read . removeLeadingPlus) . lines
  where
    removeLeadingPlus ('+':s) = s
    removeLeadingPlus s = s

freqs :: [Integer] -> [Integer]
freqs = scanl (+) 0

firstDuplicate :: [Integer] -> Maybe Integer
firstDuplicate list = dup list S.empty
  where
    dup (x:xs) visited =
      if x `S.member` visited
        then Just x
        else dup xs (S.insert x visited)
    -- This will never be reached on the cycled list
    dup [] _ = Nothing

firstCyclicDuplicate :: [Integer] -> Maybe Integer
firstCyclicDuplicate = firstDuplicate . freqs . cycle

main :: IO ()
main = do
  contents <- input <$> readFile inputFileName
  case firstCyclicDuplicate contents of
    Just a -> print a
    Nothing -> print "There is no first duplicate"


Three versions of a counting-up timer in JavaScript

Performance is not a significant concern, since all three callbacks have very little code, and they execute only once per second.  Rather, you should aim for clarity.  In my opinion, Version 1 is simplest and easiest to follow.

All three techniques suffer from the same weakness with window.setInterval(…, delay):

  delay

  The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. If this parameter is less than 10, a value of 10 is used. Note that the actual delay may be longer; see Reasons for delays longer than specified in WindowOrWorkerGlobalScope.setTimeout() for examples.

In particular, the interval may be throttled to 10 seconds for long-running scripts in background tabs, or the callback may be delayed if the JavaScript engine is busy executing other tasks.  Furthermore, the whole machine might go to sleep.

Rather, you should check the time difference with every tick.  (As a side benefit, this should help address your concern about casual Web Inspector tampering.)

Use destructuring assignment to write more meaningful names than unit[0] and unit[1].   Note that in for (unit of timeIntervals), you neglected to localize unit in any way, so it's global.

The tick function should probably be declared as const rather than var.  I'd also prefer to use let rather than var, as better software engineering practice.

Also, as better practice, use jquery.text() rather than .html(), if you know that the content is text without HTML markup.

const timeIntervals = [
    ["day", 86400000],  // milliseconds
    ["hour", 3600000],
    ["minute", 60000],
    ["second", 1000]
];
const tick = (start) => () => {
    let elapsed = Date.now() - start;
    for (let [unit, ms] of timeIntervals) {
        $("#" + unit).text(Math.floor(elapsed / ms));
        elapsed %= ms;
    }
};
let timer = window.setInterval(tick(Date.now()), 1000);

  0 days,
  0 hours,
  0 minutes,
  0 seconds


Weekly job to create or update the lessons in all locations

The code as written is fine.  And I say that as hater of all things nested.
One way or the other, you have nested loops.  One option is to retain that
structure explictly, as it currently is, but to clean it up by removing temporary
named variables that add clutter but not clarity:

def perform(*args)
  Location.all.each do |location|
    timetables = LocationLessonService.fetch(location.id)["timetables"]
    timetables.each do |timetable|
      timetable["lessons"].each do |lesson|
        Lesson.find_or_initialize_by(external_id: lesson['external_id'])
          .update_attributes(period.merge(location_id: location.id))
      end
    end
  end
end

What makes it difficult to tease these loops apart into named methods is
that the innermost loop references the location.id from the outermost loop.

That said, I'm wondering why the location isn't simply a property of the timetable?
Or can the same timetable exist in multiple locations?  Because if the location
were a property of the timetable, you wouldn't have the problem I mentioned in
the last paragraph.

That is to say, while I don't consider the code itself problematic, there may
be better ways to organize your data.  But it's hard to say without knowing more.


One method for changing one of the properties

I find there is nothing wrong with using a dictionary here. What I'm worried about are those properties:

private static int Coins { get { return resourceBox[ResourceType.Coins]; } }
private static int Diamonds { get { return resourceBox[ResourceType.Diamonds]; } }
private static int Hearts { get { return resourceBox[ResourceType.Hearts]; } }

Why do you need them? They are not only static but also private. If you cannot access them from the outside how are you going to use them?

You didn't include the complete class definition but just a small snippet so it's hard to give you more feedback.


Creating automatic resizing of subelements in WPF

I would say no. If you want to create grid-like layout, you should declare columns and rows, and specify how wpf should stretch those. For example like this:

<Grid Margin="30" x:Name="bgBorder">
    <Grid Background="#555555" x:Name="mainWindow" MouseDown="mainWindow_MouseDown">
        <Grid.RowDefinitions>
            <!-- frist row will stretch to fit the content -->
            <RowDefinition Height="Auto"/>
            <!-- second row will fill all available space -->
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Margin="2" Grid.Row="0" Height="80" Background="#779999" x:Name="topControl"/>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <!-- first column will fill all available space -->
                <ColumnDefinition Width="*"/>
                <!-- second column will stretch to fit the content -->
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <Grid Grid.Column="0" Margin="2" Background="#557777" x:Name="playListControl"/>
            <Grid Grid.Column="1" Margin="2" Width="234" Background="#668888" x:Name="optionsControl"/>
        </Grid>
    </Grid>
</Grid>

You should really do some reading on how things are done in wpf, this HTML-ish layout you are trying to create won't work.


Good

Private attributes for storing state in the class (id, owner).
Getter and setter methods are simple.

Bad
Not a RestApi

REST is an architectural style it can't be represented by an object.  It is the wrong level of abstraction for an object to represent an architectural style.
Your RestApi object has public methods: getInstance, getId and getOwner. These have nothing to do with representational state transfer.

Constructor

The constructor should only create the object. By doing so much in your constructor you make it difficult to extend your class (going against the Open / Closed principle). It also makes it harder to unit test this code.
If you construct your object with an array that doesn't contain the key 'request' your code will emit an error notice.
unset($pieces); is unnecessary. Don't worry about memory management.

getInstance

This method should not be called getInstance.
This method does too much.
It can call setOwner when it should only be getting an instance.
Also, why should the class that you create depend on your RestApi object? get_class($this) will return 'RestApi' or 'RestApiDerived' if you derive another class from it. Why should the object that you create be so tightly coupled to the RestApi class?

I'm actually left confused by this class. The naming of methods and the object itself doesn't help me to understand what sort of objects this class represents. It doesn't map to anything in the real world that I can understand.