Missed 2, indirectly blind, know the rules, & chasing the tail.

There are four problems with the functionality. The last one will present you with the biggest challenge, as proxy traps can be CPU costly and adding a check (which involves keeping a reference for each object as you step the path) may well be impractically slow.

The two you missed.

There are two additional method for modifying an object directly

An object can be modified via delete

proxy.test.a = "a";
delete proxy.test.a;  // this modification will be missed

An object can be modified via defineProperty

Object.defineProperty(proxy.test, 'c', {
    writable : false,
    enumerable : false,
    configurable : false,
    value : "definedProp",
});

You will need to use the deleteProperty and defineProperty traps to get them.

The one you don't see.

Also you will not see modification that are indirect.

const testObj = {a : 0, b : 1};
proxy.test[0] = testObj;  // this is trapped
proxy.test[0].c = "c";    // you trap this as well

testObj.c = 10;           // you miss this

The rules.

Though I am not sure if this was the intention but you are also picking up on inherited properties that may have been protected. You need to check that you can write to the property.

Object.defineProperty(Array.prototype, 'foo', {
    writable : false,
    enumerable : false,   // Also not enumerable! should you be looking?
    configurable : false,
    value : "bar",
})
proxy.test = [];
proxy.test.foo = "poo"; // You trap this as if the assignment is ok
// yet
console.log(proxy.test.foo); // outputs "bar"

Chasing the tail.

And the ever present problem that you face when doing deep searches is you have no protection against cyclic references.

It`s a little tricky as i was sure a simple cyclic reference would overflow the call stack, but that did not happen. With a little experimentation I did find a way to make it crash.

const myObj1 = {a : 0};
const myObj2 = {a : myObj1}
proxy.test = [];
proxy.test.push(myObj1)
proxy.test.push(myObj2)
proxy.test[0].a = myObj2;  // all good to this point

// this causes endless iteration and eventually the call stack will throw
// RangeError: Maximum call stack size exceeded
proxy.test[0].b = myObj1;


Enum, constants, or other to represent chess pieces

I think it definitely makes sense to use an object hierarchy here. What's the difference between a black and a white pawn? Its colour! (which will affect which way it can move relative to the board).

All pieces must have exactly one colour, and we have two to chose from:

public enum PieceColour
{
    White = 0,
    Black = 1
}

As we've already reasoned, all pieces have to have a colour and unless you've got a defective set, none of the pieces can change colour midway through. Sounds like we have an invariant that we want all pieces to obey. We can lock that up with a base class:

public abstract class Piece
{
    private readonly PieceColour colour;

    public PieceColour Colour { get { return colour; } }

    protected Piece(PieceColour colour)
    {
        this.colour = colour;
    }
}

By making the piece class abstract, we are saying "you can't have a generic Piece, you have to have a specialized subclass". Let's see what that some of those might look like:

public class Pawn : Piece
{
    public Pawn(PieceColour colour)
        : base(colour)
    {
    }
}

public class Rook : Piece
{
    public Rook(PieceColour colour)
        : base(colour)
    {
    }
}

public class Knight : Piece
{
    public Knight(PieceColour colour)
        : base(colour)
    {
    }
}

Now you can start playing around with a board. To be completely honest, I haven't thought enough about it to figure out how I'd really want it to look but something like the following would be enough to get along with. Tuple<int, int> is just a convenient wrapper around two ints (the coordinates of a space).

public class Board
{
    private Dictionary<Tuple<int, int>, Piece> currentState;

    public static Board CreateNewBoard()
    {
        var board = new Board();

        board.currentState = new Dictionary<Tuple<int, int>, Piece>
        {                      // x, y
            { new Tuple<int, int>(0, 0), new Rook(PieceColour.White) },
            { new Tuple<int, int>(1, 0), new Knight(PieceColour.White) }
            // etc.
        };

        return board;
    }
}

}

Any common behaviour you should find behind all pieces you should add it to the base class Piece, for example they can all move...

Edit

I thought the above made it clear that I think there should be an abstract method on the piece class that deals with movement. I didn't commit to making a suggestion on the signature of the method because I haven't seen what you're doing currently. I have the impression OP intends on "moving pieces" entirely within the board class.


It's not problematic in the sense that _endChain will always be called after the whole chain. In fact you could simplify the code by only creating the timer once:

var a = {
  _timer: null,
  _resetTimer: function() {
    if (!this._timer)
     this._timer = window.setTimeout(this._endChain.bind(this), 0);
  },

But the problem will come with code that follows for example:

a.A().B().B().A();
DoMoreStuff();

Most developers would be surprised to find that the first call has not completed. I think the better solution would be to implement an end method which is what many libraries do:

let result = a.A().B().B().A().end();
DoMoreStuff();

Or a promise like method:

a.A().B().B().A().then( function(result) {
  DoMoreStuff();
});


Exceptions
You don't need the sys.exc_info call since pdb.post_mortem without argument uses the exception being currently handled. You don't need pdb either since it serves for development purposes and, at this stage, you should have working code already.
And since all what's left in the except clause is traceback.print_exc(), you could remove the try .. except and let the interpreter print the traceback for you.
Also, it's a very bad habbit to use bare excepts. You should know what kind of exceptions you’re willing to handle. (Even though it can be usefull with pdb to examine various causes of issues.)
Class
Given how you use the class (initialization of attributes, computation and getting one attribute back), I think you could do equally well with a simple function. Just initialize what you need before the for loop and return the computed array:
def LMS(input_signal, desired_signal, num_taps, learning_rate):
    num_points = len(input_signal)
    weights = np.zeros(num_taps)
    equalized = np.zeros(num_points)

    for n in xrange(num_taps, num_points):
        x = input_signal[n:n-num_taps:-1]
        equalized[n]= desired_signal[n] - np.dot(x, weights)
        weights = weights + learning_rate*x*equalized[n]

    return equalized

Note that I kept the meaningfull names to help read the algorithm. I also removed y which was a temporary variable and served no purpose after computation.
main
It is also good practice to avoid keeping code at the top-level of the file. Just in case you want to import your file (for testing purposes in an interactive shell, for instance), you should guard the code in an if __name__ == '__main__': clause.
The whole code becomes:
import numpy as np
import matplotlib.pyplot as plt

def LMS(input_signal, desired_signal, num_taps, learning_rate):
    num_points = len(input_signal)
    weights = np.zeros(num_taps)
    equalized = np.zeros(num_points)

    for n in xrange(num_taps, num_points):
        x = input_signal[n:n-num_taps:-1]
        equalized[n]= desired_signal[n] - np.dot(x, weights)
        weights = weights + learning_rate*x*equalized[n]

    return equalized

if __name__ == '__main__':
    np.random.seed(1337)
    ulen = 20000
    coeff = np.concatenate(([1], np.zeros(10), [-0.9], np.zeros(7), [0.1]))
    u = np.random.randn(ulen)
    d = np.convolve(u, coeff)
    num_taps = 20
    step = 0.01

    eq = LMS(u, d, num_taps, step)

    plt.figure()
    plt.semilogy()
    plt.subplot(1,1,1)
    plt.plot(np.abs(eq))
    plt.show()

(I removed the extra whitespace arround assignements since it is recommended by PEP8)


Just 1 will work here.  It will do a cast to 1

SET @IsActive = 1

You can also assign in the declare

DECLARE
      @Model_ID INT
    , @ModelVersion VARCHAR(10) = 'lasdf'
    , @ExistsInDM INT
    , @IsActive BIT = 1

SELECT  @Model_ID = Model_ID
FROM    [sch_AM].[tblDMModelVersion] WITH (NOLOCK)
WHERE   [ModelVersion] = @ModelVersion

Above will get the last value read.

with (nolock)

Is typically not advised.


Restricted file upload to remote the Ruby way

I may be mistaken but I really do not see why using Net::SCP would be any different (more dangerous) than copying by piping through ssh. It is not like by using Net::SCP you would be giving somebody more rights, it is all contained within your code and under your control.

If somebody tries to misuse Net::SCP he can also misuse the cat solution copying anything else the user user has access to.

But - AFAIK 2>&1 doesn’t really overwrite stdout by stderr, it appends stderr to stdout, in which case you would be raising an error also on output and not only on error.

Try this instead:

def self.push_file
    output = `cat datafile | (ssh -i id_rsa user@backend 'true' | sed 's/^/O: /' >&9 ) 9>&2 2>&1 | sed 's/^/E: /'`
    errors = output.select{|e|e.match(/^E:/)}.map{|e|e.sub(/^E: /, "")}
    raise errors unless errors.empty?
end

Found in In the shell, what does “ 2>&1 ” mean?

If not using SCP you can still improve on this pipe solution by using rsync :

rsync -avz -e "ssh -i id_rsa" /home/user/datafile backend:/home/user/


You can do it with one loop that goes from a negative number to a positive, and create a string from a range calculated from the number:

int max = 5;
for (int i = 1 - max; i < max; i++) {
  Console.WriteLine(String.Join(" ", Enumerable.Range(1, max - Math.Abs(i))));
}

That is of course actually two loops, the Range method will create numbers that the Join method loops through.


Class design

A good class in general is one that corresponds to an Abstract Data Type,
which is a collection of data and operations that work on that data.
A good ADT should have a single, clear responsibility.

The Global class is not a good ADT:

It does two unrelated things:

Contain configuration information
Manage a proxy pool

Possibly as a consequence of the previous point, it is poorly named

It would be better to split this class into two:

Configuration or Config: contain configuration information
ProxyPoolManager: manage a proxy pool

Note that ProxyPoolManager should not reference Configuration directly:
it will be best to pass to it the proxyHost and proxy as constructor parameters.

As the poorly named Conn class already does half of the proxy pool management,
it would be better to rename it to ProxyPoolManager and move getPool method into it and rename Global to Configuration.

Coding style

You have several coding style violations, not conforming to PEP8:

Use spaces around = in variable assignments, for example:

proxy = True instead of proxy=True
opts = AttrDict(...) instead of opts=AttrDict(...)

No need to put parentheses in if(self.proxy):
There should be one blank line in front of method definitions of a class: put a blank line in front of get and switch methods in the Conn class
You mistyped switch as swith

Other issues

This code doesn't compile:

class Conn:
    def get(url, opts=Global.opts):
        try:
          self.pool.urlopen(...)

Because it makes a reference to self which was not passed in as method parameter.

This is a bit hard to understand,
because of reusing the name "proxy" both as method parameter and as attribute:

def getPool(self,proxy=None):
    if proxy is  None:
        proxy = self.proxy
    if(self.proxy):
        http_pool = urllib3.proxy_from_url(self.proxyHost)
    else:
        http_pool = urllib3.connection_from_url(self.host)
    return http_pool

The purpose of this method would be more clear if you used a different name for the method parameter.


Remove the second number from every group of three numbers

You want to skip every number of the form 3k+1? Then say that, using a generator expression.

print(' '.join(str(i) for i in range(30) if i % 3 != 1))


The odd behaviour is that the result gets printed twice: once in reverse(), and again in main().  reverse() should be fixed so that it returns the result without printing it.

The output will also include an extra space at the end.  It may be invisible, but I would consider it technically incorrect.

Your code, with those issues fixed, and a few tweaks:

public static String reverse(String input) {
    String delimiter = " ";
    String[] splits = input.split(delimiter);
    String reverse = "";                            // Same as new String("")
    for (int i = splits.length - 1; i > 0; i--) {   // Be more generous with spaces
        reverse += splits[i] + delimiter;           // Get rid of .concat()
    }
    if (splits.length > 0) {
        reverse += splits[0];
    }
    return reverse;
}

However, repeated string concatenation is inefficient: every += involves allocating a new buffer and copying everything.  You should really be using a StringBuilder, like this.  (Other suggested solutions in that question are also quite good.  You should study those answers and form your own opinion.)


Let's look at all of your questions, one by one:

This class doesn't really do anything, and is really a pretty struct

Yes and no. This class has a clear task within the application: it is passed around, carrying data. It represents a number of values that belong together. It's a model. Having data containers isn't just OK, it's good practice. You can use type-hinting, and doc-blocks to make your code easier to use.
You call it a glorified struct, well: in C, a FILE * is just a struct, too, but you rarely use it as such: There's an entire API that handles the nitty-gritty for you, in the same way that you can use this model to validate the data you are setting.

Code that requires this data, either to store it in a DB, or present it to the client side in a view, can then be written with a clear contract:

public function showRecipient(Recipient $recipient)
{
    //if an instance is passed, its email address is expected to be set and valid
}

But how do you best make sure when, and where to validate the email address:

The validation isn't specific to this place, I may want to check emails in other places

Don't. If you are processing data that belongs to, or is part of the dataset that makes up a Recipient, the thing to do is to wrap this data in the appropriate container: a Recipient instance.
If you validate the email elsewhere in your code, you are repeating yourself. Simply pour it into an object, that makes sure the data is valid, and pass that object around. Whatever values you extract from it (through getters), is guaranteed to be validated.

Should the validation happen in the constructor? Should it be a separate class? What would that look like?

The validation should Not be done in the constructor. I can construct an instance, and re-assign/reset the properties to a particular value, bypassing the constructor's  validation.
A separate class, then? No. Really... why would you centralize all data validation/sanitation? Such a class would be either an all-static monster, or you'd initialize all validation code, every time you want to validate a single value.

I'd make my properties protected, and use setters. These setter methods are tailored to the type of property they are setting, and can perform the necessary sanitation and validation. Simple.

Should there be an interface for every class? Would that live at the top of this file?

Depends. Is it worth while? Are there similarities between other models (database mapping: getId() and setId methods)? Is there a certain type of functionality you want to add (for example implementing one of the Traversable interfaces).
Hard to say from what code you shared, but if this is the only data-class then: no. An interface is probably not required.

Should I throw exceptions when it's not valid? Should they be an object as well? How?

Yes: a class has just one job. This class' job is to contain valid data. Raw data is passed to its setters, which validate/sanitize this data. If the data is malformed/invalid, the Recipient class is not responsible for it: the code that supplied the data is. The Recipient should throw an exception (it encountered exceptionally formed data), and the calling code should handle the problem.
Should these exceptions be objects: Of course, they are. There's no way around them. If you mean: should I throw or set a property, the answer is: throw. Your class encountered a problem. Setting a property or returning false assumes the calling code is checking return values or flags. This is not a given (return values are often ignored, and error flags seldom checked).
Throwing an exception forces the calling code to respond

To answer the how question, here's how I'd write your class:

class Recipient
{
    protected $email = null;
    protected $name = null;
    public function __construct(array $data = array())
    {
        foreach ($data as $key => $val)
        {
            //transform key to method
            $method = 'set'.ucfirst(strtolower($key));
            if (method_exists($this, $method))
                $this->{$method}($val);
        }
    }
    public function setEmail($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
        {//not a valid email address, throw exception
            throw new InvalidArgumentException(
                sprintf(
                    '%s expects valid email address, %s is not',
                    __METHOD__,
                    $email
                )
            );
        }
        $this->email = $email;
        return $this;
    }
    public function setName($name)
    {
        //add checks/sanitation you need: check length, check format, check for numeric chars...
        $this->name = trim($name);
        return $this;
    }
    public function getEmail()
    {
        return $this->email;
    }
    public function getName()
    {
        return $this->name;
    }
}

That should do it. Usage examples:

$data = array('email' => 'foo@bar.com', 'name' => 'foo');
$recipient = new Recipient($data);
echo 'From instance - email: ', $recipient->getEmail();
$recipient->setName('    Foo');
echo 'After setter: ', $recipient->getName();//leading spaces are removed

Now, why did I default the constructor argument to an empty array? Simply because it allows you to do this:

$blank = new Recipient();
$obj->EmailGetter($queryObject, $blank);//gets email, sets it on instance
$blank->setName('Unknonwn');

I can create an object, then fetch the data as I go along, and set the properties accordingly.
As far as the exception business is concerned:

$error = new Recipient(
    array(
        'email' => 'invalid'
    )
);//error
//or
$test = new Recipient();
$value = 'invalidaddress';
try
{
    $test->setEmail($value);
    echo 'If $value is valid, this will echo its value again here: ', $test->getEmail();
}
catch (InvalidArgumentException $e)
{//echos "invalidaddress was refused:  Recipient::setEmail expects valid email address invalidaddress is not"
    echo $value, ' was refused: ', $e->getMessage();
}

I've reviewed a couple of validation + data-model related questions, so I thought I'd add some of my (lengthy) reviews here, too. For completeness' sake:

details on Traversable interface
Bulk setting + inheritance
Some more bulk setting
Vaguely related


As OP did not explicitly state the review goals, here are some general ideas.

Use const when referenced data is not changed. Allows for optimizations and defined behavior when the array address passed is const.

// int IBQplain(int pos, char *str, int offset);
// int IBQdouble(int pos, char *str, int offset);
// int IBQsingle(int pos, char *str, int offset);
int IBQplain(int pos, const char *str, int offset);
int IBQdouble(int pos, const char *str, int offset);
int IBQsingle(int pos, const char *str, int offset);

Use size_t as the type for array indexes.  int maybe insufficient.

// int IBQplain(int pos, char *str, int offset);
int IBQplain(size_t pos, char *str, size_t offset);

As the functions only return 1 of 2 values, consider _Bool or bool

#include <stdbool.h>
// int IBQplain(size_t pos, char *str, size_t offset);
bool IBQplain(size_t pos, char *str, size_t offset);

As these functions appear to be stand-alone, suggest more pessimistic range checking:

// if (pos == offset)
if (pos <= offset)
  return 0;  /* Not within quotes */

... otherwise if the below 3 are only helper functions to isBetweenQuotes(), they should be static.

static int IBQplain(int pos, const char *str, int offset);
static int IBQdouble(int pos, const char *str, int offset);
static int IBQsingle(int pos, const char *str, int offset);

Unclear why code accesses the array again instead of ch

for (ch = str[offset]; ch; ch = str[++offset]) {
    if (!escaped) {
      // switch (str[offset]) {
      switch (ch) {

Expect more test cases that have incomplete '' and "" pair combinations, especially onces that begin or end the string.


You can just use the condition in a where, that will filter the single records instead of filtering groups, then you can group the result to avoid duplicates in the result.

You shouldn't convert the date to a string when you are comparing it. When you convert it to a string, you should do that after getting the lowest value, otherwise min will compare the dates as strings and give you the wrong result.

select
  t.name as [Table Name],
  convert(CHAR(11),min(stats_date(t.object_id,s.[stats_id])),106) as [Last Updated]
from
  sys.[stats] as s
  inner join sys.[tables] as t on s.[object_id] = t.[object_id]
where
  stats_date(t.object_id,s.[stats_id]) < dateadd(day, -1, getdate())
group by
  t.name
order by
  2 desc


Is this use of an array of function names and bracket-notation function calling a hacky/evil solution?

Firstly, I wouldn't say it's evil. From JS's point of view, obj["foo"]() is identical to obj.foo(). The dot-syntax and bracket-syntax are completely interchangeable. Of course, if you call your variable "abomination" then, yeah, it's going to sound evil.

Anyway, I think there's a bug or two in your code. When you loop through the json array and get to the actions property, you call the function on $(el) right away. This won't actually do anything, as far as I can tell.

Here's your code, manually interpreted, so to speak:

// this line does nothing; abomination is still === $(el)
abomination = abomination[action](); // same as: abomination = $(el)["prepend"]();

// ...

// and this line fails with "error: object is not a function", because $(el) is indeed not a function
abomination(Handlebars.templates.ratings(templateData)); // same as: $(el)(Handlebars.templates.ratings(templateData))

Also, I imagine the objects in the json array are meant to work on different sites. In that case, I'd key them to the site's domain, so you don't have to loop through everyone of the them on every site. This also eliminates the risk of "false positives" such as if a two different sites both use, say, "movie" as a class name.

Here is what I'd probably do. I've changed names here and there to make 'em more descriptive, but the comments should make it fairly clear

var sites = { // slightly more descriptive name than "json"
  'movietheatre.com': {
    container: '.FFEC-Display', // changed the name here too..
    title:     'h3',
    select:    [
      { name: 'find', args: ['.movie-link'] } // note that args is an array
    ],
    action:    'prepend'
  },

  'showtimes.randomcinema.com': { // note there's no `select` property here
    container: '.MovieItemsRotator .item',
    title:     '.Title',
    action:    'prepend'
  }
};

var domain = window.location.hostname.replace(/^www\./, ""), // the domain (incl. subdomain unless it's "www")
    config = sites[domain]; // get the config

// only do stuff if there's a configuration for the current domain
if( config ) {
  $(config.container).each(function () {
    var container = $(this);

    // I'd put the blacklist-replace/trim stuff into a `getRatings()` function
    // that does all the stuff you say is the always the same anyway. It can also
    // do the template rendering, while it's at it
    var title   = container.find(config.title).text();
    var ratings = getRatings(title); // get the rendered template

    // maybe throw in a check here, in case `getRatings` fails/refuses to return something
    if( !ratings ) { return; }

    // Now for the fun stuff
    var target = container;

    // if there's no sub-select-stuff, default to an empty array
    // (and use the built-in forEach instead of jQuery)
   (config.select || []).forEach(function (call) {
      // use `apply()` to call the requested function with the requested args (if any)
      target = target[call.name].apply(target, call.args || []);
    });

    // now `target` should be the right element
    // and we can call the required insert/append/prepend action
    target[config.action](ratings); // i.e. target.prepend(ratings)
  });
}


Is this right way to implement Abort, Retry and Ignore activity pattern?

You really shouldn't be using exceptions to control the flow of your program's logic. What you're trying to do tends to work much better as a simple state machine that, when it fails, asks whoever is listening what it should do and responds accordingly. Here's a very rough example (which hasn't been tested, is not threadsafe, etc).

public interface ISequentialActivity
{
    bool Run();
}

public enum UserAction
{
    Abort,
    Retry,
    Ignore
}

public class FailureEventArgs
{
    public UserAction Action = UserAction.Abort;
}

public class SequentialActivityMachine
{
    private Queue<ISequentialActivity> activities = new Queue<ISequentialActivity>();
    public event Action<FailureEventArgs> OnFailed;
    protected void PerformOnFailed(FailureEventArgs e)
    {
        var failed = this.OnFailed;
        if (failed != null)
            failed(e);
    }
    public void Add(ISequentialActivity activity) { this.activities.Enqueue(activity); }
    public void Run()
    {
        while (this.activities.Count > 0)
        {
            var next = activities.Peek();
            if (!next.Run())
            {
                var failureEventArgs = new FailureEventArgs();
                PerformOnFailed(failureEventArgs);

                if (failureEventArgs.Action == UserAction.Abort)
                    return;
                if (failureEventArgs.Action == UserAction.Retry)
                    continue;
            }

            activities.Dequeue();
        }
    }
}

In this example, classes would encapsulate sections of retry-able logic by implementing ISequentialActivity, returning true from their Run() method if they succeeded and false if they failed in some way. Failure would then be pushed up to the listener through the event for decision making.


Move your revert all logic to the top of the function to avoid having to exclude the newly active item.

Use a stateful class such as .is-active instead of message-head-active. Means you only have to toggle 1 class rather than 2.

toggleClass accepts multiple arguments so you can toggle the FontAwesome classes in one line. This also removes the need for the hasClass check.

Store the result of $("tr.message-head-active") to a variable and reuse it when reverting the header and the icon.


Most common occurrence of an int in an array

Whenever you're dealing with collections in C#, there's often a simple Linq solution.

Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy method on the integers. This makes each integer a key with a list of values for each occurrence.

Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending and .First methods do this for you.

static void CommonOccurrence(int[] numbers)
{
    var groups = numbers.GroupBy(x => x);
    var largest = groups.OrderByDescending(x => x.Count()).First();
    Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}

If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:

static void CommonOccurrence(int[] numbers)
{
    var dictionary = GroupByOccurrence(numbers);
    var mostCommonNumber = KeyOfLargestValue(dictionary);
    var occurrences = dictionary[mostCommonNumber];
    Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}

static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
    var result = new Dictionary<int, int>();
    foreach (int i in numbers)
    {
        if (!result.ContainsKey(i))
        {
            result[i] = 0;
        }
        result[i]++;
    }
    return result;
}

static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
    int result = dictionary.Keys.First();
    foreach (var entry in dictionary)
    {
        if (entry.Value > dictionary[result])
        {
            result = entry.Key;
        }
    }
    return result;
}


Improving Point Cloud Slice Parameter's Adjusting loop

You are using the same pattern in both your loops - enable some flag before the loop, and disable that flag immediately as you enter the loop. So basically you want to always enter the loop and always exit loop unless something will enable the flag.

bool flag = true;
while (flag)
{
    flag = false;
    // ...
    // some condition can set flag to true

    if (flag)
      continue;
}

Same can be achieved without using a flag - use infinite loop and break it only when your exit condition happen

while (true)
{
    // ...
    if (sliceDepthSubstractorAdjusted)
       break;
}

Now, what about nested loop? I stick to single indentation level rule of thumb. To avoid arrow anti-pattern. You can move loop logic to separate method and return outer exit loop condition from that method. Thus you can keep loop even without a body:

while (!TryAdjustSliceDepthSubstructor()) {}

Pretty descriptive - repeat adjustment until it done. But you should pass different values to that method - a, sliceDepthSubtractor, startDepthSlice. And this code will not look so good with all these parameters flying around. The reason is that we keep data and logic separated. So simply put logic (points adjustment with some parameters) and data (parameters) into the class.

public class Butcher// Of course, you should change the name
{
     private double sliceDepthSubtractor;
     private double startDepthSlice;

     public Butcher(double sliceDepthSubtractor, double startDepthSlice)
     {
         // initialize fields here
     }

     public void AdjustForSlicing(List<PointCloud> points) { ... }

     // TakeSlice
     // lmsSolver
}

Now you can initialize this class and your code with outer loop will look like

var points // List<PointCloud>
var butcher = new Butcher(xlm.sliceDepthSubtractor, xlm.startDepthSlice);
butcher.AdjustForSlicing(points);
Save(points); // use PascalCase names for methods

Looks clean. Let's look inside

public void AdjustForSlicing(List<PointCloud> points)
{
    while(!AllSlicesContainEnoughPoints(points)) // surprise - single loop here
    {
        if (CanAdjustStartDepthSlice)
        {
            startDepthSlice -= 0.1;
            continue;
        }

        if (CanAdjustDepthSubstractor)
        {
            // NOTE: Consider to reset startDepthSlice here
            sliceDepthSubtractor += 1;
            continue;
        }

        throw new ComputationException("Insufficient Points");
    }
}

private bool AllSlicesContainEnoughPoints(List<PointCloud> points)
{
    const int minCountOfPointsInSlice = 100;

    foreach(var point in points)
    {
        var slice = TakeSlice(point, sliceDepthSubtractor, startDepthSlice);

        if (slice.PointCount < minCountOfPointsInSlice)
            return false;

        lmsSolver(slice, point);
    }

    return true;
}

And a couple of helper methods. Consider replacing magic numbers with constants

private bool CanAdjustStartDepthSlice => startDepthSlice > 0.1;
private bool CanAdjustDepthSubstractor => sliceDepthSubtractor < 3;

Now you can read this code as a specification.

Note: Probably we should not modify initial values of startDepthSlice and  sliceDepthSubtractor when we are adjusting points in order to be able to call butcher serveral times. But I'll leave this exercise for you :)


See the source of Python's bisect module in the standard library to see the accepted implementations used for binary searches and binary insertions used in the language:

"""Bisection algorithms."""

def insort_right(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the right of the rightmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]: hi = mid
        else: lo = mid+1
    a.insert(lo, x)

insort = insort_right   # backward compatibility

def bisect_right(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]: hi = mid
        else: lo = mid+1
    return lo

bisect = bisect_right   # backward compatibility

def insort_left(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the left of the leftmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    a.insert(lo, x)

def bisect_left(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e < x, and all e in
    a[i:] have e >= x.  So if x already appears in the list, a.insert(x) will
    insert just before the leftmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo

# Overwrite above definitions with a fast C implementation
try:
    from _bisect import *
except ImportError:
    pass

Regarding your code, let us see what improvements can be made:

def binary_search(alist, item):
    first = 0
    last = len(alist)-1
    found = False
    midpoint = None
    while True:
        midpoint = first + ((last-first) // 2)
        if alist[midpoint] == item:
            return midpoint
        elif alist[midpoint] < item:
            first = midpoint
        elif alist[midpoint] > item:
            last = midpoint

The initial values of found and midpoint are never used and so can be removed:

def binary_search(alist, item):
    first = 0
    last = len(alist)-1
    while True:
        midpoint = first + ((last-first) // 2)
        if alist[midpoint] == item:
            return midpoint
        elif alist[midpoint] < item:
            first = midpoint
        elif alist[midpoint] > item:
            last = midpoint

My tests are being performed in Python 3.5, so the code may looks slightly strange. What happens when searching for something that does not exist?

def binary_search(alist, item):
    first = 0
    last = len(alist)-1
    while True:
        midpoint = first + ((last-first) // 2)
        if alist[midpoint] == item:
            return midpoint
        elif alist[midpoint] < item:
            first = midpoint
        elif alist[midpoint] > item:
            last = midpoint

alist = list(range(10, 20))
item = 9
print(binary_search(alist, item))

The function enters an infinite loop if the value is too small. What about when the value is too large?

def binary_search(alist, item):
    first = 0
    last = len(alist)-1
    while True:
        midpoint = first + ((last-first) // 2)
        if alist[midpoint] == item:
            return midpoint
        elif alist[midpoint] < item:
            first = midpoint
        elif alist[midpoint] > item:
            last = midpoint

alist = list(range(10, 20))
item = 10
print(binary_search(alist, item))

The program prints out zero. This is not correct either. Here is a rewrite of your code in hopes to correct the problem:

import random

def main():
    for _ in range(1000):
        array = sorted(random.sample(range(10000), 9000))
        value = random.randrange(10000)
        index = binary_search(array, value)
        if index is None:
            assert value not in array
        else:
            assert array[index] == value

def binary_search(array, value):
    start, stop = 0, len(array)
    while start < stop:
        offset = start + stop >> 1
        sample = array[offset]
        if sample < value:
            start = offset + 1
        elif sample > value:
            stop = offset
        else:
            return offset

if __name__ == '__main__':
    main()


Calculating a unique count within a rolling time window

How about something like this:
test.rolling('7d').apply(lambda s:s.nunique()).groupby(level=0).max()

rolling('7d') is the rolling window. The window is determined for each row. So the first window starts from the row "2020-01-01     4" and extends 7 days in the past. The second window starts from the row "2020-01-01    65" and extends 7 days in the past.
.apply(lambda s:s.nunique()) determines the number of unique items in the window. But, because of the way rolling works, we get multiple results for the same day.
.groupby(level=0) groups the results by the date.
.max() takes the maximum nunique value for that date.
The above approach seemed rather slow, so here's a different approach. Basically use a Counter as a multiset and use a deque as a FIFO queue.  For each day update the Counter with the id's for that day and subtract the ones for the day at the beginning of the window.  The len of the Counter is then the number of unique ids.
from collections import Counter, deque

WINDOW = 7

fifo = deque(maxlen=WINDOW)
uniq = Counter()

def unique_in_window(x):
    if len(fifo) == WINDOW:
        uniq.subtract(fifo.popleft())

    uniq.update(x)
    fifo.append(x)

    return len(uniq)

test.groupby(level=0).apply(unique_in_window)


Comparing two vectors of arbitrary size, block by block

If at all possible, I'd start from a slightly different direction. I'd start by defining the group of 4 ints as a type:

static const int blocksize = 4;

class block {
    std::array<int, blocksize> data;

    bool operator<(block const &other) {
        for (int i=0; i<blocksize; i++)
            if (data[i] < other.data[i])
                return true;
            if (other.data[i] < data[i])
                return false;
        }
        return false;
    }
};

Having done that, you can use a standard algorithm to get the desired result:

std::vector<block> find_diff(std::vector<block> a, std::vector<block> b) {
    std::vector<block> difference; // where we'll put the result

    // set operations require sorted inputs
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());

    std::set_difference(a.begin(), a.end(),
                        b.begin(), b.end(),
                        std::back_inserter(difference));
    return difference;
}


First, a standard approach for dealing with the skipSpaces issue is to define a higher-order parser combinator, traditionally called lexeme:

lexeme :: ReadP a -> ReadP a
lexeme p = p <* skipSpaces

Here, lexeme takes a space-naive parser p, and converts it into a new parser that parses whatever p was planning to parse, and then reads and discards any trailing spaces.  You use lexeme in the definitions of any of your parsers that would reasonably be assumed to read a complete "lexeme" and ignore any trailing space.  For example, number should be a lexeme parser:

number :: ReadP Expression
number = lexeme $ fmap (Number . read) (many1 digit)

So should operator, though obviously not digit!  expression won't need to use lexeme, because we'll arrange to end it with a lexeme parser.

It's also helpful to define a symbol parser which is essentially string that ignores trailing spaces:

symbol :: String -> ReadP String
symbol = lexeme . string

Consistently used, lexeme (and symbol) will deal with all unwanted spaces, other than any leading spaces at the very start of your parse.  If you have a non-recursive "top level" grammar production, like say a parser for program :: ReadP Program, then you would probably deal with them there.  In your example, you don't have such a production (e.g., expression is recursive), so you'd stick an extra skipSpaces in parseExpression.  This is also a good place to put eof to make sure there isn't any trailing material that you aren't parsing:

parseExpression :: String -> Maybe Expression
parseExpression input = case readP_to_S (skipSpaces *> expression <* eof) input of
    [] -> Nothing
    xs -> (Just . fst . last) xs

Second, your use of a Read instance for parsing your operators is very unusual.  It would be more standard to make it a helper in the operator parser, writing something like:

operator :: ReadP Operator
operator = readSymbol <$> (symbol "+" <|> symbol "-")
  where readSymbol "+" = Add
        readSymbol "-" = Subtract

(though an even more standard version is given below).

Third, in expression, you can avoid the case construct by using alternation (<|>) like so:

expression' :: ReadP Expression
expression' = do
    left <- number
    (do op <- operator
        right <- expression
        return (Infix left op right)
     <|> return left)

This would be the standard approach for non-parallel parser libraries (e.g., Parsec or Megaparsec).  For ReadP, it's better to replace the (<|>) operator with the ReadP-specific (<++) operator to avoid also following the unwanted second parse in parallel.  Beware that (<++) has higher precedence than (<|>), so some extra parentheses might be needed if it's being used in combination with other operators, as in the examples below.

Fourth, you've probably noticed my use of the applicative operators <* and *> and the alias <$> for fmap in the code above.  It is very common to use these -- plus the additional applicative operator <*> and sometimes the operators <**> or <$ -- in parsers.  Once you get used to them, they tend to lead to less cluttered code.

For example, a more standard way of writing expression would be:

expression' :: ReadP Expression
expression' =     Infix <$> number <*> operator <*> expression
              <|> number

or the slightly more efficient solution:

expression :: ReadP Expression
expression = do
  left <- number
  (Infix left <$> operator <*> expression) <++ return left

Note that, in the context of parsers, an expression like f <$> p <*> q means "try to run the parser p, and then the parser q; assuming they both succeed, pass their return values to f".  In other words, that Infix expression is essentially:

Infix left op right

where op is the return value from the parser operator and right is the return value from the parser expression.

Similarly, the standard way of writing operator is actually:

operator :: ReadP Operator
operator = Add <$ symbol "+" <|> Subtract <$ symbol "-"

This one requires an additional word of explanation.  The operator <$ is kind of an odd duck.  It's type signature is:

(<$) :: a -> f b -> f a

but in the context of parsers specifically, the meaning of x <$ p is "try to run the parser p; if it succeeds, ignore its return value and return x".  Basically, it's used to replace the return value of a parser that's used only for its success or failure and not its return value.

Note that these versions of expression, like your original version, treat the operators as right associative.  This may be a problem if you're trying to parse "1-2-3" as equivalent to "(1-2)-3" instead of "1-(2-3)".

A few additional minor points:

isDigit is a more readable name for \c -> c >= '0' && c <= '9'
munch1 is more efficient than many1 (satisfy xxx), so I'd redefine number to use it
for testing, it's probably a good idea to have a parseExpressions function that looks at all the parses
for production, it's probably a good idea to check for ambiguous parses and do something about it, rather than (fairly arbitrarily) selecting the last parse in the list

With all of these suggestions implemented, the final version would look something like:

{-# OPTIONS_GHC -Wall #-}

import Data.Char (isDigit)
import Control.Applicative
import Text.ParserCombinators.ReadP (eof, munch1, ReadP, readP_to_S,
                                     skipSpaces, string, (<++))

data Operator = Add | Subtract

data Expression = Number Int
                | Infix { left :: Expression, op :: Operator, right :: Expression }

lexeme :: ReadP a -> ReadP a
lexeme p = p <* skipSpaces

symbol :: String -> ReadP String
symbol = lexeme . string

number :: ReadP Expression
number = lexeme $ Number . read <$> munch1 isDigit

operator :: ReadP Operator
operator = Add <$ symbol "+" <|> Subtract <$ symbol "-"

expression :: ReadP Expression
expression = do
  x <- number
  (Infix x <$> operator <*> expression) <++ return x

top :: ReadP Expression
top = skipSpaces *> expression <* eof

parseExpressions :: String -> [(Expression, String)]
parseExpressions = readP_to_S top

parseExpression :: String -> Maybe Expression
parseExpression input = case parseExpressions input of
    [] -> Nothing
    [(x,"")] -> Just x
    _ -> error "ambiguous parse"


Bash script to replace string in database

You can make Bash's read built emit a prompt by using its -p option:

read -p "Database name: " databaseName

and you can make it turn off echoing with -s:

read -s -p "Database password for $user: " password

Avoid writing "$password" into the mysql command line like that - as the man page says:

  Specifying a password on the command line should be considered insecure. See Section 6.1.2.1, “End-User Guidelines for Password Security”. You can use an option file to avoid giving the password on the command line.

It also says

  If you omit the password value following the --password or -p option on the command line, mysql prompts for one.

So I'd recommend not reading the password in this script, but passing --password to tell mysql to do its own prompting.

The other thing that's dangerous is using user input to construct the SQL query string - even if your users are trusted (and you know they have permission to connect and execute this command), it's worth validating the strings to prevent accidents.  An alternative could be to use Bash to quote the arguments:

command=$(printf 'UPDATE messages SET message = REPLACE(message, %q, %q') \
                 "$searchUrl", "$replaceUrl")

mysql --user="$user" --password \
   --host="$databaseHost" --database="$databaseName" \
   -e "$command"

It may be worth writing the script in a different language (or passing these variables to a sub-script in the different language), to enable the use of prepared statements.  I thought there might be a way to define variables for the mysql command like you can for Awk, and then use them in statements, but I couldn't find any provision for that, unfortunately.

An enhancement I would make is to ask for confirmation after reading all the interactive inputs.  Right now, if I make a mistake in replaceUrl (e.g. I manage to press \ and Enter together), then I don't get a chance to interrupt the update.  At the very least sleep 2 && mysql so I can Control+C before it's too late.


Security

General Approach

Your reason for this approach are not reasonable. The only reason to provide a different hash function is to deal with systems which do not support password_hash. And really, those systems should be updated.

You definitely do not want to switch to a weaker hash function after a breach. You can ask users to change their passwords via other mechanisms.

tl;dr: Yes, just use bcrypt.

Salt vs Pepper

Based on your comments, you seem to understand the difference between a salt and a pepper. But your code doesn't seem to differentiate, both your salt and your pepper are a pepper (this is also not as easy to fix as "replace this string with a random function", as you not only need to generate the salt, but also store and retrieve it).

A salt should be unique for each hash, so that it actually slows down attacks.

Bcrypt usage

The bcrypt part of your approach is fine; you are using password_hash and password_verify correctly.

Note that bcrypt actually handles salts for you though, so adding your own salt is unnecessary. As bcrypt can only handle passwords up to 72 characters, your approach may actually be harmful, as a long salt + password + pepper may cut of (parts of) the pepper. I would at least comment on this, but ideally, just remove the salt for bcrypt.

Custom Implementation: Empty Hash

If you set your $algo to something invalid, you will - silently - store an empty string instead.

Currently, you actually return false on the check, so it's not catastrophic, but it can lead to usability issues. I would throw an exception here.


c# best way to declare a class-level value in base class and set it at derived classes

What I've guessed from your code (and I might be wrong) is that you need to get some string from a type used in a persistence layer. The string might be a table name, or a value for a certain column. I've decided to call this a discriminator. Multiple types can have the same discriminator but each type can only have one.

I think it makes sense to introduce an inheritable attribute here, let's do that:

[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
sealed class DiscriminatorAttribute : Attribute
{
    readonly string discriminator;

    public DiscriminatorAttribute(string discriminator)
   {
        this.discriminator = discriminator;
   }

    public string Discriminator
    {
        get { return discriminator; }
    }
}

We'll also add a class which takes a type and gets us our string (if we have one).

public static class DiscriminatorService
{
    public static string LookupDiscriminatorForType(Type t)
    {
        var result = (from a in t.GetCustomAttributes(true)
                 where a is DiscriminatorAttribute
                 select a).SingleOrDefault() as DiscriminatorAttribute;
        return result != null ? result.Discriminator : null;
    }
}

This will allow you to change your repository to the following:

public class Repository<T> where T : CoreEntity
{
    public void DoSomething()
    {
        var objType = DiscriminatorService.LookupDiscriminatorForType(typeof(T));
        Console.WriteLine("Object Type for: " + typeof(T).Name  + " is " + objType);
    }
}

Some important things to note:

You no longer need to create an instance to get the string
you can remove the new() generic constraint

Obviously you need to decorate your classes with the new attribute:

[Discriminator("DEPARTMAN")]
public class DepartmanBase : CoreEntity
{
    public string DepartmanName { get; set; }
    public int ManagerId { get; set; }
}
public class Departman : DepartmanBase
{
    // Inherits discriminator from DepartmanBase
}

public class DepartmanView : DepartmanBase
{
    // Inherits discriminator from DepartmanBase
    public string ManagerName { get; set; }
}

[Discriminator("PERSONEL")]
public class Personnel : CoreEntity
{
    public string PersonnelName { get; set; }
}

Here's the full code in .Net Fiddle


Simulate Tic Tac Toe game using C language

void main() is not portable

Although it "works" in a lot of cases, the only two portable definitions of main are:

int main(void)

and

int main(int argc, char **argv)

Error checking

You don't check the return value of scanf.

This would be better:

if(scanf("%d", &n) != 1)
{
    fputs("Error; enter a number.", stderr);
    return EXIT_FAILURE; /* entering a letter will cause infinite loop so error out here */
}

Note that EXIT_FAILURE requires stdlib.h to be included.

Out-of-bounds write

If a user enters a 0 or a number greater than 9 in the scanf mentioned above, this line will write outside of the array bounds:

    TOT[n-1]=a;

This can cause a segmentation fault.

Spelling

There are a couple spelling errors in this code:

  cheak -> check
  tern -> turn

Formatting

There are a few issues with formatting here; first of all, each line in a function should be indented by at least 4 spaces. In addition, you should put spaces after commas  in function calls, and around most (if not all) operators.

Portability

Although clrscr and getch work with Windows and DOS, I would suggest simply removing clrscr and replacing getch with getchar. This makes your code portable to the point where it can run on most other systems.

Non-descriptive variable names

At first glance, I don't know what t, T, TOT, a, i, n, r, or p are for. The variable names should describe what they contain.

Spacing

Although the board is nice, the prompt to the user isn't. I would suggest something like this:

    printf("\n\n\nPlayer 1 = X\nPlayer 2 = O");
    printf("\nPlayer %d's turn.",p);
    printf("\n\nEnter a number: ");

...

    if(r == 1 || r == 2)
    {
        board(TOT);
        printf("\nPlayer %d wins!", r);
        break;
    }

Misc.

p is already 1 here. You don't need to set it again:

    else
        {
        p=1;
        }


My code examples are excerpts. Don't copy/paste them, they are suggestions you can incorporate into your code.

if (waited > GAMESERVER_CONNECT_TIMEOUT && connectedOnGameServer)
{
   throw new RuntimeException("Client didn't connect to game server in time (" + GAMESERVER_CONNECT_TIMEOUT + " ms)");
}

can be reduced to:

if (!connectedOnServer) {
   throw new RuntimeException("Client didn't connect to game server in time (" + GAMESERVER_CONNECT_TIMEOUT + " ms)");
}

Now, you can handle this without an exception. Connections fail quite regularly, and it's easy to handle that.

public boolean waitForConnection() {
   synchronized (conGameServerMonitor) {
      // loop, guard
      return connectedOnGameServer? true : false;
   }
}

With this you can ask the player if he wants to try again, or wait a bit and try again, etc without having to catch an exception.
But what if B calls connectedToGameServer() after the wait completes?

boolean connectionInProgress;

public void connectedToGame() {
   synchronized (conGameServerMonitor) {
      if (connectionInProgress) {
         connectedOnGameServer = true;
         conGameServerMonitor.notifyAll();
      }
   }
}

public boolean waitForConnection() {
   synchronized (conGameServerMonitor) {
      connectionInProgress = true;
      // wait
      connectionInProgress = false;
      return connectedOnGameServer? true : false;
   }
}

You handle the wakeups and interuptions correctly. Kudos for the waited part - I thought "Useless!" for a second, but I forgot that a thread could wake anytime, and it's the thread's responsibility to be sure that it's conditions are fulfilled.


Wrap pattern "using std::begin; return begin(c);" into a function

namespace Dlugosz::d3 {
  inline namespace twostep_wrapper {
    using std::begin;
    using std::end;

    inline namespace twostep_inner {
      inline auto Begin = [](auto&& r)
      //...

The use of inline namespaces seems inappropriate.  Did you intend for the content of your inline namespaces to percolate up to d3 and pollute it?  The user essentially gets access to

d3::begin(), (intended?)
d3::Begin(), (intended?)
d3::twostep_wrapper::begin(), (user shouldn't call this)
d3::twostep_wrapper::Begin(), (user shouldn't call this)
d3::twostep_wrapper::twostep_inner::Begin(), (user shouldn't call this)
d3::twostep::Begin(), (intended!)

as well as the end()/End() versions.

inline auto Begin = [](auto&& r)
-> decltype(begin(std::forward<decltype(r)>(r)))
{
    return begin(std::forward<decltype(r)>(r));
};

C++17 provides constexpr lambdas.  While lambdas may evaluate in a constexpr context implicitly, consider being explicit.

Consider inheriting the noexcept specification from the function that is selected in overload resolution.

inline constexpr auto Begin = [](auto&& r)
noexcept(noexcept(begin(std::forward<decltype(r)>(r))))
-> decltype(begin(std::forward<decltype(r)>(r)))
{
    return begin(std::forward<decltype(r)>(r));
};

You listed Niebler's blog post, but he also has a proposal you may want to check out.


Min function accepting varying number of arguments in C++17

template <typename Less, typename T, typename... Ts>
constexpr const T& min(Less less, const T& a, const T& b, const Ts&... rems) {

This function requires a minimum of 2 elements. A minimum element will exist if the user provides a single argument variadic list. Consider handling that.

auto& min1 = min(std::less<>{}, 4, 5);  // okay!
auto& min2 = min(std::less<>{}, 4);     // candidate function not viable, reqs 3 args, 2 provided

        return min(less, std::min(a, b, less), rems...);

Your approach here uses recursion and implementations are permitted to put a recursion depth limit on constexpr calculations. Consider an iterative solution  that expands the pack while calculating the minimum.

template <typename Comparator, typename First, typename... Rest>
constexpr decltype(auto) variadic_min(Comparator cmp, First const& first, Rest const&... rest) {
    const First* result = std::addressof(first);

    // cast each evaluated expr to void in case of overloaded comma operator shenanigans
    ((void)(result = std::addressof(std::min(*result, rest, cmp))), ...);

    return *result;
}

An explanation with what is going on with the fold expression:

((void)(result = std::addressof(std::min(*result, rest, cmp))), ...);
 ^     ^         ^                                            ^
 |     |         |                        expand using comma op
 |     |         safer than built-in, now constexpr in 17
 |     evaluate the expression for each pack variable
 cast to void the entire expression to avoid overloaded comma op.

Just thinking beyond the standard library and reinventing the wheel. This min works fine for homogenous packs. What about heterogenous packs?

auto& min1 = min(std::less<>{}, 4, 5, -1);  // min1 = -1
auto& min2 = min(std::less<>{}, 4, 5, -1.); // candidate template ignored...

One of the benefits of the conditional operator (?:) is that if both resulting expressions return lvalues of the same type, then the result will have the same type. If that type is T&, we could assign to that variable. Could we mimic that behavior with min and friends?

auto a = 4;
auto b = 5;
((b < a) ? b : a)  = 42;        // a = 42, b = 5
min(std::less<>{}, a, b) = 42;  // cannot assign to return value, returns const-qualified type
std::min(a, b) = 42;            // same with standard library.
min(std::less<>{}, 5, 6) = 42   // cannot assign, makes sense!


Best way to handle elements of a private array

If you expose it via a public property then it's not a "private" array any more:it's part of the public interface.

If resetting its elements is something that you want clients to do, I'd choose the first option (because it's simplest).

Or, these ...

public void SetColor(int id, Color value) { ... }
public bool GetColor(int id, out Color result) { ... }

... could perhaps be done using indexers ...

public Color this[int id]
{
    get { ... }
    set { ... }
}

... but that's not very different from exposing the array (and there can be only one indexer of a given signature, which doesn't work if there's more than one array to be exposed).

Here's a blog post on the topic: http://blogs.msdn.com/b/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx

Another possibility (I've just thought of it, haven't tested/researched this idea) might be to pass the array into the constructor:

public sealed class Emitter
{
    private readonly Color[] _colors;
    public Emitter(Color[] colors) { _colors = colors; }
}

The reason excuse for that is that so that whoever constructs Emitter has the array, can keep that array, and can (evilly) modify that array after it has used it to construct Emitter.

Color[] colors = new Color[8];
Emitter emitter = new Emitter(colors);
colors[0] = Color.Red; // changes constents of array inside the Emitter

The official recommendation is to use a List<Color> instead of a Color[] array, and return IList<Color> ... conceptually similar IMO, but you won't get the compiler and FxCop warnings.

public sealed class Emitter
{
    private readonly List<Color> _colors;
    public IList<Color> Colors { get { return _colors; } }
}

As @svick noted in a comment below, because arrays implement the IList<T> interface, you can also do this:

public sealed class Emitter
{
    private readonly Color[] _colors;
    public IList<Color> Colors { get { return _colors; } }
}

IList<T> supports the API you want (i.e. an indexer property). Using IList<T> supresses the compiler warning. It may be less intuitive to the client/user though (who may think, incorrectly, that the IList<T> would allow them to change its size).


Just a quick shot at case "Greater Than":

case "Greater Than":
    if (fieldTypeName == "int")
    {
        var one = Convert.ToInt32(givenValue);
        var two = Convert.ToInt32(expectedValue);
        return one > two;
    }
    if (fieldTypeName == "double")
    {
        var one = Convert.ToDouble(givenValue);
        var two = Convert.ToDouble(givenValue);
        return one > two;
    }
    return false;

if fieldTypeName is double it is always returning false because copy&pasta should be done carefully. This applies to Less Than as well.


Recursively traverse directory tree and print all files

let allFiles' = Seq.append allFiles files
let allFiles'' = dirs |> Seq.map (traverse allFiles') |> Seq.concat

Just because you can use ' to differentiate variables does not mean that you should. Unless it's very clear what the different variables mean, you should use separate name for each of them.

dirs |> Seq.map (traverse allFiles') |> Seq.concat

You can simplify Seq.map followed by Seq.concat to just Seq.collect:

dirs |> Seq.collect (traverse allFiles')

let rec traverse allFiles dir =
    let dirs,files = getDirObjects dir
    let allFiles' = Seq.append allFiles files
    let allFiles'' = dirs |> Seq.map (traverse allFiles') |> Seq.concat
    Seq.append allFiles' allFiles''

This code is wrong. You pass files from the parent directory to each child directory and then return the parent directory files from each child directory and concat them.

For example, if you had two subdirectories, dir1 and dir2 and two files, file-in-root and dir1/file-in-dir1, then your code outputs:

file-in-root
file-in-root
file-in-root
dir2/file-in-dir2

Notice how file-in-root is output three times: once for the root directory, and also once for each subdirectory.

The solution here is not to pass allFiles to traverse:

let rec traverse dir =
    let dirs,files = getDirObjects dir
    let filesInDirs = dirs |> Seq.collect traverse
    Seq.append files filesInDirs

let dirs = dir.GetDirectories()
let files = dir.GetFiles()

Since you're using lazy seqs extensively, it would make sense to make dirs and files lazy seqs too, by using seq-returning Enumerate* methods instead of array-returning Get* methods. This way, if you enumerate the resulting seq only partially, it's going to be more efficient.

let dirs = dir.EnumerateDirectories()
let files = dir.EnumerateFiles()


This looks quite good, one nitpick I have is that you spend a significant amount of lines showing messages, that should be a more generic information setting function like

function notifyUser( messageClass, message ){
  config.notifyEle
        .removeClass( 'alert-info alert-warning' )
        .addClass( messageClass )
        .attr('data-i18n', message );
}

And I must warn you that not putting curly braces is playing a bit with fire: if (lang) params['lang'] = lang; at least use a new line?

Edit:
I would go for an MVC approach, create a Model object that knows what fields are on the form and knows how to validate them. Then a View object that knows how to style and update the form ( put red borders around blank input types, show messages etc. ) and a a Controller object which puts all the listeners in place and also takes care of working with the model to validate the data on the form before submitting web requests.


Calculating highs, lows, and volumes of stocks

First, the obvious ones:

Change nCurLow and nCurHigh to floats since you are reading float from file.
Change

nCurLow(0)

to

nCurLow(std::numeric_limits<float>::infinity())

and

nCurHigh(0)

to

nCurHigh(-std::numeric_limits<float>::infinity())

because initializing min/max with 0 can lead to bugs if values are all >0 or <0.
Drop typedef basic_string<char> string; and use std::string instead.
Check argc if you have arguments before you use argv (prevents crash when invalid arguments are passed).
Don't use cerr only when you want to report error, use std::cout instead.
Don't increment i like this: ... &Lows[i++]);. In fact drop those arrays all together and use std::vector, and std::string instead (because that while so broken in so many ways ...).
The iteration looks bogus, for (int s = 0; s <= i; ++s) because of <= so change it to ranged-based fors.
Avoid stdcmp; use operator== from std::string.

These points only refer to potential errors and bugs.

Now for the less obvious ones:

I see a comment //write to a file. std::cout does not write to file but to standard output. use file streams if writing to a file is the intended behavior
This code:

for (int s = 0; s <= i; ++s)
{
    std::string stockname = Stocks[s];

    for (int j =0; j <= i; ++j)
    {
        if (!strcmp(Stocks[j], stockname.c_str()))
        {
            TotalVolumes[stockname] += Volumes[j];
        }
    }
}

What does it actually do? It looks totally inefficient. The obvious thing is that TotalVolumes[stockname] can be evaluated only once. The second is that j can be equal to s.
The rest of the code seems to make excessive use of memory. It looks like it can be simplified a lot, with fewer iterations, less memory usage, less confusion.
It would be nice if there would be some comments to describe what the code actually does.
return 1 in main. If this will be used in an automated tool return 1 might mean that an error has occurred. Change it to return 0 and return 1 only when an actual error has happened (invalid argument, file not found, corrupted file data, etc).
More error checking.

There could be other things, but having some test data would be nice. There could be soft bugs in the code.


Counting numbers whose digits all go up or down

To make Ruby internally use a loop instead of an Array you may want to use 1.upto(10 ** x) that is an Enumerator.

But I doubt the "HUGE array" is the performance issue here.

First of all Ruby says to do total = .count{ ... } instead of total = 0; .each{ total += 1 if ... }
Then do this thing only once and store in a variable t = i.to_s.split("").sort -- x2 faster
Then use .chars instead of .split("") -- x4 faster

Then conversions between Integer and String seem to be unnecessary:

def total_nums x
  return 0 if x == nil
  return 1 if x == 0

  1.upto(10 ** x).count do |i|
    s = i.to_s.chars
    t = s.sort
    s == t || s == t.reverse
  end
end

Note: probably you want either return 0 if x == 0 or start the loop from 0, not 1.


Determining if a possible new entry already exists in a dataset

Introduce a new object:

public class PrimaryKey
{
    public int TicketId { get; set; }
    public DateTime CreateTime { get; set; }
    public string Creator { get; set; }

    public PrimaryKey(int ticketId, DateTime createTime, string creator)
    {
        TicketId = ticketId;
        CreateTime = createTime;
        Creator = creator;
    }

    public override int GetHashCode()
    {
        int hash = 13;
        hash = (hash * 7) + TicketId.GetHashCode();
        hash = (hash * 7) + CreateTime.GetHashCode();
        hash = (hash * 7) + Creator.GetHashCode();
        return hash;
    }
    public override bool Equals(object value)
    {
        var other = value as PrimaryKey;
        return other != null
             && other.TicketId == TicketId
             // ... etc.
    }
}

Use this in a hashset:

// right at the beginning...
var dedupeList = new Hashset<PrimaryKey>();
// Populate hashset from data table

if (dedupeList.Add(new PrimaryKey(newEntry.TicketId, newEntry.CreateTime, newEntry.Creator))
{
    // New
}
else
{
    // Already added.
}

You wont have to search through the whole data table each time which should save a lot of time when the data table is large. However, you will use more memory.


Converting an integer into the written form

Use STL Containers

Prefer using std::array (if your compiler supports it or) std::vector instead of raw arrays.  Also, I would recommend using std::string instead raw character pointers.

const std::array<std::string, 20> Numbers::lessThan20 = {
  "zero",     "one",      "two",      "three",   "four",    "five",
  "six",      "seven",    "eight",    "nine",    "ten",     "eleven",
  "twelve",   "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
  "eighteen", "nineteen"
};
const std::array<std::string, 10> Numbers::over19 = {
  "",       "",      "twenty", "thirty", "fourty", "fifty", "sixty", "seventy",
  "eighty", "ninety"
};
const std::string Numbers::hundred  = "hundred";
const std::string Numbers::thousand = "thousand";

Edge Cases

Currently there is no handling for edge cases.  If the number is 0 it will return an empty string instead of "zero".  Numbers greater than or equal to 20000 will cause an out of range access.  Therefore, numbers too large need to be properly handled.  These cases can checked at the beginning of the function.

A couple other minor points: I would remove the line int whole, remainder and declare the variables when they are initialized.  This will reduce the variables' scope and does not leave them initialized.  Also, prefer text += ... over text = text + ....  It's more clear that you are appending and less typing.  Lastly, I would recommend to always use curly braces even when there is only one statement.

Here is your function with my recommendations:

std::string Numbers::print() const
{
  int remainder = this->number; // <- number is a member variable of the Numbers class
  if(remainder == 0)
  {
    return lessThan20[0];
  }

  if(remainder >= 20000)
  {
    // handle this case
  }

  int whole = remainder / 1000;
  remainder %= 1000;

  std::string text;
  if (whole > 0)
  {
    text += lessThan20[whole] + " " + thousand + " ";
  }

  whole = remainder / 100;
  remainder %= 100;

  if (whole > 0)
  {
    text = text + lessThan20[whole] + " " + hundred + " ";
  }

  if (remainder > 19)
  {
    whole = remainder / 10;
    remainder %= 10;
    text = text + over19[whole];
    if (remainder > 0)
    {
      text = text + "-" + lessThan20[remainder];
    }
  }
  else if (remainder > 0)
  {
    text = text + lessThan20[remainder];
  }
  return text;
}


The line that jumps out at me as being a performance concern is this one:

words = [line.strip() for line in infile]

You’re generating a list that contains every word in dictionary.txt. This means a 500 MB dictionary file will create a similarly large list (which is going to be a huge structure). It also means that if the password is early on in the list, you still have the whole file as a list in memory.

This gets followed by the line

for word1 in itertools.product(words, repeat=1):
    fword = word1[0]

and I’m not sure quite why you’re getting the words out in this way. As you go through itertools.product, you get tuples, and you need to get the first element out. Using an iterable is generally good for performance, but the problem is creating the list in the first place, more than iterating over it.

The advice in How to read large file, line by line in Python is helpful here. Consider reading your file as

with open('dictionary.txt') as f:
    for line in f:
        # try that line as your password

That’s probably going to give a noticeable benefit.

Other comments:

Right now, all the functionality is tied up together. I’d separate the code which tests a password, and the code which gets an iterable of passwords from dictionary.txt. For example:

def try_password(fword, rar_file):
    print "Attempting: %s" % fword

    # open unrar and test password
    output = os.popen("unrar.exe x %s -p %s" % (fword, rar_file))
    outstring = output.read()

    # unrar.exe returns "All OK" for correct password
    validate = outstring.find("All OK", 0, len(outstring))
    if validate != -1:
        print "Found password: %s" % fword
        return 0
    else:
        # continue searching
        return 1

with open('dictionary.txt') as f:
     for line in f:
         attempt = try_password(line.strip(), 'protected.rar')
         if attempt == 0:
             break

Now you could also use the same code which gets your passwords to tackle, say, a bunch of encrypted ZIP files.

I added the return codes 0 and 1 to denote success and failure when trying a password.

What did the slng variable stand for? Anyway, it was only used once so I removed it.

There are a few other tweaks I made, but nothing very major.
Your import sys, traceback statement should really be split onto two separate lines. Quoting from PEP 8, the Python style guide:

  Imports should usually be on separate lines

Why is the final line a raw_input instead of a print statement?

Where did dictionary.txt actually come from? You say you “generated” it, so could you just bypass the step where you write the passwords out to a file and just try them directly within the generator?


Converting a DropDownList retrieval service to generics or delegate methods

The number of dependencies suggests this class is doing too much work and violates single responsibility principle. Instead of having one class factor all different enumerations, have multiple classes, e.g. one for project members, one for states, etc.


Don't have time for a full review but hopefully this will give you some food for thought.

Why add an extra variable show? Angular is more than capable of binding to an expression:

ng-show='message != ""'

Then you have one less thing to juggle in your controller:

$scope.addMsg = function (qty, item) {
    $scope.message = "Added " + qty + " " + item + " to the cart";
    // console.log($scope.message); // if you want to debug
    $timeout(function() {
      $scope.message = "";
    },3000);
}

Some notes about code clarity:

Don't forget your semicolons
Add some spacing between operators e.g. a + b + c + d is easier to read than a+b+c+d
addCartMessage is probably more descriptive than addMsg

As for your question about directives:

msgpallete should be killed with fire
itemContainer seems like a good candidate but execution isn't great (will come back to this if I get time)

By removing the msgpallete directive you can change your view to:

{{message}}

(Your controller will be unchanged).


Parsing website info with a database and web service

One comment I'd have is that there is a LOT going on in that method... but for the most part
each section is the same...

GetNodeCollection
Loop Through it
Add it to a list

You could probably pull that out into a method to shorten your code.

public List<string> ParseSection(HtmlNode root, string nodePath, bool isLink = false)
{
    HtmlNodeCollection nodes = root.SelectNodes(nodePath);
    List<string> parsedNodes = new List<string>();
    foreach (HtmlNode node in nodes)
    {
        if(isLink)
        {
            parsedNodes.Add(node.GetAttributeValue("href", null).Trim());
        }
        else
        {
            parsedNodes.Add(node.InnerText.Trim());
        }
    }
    return parsedNodes;
}

public void HtmlParser()
{
    Encoding enc = Encoding.UTF8;
    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
    htmlDoc.Load(client.Request(), enc);
    HtmlNode root = htmlDoc.DocumentNode;
    HtmlNodeCollection linkNode = root.SelectNodes();

    List<string> jobs = ParseSection(root, "//div[@class='jobBox']");
    List<string> headers = ParseSection(root, "//div[@class='jobBox']/h1");
    List<string> content = ParseSection(root, "//div[@class='jobBox']/div[@class='content']");
    List<string> links = ParseSection(root, "//div[@class='jobBox']/a", true); //TRUE
    List<Uri> fullLinks = links.Select(l => new Uri(l));

    htmlDoc.Save("file.htm", enc);
    StringParser();
}


Coding Challenge : Build Tower refactoring code is it necessary

How did you determine the output ' # ' for the case n==1? I'd have expected it to just be '*'. If you're unclear about the specification for code you're writing in an interview, it's best to either ask for clarification or document your assumptions -- it's possible they deliberately handed you an unclear spec and are testing how you handle that.
If we take the interviewer request literally, you're still missing the [ ... ] formatting.
Naming
public string[] PrintStairs(int n)
This method is named as a verb indicating it's useful for its side effect, but it returns a value indicating it's useful for its return value. You should design APIs for one or the other but not both. Since your method is useful for its return value, a more appropriate name might be GenerateStairs or GetStairs.
Use more descriptive parameter names. numberOfStairs instead of n for example.
You use two different names, row and level, for different manifestations of the same concept: a step in your staircase. I'd unify these and call them rowIndex and rowBuilder respectively, or maybe stepIndex and stepBuilder.
Input validation
Your method crashes for negative values of n. If negative numbers are not valid inputs to the method, that fact should be documented by a method header and by throwing an ArgumentOutOfRangeException.
String APIs
result[row] = string.Concat(new string(level.ToString()));
This is a very complicated way of saying result[row] = level.ToString()! string.Concat is an API for concatenating strings, but you are only giving it one string which does nothing but give you the same string out again.
Explicit string constructors are intended to be used for creating strings from individual characters or from unmanaged code; here you're just giving it another string, which also does nothing but give you the same string out again.
General behaviour
var midpoint = ((2 * n - 1) / 2);
You are doing integer division here. Double-check your math because this expression simplifies to n - 1 for positive n -- were you intending for something more elaborate to happen with this calculation? A reader might wonder if there's a bug here.
n doesn't change inside the loop, so this whole line can be moved outside of it.
General formatting
Your spacing is inconsistent:
for (int row =0; row < n; row++)
if((midpoint-row <= col) && (midpoint + row >= col))
for (int col =0; col < 2 * n - 1; col++)
LINQ
Having everything on one line isn't necessarily a good thing. The LINQ solution is impenetrable when written like that. It deserves to be on multiple lines anyway for the sake of being able to read it properly:
return Enumerable.Range(1, nFloors)
    .Select(i => string.Format("{0}{1}{0}",
        i == nFloors
            ? ""
            : new string(' ', nFloors - i),
        new string('*', 2 * i - 1)))
    .ToArray();

Yes, it's technically LINQ, but the guts of that Select is what's doing all the heavy lifting.
The LINQ solution doesn't give the same output for n==1, which again begs the question where you got the idea that it should output ' # ' in the previous solution.
A more LINQ-y solution would have you build up the building blocks needed to write code that really is shorter. LINQ is all about operations on sequences; the thing that throws a wrench in any LINQ solution here is the fact that the output depends on how many things are in the sequence (the amount of space you use to pad the stairs depends on how many stairs there are), so you're probably going to have to enumerate sequences more than once.
Here's my LINQ-y take: start with a simple enumerator that gives you unformatted steps, from which you can take any arbitrary number of them:
private string GenerateStep(int stepIndex)
{
    if (stepIndex < 1)
        throw new ArgumentOutOfRangeException(nameof(stepIndex));
    return new string('*', stepIndex * 2 - 1);
}

private IEnumerable<string> EnumerateSteps()
{
    for (int stepIndex = 0; stepIndex < int.MaxValue; stepIndex++)
    {
        yield return GenerateStep(stepIndex);
    }
}

Now I can say EnumerateSteps().Take(3) to get:
[
  '*',
  '***',
  '*****'
]

Then define a method that takes a sequence of strings and centers them:
static class StringExtensions
{
    private static string CenterFormatted(string original, int totalWidth)
    {
        if (original == null)
            throw new ArgumentNullException(nameof(original));
        if (totalWidth < original.Length)
            throw new ArgumentOutOfRangeException(nameof(totalWidth));

        int paddingNeededOnLeft = (totalWidth - original.Length) / 2;
        int paddingNeededOnRight = totalWidth - original.Length - paddingNeededOnLeft;

        return String.Concat(
            new string(' ', paddingNeededOnLeft),
            original,
            new string(' ', paddingNeededOnRight));
    }

    public static IEnumerable<string> CenterFormatted(this IEnumerable<string> sequence)
    {
        // Exercise: how will you check for a null input sequence here? If you check it here and throw ArgumentNullException, will it actually throw when you call CenterFormatted?
        int largestStringLength = sequence.Max(s => s.Length);
        foreach (string original in sequence)
        {
            yield return CenterFormatted(original, largestStringLength);
        }
    }
}

Now you have two orthogonal and reusable things: a thing that generates steps and a thing that centers sequences of strings. You can compose these quite concisely in a LINQ statement to solve the original problem:
EnumerateSteps().Take(3).CenterFormatted().ToArray()
which gives me
[
  '  *  ',
  ' *** ',
  '*****'
]


Page Object Model class structure in Selenium

Some lines may be simplified.

1) elementExists() already returns boolean, so use it directly:

return ((elementExists(by)) ? true : false);

to

return elementExists(by);

2) You may inline a method calls into condition statements:

Boolean result = accountsToRemove();
if(result == false) {

to

if(!accountsToRemove()) {

3) Name the main test method correspondingly:

removeAccounts()

to

testRemovingAllAccounts()
userRemovesAllAccounts()


Simple Python Old Email Eraser From Inbox

One nice programming principle is the principle of least astonishment, which you violate with your code. Imagine someone using your module and calling Connect_And_Login. If it was me I would be very astonished that suddenly many of my emails are deleted! At least the function does not have today as a default bedate, otherwise it would be a disaster waiting to happen.

It would be a lot better if that function just returned the mail object, which the function Mark_emails_as_Deleted then takes as parameter.

mail, inbox = connect_and_login(args.uname, args.path)
mark_emails_as_deleted(mail, args.bedate, inbox)

(Before the return in Connect_And_Login was actually superfluous,  because python automatically returns None at the end of a function body

And here we are at another thing. You should use a consistent naming scheme for your variables. Python actually has an official style guide, PEP8, which programmers are encouraged to follow to improve readability. It recommends using lower_case for variables and functions (and PascalCase for classes).

It also recommends avoiding unnecessary white-space, such as between an if block and an else block, or between try and except.

Excepting an import error and then just printing the error does you no good. It will print the error, try to continue running the code, encounter wherever that module is actually needed and fail there with another cryptic error code. The output saying that it was actually an import error is buried above the stacktrace. It is better to just let it fail as an import error or at least terminate the program there.

The different email provider could be stored in a dictionary mapping to their data. This way it is more easily extendable to more providers:

supported_provider = {"gmail.com":{"mail": "imap.gmail.com",
                                   "inbox": "INBOX",
                                    "url": 'https://www.google.com/settings/security/lesssecureapps'},
                       "yahoo.com": {...}}
provider = supported_provider[uname.split("@")[-1]]
mail = imaplib.IMAP4_SSL(provider['mail'])
inbox = provider['inbox']
url = provider['url']

It is in general faster, more readable and extendable to use str.format instead of string additions:

result, data = mail.search(None, '(BEFORE "{}")'.format(bedate))

Lastly, you could use the nice functionality of argparse to validate your input as a date as explained e.g. in this answer:

parser.add_argument('bedate', type=lambda s: datetime.datetime.strptime(s, '%d-%b-%Y'), help="Enter Date, Before this date all emails will be cleaned. Format: 01-Jan-2016")

%b is the abbreviated month name *in the current locale. So in English it will beJan, Feb, ..., Dec, while e.g. in German it will beJan, Feb, ..., Dez`. I guess gmail/yahoo can actually handle this because it is also localized for the user.


Check whether string of brackets are well-formed

There are some issues with the code:

isBracketBalanced - Should be plural. It checks more than one bracket.
bracketIsBalanced - Is basically the same name as the parent function, except it does more than just check if the bracket is balanced. It also manipulates the stack.
braces - Didn't we just call them brackets?
expectCloseStack declaration - This is perhaps just my personal preference, but to me, writing the declaration after a comma like that makes me look twice to see if it is part of the object that was declared above it.

All in all, I find this solution a bit harder to read than the original. Also, it's actually not more concise.


How about something like this there is some checking that needs to be done because I inverse the $isPost bool and that could be buggy

public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args->getObject();
    $entityManager = $args->getObjectManager();

    $isPost = $entity instanceof Post;

    $thread = $isPost ? $post->getThread() : $entity;

    $details = $isPost ? $entity : $thread;

    $category = $thread->getCategory();
    $category->setLastPostThreadTitle($thread->getTitle());
    $category->setLastPostThreadSlug($thread->getSlug());
    $category->setLastPostBody($details->getBody());
    $category->setLastPosterUsername($details->getUser()->getUsername());
    $category->setLastPostCreatedAt($details->getCreatedAt());

    //NOTE the inversion of the isPost bool
    //TODO Test this
    $category->setIsLastPostOp(!$isPost);

    if($isPost){
        $category->setPosts($category->getPosts() + 1);
    }

    $entityManager->merge($category);
    $entityManager->flush();
}


Project Euler #35 - Circular primes solution is slow

BUG

Your program gives the wrong answer, yielding 53 instead of 55. The reason for this is you over-eagerly exclude rotations in circularPrime if anything ends in an even digit or 5. But 2 and 5 are prime, yet end in a digit that you exclude!

It turns out that the exclusion check (in addition to giving you the wrong answer) doesn't actually help you anyway. Timing your function run ten times:

with check:    6.094s
w/o check:     6.075s

So drop it, and you get the correct answer, and it runs faster (or the same, within noise).

Semicolons

Semicolons are a C/C++/Java/etc. thing. While they're technically correct Python syntax, you don't need them, and they look weird, so you can simply drop them.

Sieve

Typically, we'd start our sieve with something like is_prime = [True] * limitn. It's a little weird to see it backwards, but I guess that's ok.

More efficient sieving

Let's take a look at the sieve part of your code, swapping bools like I suggested:

for i in range(2, limitn):
    if not is_prime[i]:
        continue
    for f in range(i*2, limitn, i):
        is_prime[f] = False

    primes.append(i)

First of all, having the continue makes it harder to read - better to keep the flow mono-directional:

for i in range(2, limitn):
    if is_prime[i]:
        primes.append(i)
        for f in range(i*2, limitn, i):
            is_prime[f] = False

Now, there's two issues here. In Python 2.7, range() gives you a list. The full list. That's hugely wasteful since you never want the full list, only the next element one at a time. For that, there's xrange(). Just swapping out those two functions:

range()    6.075s
xrange()   4.913s

Now, let's take a look at your inner loop:

for f in xrange(i*2, limitn, i):
    is_prime[f] = False

f is a bad variable name for this, prefer something like j, but that's not important. Consider the bounds. At this point, we know that \$i\$ is prime. We also know that this is the first time we've gotten to it, so every multiple of \$i\$ is still marked as being potentially prime, except for those divisible by some other prime \$p < i\$. So \$2i\$ we already know isn't prime, because it's divisible by \$2\$. \$3i\$ likewise. And so on. The first composite number that we have to cross off will be the first one not divisible by any such prime \$p\$... which is \$i^2\$.

for j in xrange(i*i, limitn, i):
    is_prime[j] = False

That improves us to:

OP, w/ bugfix         6.075s
range() -> xrange()   4.913s
inner loop from i^2   4.343s

Bring back the bug

I love deliberately provocative headings. Anyway, you had the right idea of checking for the even digits, but we can be more aggressive with it. Before we check any of the rotations, let's check for the presence of any of those digits first:

def circularPrime(n):
    ss = str(n)
    if any(c in ss for c in '024568'):
        return 0

    # now check everything else

This way, we can avoid a whole bunch of work for all of our 6-digit primes that start with an even number. However, from the very first thing I wrote, we know that this will give us the wrong answer. However, we know how to fix it. We know we are erroneously excluding 2 and 5, so let's just add them back:

gg = 2 # because 2,5
for num in primes:
    gg += circularPrime(num)
return gg

That drops us down to:

OP, w/ bugfix         6.075s
range() -> xrange()   4.913s
inner loop from i^2   4.343s
excluding again       3.721s

I had originally said your check didn't give you any performance benefit, but this one does - since building up all the string rotations and doing all the int casting is expensive and in this way we're able to avoid all of that up front. Since the number of circular primes is sparse (only 55 out of ~75k primes!), anything we can do to aggressively weed our set down is good.


Considering that there is no else to if (!response.IsSuccessStatusCode), you should do:

if (response.IsSuccessStatusCode)
{
   return;
}

This saves on indentation and makes your method easier to read.

I'd use string.Format for things like this:

message = this.localizer["Forbidden"] + ": " + this.localizer["You have not the appropriate rights to access this page."];

Why is localizer a property on the class this method belongs to, but logger is not? And why do you need to write this.localizer?

In the end there's not much code to review, and perhaps you should consider posting the whole class.


So my question is this: is this block at the end some sort of anti-pattern, and is it something that's going to come back to bite me in the future?

Not necessarily.
It depends on whether line can contain end-of-line markers.

If line can contain an EOL character that marks the end of the CSV record for you,
then you could move the logic from the last switch into case EOL: for the state-specific handling as appropriate,
and stop further processing.
Or you want to support multi-line CSV records (newline characters embedded within quotes), then you could continue processing the next line.

If the full length of line is expected to be the complete CSV record,
then it's fine to not terminate it with an explicit EOL and handle it in the extra switch as you did.


There are significant issues here:

; draw-rocket: rocket scene --> scene
; Purpose: To draw the given rocket in the given scene
(define (draw-rocket a-rocket a-scene)
(place-image rocket-img a-rocket ROCKET-Y a-scene))

Why break the pattern from drawing code for the others? Use (pos-x a-rocket), (pos-y a-rocket) instead of a-rocket ROCKET-Y. That will help you abstract the code later on.

; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-shots a-los scn)
(cond [(empty? a-los) scn]
[else (draw-shot (first a-los) (draw-shots (rest a-los) scn)
         )]))

This method has the wrong purpose and signature. This should be:

; draw_shots: los scn --> scn
; Purpose: To draw the shots in the given scene

This code seems to have multiple issues:

; draw-world: world --> scene
; Purpose: Draw the world in the empty scene
(define (draw-world a-world)
(draw-rocket (world-rocket a-world)
(draw-aliens (world-aliens a-world)

The parentheses are mismatched, as mentioned in the comments.
Why are the draw-shots methods not called here?

I also think that you want to nest the calls so that the results are cumulative.
This is done like so:

; draw-world: world --> scene
; Purpose: Draw the world in the scene (why would does it have to be empty?)
(define (draw-world a-world)
(draw-shots (world-shots
(draw-rocket (world-rocket
(draw-aliens (world-aliens a-world)))))))

As for using higher-order functions:

Try using foldr like so:

(define (draw-shots a-los scn)
(foldr draw-shot (first a-los) (rest a-los)))

Similarly, you can apply this to all the functions on lists.

Finally, using abstraction is very easy here. Create a new type, called Sprite or Actor or something similar, and have Aliens, Shots and Rocket all extend it. That way you only need 2 functions: 1 for singular, 1 for plural.


This is more efficient than the accepted answer.  min is O(1) memory and O(n) time while sorted is O(n) memory and O(n*log(n)) time:

import static java.util.Comparator.comparingLong;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

Comparator<Map.Entry<Integer, Long>> byRarity = comparingLong(Map.Entry::getValue);
Comparator<Map.Entry<Integer, Long>> byAge = comparingInt(Map.Entry::getKey);

int rarest = data.values().stream()
        .collect(groupingBy(x->x, counting()))
        .entrySet().stream()
        .min(byRarity.thenComparing(byAge))
        .get()        // or throw if map is empty
        .getKey();