I'm probably no better in Elixir than you are, but I will give it a go.

First of all the good parts: I think the function does what it should, and it's fairly neat. Not bad for a language that doesn't even have a concept of date, huh? :-)

Suggestions for improvement:

You should have a @doc attribute and unit tests :-) Remember to document that the range is inclusive (which is not what I would expect).
And if you add @doc, consider adding an example which can be run via a doctest in ExUnit. More info: elixir-lang.org/docs/stable/ex_unit/ExUnit.DocTest.html (thanks to @alxndr).
Consider making the range not inclusive, but rather [from, to) or (from, to]. The former is common in computer science, the latter is common in daily speech.
The _word style is usually used for arguments that aren't used as part of the pattern matching. This is why elixir doesn't warn you if you haven't used an argument whose name starts with an underscore. I would rename to start_date and end_date.
I would introduce an anonymous function working as an alias, to make the first line a bit easier on the eye. See example below.
Your function would give a MatchError on invalid output. I would probably deliberately check it and raise an ArgumentError instead.

Update: The Erlang/Elixir philosophy is let it fail, and therefore this suggestion might be contrary to common E/E style. From the creator himself:

  This is typically how Elixir/Erlang code is written indeed. If a condition is not met, it fails as MatchError or FunctionClauseError. We typically don't add an extra clause saying what went wrong. The upside is that we simply worry about the happy path (forcing us to write more assertive code). The downside is that it may be cryptic sometimes to find exactly what went wrong. We do include the arguments in the stacktrace though. — José Valim

You can neatify the last line to |> Enum.map &:calendar.gregorian_days_to_date/1.

All in all, I would transform it into something like this:

@doc """
Insert insightful documentation here.
"""
def generate_all_valid_dates_in_range(start_date, end_date)
when start_date <= end_date do
  to_days = &:calendar.date_to_gregorian_days/1
  to_days.(start_date) .. to_days.(end_date)
  |> Enum.to_list
  |> Enum.map &:calendar.gregorian_days_to_date/1
end

def generate_all_valid_dates_in_range(start_date, end_date)
when start_date > end_date do
  raise ArgumentError, "start_date must be before end_date"
end

Note that the second guard (when) is there only to highlight what the invariant is. It should catch all calls that the first definition doesn't. If any calls "fall through", we will get a MatchError and know there's something wrong in our logic.

Using the to_days alias, including the guard in the latter function definition and wrapping the guards to make the lines shorter are a matter of taste, and therefore optional.


Code for simplifying the creation of Dimension Objects

The concept/pattern that you are trying to apply to DimensionGenerator is actually a factory.
You can approach this problem in two major ways, the factory which is what you were trying to do and by subclassing.

To make the factory pattern correct your dimension class must not have any public constructor and all instances shall be created by calling the factory method:

public class DimensionFactory
{
    public Dimension MakeInchDimension(double distance){
        return new Dimension(DimensionType.Millimeter, distance);
    }
    //more methods for other types
}

Should there be many of DimensionType that would be impractical to define a method for each type then you could do the factory like you already pretty much do.

public class DimensionFactory{
    private readonly DimensionType dimensionType;
    public DimensionFactory(DimensionType dimensionType){
        this.dimensionType = distance;
    }
    public Dimension MakeDimension(double distance){
        return new Dimension(dimensionType, distance);
    }
}

In this approach you will end up with a factory object per each dimension type and you will have a generic Make method for all types, this is a big pro since all types are built in the same way. In the first approach you would have to change the interface if you wanted to add a new dimension type in this approach you don't have to do anything at all.

You could also sub class Dimension so you would have one class per DimensionType, once again this approach is only feasible if there are few DimesnionTypes. in this approach Dimension shall be abstract:

public InchDimension : Dimension{
     public InchDimension(double distance):base(DimensionType.Inch, distance){}
}

Edit
Asside from creating dimension your major concern was about comparing them. I'll assume that you can only compare objects of the same dimension and that you can convert any dimension to any other dimension. This way you are detaching conversion from comparison and comparison algorithm is solved easier.

public Dimension{
   public DimensionType DimensionType{get; private set;}
   public Dimension(DimensionType type, double value){
       DimensionType = type;
       Value = value;
   }
   public double Value{get; set;}
   public Dimension ConvertTo(DimensionType type){
      //if this dimension type is not consersible to type then throw NotSupportedException()
      //else do the convertion logic between this type and the other.
   }
}

public DimensionComparer : IEqualityComparer<Dimension>{
   public bool Equals(Dimension d1, Dimension d2){
       if(d1.DimensionType != d2.DimensionType){
           throw new NotSupportedException("cannot compare different dimmension types, please convert your dimension first");
       }
       return d1.Value == d2.Value;
   }
   public int GetHashCode(Dimension d){
      return d.Value ^ d.DimensionType.GetHashCode();
   }
}


You can easily give more structure to your code:

-module(coins).
-export([coins/2]).

-spec coins([CoinValue::integer()], Goal::integer()) -> Combinations::integer().

coins(_, 0) -> 1;
coins([], _) -> 0;
coins(_, Goal) when Goal < 0 -> 0;
coins([CoinValue|Rest], Goal) ->
  WithCoinValue = coins([H|T], Goal-H),
  WithoutCoinValue = coins(T, Goal),
  WithCoinValue + WithoutCoinValue.


Calculating all prime palindromes from 0 to 1000 and printing the largest

The list comprehension [x for x in range(0,1001)] is redundant, as range already returns a list in Python 2. In Python 3 one can use list(range(1001))
Write a docstring instead of a comment to describe a function.
Why is count a float (2.0) in prime_check? Should be an int.
Prefer for loops to while loops when they do the same thing. Eg. use for count in xrange(2, k) in prime_check.
if any_num < 20 and any_num >= 1: can be written as if 1 <= any_num < 20:
You may want to look for more efficient algorithms for generating primes.


Recursive File Search Using the Dir() Function

Just remove it from parameter,
and make it a variable.

Function FindFile(ByVal folderName As String, ByVal FileName As String) As String
    Dim search As String
    Dim dirList As New Collection

    If Not Right(folderName, 1) = "\" Then folderName = folderName & "\"
    search = Dir(folderName & "\*", vbDirectory)
    While Len(search) > 0
        If Not search = "." And Not search = ".." Then
            If GetAttr(folderName & search) = 16 Then
                dirList.Add folderName & search
            Else
                If LCase(search) = LCase(FileName) Then
                    FindFile = folderName & FileName
                    Exit Function
                End If
            End If

        End If
        search = Dir()
    Wend

    Dim fld
    Dim FoundFile As String
    For Each fld In dirList

        FoundFile = FindFile(CStr(fld), FileName)
        If Len(FoundFile) > 0 Then
            FindFile = FoundFile
            Exit Function
        End If
    Next

End Function


How is my program for computing the Hardy-Ramanujan number?

Discrete Mathematics

Discrete calculations should not be done using floating-point math.  You should be suspicious of any results contaminated by floating-point math.  The way to compute the cube of an integer is n * n * n.  For larger powers, do repeated squaring, or use BigInteger.pow() (which is slower, but immune to overflow).

Variable Usage

To be honest, I found your code extremely difficult to read, mainly due to the way you misuse variables.

Scope: You should declare and define variables as close as possible to the point of use.  If a variable only applies within a loop, declare and define it inside the loop.  If it's local to a function, define it as a local variable in the function.  Instead, you've used a lot of instance variables, which, for all practical purposes, are "global" (since you only have one class).  As you really only have one function, all of the variables should have been local!
Proliferation: You've declared 19 instance variables.  Surely fewer variables would suffice?  A human brain can keep track of about 7 items at a time.  You have cSum (an int), cubeSum (an Integer), and cs (a double) — which raises the question, how are they related?  (Answer: cSum is never used, and cs is just a temporary variable that shouldn't have been needed at all.)  Also, answer and iterations are never used.  You've got so many variables that you couldn't keep track of the dead ones to prune.
Cryptic naming: Without studying the code, can you remember what x, y, k, X, Y, K, J, and floor mean?  If not, then your variables are named too cryptically.
Unconventional naming: By connotation, I would expect x to represent a floating-point number, not a list of Integers.  Then, you've also got X, which is a boxed version of j.
Misuse for flow control: To terminate the loop, why do you set a variable and test for found != true elsewhere?  Just return after printing the result — you're done!

Language Disfluency

If you familiarize yourself with the Java language a bit more, you can express yourself less clumsily.

Prefer primitives: You should always prefer the primitives (e.g. int) to their boxed counterparts (Integer).  Code written using primitives reads better and performs better.  The boxed types exist mainly so that you can store them in collections such as ArrayList<Integer>.  Even then, the compiler will automatically box and unbox the values for you, so you don't have to say new Integer(n).
Type Promotion: The compiler will automatically perform widening conversions, such as promoting int to double, so casting is unnecessary in those cases.
Integer division: When dividing an integer by an integer, the result will also be integral (with truncation towards 0).  When you do (int)Math.floor(i/2), you're just promoting i / 2 to a double argument, rounding it to the same double, and casting the result back to an int.  It would have been sufficient to just do i / 2.

Time Out… Let's Rewrite!

Let's rewrite the code using the trivial simplifications mentioned so far.

import java.util.ArrayList;

public class Cubes {

    public static void main(String[] args) {
        new Cubes().find();
    }

    private void find()
    {
        ArrayList<Integer> sum = new ArrayList<Integer>();
        ArrayList<Integer> x = new ArrayList<Integer>();
        ArrayList<Integer> y = new ArrayList<Integer>();
        int a, b, c, d;

        sum.add((2 * 2 * 2) + (1 * 1 * 1));
        x.add(1);
        y.add(2);

        int i = 4;

        while(true)
        {
            for(int j = 1; j < i/2 +1; j++)
            {
                int k=i-j;
                int cubeSum = (k * k * k) + (j * j * j);

                for (int l = 0; l < sum.size(); l++)
                {
                    a = (int)x.get(l);
                    b = (int)y.get(l);
                    if(cubeSum == sum.get(l))
                    {
                        if (a != j && a != k && b != j && b != k)
                        {
                            c=j;
                            d=k;
                            System.out.println("The first positive integer "
                            + "expressible as the sum\nof 2 different positive"
                            + " cubes in 2 different ways\nis "
                            + cubeSum + " = " +a+"^3 + "+b+"^3 = "
                            + c+"^3 + "+d+"^3");
                            return;
                        }
                    }
                }

                sum.add(cubeSum);
                x.add(j);
                y.add(k);
            }
            i++;
        }
    }
}

I find the rewritten version slightly more readable than the original, though I still can't really understand it.

Now, back to our regularly scheduled programming…

Algorithm

Magic numbers: You start with x.add(1), y.add(2), and i = 4.  Where did those magic numbers come from?  They're not naturally part of the problem, and you didn't explain.
x vs. y: What do lists x and y represent?  How does a number end up on these lists, why would it appear on x rather than y, or y rather than x?
Commenting: What is the strategy of your code?  Please outline it in a comment.  Mathematical algorithms in general are complicated, and algorithms, more than anything else, need comments!
False proof: How do you know that you've found the minimum answer rather than just any answer?  I'm not convinced at all.  In fact, if you remove the return after System.out.println() and just let it run, you'll see that it prints 110808 = 6^3 + 48^3 = 27^3 + 45^3 before 110656 = 4^3 + 48^3 = 36^3 + 40^3.  Therefore, the fact that your program prints 1729 is luck, not skill.
Separation of concerns: If you force yourself to separate the code that does input/output from the code that does pure computation, then you will also force yourself to write well organized code.

Proposed Solution

Since your algorithm is bogus, we'll have to start from scratch.  I propose an algorithm in which we iterate through n = 1, 2, 3, 4, … until we find one that is the sum of two cubes.  Then we test if it is also expressible as a sum of another two cubes.  Since we're testing n in increasing sequence, we can be sure that the first result is indeed the minimum number meeting the criteria.

To test whether n is a sum of two cubes, we can successively try subtracting 13, 23, 33, 43, … and test whether the difference is also a perfect cube.  To test whether the difference is a perfect cube, we could take its cube root (floating point — nope!), or check it against a list of perfect cubes (better — raising integers to the third power is easy).  I've written a class called Cubes to help enumerate all perfect cubes.

There's a lot of verbose supporting code.  However, if you look at the heart of the solution, which is hardyRamanujanBreakdown(long n), you'll find it to be very readable.

I've also written it such that you can easily modify the program to find subsequent numbers that are representable as sums of two cubes in two ways.  If you let this run infinitely, it's vulnerable to overflow, but you'll have hit CtrlC long before that happens. ☺

It's also slower than your original, but the original strategy is flawed, so it doesn't count.

import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

//////////////////////////////////////////////////////////////////////

/**
 * An iterator of positive perfect cubes, starting from 1, and ignoring
 * overflow.
 */
class Cubes implements Iterator<Long> {
    /**
     * An "infinite" set of all perfect cubes.
     */
    private static SortedSet<Long> allCubes = new TreeSet<Long>();

    /**
     * Helper to generate more members of allCubes as needed.
     */
    private static Cubes allIter = new Cubes();
    static {
        allCubes.add(allIter.next());
    }

    public static boolean isCube(long num) {
        while (num > allCubes.last()) {
            allCubes.add(allIter.next());
        }
        return allCubes.contains(num);
    }

    public static int cubeRoot(long num) {
        while (num > allCubes.last()) {
            allCubes.add(allIter.next());
        }
        return 1 + allCubes.headSet(num).size();
    }

    public static final long cube(int num) {
        return (long)num * num * num;
    }

    private int i = 1;

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Long next() {
        return cube(this.i++);
    }

    public Cubes dup() {
        Cubes moreCubes = new Cubes();
        moreCubes.i = this.i;
        return moreCubes;
    }
}

//////////////////////////////////////////////////////////////////////

public class HardyRamanujan implements Iterator<Long> {

    private long n;
    private long[] breakdown;

    public HardyRamanujan() {
        this.n = 1;
    }

    @Override
    public boolean hasNext() {
        // Ignores overflow
        return true;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Long next() {
        while (null == (this.breakdown = hardyRamanujanBreakdown(this.n))) {
            this.n++;
        }
        return this.n++;
    }

    /**
     * Returns the breakdown of the current Hardy-Ramanujan number n as an
     * array of four perfect cubes [a, b, c, d].  n = a + b = c + d.
     * a < c <= n/2 <= d < b.  Returns null if next() has never been called.
     */
    public long[] breakdown() {
        return this.breakdown;
    }

    private static long[] hardyRamanujanBreakdown(long n) {
        long a, b, c, d;

        // Exists n == a + b, where a and b are cubes?
        Cubes cubes = new Cubes();
        while ((a = cubes.next()) < n / 2) {
            if (!Cubes.isCube(b = n - a)) {
                continue;
            }

            // If so, exists n == c + d, where c and d are cubes, and c > a ?
            Cubes moreCubes = cubes.dup();
            while ((c = moreCubes.next()) <= n / 2) {
                if (!Cubes.isCube(d = n - c)) {
                    continue;
                }
                return new long[] { a, b, c, d };
            }
        }
        return null;
    }

    public static void main(String[] args) {
        HardyRamanujan hrIter = new HardyRamanujan();
        do {
            long hrNum = hrIter.next();
            long[] breakdown = hrIter.breakdown();
            System.out.format("%d = %d^3 + %d^3 = %d^3 + %d^3\n",
                              hrNum,
                              Cubes.cubeRoot(breakdown[0]),
                              Cubes.cubeRoot(breakdown[1]),
                              Cubes.cubeRoot(breakdown[2]),
                              Cubes.cubeRoot(breakdown[3]));
        } while (false); // Change to true to get more!
    }
}


Hmm... Not sure how much faster this will be, but it may be easier to wrap your head around.
You can use a recursive CTE:

WITH Splitter (id, start, e, section, original, num) as (
               SELECT id, 1, CHARINDEX('-', budgetCode), CAST('' AS VARCHAR(20)), budgetCode, 0
               FROM PC
               UNION ALL
               SELECT id, e + 1,
                      CASE WHEN CHARINDEX('-', original, e + 1) > 0
                           THEN CHARINDEX('-', original, e + 1)
                           ELSE LEN(original) + 1 END,
                      SUBSTRING(original, start, e - start),
                      original, num + 1
               FROM Splitter
               WHERE e > start)

Results:

SELECT *
FROM splitter

Makes a table that looks like this:

Id  BudgetCode
=====================
1   xxxx-yyyyy-zzzzz

Into this:

Id  Start  End   Section   Original           Num
1   1      5               xxxx-yyyyy-zzzzz   0
1   6      11     xxxx      xxxx-yyyyy-zzzzz   1
1   12     17    yyyyy     xxxx-yyyyy-zzzzz   2
1   18     17    zzzzz     xxxx-yyyyy-zzzzz   3

SQL Fiddle Example

You can then join to the result set multiple times based on Num or something to get the particular index you need.  It'll automatically handle any additional 'subfields' (to the limit of the recursion, of course).


Concatenate two arrays generated randomly

Use the native method arraycopy as opposed to manually copying the elements for your concatenation method for better performance:

public static int[] concat(int[] a, int[] b) {
   int aLen = a.length;
   int bLen = b.length;
   int[] c= new int[aLen+bLen];
   System.arraycopy(a, 0, c, 0, aLen);
   System.arraycopy(b, 0, c, aLen, bLen);
   return c;
}

Also think about making more use of enhanced for loops, how come you are only using them for part of your solution and not the rest?

for(int i:arr){
    i = rand.nextInt(maxValue);
}


Have you tried something like this:

Create the following vector:

  System.Numerics.Vector<float> maxima = new System.Numerics.Vector<float>(maximimum);

Then after the multiplication call:

arrayvector = System.Numerics.Vector.Min(arrayvector, maxima);

Here you may have to create an new vector instead of reassigning to arrayvector?

So all in all it ends up like:

  int length = array.Length;

  int floatcount = System.Numerics.Vector<float>.Count;
  System.Numerics.Vector<float> maxima = new System.Numerics.Vector<float>(maximimum);

  for (int i = 0; i < length; i += floatcount)
  {
    System.Numerics.Vector<float> arrayvector = new System.Numerics.Vector<float>(array, i);

    arrayvector = System.Numerics.Vector.Multiply(arrayvector, 2.0f);
    arrayvector = System.Numerics.Vector.Min(arrayvector, maxima);
    // There may be different or multiple vector operations in here.

    arrayvector.CopyTo(array, i);

  }

Disclaimer: I haven't tested the above, so don't hang me if it's not an improvement :-)


public void MakeCall()
{
    switch (callType)
    {
        case CallType.Regular:
            ratePerMinute = regularRate;
            break;
        case CallType.Important:
            ratePerMinute = regularRate * 1.5M;
            break;
        case CallType.Critical:
            ratePerMinute = regularRate * 2.5M;
            break;
    }
}

Seeing this method I would say the same. You cannot easily add new call-types and you cannot easily change their rate because they are all in the same switch. You have to open it every time. The Open-Closed-Priciple is violated. Even worse, the rate is not a part of the call-type but some magic number inside the switch.

What you can do is to create a class for each call-type. This means forget about the enum. Remove everything but the basic stuff from the Call and give it a protected constructor:

public abstract class Call
{
    protected Call(decimal rate) => Rate = rate;

    public decimal Rate { get;}

    public void MakeCall()
    {
        // do something...
    }
}

Use it to derive other calls (I did it for one of them);

public class RegularCall : Call
{
    private const decimal DeafultRate = 0.25m;

    public RegularCall() : base(DeafultRate ) {}
}

Alternatively you can make the property abstract and return the value here instead of passing it via the constructor:

public class RegularCall : Call
{
    public override decimal Rate => 0.25m;
}

And use some other service to create an instance of a call and do some other stuff:

public class Caller
{
    public static void MakeCall<TCall>() where TCall : Call, new
    {
        var call = new TCall();
        call.MakeCall();
    }
}

Each button would the just do this:

private void button1_Click(object sender, EventArgs e)
{
    Caller.MakeCall<RegularCall>();
}

Now you can add as many calls as you like without modifying anything.


How to Unit Test a Thread which has an infinite loop?

When you want to test things that happened asynchronously, one solution is to give them some time to happen as you did. A bit more practical approach is to check if the assert condition is met in a loop and sleep a bit between the checks. if the condition is met no need to continue waiting. eventually, it needs to stop after a few tries or you have an infinite loop in your test.

Usually, you need to use this approach in E2E / Integration tests and not unit tests.


Real time metal prices and conversion fro USD to MXN using BeautifulSoup updated version

I think it would be better to handle the API stuff to convert prices using a Python package like CurrencyConverter.
The site that you are using currently might be down some day or may blacklist your IP because of the many requests that your code is making to convert the prices.
Also, your code seems to be better converted to a Scrapy project if you are interested in web scraping. Scrapy Tutorial by ScrappingHub


Real inheritance is not possible in DataTemplate through XAML, as far as I know. What you can do with is use a nested construction of DataTemplates.

The method boils down to using a ContentPresenter and setting the ContentTemplate property in order to achieve your nesting.

Solutions are already presented on SO and Google; both give a good bit of information:

Stack Overflow
Stack Overflow
Google


Check if all of the delimiters in an expression are matched and closed

Performance

Checking if a list contains a value is an \$O(n)\$ operation.
To make if v not in delimiters fast,
it would be better to make delimiters a set instead of a list.

The elif v in delimiters: is unnecessary, because at that point we already know that v is in delimiters, so you can replace with a simple else:.

Creating lists and maps of characters

This is a PITA to type:

delimiters = ['[', ']', '(', ')', '{', '}']
delimiters_map = {']':'[', ')':'(', '}':'{'}

An easier and less error-prone way is to call list to turn a string into a list of characters:

openers = list('[({')
closers = list('])}')
delimiters = set(openers + closers)
delimiters_map = dict(zip(closers, openers))

If it's a stack, call it a stack

working_set is a misleading name. It suggests a set, but it's a list.
And you're using it as a stack, so I suggest to call it a stack.

Use doctests

Doctests are awesome. You can run them with python -mdoctests script.py.

def check_match(source):
    """
    >>> check_match('{(abc)22}[14(xyz)2]')
    True

    >>> check_match('[ { ] }')
    False

    >>> check_match('{ (x) } [')
    False

    >>> check_match('')
    True

    """
    # ... (your implementation)


Calculating pi to 7 significant figures without using Math.PI

Your implementation is fine. You could add some tweaks (i += 4 instead of i += 2) to avoid multiplying i by 2.0, but this won't help much to make your program fast.

This is because you chose a simple formula, but that formula converges very slowly towards \$\pi\$.

Read on Wikipedia about efficient algorithms for computing \$\pi\$, there are several.

Or, if you want to cheat a bit, just return 4 * Math.atan(1.0).

You don't need a delta in the whole program, so only declare it where you really need it. You already did that with firstFrac, for example.

Be consistent with your chosen names. What's the difference between firstFrac and firstNum? — There is none, therefore you should use the same name in both places.

What does sumOne mean? Think of a better name for it.


Generally in .NET (especially C#) public members are PascalCase.

On a more important note: don't use strings for the errorCode. Instead, use an enum.

public enum ErrorCode
{
    ServerSocketBeginListeningFailure, // Rename this to something shorter if desired.
    LogFileNotFound,
}

You could also, potentially, make this a Flags enum, which would mean that error codes could be easily combined and used together to indicate multiple errors occurring at a time.

This will allow you to make more certain that the user doesn't specify a bad error code.

Use braces even when not necessary, they won't generally prevent bugs, but they will help prevent bugs.

Just as well, do not inline an if/else if/else statement when not using braces. Typically, when I see one of those, my eyes immediately follow the next line. I didn't notice return "" on your else in tryGetErrorMessage until I realized there was not a statement below it.


you should separate the IRCBot from the Main into its own class with it's own fields/properties
you should specify all required parameters via the construtor so that it is not possible to create an invalid ircbot
I don't think it's a good idea to make the retry recursive - IMHO it would be better to create a loop and limit the retries so that you don't have an infite loop (ok, unless it was desired)
you really should use the using statement. In your current implementation the resources will be closed only if there was no execption - if an exception occurs the Closees won't be called. You also don't free the resources because you don't call the Dispose, you just close them and then create new resources on retry, this is a memory leak.

Here's an example:

public class IRCbot
{
    // server to connect to (edit at will)
    private readonly string _server;
    // server port (6667 by default)
    private readonly int _port;
    // user information defined in RFC 2812 (IRC: Client Protocol) is sent to the IRC server
    private readonly string _user;

    // the bot's nickname
    private readonly string _nick;
    // channel to join
    private readonly string _channel;

    private readonly int _maxRetries;

    public IRCbot(string server, int port, string user, string nick, string channel, int maxRetries = 3)
    {
        _server = server;
        _port = port;
        _user = user;
        _nick = nick;
        _channel = channel;
        _maxRetries = maxRetries;
    }

    public void Start()
    {
        var retry = false;
        var retryCount = 0;
        do
        {
            try
            {
                using (var irc = new TcpClient(_server, _port))
                using (var stream = irc.GetStream())
                using (var reader = new StreamReader(stream))
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine("NICK " + _nick);
                    writer.Flush();
                    writer.WriteLine(_user);
                    writer.Flush();

                    while (true)
                    {
                        string inputLine;
                        while ((inputLine = reader.ReadLine()) != null)
                        {
                            Console.WriteLine("<- " + inputLine);

                            // split the lines sent from the server by spaces (seems to be the easiest way to parse them)
                            string[] splitInput = inputLine.Split(new Char[] { ' ' });

                            if (splitInput[0] == "PING")
                            {
                                string PongReply = splitInput[1];
                                //Console.WriteLine("->PONG " + PongReply);
                                writer.WriteLine("PONG " + PongReply);
                                writer.Flush();
                                //continue;
                            }

                            switch (splitInput[1])
                            {
                                case "001":
                                    writer.WriteLine("JOIN " + _channel);
                                    writer.Flush();
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // shows the exception, sleeps for a little while and then tries to establish a new connection to the IRC server
                Console.WriteLine(e.ToString());
                Thread.Sleep(5000);
                retry = ++retryCount <= _maxRetries;
            }
        } while (retry);
    }
}

Usage:

void Main()
{
    var ircBot = new IRCbot(
        server: "irc.changeme.com",
        port: 6667,
        user: "USER IRCbot 0 * :IRCbot",
        nick: "IRCbot",
        channel: "#opers"
    );

    ircBot.Start();
}


Converting string to dict using Python ast library

To answer your question, yes ast is ok to be used for this. Per the documentation for literal_eval:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.


I have an answer which also changes the logic of your code but I think there is a good reason why you should consider it:

function passtest($pass) {
    $errors = array();
    if (empty($pass)) $errors[] = 'Password field is empty';
    if (ctype_alnum($pass)) $errors[] = 'Password has special character';
    [...]

    return '
' . implode('
', $errors);
}

Since it appears like this is somehow shown to the user I would notifyabout all  the errors that happened in choosing the password, so that they can all be corrected in a single try.

Another sidenote: Since your code reminds me of the time where I was just getting started and this seems to be at least somewhat related:
Don't save passwords, save their hashes. And use a good hashing implementation. If you're using PHP >= 5.5, there is a really easy way.

And thanks to "Fge", I can also give you a slightly less easy way for earlier PHP versions (>= 5.3.7).


Instantiating icons, labels, and text fields for a contact form

Personally, I don't think this is too bad. What would be better, though, is to keep them as lists:

icons = [wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) for _ in range(4)]
labels = [wx.StaticText(self.panel, wx.ID_ANY, txt ) for txt in
         ('Name', 'Address', 'Email', 'Phone')]
texts = [wx.TextCtrl(self.panel, wx.ID_ANY, '') for _ in range(4)]

This way you can later do stuff like:

for icon, label, text in zip(icons, labels, texts):
    do_stuff()

Note that I renamed you variables with lower_case as recommended by PEP8, Python's official style-guide, removed unnecessary whitespace and limited the line width to 80 characters.

If all three things describe a single object, why not make it an actual object? Add another class:

class Button():
    def __init__(self, panel, label, bmp):
        self.icon = wx.StaticBitmap(panel, wx.ID_ANY, bmp)
        self.label = wx.StaticText(panel, wx.ID_ANY, txt)
        self.text = wx.TextCtrl(panel, wx.ID_ANY, '')

bmp = None  # Seems to be defined elsewhere in your code
labels = ('Name', 'Address', 'Email', 'Phone')
buttons = [Button(self.panel, label, bmp) for label in labels]

Or maybe a namedtuple is sufficient here, even though the class is able to hide more complexity:

from collections import namedtuple

Button = namedtuple("Button", "icon label control")

bmp = None  # Seems to be defined elsewhere in your code
names = ('Name', 'Address', 'Email', 'Phone')

buttons = [Button(wx.StaticBitmap(self.panel, wx.ID_ANY, bmp),
                  wx.StaticText(self.panel, wx.ID_ANY, txt),
                  wx.TextCtrl(self.self.panel, wx.ID_ANY, '')
                  ) for txt in names]

Then, both for the class and the namedtuple, you can do stuff like:

for button in buttons:
    print button.label


ResizableArray based queue implementation

private T[] mQueue;
    private int mHead, mTail, mCurrentSize, mSize;

The value that you are storing in mSize is available as mQueue.length.

    private T[] mQueue = (T[]) new Object[1];
    private int mHead = 0;
    private int mSize = 0;

But if you get rid of mSize, then there is no reason to differentiate mCurrentSize.  So just call that mSize.

You also don't need mTail, as mHead, mSize, and mQueue.length determine mTail uniquely.

You don't need a constructor, as you can initialize these values without further calculation.

        T[] newQueue = (T[]) new Object[size];
        int mCurrent = 0;
        while(mCurrent < mCurrentSize){
            newQueue[mCurrent] = mQueue[(mCurrent + mHead) % mSize];
            mCurrent++;
        }

        mQueue = newQueue;
        mSize = size;
        mHead = 0;
        mTail = mCurrentSize - 1;

There's a built-in for this.

        mQueue = Arrays.copyOfRange(mQueue, mHead, mHead + size);
        mHead = 0;

Now you don't newQueue or mCurrent.

As previously said, you don't need mSize or mTail.

    public void enQueue(T valueToEnque){
        if (mCurrentSize == mSize) {
            resize(2 * mSize);
        }
        mTail = ++mTail % mSize;
        mQueue[mTail] = valueToEnque;
        mCurrentSize++;
    }

    public T deQueue(){
        if(mCurrentSize == mSize / 4) {
            resize(mSize / 2);
        }
        T value = mQueue[mHead % mSize];
        mQueue[mHead % mSize] = null;
        mHead++;
        mCurrentSize--;
        return value;
    }

To implement, you could do it like

    public void enQueue(T valueToEnque) {
        if (mSize >= mQueue.length) {
            resize(2 * mQueue.length);
        }

        mQueue[(mHead + mSize) % mQueue.length] = valueToEnque;
        mSize++;
    }

    public T deQueue() {
        if (mSize <= mQueue.length / 4) {
            resize(mQueue.length / 2);
        }

        T value = mQueue[mHead];
        mQueue[mHead] = null;
        mHead = ++mHead % mQueue.length;
        mSize--;

        return value;
    }

By using <= or >= rather than strict equality, we can catch situations where the size jumped over the gating.  For example, if you implemented QueueIterator.remove without calling deQueue, you might find that you had skipped over the resize check.

See how we determine the value that would have been held in mTail as needed rather than maintaining it.

Notice how things are easier if we maintain mHead as the actual index rather than allowing it to grow unbounded.  Note that this also avoids integer overflow in an edge case (if you never resize, mHead always grows).


This looks quite fine to me. Granted, you make several passes over the entire string, but that doesn't matter much, as the time complexity remains \$O(n)\$, space complexity constant, and this is easy to read and understand.

You could reduce the number of passes by using extra storage, in which you could prepend the reversed segments. But due to the extra storage, such algorithm would not be better, it would be different. Whether one solution is better than the other depends on external constraints not stated in the problem. Talking about this is important at an interview, more important than whatever solution you gave.

In terms of the implementation, the only thing I would change is convert the main while loop to a for loop. The reason is that the start and end variables are only used inside the loop body, and the for loop would help confining them into that scope, which is a good thing, reducing the live time of those variables, and preventing accidental uses outside the loop.


Remove nodejs/browser specific code in library

Yeah..

Are you against maintaining 2 repositories or maintaining 2 main files? Honestly I would have 2 main files with a third file ( or more ) containing routines that are host agnostic.

docxgen_node.coffee , docxgen_www.coffee and docxgen_common.coffee

It sounds uncool, but I think in the end, this should be easiest on the eyes.

Other, than that, I would take the opportunity to use that massive ( ugly ) string array to document why you need each library and maybe which versions are usable for your repository:

var requiredLibraries = [
  "grid.js",     //Use xyz version, uses abc features
  "version.js",  //...
  "detector.js", //..
  ...
]

requiredLibraries.forEach (file) ->
    vm.runInThisContext(global.fs.readFileSync(__dirname + '/../vendor/jsqrcode/' + file), file)


Number of files with specific file size ranges

suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] you never change the value of suffixes, so it should be a constant, the standard naming of constant in Python is  ALL_UPPERCASE, rename it to SUFFIXES
You should name variables with snake_case.
You wrote for r in files: the details count: the standard one-letter identifier for file is f, use that.
Look at f = ('%.2f' % nbytes).rstrip('0').rstrip('.'), f is a meaningless one-letter name. You should use a longer and more meaningful name
You are checking and i < len(suffixes)-1 in the loop: it is not possible that the user has a file bigger than one Petabyte (10**15 bytes) so you can safely remove that check. and it is very good that you that, code that crashes when you find an unexpected condition should be avoided with error checking like this one. (Thanks to @Veedrac for correcting me)

f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i])

You are a C programmer, aren't you? :) Using "%s" string formatting in Python is considered obsolete and should be avoided, instead use string.format()

print "Number of files greater than %s less than %s:" %(human_Readable(start), human_Readable(end)),  counter

You are printing from inside a function this is not nice, you should return values, not print them.

It is common to take the parametres from the command line so:

route = raw_input('Enter a location')

should become:

import sys
route = sys.argv[1]

this also makes the code compatible with Python 3 if you add brackets around the print

You are repeating yourself so much:

file_Dist(route, 0, 1024)
file_Dist(route,1024,4095)
file_Dist(route, 4096, 16383)
file_Dist(route, 16384, 65535)
file_Dist(route, 65536, 262143)
file_Dist(route, 262144, 1048576)
file_Dist(route, 1048577, 4194304)
file_Dist(route, 4194305, 16777216)

It would be better to use a loop:

for start in [1024,4096,16384,262144,1048577,4194305]:
    end = start * 4
    file_Dist(route,start,end)

You may want to import this script, using if __name__ will allow you to run the tests only if this script is the main file

def test():
    for start in [1024,4096,16384,262144,1048577,4194305]:
        end = start * 4
        file_Dist(route,start,end)

if __name__ == "__main__":
    test()


Long name

ThorsAnvil::Util::getRandomIteratorFromContainer is a really long name. I suggest something like getRandomElement or even randomElement.

Unnecessary function

getDist seems kind of unnecessary to me. I think it would be cleaner to construct the distribution directly.

std::uniform_int_distruction<int> dist{0, container.size() - 1};

Types

The integer type used for iterator arithmetic is typename C::difference_type. This is almost always equivalent to std::ptrdiff_t so to be crystal clear, use std::ptrdiff_t.

std::uniform_int_distruction<std::ptrdiff_t> dist{0, container.size() - 1};

Unnecessary variable

offset is initialized with a random offset and is only used once. If it's only used once then it doesn't really need to exist.

std::advance(pos, dist(generator));

Wrong function

std::advance modifies an existing iterator. This means that we need store the iterator, advance it, then return the iterator. That's three steps. std::next takes an iterator and returns an incremented one.

return std::next(container.begin(), dist(generator));

Covering all cases

Using .begin() and .size() is a little bit restrictive. If we use std::begin and std::size, this function will work on C-style arrays which is a nice. If we want to be even more general (as Toby mentioned in the comments), we can let ADL pick up the right function for containers that declare their own begin and size functions.

using std::begin;
using std::size;

Short names

My answer has been pretty nitpicky so far but this is particularly nitpicky. Long template parameter names that clearly describe the parameter are better than single character names.

template <typename Container, typename Generator>

How I would write it

After applying the above transformations. We get this function:

template <typename Container, typename Generator>
auto random_element(Container &con, Generator &gen) {
  using std::begin;
  using std::size;
  std::uniform_int_distribution<std::ptrdiff_t> dist{0, size(con) - 1};
  return std::next(begin(con), dist(gen));
}


Generating and finding parent nodes in a post-order tree

The problem of "what is the parent of one node in the tree" can be solved as a recurrence relation, either using arithmetic or using the bits in the binary representation of the number.

The problem of "what are the various parents of many nodes in the tree" is a group solution that cries out for some batch computation followed by speed-oriented lookups.

Look at the numeric properties of the nodes. You should not be computing a tree for this.

Also, look at the desired problem solution: you want to perform a computation or lookup for each number in a list. Thus, your information storage should be optimized for this.

Given that your tree represents a range of numbers, I'll suggest either a dictionary or a list. Since the numbers are a dense group of integers that start from 1, I'll suggest a list.

Parents = [0] * (n+1)

Given h, how can you predict n (above)? What's the number at the root of the tree?

Given R the number at the root of a tree, what are the values of the numbers at the root of the next lower subtrees? (Hint: easy for the left, harder for the right.)


The Show typeclass is for debugging

The Show typeclass is really meant to be derived, not implemented yourself. The purpose of Show is mostly for debugging, and the closest thing to a law for Show is that it should be the inverse of Read. The result of show should usually be a string that represents a Haskell expression that would produce the value itself.

While it is tempting to create a custom instance of Show for your own purposes, I would just convert your instance into a separate function, showOperator (which can also be implemented more simply with direct pattern matching rather that explicitly using case):

showOperator :: Operator -> String
showOperator Add = "+"
showOperator Subtract = "-"
showOperator Multiply = "-"

randomSensibleInts is poorly-named

What makes integers in the range [1, 10] any more “sensible” than any other integers? Given how incredibly simple it is, and given it’s only used in one place, I would honestly just inline it into the place it’s used. I think it’s clearer that way than any name you could give it.

Avoid !!

The !! function is unsafe, since it will crash if the provided index is out of bounds. Admittedly, in your case, you know the length of the list will always be exactly 2, so it’s not dangerous, but in that case, you should just use pattern-matching instead:

genQuestion :: StdGen -> (Int, Operator, Int, StdGen)
genQuestion gen = (x, operator, y, gen')
  where [x, y] = take 2 $ randomRs (1, 10) gen
        (operator, gen') = random gen

(You also don’t need the type annotation on random gen, so I’ve removed it.)

Package tuples into named datatypes

The long tuple return type for genQuestion is a little bit suspicious. The name even provides a good suggestion for naming the datatype: Question. Create a datatype for that instead of having such a large tuple:

data Question = Question Int Operator Int

genQuestion :: StdGen -> (Question, StdGen)
genQuestion gen = (Question x operator y, gen')
  where ...

askQuestion :: (Question, StdGen) -> IO Bool
askQuestion (Question i1 o i2, gen) = ...

Avoid using booleans directly

Using Bool as a return type of a non-predicate function can be confusing (this is referred to as “boolean blindness”). Using a separate, named type can be both more readable and more scalable if the number of cases ever changes:

data AnswerResult = Correct | Incorrect
  deriving (Eq)

askQuestion :: (Question, StdGen) -> IO AnswerResult
askQuestion = ...

This also allows adjusting the score summing logic to be a bit more reliable. Using toEnum and assigning significance to the indices is both unnecessary and mixing concerns.

putStrLn $ "Your score was " ++ show (length $ filter (== Correct) answers)

Avoid mixing pure and impure logic

The askQuestion function has too many responsibilities: formats a prompt for input, displays it to the user, calculates the answer to the question, validates the answer to the question, and prints out a response based on the answer. Three of those responsibilities are totally pure, and they should ideally be pulled into their own functions:

questionPrompt :: Question -> String
questionPrompt (Question x op y) = "Enter the answer to " ++ show x ++ showOperator op ++ show y ++ ": "

questionAnswer :: Question -> Int
questionAnswer (Question x op y) = operatorFunction op x y
  where operatorFunction Add = (+)
        operatorFunction Subtract = (-)
        operatorFunction Multiply = (*)

validateAnswer :: Question -> Int -> AnswerResult
validateAnswer question answer =
  if questionAnswer question == answer
  then Correct
  else Incorrect

askQuestion :: (Question, StdGen) -> IO AnswerResult
askQuestion (question, gen) = do
  putStrLn $ questionPrompt question
  userAnswer <- getLine
  let answerResult = validateAnswer question (read userAnswer)
  case answerResult of
    Correct -> putStrLn "Well done!"
    Incorrect -> putStrLn $ "Wrong - the answer was " ++ show (questionAnswer question)
  return answerResult

Eliminate unused variables

If you turn on -Wall, GHC will tell you that gen is never used in askQuestion at all, so it can be removed:

genQuestion :: StdGen -> Question
genQuestion gen = Question x operator y
  where [x, y] = take 2 $ randomRs (1, 10) gen
        (operator, _) = random gen

askQuestion :: Question -> IO AnswerResult
askQuestion question = do
  putStrLn $ questionPrompt question
  userAnswer <- getLine
  let answerResult = validateAnswer question (read userAnswer)
  case answerResult of
    Correct -> putStrLn "Well done!"
    Incorrect -> putStrLn $ "Wrong - the answer was " ++ show (questionAnswer question)
  return answerResult

main :: IO ()
main = do
  gens <- mapM (const newStdGen) [1..10]
  let questions = map genQuestion gens
  answers <- mapM askQuestion questions
  putStrLn $ "Your score was " ++ show (length $ filter (== Correct) answers)

Use where or let instead of case when there is only one pattern

In the Random instance for Operator, it’s possible to avoid case if you’re simply destructuring rather than matching against multiple patterns:

instance Random Operator where
  random gen = (toEnum item, gen')
    where (item, gen') = randomR (0, 2) gen

  randomR (lo, hi) gen = (toEnum item, gen')
    where (item, gen') = randomR (fromEnum lo, fromEnum hi) gen

Final result

import System.Random

data Operator = Add | Subtract | Multiply
  deriving (Eq, Enum)

data Question = Question Int Operator Int

data AnswerResult = Correct | Incorrect
  deriving (Eq)

instance Random Operator where
  random gen = (toEnum item, gen')
    where (item, gen') = randomR (0, 2) gen

  randomR (lo, hi) gen = (toEnum item, gen')
    where (item, gen') = randomR (fromEnum lo, fromEnum hi) gen

showOperator :: Operator -> String
showOperator Add = "+"
showOperator Subtract = "-"
showOperator Multiply = "-"

questionPrompt :: Question -> String
questionPrompt (Question x op y) = "Enter the answer to " ++ show x ++ showOperator op ++ show y ++ ": "

questionAnswer :: Question -> Int
questionAnswer (Question x op y) = operatorFunction op x y
  where operatorFunction Add = (+)
        operatorFunction Subtract = (-)
        operatorFunction Multiply = (*)

validateAnswer :: Question -> Int -> AnswerResult
validateAnswer question answer =
  if questionAnswer question == answer
  then Correct
  else Incorrect

genQuestion :: StdGen -> Question
genQuestion gen = Question x operator y
  where [x, y] = take 2 $ randomRs (1, 10) gen
        (operator, _) = random gen

askQuestion :: Question -> IO AnswerResult
askQuestion question = do
  putStrLn $ questionPrompt question
  userAnswer <- getLine
  let answerResult = validateAnswer question (read userAnswer)
  case answerResult of
    Correct -> putStrLn "Well done!"
    Incorrect -> putStrLn $ "Wrong - the answer was " ++ show (questionAnswer question)
  return answerResult

main :: IO ()
main = do
  gens <- mapM (const newStdGen) [1..10]
  let questions = map genQuestion gens
  answers <- mapM askQuestion questions
  putStrLn $ "Your score was " ++ show (length $ filter (== Correct) answers)


Interview solutions to reverse a string and reverse a sentence

The reverse of an empty string should be an empty string, not null.

In reverseSentence(), the reversed.trim() call inefficiently copies the entire string, less one final space.  You would have been better off shortening the StringBuilder instead of trimming the string.

All of your uses of final are excessive, I think.  The final keyword merely prevents reassignment, and doesn't make anything more immutable than it already is.  For short functions like this, writing final just adds noise.


Converting a SecureString to a byte array

Although you have done a decent job, you could do this in a better way, without even to use unsafe.

First thing to mention, you should always use braces {} although they are optional for single lined if statements. This will just make your code less error prone which is in such a security context wanted.

Instead of using if (encoding==null) { encoding = Encoding.UTF8; } you can use the null coalescing operator ??.

How I use this usually (integrated in your method)

private byte[] ToByteArray(SecureString secureString, Encoding encoding = null)
{
    if (secureString == null)
    {
        throw new ArgumentNullException(nameof(secureString));
    }

    encoding = encoding ?? Encoding.UTF8;

    IntPtr unmanagedString = IntPtr.Zero;
    try
    {
        unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);

        return encoding.GetBytes(Marshal.PtrToStringUni(unmanagedString));
    }
    finally
    {
        if (unmanagedString != IntPtr.Zero)
        {
            Marshal.ZeroFreeBSTR(unmanagedString);
        }
    }
}

Based on the valid comment

  Marshal.PtrToStringUni allocates managed string so until GC clear this we will have unprotected string with sensitive data in memory.

I would like to suggest another aproach which depends on your implementation. The main problem I see is that with your implementation the returned byte[] needs to be cleaned up from the caller of the code.

How about having a class which implements IDisposable which is wrapping the shown method ?

public sealed class SecureStringWrapper : IDisposable
{
    private readonly Encoding encoding;
    private readonly SecureString secureString;
    private byte[] _bytes = null;

    public SecureStringWrapper(SecureString secureString)
          : this(secureString, Encoding.UTF8)
    {}

    public SecureStringWrapper(SecureString secureString, Encoding encoding)
    {
        if (secureString == null)
        {
            throw new ArgumentNullException(nameof(secureString));
        }

        this.encoding = encoding ?? Encoding.UTF8
        this.secureString = secureString;
    }

    public unsafe byte[] ToByteArray()
    {

        int maxLength = encoding.GetMaxByteCount(secureString.Length);

        IntPtr bytes = IntPtr.Zero;
        IntPtr str   = IntPtr.Zero;

        try
        {
            bytes = Marshal.AllocHGlobal(maxLength);
            str   = Marshal.SecureStringToBSTR(secureString);

            char* chars = (char*)str.ToPointer();
            byte* bptr  = (byte*)bytes.ToPointer();
            int len     = encoding.GetBytes(chars, secureString.Length, bptr, maxLength);

            _bytes = new byte[len];
            for (int i = 0; i < len; ++i)
            {
                _bytes[i] = *bptr;
                bptr++;
            }

            return _bytes;
        }
        finally
        {
            if (bytes != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(bytes);
            }
            if (str != IntPtr.Zero)
            {
                Marshal.ZeroFreeBSTR(str);
            }
        }
    }

    private bool _disposed = false;

    public void Dispose()
    {
        if (!_disposed)
        {
            Destroy();
            _disposed = true;
        }
        GC.SuppressFinalize(this);
    }

    private void Destroy()
    {
        if (_bytes == null) { return; }

        for (int i = 0; i < _bytes.Length; i++)
        {
            _bytes[i] = 0;
        }
        _bytes = null;
    }

    ~SecureStringWrapper()
    {
        Dispose();
    }
}

now the caller could use it like so

using (SecureStringWrapper wrapper = new SecureStringWrapper(secureString))
{

    byte[] _bytes = wrapper.ToByteArray();
    // use _bytes like wanted

}

A good read about the topic of SecureString: http://web.archive.org/web/20090928112609/http://dotnet.org.za/markn/archive/2008/10/04/handling-passwords.aspx


You can try something like this (obviously names can be shorter):

if_user_is_a = ->(klass) { { if: -> { user.is_a?(klass) } } }
validates :inn, presence: if_user_is_a[Client], ..., absence: if_user_is_a[Department]

or

if_user_is_a = ->(klass) { { if: -> { user.is_a?(klass) } } }
if_user_is_a_client = if_user_is_a[Client]
...
validates :inn, presence: if_user_is_a_client, ...


Selecting employees in certain departments using LINQ

lstdepartment

We don't use Hungarian notation with prefixes like lst in C#. It's just departments

This is notepad coding but you can use a join to get the matching deparment

var results =
    from e in _context.Employee
    join d in _context.Department on e.DepartmentId equals d.DepartmentId
    where e.EmployeeId = EmployeeId
    select new EmployeeInfo
    {
        EmployeeId = e.EmployeeId,
        FirstName = e.FirstName,
        LastName = e.LastName,
        MiddleName = e.MiddleName,
        DepartmentName= d.DepartmentName
    }).ToList();

although this is not yet exactly what you have because this will yield only exact matches. If you want deparment-name to be null then you need a left join and I think this should work:

var results =
    from e in _context.Employee
    join d in _context.Department on e.DepartmentId equals d.DepartmentId into ds
    from d in ds.DefaultIfEmpty()
    where e.EmployeeId = EmployeeId
    select new EmployeeInfo
    {
        EmployeeId = e.EmployeeId,
        FirstName = e.FirstName,
        LastName = e.LastName,
        MiddleName = e.MiddleName,
        DepartmentName= d?.DepartmentName
    }).ToList();


You can create a manifest file and set the app to require administrative privileges. This will trigger the UAC user prompt with the dimmed screen when your application is run without requiring any code on your part.

See MSDN for the gory details:

  This file can be created by using any text editor. The application manifest file should have the same name as the target executable file with a .manifest extension.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="<your exec name minus extension>"
     type="win32"/>
  <description>Description of your application</description>
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="requireAdministrator"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>


Sum of squares of two largest of three numbers

Scheme is a lot more functional than Common Lisp. The way you can apply that to this situation is by making more use of passing functions around (to the point that this problem is almost a one-liner). For the puzzle as written, I'd do something like

(define (big-squares a b c)
   (apply + (map (lambda (n) (* n n))
                 (take (sort (list a b c) >) 2))))

If you wanted to decompose it properly into named functions

(define (square num) (expt num 2))
(define (sum num-list) (apply + num-list))
(define (two-biggest num-list) (take (sort num-list >) 2))

(define (big-squares a b c) (sum (map square (two-biggest (list a b c)))))

If you wanted to go completely overboard, also toss in

(define (squares num-list) (map square num-list))

which would let you define big-squares as

(sum (squares (two-biggest (list a b c))))

(code above in mzscheme)


Stop connecting to a server after n unsuccessful attempts

The smart and polite thing to do when retrying is to wait some random (and possibly increasing) interval between retries.  The last thing you want to do to a failing server or network is to overwhelm it with connections as fast as the clients are able to generate them.

In connect_to_server(), squashing the EnvironmentError into a string is a bad idea.  Just letting the exception propagate would better convey the fact that a failure occurred.  Besides, what if the server really wanted to send the string "Connection Error" as its message?  Changing the client's behaviour based on the payload might even be considered a mild denial-of-service vulnerability.

The idiomatic way to write a counting loop in Python is to use range().

Defining a retry() function would be worthwhile for three reasons:

It makes your code self-documenting
It declutters your main()
You might be able to reuse the retry logic if it's needed elsewhere

One solution is to define a @retry decorator for functions:

from functools import wraps
from random import random
from time import sleep

def retry(max_tries=3, max_retry_interval=2, exceptions=[Exception],
          failure_callback=lambda exc, attempt, max_tries: None):
    """Tries calling the decorated function up to max_tries times until
    it succeeds, and returns its result.

    Any exceptions of the specified types thrown by the decorated function
    will trigger a retry.  The failure_callback is called with each failure,
    with the exception, the attempt number (starting with 0), and max_tries
    max_tries as callback parameters.

    There is a random delay of up to max_retry_interval seconds between
    tries.

    If max_tries attempts all result in failure, then the last encountered
    exception is raised. """
    def decorator(f):
        @wraps(f)
        def retry_wrapper(*args, **kwds):
            exception = None
            for attempt in range(max_tries):
                try:
                    return f(*args, **kwds)
                except Exception as e:
                    if not next((e for cls in exceptions if isinstance(e, cls)), None):
                        # Unexpected type of exception
                        raise
                    failure_callback(e, attempt, max_tries)
                    exception = e
                    if attempt < max_tries - 1:
                        sleep(max_retry_interval * random())
            if exception is not None:
                raise exception
        return retry_wrapper
    return decorator

Then your code would look like:

@retry(3, 5, [EnvironmentError], lambda exc, attempt, max_tries: print("Connection Error"))
def connect_to_server():
    …

def main():
    try:
        connection = connect_to_server()
        print(connection)
    except EnvironmentError as e:
        print(e)
        print("No more connection attempts")

Or, without hard-coding the retry parameters in a decorator:

def connect_to_server():
    …

def main():
    try:
        retry3times = retry(3, 5, [EnvironmentError],
                            lambda _, _, _: print("Connection Error"))
        connection = (retry3times(connect_to_server))()
        print(connection)
    except EnvironmentError as e:
        print(e)
        print("No more connection attempts")


A simple function to rename columns in data frame to standardized names in R

Most R functions are vectorized, you don't need the for loop:

colRename <- function(x) {
   setNames(x, paste0("column", seq_len(ncol(x))))
}


choice of language

Unfortunately Java is not the best choice for doing such tasks. Object creation, reference handling and alike simply takes time.

So to speed up we need to throw away some of the benefits provides by the JVMs standard lib and switch to procedural programming on arrays.

optimizations

The calculation of the cycle length is a clever trick. But there must be an algorithm without looping which would speed up this calculation too.

implementation

As mentioned a fast solution must avoid object creation at all and should work on an array of chars rather than on  Strings. It should basically look like this:

public final class XIterations {
    public static String xReverse(String input, long iterations) {
      long iterationsRequired =  iterations% calculateCycleLength(input.length());
      char[] chars = input.toCharArray();
      for(int i = 0 ; i < iterationsRequired ; i++)
        chars = reverse(chars);
      return new String(chars);
    }
}

In your code I cannot find how you handle the skipping of the start of the string. I would do this by using a recursive call like this:

private char[] reverse(char[] chars, int startIndex){
   if(chars.length == startIndex) {
        return chars;
   } else {
      // reverse chars in array starting at startIndex
      return reverse(chars, ++startIndex);
   }
}


Class to fill model objects with data from the database

Why do you think that your version in "very bad" ?

There are of course some little improvements that you can do. Like declaring List<M> instead of ArrayList<M> as the return type. Also you can pass Class<M> cls instead of an empty instance of your model.

Another think to improve the readability of your code is to split your main method into many little methods. Like one for the mapping of a class.

Many dislike the switch and specially for a long one like that. If you want you can replace it with a Map<String, BiConsumer<Cursor, Field>> that associate a type and a consumer to set the value to a field. It is usually a wrong parctive to silently ignore an edge case. You may consider to throw an exception or at least log something instead of continuing in the default case.

Instead of testing the name of the type, you can compare the types and add the support for the wrapper types.

Finally for the exception. I am not sure that IOException is the best type, you can also use a logger instead of e.printStackTrace() because this one will pollute your output without any means to control it.

if ( Integer.class.equals(type) || Integer.TYPE.equals(type) ) {
  // ...
} else if ( .. ) {
  // ...
} else {
  throw new UnsupportedTypeException("Type "+type.getName()+" cannot be mapped.");
}


Selection sort algorithm with increasing/decreasing sort options

There are a few things I would point out as being poor go style. The two different nesting loops is where I would start:

for i := range A {
    for j := i + 1; j < len(A); j++ {

The outer loop does a index-only range on the A slice, which in itself is not a problem, but logically it is for i := 0; i < len(A); i++ {. Again, this is not really a problem, other than the fact that you are looping the indexes of the slice. The problem is that in your inner loop, you make that index-loop obvious with the full-syntax loop.

I would be tempted to use a full loop for the outer loop so that the index  functions on i and j are obvious.

The other thing I would suggest is that you supply a function for the S parameter, instead of a string.

While mentioning parameters, it is not common practice to use upper-case parameter names. These parameters are never exported, so should be lower-case initial, and mixedCase for multi-word names.

If you supply a function for the sort order, then your sort function is improved as well. Consider:

func SelectionSort(data []int, ordered func(int, int) bool) []int {
    for i := 0; i < len(data); i++ {
        for j := i + 1; j < len(data); j++ {
            if !ordered(data[i], data[j]) {
                data[i], data[j] = data[j], data[i]
            }
        }
    }
    return data
}

Now, you can call that code with something like:

increasing := func(a, b int) bool {
    return a <= b
}

decreasing := func(a, b int) bool {
    return a > b
}

data := []int{31, 41, 59, 26, 41, 58}
fmt.Println("Increasing sort array: ", SelectionSort(data, increasing))
....


Since you are executing the RMToggle function whenever a checkbox is selected, extend it a little by passing in the IDs too. (I've changed the IDs as well):

<div class="someRow" style="width: 100%">
    <asp:CheckBox ID="Open" runat="server" ClientIDMode="Static" Checked="true" onclick="RMToggle(this)" />
    <asp:CheckBox ID="New" runat="server" ClientIDMode="Static" onclick="RMToggle(this)" />
    <asp:CheckBox ID="Closed" runat="server" ClientIDMode="Static" onclick="RMToggle(this)" />
    <asp:CheckBox ID="Rejected" runat="server" ClientIDMode="Static" onclick="RMToggle(this)" />
</div>

Now, moving to the toggle function:

function RMToggle( elm ) { // elm = element
    var ischecked = elm.checked,
        $target = $('#table1 tr[data-id="' + elm.id + '"]');
    $target.toggle( ischecked );
}


Optimising an iterative function over long strings

So let's look at what the basic idea of the sequence is (if I understand correctly):

Break the sequence into contiguous blocks of identical values.
Figure out the lengths of those blocks.
Create a new sequence with the length of each block followed by the value of that block.

Step 1 seems to be the problem here.  The key issue is to me is that you are rolling your own solution when python provides something to do step 1 for you: itertools.groupby.

So consider your last number:

>>> from itertools import groupby
>>> inp = "1113122113"
>>> print([(k, list(g)) for k, g in groupby(inp)])
[('1', ['1', '1', '1']), ('3', ['3']), ('1', ['1']), ('2', ['2', '2']), ('1', ['1', '1']), ('3', ['3'])]

This gives you an iterator of tuples, where the first tuple is the value of the group and the second is the group itself.  You can use the value of the group for second element of each number pair and length of the group as the first element.  Then you just have to put them together into a new string.

So the algorithm can be reduced to:

new = ''.join(str(sum(1 for _ in g))+k for k, g in groupby(inp))

Other comments:

Your multi-run is done in the root of the script.  It would be better to give it its own function.
You are printing in the same function that generates the sequence.  This assumes you will always want to print.  Better to just return the results and let whatever calls the function determine what to do with those results.
You should put all the automatically-run code in if __name__ = '__main__': so you can use the functions elsewhere.
You should use from __future__ import print_function to make your code python3 compatible.
Use _ in place of i for loop indices you don't care about.
You can use default function arguments to make the code a bit simpler to run

So here is my complete solution:

from __future__ import print_function

def iterate(num):
    return ''.join(str(sum(1 for _ in g))+k for k, g in groupby(num))

def multiiter(n, inp='1'):
    for _ in range(n):
        print(inp, len(inp))
        inp = iterate(inp)

if __name__ == '__main__':
    multiiter(n=50, inp='1113122113')

Using a version that commented out the print took 5.53 seconds to run 50 answers.

Edit: Included Copperfield's sum suggestion.


Java is a just-in-time compiled language. As a side-effect of this, it is common for performance problems to happen when you have all the code in the main method. The reason is that Java often only compiles methods that are called very often, but the main method is only called once, so it is not compiled optimally.

This is one reason why 'function extraction' is often suggested (as well as the other benefits like readability).

So, consider a method that's called 'countDivisors':

private static long countDivisors(long value) {
    long count = 1;
    for (long i = 1; i <= value/2; i++) {
        if (value % i == 0) {
            count++;
        }
    }
    return count;
}

This code will be called often, and will thus be compiled optimally.

The main method also becomes simpler, with:

public static void main(String args[]){
    long count = 1, sum = 0, i = 0;
    do {
        i++;
        sum += i
        count = countDivisors(sum);
    } while (count < 500);
    System.out.println(i);
}

Now, whether this improves the performance enough, is uncertain, but it is more readable, and will be faster.

There's probably a smarter way to do this too, a better algorithm is normally what's required with Euler problems.


Reducing repetition of sequence-like properties

I don't have VS on my laptop, but perhaps an enum might make it a bit simpler?

(Heads up: You might need to make a few changes to get this to work)

Model

public class TabelaMemoria {
    public string Nome { get; private set; }

    int Numero { get; set; }
    MiotoolWrapper _device;

    public TabelaMemoria(MiotoolWrapper deviceWrapper, string nome, int numero)
    {
        _device = deviceWrapper;
        Nome = nome;
        Numero = numero;
    }

    public enum Position{
        A1=0,
        B1,
        A2,
        B2,
        A3,
        B3,
        A4,
        B4
    }

    public float getval(Position p){
        return _device.GetCalibrationValue((int)p);
    }
}

View.xaml

<DataGrid.Columns x:Name="grdColumns"/>

View.Xaml.cs

public View{
    public View(){
        InitializeComponent();
        InitializePositions();
    }

    private void InitializePositions(){
        foreach (Position p in Enum.GetValues(typeof(Position))) {
            DataGridTextColumn dgrid = new DataGridTextColumn();
            dgrid.Width = 100;
            dgrid.Header = p.ToString();
            dgrid.Text = (int)p;
        }
    }
}

Now if you add anymore positions, just add it to the enum and it should automatically be picked up. I know it screws up the binding, but I wasn't sure what your specific use case was.

If nothing else, perhaps this will get your gears spinning on a better solution.
Good luck, mate!


Design

It's relatively simple to create a double linked list!

Some things you should think about some more:

Please put your code into a namespace. Do you think that SinglyLinkedList is a very unique name in the global scope?
You need to look into const correctness.
You need to look into move semantics.

Major Bug.

You have not implemented the rule of three (or five). When a class contains an owned pointer the compiler generated copy constructor, copy assignment operator and destructor are not going to work correctly.

Your SinglyLinkedList contains the owned pointer: head. An owned pointer is one that you have taken responsibility for the lifespan of (and are thus going to call delete on it when it the object is destroyed.

{
     SinglyLinkedList<int>    list1;
     list1.addFirst(1);

     SinglyLinkedList<int>    list2(list1);
}
// This code is broken as you have a double delete.

Upgrade you need to do.

The standard library defines things called concepts. A concept is a set of properties that a class has. One of the big concepts of the standard is the concept of a "Container" (of which a singly linked list is). Ao you should probably make your list "Container" compliant.

Code Review

I hate useless comments.

    /** BEGIN NESTED NODE CLASS **/
    class Node {

That counts as a useless comment.

OK good start.

        Node(Node* n, const E& d) : data(d), next(n) {}   ;
                 // Not Needed                           ^^^

But it does mean that you are required to copy the object into the list. Modern C++ has the concept of move semantics. So you should allow for moving the object into the list.

        Node(Node* n, E&& d) : data(std::move(d)), next(n) {}

Also you should allow the object to be constructed in place:

        template<typename... Args>
        Node(Node* n, Args&&... args)
            : data(std::forward<Args>(args)...)
            , next(n)
        {}

Here you get a reference to the object.
That's fine.

        E& getData() { return data; }

But what happens if your list has been passed by const reference to a function. Now you can no longer accesses the data as you can't get a const reference to the data.

        E const& getData() const {return data;}

Its a bit strange that you only return reference from the node. But you return only const references from the list?

    const E& first() const;
    const E& last() const;

I actually hate your get/set mentatility here. I see no need for it inside the node object itself.

        void setNext(Node* n) { next = n; }

That's fine.

    void print() const;

But two things to note.

There is more streams than the std::cout so allow this to be pramertized.
The normal way of streaming is via the output operator: operator<<()

void print(std::ostream& stream = std::cout);
friend std::ostream& operator<<(std::ostream& str, SinglyLinkedList const& data)
{
    data.print(str);
    return str;
}


Yes, the comments are too much. You don't need to explain why you're doing it all; you might not always be using this function for its current purpose. And I wouldn't put general explanatory comments like that inline; put them in the function docstring.

Also, it's not at all Pythonic to do something like:

[datetimes.append(today + timedelta(days=i)) for i in [0, -1, 1, 2]]

filling a list with None then discarding it; either use a list comprehension:

datetimes = [today + timedelta(days=i) for i in [0, -1, 1, 2]]

or append:

 for i in [0, -1, 1, 2]:
     datetimes.append(today + timedelta(days=i))

I would also encapsulate more of the variables in default parameters, to make the function more flexible:

from datetime import datetime, timedelta

def adjacent_dates(date, deltas=[0, -1, 1, 2], format="%Y%m%d"):
    """Generate date strings adjacent to the argument date.

    Note:
      The default order of deltas is to ensure that the most
      likely date is first in the output.

    Args:
      date (str): The date to process.
      deltas (iter of int): The offsets to apply, in days, to the input
        date (defaults to [0, -1, 1, 2]).
      format (str, optional): The format to use for input and output
        (defaults to "%Y%m%d").

    """
    start = datetime.strptime(date, format)
    days = [start + timedelta(days=i) for i in deltas]
    return [d.strftime(format) for d in days]

Now you can use your defaults:

>>> adjacent_dates("20141030")
['20141030', '20141029', '20141031', '20141101']

or easily switch to something else:

>>> adjacent_dates("30-10-2014", range(-2, 3), "%d-%m-%Y")
['28-10-2014', '29-10-2014', '30-10-2014', '31-10-2014', '01-11-2014']

Note that strftime is a datetime instance method, so you can call it on the instances rather than the class - d.strftime(format) is neater than datetime.strftime(d, format).


Get mod date to attach a version number to JS src script

API

The documentation says the function returns a string, yet the last line of the implementation says otherwise...

/**
 * ...
 *
 * @return string
 */
function js($path){
    ...
    return false;
}

Replace a loop with array_map

Instead of this:

$return = '';
foreach($path as $value){
    $return .= js($value);
}
return $return;

You can write a bit simpler using array_map and join:

if (is_array($path)) {
    return join('', array_map('js', $path));
}

Getting the first character from a string

Instead of substr($path, 0, 1), when you know that $path is not empty (as in the posted code), a more natural way is to use indexing: $path[0].

Don't repeat yourself

dechex(filemtime(...)) is common in the two branches of this conditional:

if (substr($path, 0, 1) <> '/') {
    $version = dechex(filemtime(getcwd().'/'.$path));
} else {
    $version = dechex(filemtime(__DIR__.$path));
}

Extract the common part:

if ($path[0] <> '/') {
    $dir = getcwd().'/';
} else {
    $dir = __DIR__;
}

Use early returns

Instead of this kind of code:

if (cond1) {
    if (cond2) {
        // ...
        return X;
    } else {
        // ...
        return Y;
    }
}
return Z;

You can use "early returns" to reduce the nesting,
and thereby making the code slightly easier to read:

if (!cond1) {
    return Z;
}

if (cond2) {
    // ...
    return X;
}

return Y;

Alternative implementation

Putting the above tips together:

function js($path) {
    if (empty($path)) {
        return '';
    }

    if (is_array($path)) {
        return join('', array_map('js', $path));
    }

    $dir = $path[0] <> '/' ? getcwd().'/' : __DIR__;
    $version = dechex(filemtime($dir.$path));
    return "<script src='$path?v=$version'></script>\r\n";
}


Drawing a castle and towers with acm.graphics

here are my comments:

1) instead of having a create method for objects, why not have classes that you can instantiate? seems more clear to me

public class Tower extends GRect {
  final double width = 150;
  final double height = 600;
  public Tower() {
    super(width, height);
  }
}

2) instead of creating a GRect and then moving it, you can specify the location when you add it: add(new Tower(), 700, 250); this shows more clearly the intention of placing the tower at a certain location


Three very similar functions operating on XML files

One of the possible ways to improve on following the DRY principle would be to extract the XML tree iteration part which is the same in all 3 functions. Something like this generator:

def values(tree):
    root = tree.getroot()
    for child in root.iter('data'):
        if child.attrib.get('namespace') == 'preserve':
            node = child[0]
            if node.tag == "value" and node.text is not None:
                yield node

Then, you can use it this way:

tree = ET.parse(caminho)
for node in values(tree):
    # do something with node


Shared counter variable among different threads

If I would get this code at my job, I would reject it. There is NO valid reason for using the pthread library directly to manage threads. Please use std::thread instead. Normally, I wouldn't even do the effort to read further. The same holds for the mutex, just use std::mutex, std::shared_mutex ... instead.

I see your usage of shared_integer, which raises a few questions:
 - Isn't this std::atomic<int>, less performant? (Yes, I know you don't want to get into it, though, I would still recommend looking into it if you don't expose the mutex)
 - Secondly, your implementation is flawed, as operator-- and display() don't use the lock
 - Thirdly, I would urge you to make this a template. It's easy to make mistakes into this, you only want to have that kind of code once.

Looking at your main-function, it looks like you have a memory leak.

The same code using the C++ standard library:

#include <thread>
#include <iostream>
#include <chrono>
#include <atomic>

int main(int argc , char ** argv)
{
    std::atomic<int> workdonecount{0};

    auto workdone = [&workdonecount]()
    {
        for (int i = 0; i < 10; i++) {
            std::cout<<"thread "<<std::this_thread::get_id()<<std::endl;
            //Currently testing with only work done
            workdonecount++;
            std::cout << "Value became:" << workdonecount << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds{1});
            }
        std::cout<<"thread done "<<std::this_thread::get_id()<<std::endl;
    };

    std::cout<<"main After creating threads"<<std::endl;
    auto thread1 = std::thread(workdone);
    auto thread2 = std::thread(workdone);
    auto thread3 = std::thread(workdone);
    auto thread4 = std::thread(workdone);
    std::cout<<"main Before joining first therad"<<std::endl;
    std::cout<<"main Before joining second therad"<<std::endl;
    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();

    std::cout<<"main done"<<std::endl;
return 0;

}

Code at compiler explorer using c++17

From C++20, you could even use std::jthread and let the threads join automatically.

PS: This code contains the same bug that you have:

 workdonecount++;
 std::cout << "Value became:" << workdonecount << std::endl;

Should become:

 auto newValue = ++workdonecount;
 std::cout << "Value became: " << newValue << std::endl;


The easiest way to create Stack that I found was this:

class Stack:
    def __init__(self):
        self.stack = []
    def push(self,data):
        self.stack.append(data)
    def pop(self):
        if self.isEmpty():
            raise Exception("nothing to pop")
        return self.stack.pop(len(self.stack)-1)
    def peek(self):
        if self.isEmpty():
            raise Exception("Nothing to peek")
        return self.stack[len(self.stack)-1]
    def __sizeOf__(self):
        return len(self.stack)
    def isEmpty(self):
        return len(self.stack) == 0
    def __str__(self):
        for x in self.stack.reverse(): #Reverse list, so when printing last pushed value is first and the oldest is printed last.
            print(x)

What it does is when creating Stack Variable:

it makes new list called stack.
When you push something to Stack, it is added at the end of list.
When you pop something from Stack, it is taken away form list (method pop() will not only return value from list, but also delete it)
When you peek something from Stack, it returns last value on list without deleting it.
When you want to check size of stack, it measures list size.
When you want to use __str__ you print all variables from list.

I have reversed the list using
for x in stack:. This was done because otherwise x would be equivalent to stack[0] in first run, stack[1] in second etc. However we must not forget that stack[0] is the oldest value placed in stack, and the newest is the value with the highest index in list. Reversing the list allows to print from the newest value to the oldest.

A little bit more of explanation:

self.stack.pop(len(self.stack)-1) - This code will pop last value from list. It contains -1 because length of stack is started from 1 while indexing is started from 0. Function len() returns (in this case) length of list
if self.isEmpty(): raise Exception("Nothing to peek") - This code will run its function isEmpty() from its own class, which returns Boolean value (which is perfect for our if statement).
self.stack[len(self.stack)-1] while using list you will use list name (in this case stack) and then index you want to access, e.g. stack[1] (will return second value in list, dont forget about 0-indexing).


Minimum Steps to One to find minimum operations to transform n to 1

Overall this looks very good. It's even fits nicely with PEP 8 guidelines.

I would suggest preallocating your array, with something like work = [0] * (n + 1) to help slightly with speed and memory use. append is slightly wasteful in that regard because it keeps resizing the array and copying its contents elsewhere.

In terms of naming, i could perhaps helpfully be renamed something like candidate and work could do with being renamed too. Nothing is that unclear though.

It's good to see tests along with the code, and particularly good to see 1 tested. However, it's better to prefer standard testing libraries such as unittest to writing your own test routines. It's particularly hard to read code that redefines functions as you go, so if you must roll your own I'd strongly suggest redoing expect to take the input and expected output rather than some freshly defined test function. (But really, use a library!)

Finally, a comment on the underlying algorithm. The bottom up algorithm here is simple, thorough, and correct which are all good things. However, it is potentially wasteful because it has to check every number up to the target.

Consider that every number is either even or is 1 away from being even. Therefore you can always either divide or divide next time. That means that, even without the rule about 3s, you should expect the solution to take at worst \$ 2 log_2(n) \$ steps. That in turn indicates that at almost all of the second half of your work list for large numbers is guaranteed to be unused: you can't divide to it (because you can't divide by less than 2) and it's not worth stepping to it 1 element at a time because that would quickly overshoot the logarithmic lower bound. (Experimentally, if you check the value for say 10,000,000 then over 70% of entries in your cache have paths at least as long as your target path and so are useless to you.)

Therefore, consider instead using a top-down dynamic programming approach instead of a bottom up one to avoid storing results that you are never going to use. (Essentially, this works out as a breadth first search.)


SASS + Compass - File Structure and @Import order

Your way works, but it is not very scalable, since you have to compile all the sass files every time you make a change, this is time consuming when the project gets bigger.

here you watch all the files via grunt/gulp, but only compile the _watchables, the _procompiled file is compiled upon start of server only, not during file watch.

when building for production, use build.scss to build the final css file, the build contains the watchables and precompiled files.

the _globals file will contain global configurations, styleguide variables, and functions/mixins. the global file does not have css in it, only utilities and functions, and is imported in both watchables and precompiled files.

Structure

.style
├── build.scss
├── _globals.scss
├── _watchables.scss
├── _precompiled.scss
├── vendors
|   ├── index.scss
|   └── _bootstrap.scss
├── helpers
|   ├── index.scss
|   └── _variables.scss

build.scss

@include '_globals.scss';
@include '_precompiled.scss';
@include '_watchables.scss';

_precompiled.scss

//contains vendor files and other unchanged scss files.
@include '_globals.scss';
@include 'vendor/_index.scss';

_watchables.scss

//contains the files you want to build everytime you save
@include '_globals.scss';
@include 'pages/homepage.scss';

any index.scss file

//include everything in the folder.
@include '_bootstrap.scss';

I developed this way while working on a big project with my company, the build time got reduced from 8ms per file save to less than a second. i was compiling only the pages folder in my watchables.scss file, since the rest of the files are almost always stable, but sometimes i include a component in my watchables to develop the component then put it back to the precompiled file.


all I wanted was a circular buffer

Consider using an array accessed with mod.
That is, assign size s = k.length - 1,
allocate a "previous" array p,
and then access p[i % s].
If you're lucky, the compiler may notice that
a portion of the code is just copying,
and it will issue memcpy instructions.


Yes! Introduce a keyCode variable to hold the one difference between the two otherwise identical code blocks.

var keyCode = isNodeWebkit ? 113 : 112;
$(document).keyup(function (e) {
    if (e.which == keyCode) {
        $.ajax({
            type: "POST",
            url: "/submit/role/",
            data: {},
            dataType: "json",
            success: function (admin) {
                if (admin == true) {
                    window.location = urllink;
                }
            }
        });
    };
});

Edit: Reverted equality tests since I don't know what you expect to appear in admin, and heck, perhaps some browsers convert the key code to a string!


Using one less variable seems faster:
cdef int fib_c(int n):
    if n == 0:
        return 0
    cdef int a = 0
    cdef int b = 1
    for _ in range(n - 1):
        a, b = b, a + b
    return b

Running your test on my machine:
Original = 2.934 s
Improved = 1.522 s


Parsing version number from a Java source file

Since you are only looking for a single occurrence of the variable in the file you could  match the whole file at once. For example like this:

version = {->
    def text = file('src/main/org/h2/engine/Constants.java').text
    def extract = {name ->
        nameValue = text.replaceAll(/(?s)^.*public\s+static\s+final\s+int\s+$name\s+=\s*(\d+);.*$/, '$1')
        text.length() == nameValue.length() ? "Cannot find name" : nameValue;
    }
    extract('VERSION_MAJOR') + '.' + extract('VERSION_MINOR') + '.' + extract('BUILD_ID')
}()

Instead of getting the lines this script reads the file to one single String, and then uses a regular expression to replace the while text with the variable of interest.

In order to do this, we first make sure that the . in the regexp will match newlines by adding (?s) to the pattern. We then match everything from the start (^.*) up until public static final int $name, capture the value with (\d+), and then match everything to the end of the file with .*$.

Although the regular expression is slightly more involved, this way makes it easier to check whether the replacement has worked and prevents a NullPointerException. We can now simply compare the length of the original text with the length of the result. If they are the same the replacement has not succeeded and we can return a custom error-message, otherwise we found the variable of interest.


Type names in Swift use UpperCamelCase (compare API Design Guidelines), so it should
be class CodeGen.

I do not see any reason why the class must inherit from NSObject.
Actually the methods do not use any state. If the sole purpose of
the class declaration is to provide a namespace (and to avoid free
global function) then you use an enum with type methods instead:

enum CodeGen {

     static func generate(length: Int) -> String { ... }

}

so that you can call them as

let password = CodeGen.generate(length: 16)

instead of creating an instance:

let password = CodeGen().generate(length: 16)

The advantage of usage an enum over a struct is that you can not
(inadvertently)  create an instance of the type
(compare https://github.com/raywenderlich/swift-style-guide#constants,
or Swift constants: Struct or Enum).

The explicit type annotations in

private let base: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// ...

are not necessary, that can be simplified to

private let base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// ...

You have two functions implemented independently:

func generate(length: Int) -> String

func generate(length: Int, lowers: Bool, numbers: Bool, specials: Bool) -> String

but actually the first function is a special case of the second.
Therefore the first method can simply forward to the second:

func generate(length: Int) -> String {
    return generate(length: length, lowers: true, numbers: false, specials: false)
}

Alternatively, implement only a single method with default
parameter values:

func generate(length: Int, lowers: Bool = true, numbers: Bool = false, specials: Bool = false) -> String

Testing a boolean value if (lowers == true) can always be
simplified to if (lowers), and the parentheses are not needed:

if lowers {
    letters += lowerChars
}

The type annotation in

let NSletters : NSString = letters as NSString

is again unnecessary, and variable names should start with a lowercase
letter. But the bridging to NSString can be avoided completely by creating a Swift Array of Character:

let characters = Array(letters.characters)
let numChars = UInt32(characters.count)
var result = ""
for _ in 0 ..< length {
    let rand = Int(arc4random_uniform(numChars))
    let nextChar = characters[rand]
    result.append(nextChar)
}

which can be simplified to

let characters = Array(letters.characters)
let numChars = UInt32(characters.count)
let result = String((0..<length).map { _ in
    characters[Int(arc4random_uniform(numChars))]
})

The argument names can be improved, perhaps useLowercase or
withLowercase instead of lowers etc.

Putting it all together the code would look like this:

enum CodeGen {

    private static let base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    private static let lowerChars = "abcdefghijklmnopqrstuvwxyz"
    private static let numberChars = "1234567890"
    private static let specialChars = "!@#$%^&*"

    static func generatePassword(length: Int, useLowercase: Bool = true,
                                 useNumbers: Bool = false,
                                 useSpecialChars: Bool = false) -> String {
        var letters = base
        if useLowercase {
            letters += lowerChars
        }
        if useNumbers {
            letters += numberChars
        }
        if useSpecialChars {
            letters += specialChars
        }

        let characters = Array(letters.characters)
        let numChars = UInt32(characters.count)
        let result = String((0..<length).map { _ in
            characters[Int(arc4random_uniform(numChars))]
        })

        return result
    }

}

The static variables can also be moved into the method unless
you need to share them with other methods of the CodeGen type.