First: Please format your code more consistently.

The indention of the whileloop is very unusual. Better (and more common):

public static String getBinary(int given) {
    char binNumbers[] = {'0','1'};
    String str = "";
    int rem;
    while (given > 0) {
        rem = given % 2;
        str = binNumbers[rem] + str;
        given /= 2;
    }
    return str;
}

Next: Please use the default cases for identifiers. Classes should start upper case (Convert instead of convert).

Also use StringBuilder instead of String-concatenation:

public static String getBinary(int given) {
    char binNumbers[] = {'0','1'};
    StringBuilder sb = new StringBuilder();
    int rem;
    while (given > 0) {
        rem = given % 2;
        sb.append(binNumbers[rem]);
        given /= 2;
    }
    return sb.toString();
}

Ths will be a large performace gain. Your code basically translates to:

public static String getBinary(int given) {
    char binNumbers[] = {'0','1'};
    String str = "";
    int rem;
    while (given > 0) {
        rem = given % 2;
        //str = binNumbers[rem] + str;
        // Code generated by compiler for the above line of code
        StringBuffer sb = new StringBuffer();
        sb.append(binNumbers[rem]);
        sb.append(str);
        str = sb.toString();
        // End of generated code
        given /= 2;
    }
    return str;
}

As you can see the code generated many objects which have to be cleaned up afterwards by the Garbage Collector.

Hint:

You can use Integer.toString(given, 2) instead of your Convert.getBinary(given) for the same result.


In the tests (and anywhere else), you should use constants to ensure correct spelling of the properties :

const PERSON_NAME = 'name';
const PERSON_SURNAME = 'surname';
...
$expectedProperties = array(self::PERSON_NAME,self::PERSON_SURNAME);

Then the Filtering and Serialization tests are very similar while they should be atomic (one test tests one thing) : you should not test Filtering whike testing Serialization.

In the production code there is one error : you set the desired property (i.e. $this->name) while you get the internal array's key ($this->properties['name']). To keep the simplicity of defining an object as a class with public properties you should drop the internal array. This will also make the __sleep and __wakeup calls much clearer.

Also a design flaw is to use the Reflection : it seems unavoidable but depending on your usage there might be performance issues. Using a caching system such as a static array will help. In particular if you look at the __wakeup and __sleep function you will notice a repeted call to the getPropertyNames method.

Finally what might be problematic is that you don't check if the property exists when setting or getting. If it does not you should throw an exception. There are magic methods in PHP5.3 (__get, __set and __call) ; you may do better using them. This way you will be able to use $personName = $person->getName() / $person->setName('Simone') as well as $personName = $person->name / $person->name = 'Simone'

Tests :

const PERSON_NAME = 'name';
const PERSON_SURNAME = 'surname';

public function testProvideDtoPropertyNames()
{
    $propertyNames = Person::getPropertyNames();

    $expectedProperties = array(
        self::PERSON_NAME,
        self::PERSON_SURNAME,
    );

    $this->assertEquals(
        $expectedProperties,
        $propertyNames
    );
}
public function testProvidePropertyViaGeneralGetter()
{
    $dto = Person::createFromArray(array(
        self::PERSON_NAME => 'Simone',
    ));

    $this->assertEquals(
        'Simone',
        $dto->getName()
    );
}
public function testDTOAcceptOnlyItsOwnProperties()
{
    $dto = Person::createFromArray(array(
        self::PERSON_NAME => 'Simone',
        'non existent property' => 'Simone',
    ));

    $expectedProperties = array(
        self::PERSON_NAME => 'Simone',
        self::PERSON_SURNAME => null,
    );

    $this->assertEquals(
        $expectedProperties,
        $dto->asArray()
    );
}
public function testSerializationKeepSameProperties()
{
    $properties = array(
        self::PERSON_NAME => 'Simone',
        self::PERSON_SURNAME => null,
    );

    $dto = Person::createFromArray($properties);

    $serialized = serialize($dto);
    $unserialized = unserialize($serialized);

    $this->assertEquals(
        $dto->asArray(),
        $unserialized->asArray()
    );

    $this->assertEquals(
        $properties,
        $unserialized->asArray()
    );
}

Production code :

class DtoException extends Exception
{
}
abstract class Dto
{
    private static $propertyNamesByClass = array();

    private function __construct(array $properties)
    {
        foreach($properties as $propertyName=>$propertyValue)
            if(Static::hasPropertyName($propertyName))
                $this->set($propertyName,$propertyValue);
    }
    public function __call($method, array $arguments)
    {
        $getOrSet = substr($method, 0, 3);
        if($getOrSet != 'get' && $getOrSet != 'set')
            throw new DtoException('"'.get_class($this).'" has no method "'.$method.'"');

        $propertyName = strtolower(substr($method, 3));
        if(!Static::hasPropertyName($propertyName))
            throw new DtoException('"'.get_class($this).'" has no property "'.$propertyName.'"');

        $getOrSetMethod = array($this,$getOrSet);
        array_unshift($arguments,$propertyName);
        return call_user_func_array($getOrSetMethod, $arguments);
    }
    public function __get($propertyName)
    {
        if(!Static::hasPropertyName($propertyName))
            throw new DtoException('"'.get_class($this).'" has no property "'.$propertyName.'"');

        return $this->get($propertyName);
    }
    public function __set($propertyName, $propertyValue)
    {
        if(!Static::hasPropertyName($propertyName))
            throw new DtoException('"'.get_class($this).'" has no property "'.$propertyName.'"');

        return $this->set($propertyName, $propertyValue);
    }

    public static function createFromArray($properties)
    {
        return new Static($properties);
    }

    public function set($propertyName, $propertyValue)
    {
        $this->$propertyName = $propertyValue;
    }

    public function get($propertyName)
    {
        return $this->$propertyName;
    }

    public static function getPropertyNames()
    {
        $className = get_called_class();
        if(isset(self::$propertyNamesByClass[$className]))
            return self::$propertyNamesByClass[$className];

        $reflected = new ReflectionClass($className);
        $reflectedProperties = $reflected->getProperties(
            ReflectionProperty::IS_PUBLIC
        );

        $propertyNames = array();
        foreach($reflectedProperties as $reflectedProperty) {
            $propertyNames[] = $reflectedProperty->getName();
        }

        self::$propertyNamesByClass[$className] = $propertyNames;
        return $propertyNames;
    }
    public static function hasPropertyName($propertyName)
    {
        $propertyNames = Static::getPropertyNames();
        return in_array($propertyName,$propertyNames);
    }

    public function asArray()
    {
        $values = array();

        foreach (Static::getPropertyNames() as $propertyName) {
            $values[$propertyName] = $this->get($propertyName);
        }

        return $values;
    }

    public function __sleep()
    {
        $propertyNames = self::getPropertyNames();

        foreach ($propertyNames as $propertyName) {
            $propertyValue = $this->get($propertyName);
            $this->set($propertyName, $propertyValue);
        }

        return $propertyNames;
    }

    public function __wakeup()
    {
        $propertyNames = self::getPropertyNames();

        return $propertyNames;
    }
}

I tested it on PHP5.3 and it works, however I have to tell you that it does not work on PHP5.2- or PHP7+.


Find max-number div by three to be formed by array elements

For example, if the input array is {8, 1, 9}, the output should be “9 8 1″

So, let's say that the input array is { 4, 8, 15, 16, 23, 42 }, what should the output be then? At first I expected it to be "4 8 15 16 23 42", but then @Marc-Andre made me realize that in fact, that's not the case. I misunderstood the question at first.

Although not explicitly written, all the numbers in the array are required to be less than 10. I strongly suggest you add a check in your loop: (which btw can be written as for-each instead, which also applies to your last loop for looping through the list)

for (int i : a) {
    sum = sum  + i;

    if (i >= 10) {
        throw new IllegalArgumentException("All numbers must be less than 10.");
    }

    int remainder = a % 3;
    ...
}

I have to say though that the example you give is a bit weird, as your example output is a string separated by space. The question though is about what number can be formed, which don't speak anything about string at all.

In addition to this, you also suffer from a case of severe code-duplication. This can be treated easily with the medicine of extracting method. This extracted method also deserves a little simplification as I really don't like that you're doing isEmpty-remove-isEmpty-remove, why not just check if size > 2 in the first place? (Alright, size can be a costly operation compared to isEmpty for some queue implementations, but LinkedList is not one of those - at least not anymore).

private static boolean removeOneOrTwo(Queue<?> removeOneFrom, Queue<?> removeTwoFrom) {
    if (!removeOneFrom.isEmpty()) {
        removeOneFrom.remove();
    } else if (removeTwoFrom.size() < 2) {
        return false;
    } else {
        removeTwoFrom.remove();
        removeTwoFrom.remove();
    }
    return true;
}

Note that here I actually use Queue<?>, more or less just for the fun of it but mostly for the reason that for this method, it doesn't need to know what kind of Queue we're dealing with. It only needs to be able to know the size of it and remove items.

By doing this simple method extraction, we've reduced your original method a bit:

if (sum % 3 == 1) {
    if (!removeOneOrTwo(queue1, queue2)) {
        return -1;
    }
} else if (sum % 3 == 2) {
    if (!removeOneOrTwo(queue2, queue1)) {
        return -1;
    }
}

Although now that I'm dealing with that code anyway, I have to add: return -1; smells. -1 is a special return value for "no possible combination found". In this case I would find 0 a better choice of return value for that, as that would correspond to an empty array (and is a multiple of 3). Either that, or throw an exception. In this case, I would find returning zero perfectly reasonable.


Printing removed items using lambdas and streams

Your "fluid" example is fine, well structured, the newlines are consistent, and is in line with code styles that I have seen and like. It is perhaps a bit too soon to say it follows "best practice", but it does look right.

// #2 fluid lambdas
existing.stream()
    .filter(item -> !updated.contains(item))
    .forEach(item -> System.out.println("item " + item + " removed"));

The "middle-ground" approach you have is immediately "identical" to the fluid approach, but in this context is less readable, even if functionally identical. It does have advantages when your function is, for example, a method parameter, or an injected constant (like a custom comparator, or something). Since the code is all localized to a single method, though, the need to separate the declaration and use of the function is simply not there.

My only concern with your fluid approach, and it is a small one, is that you reuse the item placeholder in two contexts. While it is logical, in this case, to use item, I find it is typically better to have unique variable names at each stage in the pipeline, perhaps:

// #2 fluid lambdas
existing.stream()
    .filter(item -> !updated.contains(item))
    .forEach(removed -> System.out.println("item " + removed + " removed"));

Additionally, using printf helps too:

    .forEach(removed -> System.out.printf("item %s removed\n", removed));

One lase comment, I have found that the more I use Java 8 features the easier it gets to establish the right mindset when reading the code. You may just find that it grows on you, and your statement "I find the lambda approaches more difficult to read than the simple for-loop" is no longer true. Also, consider this:

// #2 fluid lambdas
existing.stream()
    .parallel()
    .filter(item -> !updated.contains(item))
    .forEach(removed -> System.out.printf("item %s removed\n", removed));

and consider doing that in "the simple for loop".


Is this the best approch to combine 2 Interfaces?

You don't necessarily need to have another interface that extends the two you want to combine, you just have to say that he class implements both of them.  One java class can implement as many interfaces as you desire.

Problems may arise if you have any shared data problems, but by saying you are implementing the interface you are guaranteeing that the class has the specified functions.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyClass{

    public interface Combined extends Runnable, Callable<Object> {}

public class Mixed implements Runnable, Callable<Object> {

    @Override
    public Mixed call() throws Exception {
        System.out.println("Called Mixed");
        return this;
    }

    @Override
    public void run() {
        System.out.println("Ran Mixed");
    }

}

public class Single implements Combined{
    @Override
    public Single call() throws Exception {
        System.out.println("Called Single");
        return this;
    }

    @Override
    public void run() {
        System.out.println("Ran Single");
    }
}

/**
 * @param args
 */
public static void main(String[] args) {
    MyClass top = new MyClass();
    Mixed mixed = top.new Mixed();
    Single single = top.new Single();
    ExecutorService es = Executors.newFixedThreadPool(1);

    es.execute(mixed);
    es.execute(single);

    es.submit((Callable<Object>) mixed);
    es.submit((Callable<Object>) single);

}

}

Output is:

Ran Mixed
Ran Single
Called Mixed
Called Single


It's a fine script, but you have a bug: executing cd ./archive in a loop.
Perhaps you did not notice it because you tested with only a single matching file. If there are multiple matching files, then cd ./archive will not work, unless you have multiple nested archive/archive/archive/... directories, which would be silly.

One solution is to wrap the cd command and the rest of the loop body in a (...) subshell:

if [[ "$f" < "/var/mail/catchall-$fortnight.gz" ]] ; then
    mv "$f" ./archive
    echo "$f"
    echo "$(basename $f)"
    (
        cd ./archive
        if s3cmd sync "$(basename $f)" s3://vpcgwmail ; then
            echo "S3 sync successful, removing file"
            rm "$(basename $f)"
        else
            echo "s3 sync not succesful"
        fi
    )
fi

Another solution is to not cd ./archive at all:

if [[ "$f" < "/var/mail/catchall-$fortnight.gz" ]] ; then
    mv "$f" ./archive
    echo "$f"
    echo "$(basename $f)"
    if s3cmd sync ./archive/"$(basename $f)" s3://vpcgwmail ; then
        echo "S3 sync successful, removing file"
        rm ./archive/"$(basename $f)"
    else
        echo "s3 sync not succesful"
    fi
fi

Whichever alternative is fine.

The indentation was also a bit off, from about the middle of the for-loop body.


Given an array A[] and a number x, check for pair in A[] with sum as x

Your algorithm isn't the most efficient out there.

As you process the input, you can keep track of the numbers you have already seen and which numbers would complement those to sum to x. For instance, in your example, x=4: You read 1, you know that if you encounter a x - 1 = 3, you have found a pair. Next you read a 2, you know that if you encounter a x - 2 = 2, you have found a pair. Then you encounter a 3, which we knew we needed earlier. We can return true.

In code:

public static bool AnyPairSumAlternative(this IEnumerable<int> source, int sum) {
  var complements = new HashSet<int>();
  foreach(var item in source) {
    if (complements.Contains(item)) {
      return true;
    }
    try {
      checked {
        complements.Add(sum - item);
      }
    } catch (OverflowException) {
      // If sum - item overflows, that means that no two ints together can sum to sum.
      // We swallow the exception and don't add anything to complements, since the complement
      // clearly doesn't exist within the data type.
    }
  }
  return false;
}

This approach skips out of the sorting, and loops through the input list only once. Checking for inclusion in the Hashset is \$O(1)\$, so if I'm not mistaken, this takes the solution from \$O(n\log n)\$ to \$O(n)\$.

As comment by @slepic points out, we need to be careful that sum - item doesn't overflow. If that happens, that automatically means that the complement cannot appear in the array, since it wouldn't fit in our datatype. To account for this, we can do the subtraction in checked context and catch any OverflowException.


VBA performance with Early Bind vs. Late Bind on called Sub-procedure

Kudos for Option Explicit and explicitly making the procedures Public - I suppose the ContinueMatchArray procedure looks something like this?

Private Sub ContinueMatchArray(ByVal arrayMatchDictionary As Object)
    'do something
End Sub

This arrayMatchDictionary As Object parameter is nice - you have a dependency and you're putting its creation in its own method, and the dependency can be a Dictionary obtained with New Dictionary or CreateObject, it makes no difference... because as far as VBA is concerned, this arrayMatchDictionary is late-bound, regardless of whether it was MatchArrayMatchEarlyBind that created the object.

Calling members of an Object type means the runtime is going to have to query the IDispatch interface of the object to discover the handle to the member being called.

By declaring the parameter As Object, you're actually downcasting to the simplest COM interface that is known to VBA - as long as the object is in scope,  to the face of the world that procedure its underlying type is unknown.

The VBA type casting mechanism involves Setting a reference to another pointer type:

Dim foo As Object
Set foo = New Scripting.Dictionary

Here foo is a Dictionary, but even if the reference assignment was early bound, every single member call to foo will be late-bound - you're asking the underlying COM engine to query the object's interface, and because we're looking at an Object, that interface is IDispatch; the query locates a function pointer in the object's vtable, or blows up if it can't find it.

The performance penalty with late binding isn't only with the original reference assignment: every single member call incurs a hit.

An early-bound member call is easy: the runtime doesn't need to query IDispatch, it has the actual object's interface handy, so the whole "lookup the function pointer" part is skipped, because the function pointer's location is already known.

ContinueMatchArray works late-bound in both cases.

Compilation

Your code runs, but doesn't compile: it relies on the interpreted nature of the language - if no scope in the execution path encounters an early-bound Dictionary, the code can run. But if you go Debug > Compile VBAProject, your project fails to compile:

Code that runs but doesn't compile isn't... ideal.

Explicit Call Syntax

Visual Basic for Applications (VBA) didn't just appear; it evolved from older languages: this is a fizzbuzz program written in Commodore-64 BASIC 2.0, which didn't even have a Mod operator:

10 GOSUB 100
20 GOSUB 1000
99 END
100 REM CLEAR SCREEN
110 PRINT CHR$(147)
120 RETURN
200 REM MODULO
210 LET MOD% = V%-INT(V%/FB%)*FB%
220 RETURN
1000 REM INIT VARIABLES
1010 LET FIZZ$ = "FIZZ"
1011 LET BUZZ$ = "BUZZ"
1020 LET FIZZ% = 3
1021 LET BUZZ% = 5
1030 LET MIN% = 1
1031 LET MAX% = 15
1100 PRINT FIZZ$ + ":" + STR$(FIZZ%)
1101 PRINT BUZZ$ + ":" + STR(BUZZ%)
1102 PRINT FIZZ$ + BUZZ$ + ":" + STR$(FIZZ%*BUZZ%)
1105 PRINT
2000 REM ACTUAL FIZZBUZZ LOOP
2010 FOR X = MIN% TO MAX%
2015 LET RESULT$ = STR$(X)
2020 LET FB% = FIZZ%*BUZZ%
2021 LET V% = X
2024 GOSUB 200
2025 IF MOD%=0 THEN LET RESULT$=FIZZ$+BUZZ$ : GOTO 2050
2030 LET FB% = FIZZ%
2031 GOSUB 200
2035 IF MOD%=0 THEN LET RESULT$=FIZZ$ : GOTO 2050
2040 LET FB% = BUZZ%
2041 GOSUB 200
2045 IF MOD%=0 THEN LET RESULT$=BUZZ$ : GOTO 2050
2050 PRINT RESULT$
2090 NEXT X
2099 RETURN

With pretty slight modifications, the BASIC 2.0 code above can be executed by the VBA runtime:

Sub Main()
10     GoSub 100
20     GoSub 1000
99     End
100     Rem CLEAR SCREEN
110     Debug.Print Chr$(147)
120     Return
200     Rem MODULO
210     Let Modulo% = V% - Int(V% / FB%) * FB%
220     Return
1000     Rem INIT VARIABLES
1010     Let FIZZ$ = "FIZZ"
1011     Let BUZZ$ = "BUZZ"
1020     Let FZZ% = 3
1021     Let BZZ% = 5
1030     Let Min% = 1
1031     Let Max% = 15
1100     Debug.Print FIZZ$ + ":" + Str$(FZZ%)
1101     Debug.Print BUZZ$ + ":" + Str(BZZ%)
1102     Debug.Print FIZZ$ + BUZZ$ + ":" + Str$(FZZ% * BZZ%)
1105     Debug.Print
2000     Rem ACTUAL FIZZBUZZ LOOP
2010     For X = Min% To Max%
2015     Let RESULT$ = Str$(X)
2020     Let FB% = FZZ% * BZZ%
2021     Let V% = X
2024     GoSub 200
2025     If Modulo% = 0 Then Let RESULT$ = FIZZ$ + BUZZ$: GoTo 2050
2030     Let FB% = FZZ%
2031     GoSub 200
2035     If Modulo% = 0 Then Let RESULT$ = FIZZ$: GoTo 2050
2040     Let FB% = BZZ%
2041     GoSub 200
2045     If Modulo% = 0 Then Let RESULT$ = BUZZ$: GoTo 2050
2050     Debug.Print RESULT$
2090     Next X
2099     Return
End Sub

So BASIC went from  to structured programming, where "structure" started meaning procedures instead of line number ranges, and eventually modules too - and then the Call keyword showed up. BASIC eventually became Visual; comments were denoted by a single quote instead of a REM statement, and the explicit call syntax was abandoned, along with the explicit value assignment syntax: the Call and the Let keywords were deprecated. Oh you can still use them and they still work... just like the above fizzbuzz program still works. It's just that, the modern language has more elegant ways to do things.

Instead of this:

Call ContinueMatchArray(arrayMatchDictionary)

You can simply have this:

ContinueMatchArray arrayMatchDictionary

Don't write dino-basic, use the implicit call syntax.

Early-bind?

If you're going to be working against an Object, don't bother with early-binding: remove the reference and delete the early-bound method - at least your code will be compilable and so a compile error becomes meaningful.

On the other hand, why late-bind the Microsoft Scripting Runtime library? It's on every Windows machine, and hasn't changed this century, and is somewhat more likely to not ship at all with a new version of Windows than to be issued a new version anytime soon: if you add the project reference, it will work on every Windows user that uses it.

  some users might not be willing to manually add the reference to use it and just consider the macro to be 'broken'.

That makes no sense - if you save the VBA project with a reference to the scripting runtime, the reference isn't gone when another user opens your macro-enabled workbook: if a user needs to manually add a reference, it's because they broke it themselves.

If the referenced library is missing or unregistered on the other computer, late-binding isn't going to make it work any better: there's nothing to bind to. When you call CreateObject like this:

Set foo = CreateObject("Scripting.Dictionary")

You're telling the runtime to fetch the CLSID from this registry key:

That CLSID is then used to locate the library:

And then the ProgId "Scripting.Dictionary" is used to locate the type and create the object, which is returned to VBA as an IDispatch - an Object.

If you don't need late-binding, don't late-bind - keep it simple:

Private Sub ContinueMatchArray(ByVal arrayMatchDictionary As Scripting.Dictionary)
    'do something
End Sub


To be honest, for a simple, one-off problem, I disagree that hardcoding an input file name is disadvantageous. Similarly for error handling; you know the file is there and will read fine, so unwrapping it is fine; if it fails for some stupid reason there's no recovery you can do anyway.

And because the problem is so simple, there's not much to go about complaining about. This is a perfectly fine solution, because it's very readable.

But there are a few places where the standard library could be better utilized: (Note: I may go a little far here. Go as far iterator as you feel comfortable.)

The iteration over content's indices in get_input can be replaced by a mutating iterator:

for byte in &mut content {
    *byte -= b'0';
}

Here I've also used a byte character literal, rather than casting to u8, which clippy will warn you about. With a known constant, it's safe, but then you should just use the byte literal.

What this says is to, for each position in content, take the thing at the position *byte, and decrement (-=) it by b'0'. It's the exact same as what you did, except without the manual indexing. (It's probably lowered to the same machine code in the end, but iterators are fun!)

offset_sum provides a more interesting field for refactoring, though. It can be done in one iterator chain by cleverly utilizing the available tools.

input

Start with the slice,

    .iter()

and get an iterator from it.

    .cloned()

Since we're operating over a Copy type, I dereference it here for convenience. If we just call iter, we get an iterator over &u8, but calling cloned clones each element, which in this case is just a cheap Copy. Don't go doing this with non-copy types, though; this is just a convenience.

    .enumerate()

We pair up each byte with its index in the iterator.

    .filter(|&(i, b)| b == input[(i + offset) % input.len()])

Filter out all of the numbers that don't match our requirements.

    .map(|(_, b)| u32::from(b))

Map our iterator back to just the number we care about. Convert it to a u32 so that we can

    .sum()

it into a u32 and consume the iterator.

Try it Online!

Some fun extensions you might try:

This is always going to be an \$O(n)\$ algorithm because you have to scan the whole string. But rather than handle indices, in the first half you could use  windows to grab each neighboring pair of bytes, though you will have to handle wraparound somehow. In the second half, you can reduce the number of comparisons you have to do by half, because each number is compared against the same number in either direction (the absolute opposite of a circular buffer). Maybe you can split the slice into two halves, then zip the two halves together for comparisons?


My two cents : MemoryStream is a disposable object (inherited from Stream)

using (var reader = new BinaryReader(new MemoryStream(data)))

should grant you with a warning CA2000.

You may check this point with something like

Stream stream = null ;
try
{
   Stream = new MemoryStream(data) ;
   using (var reader = new BinaryReader(stream))
...
}
finally
{
    if (stream != null)
    {
        stream.Dispose() ;
    }
}

This should ensure you are freeing the stream in time.

Hope this helps !


Not sure whether there's some trickery here... But a simple solution could be:

Simplest way would be an array of boolean for all possible numbers. When you enter 50, check position 50 and if it's false, it was the first time, now set that position to true so it can't be true the next time it is checked. Make it 90 in size and always add 10 to the index :).

bool[] hasBeenEntered = new bool[100-10];

while (true)
{
    int nr = Int.Parse(Console.Readline());
    if (nr >= 10 && <= 100)
    {
        if (hasBeenEntered[nr+10])
            continue;

        hasBeenEntered[nr+10] = true;
        Console.WriteLine(nr);
    }
}

There might be creative solutions using shorts and bit shifting to use a smaller array or actually use all the binary positions in an array of 2 Longs instead to make it a much smaller array. That's probably not the solution direction, but it would work pretty well...

bool[] hasBeenEntered = new long[2];

then check using bitmasks:

if (hasBeenEntered[nr/64] & (nr % 64) > 0)
    continue;

hasBeenEntered[nr/64] |= (nr % 64);
Console.WriteLine(nr);


C++ overloading += operator in custom string class better implementation

You did a single-null-allocation correctly(ish) once:
if(str == nullptr){
    this->str = new char;
    *(this->str) = '\0';

and incorrectly a second time:
if(str == nullptr){
    this->str = new char;
    this->str = '\0';

This will produce a memory leak. That aside, if your compiler allowed this without yelling about incompatible types, that makes me sad.
Even then, as @TobySpeight indicates, the first style of allocation has a mismatch with your delete[] and also needs to follow array-like syntax.


Binary Search tree deletion optimization

You are always returning true so I guess you don't really need current return value. In that case you might want to try a bit different approach.
You want to do something like:

 if( data < node.key) {
    node.left = deleteNode(data, node.left);
 } else if( data > node.key) {
    node.right = deleteNode(data, node.right);
 } else {
    //here return resulting node after deletion, null if node had no children
 }

That way you don't need to know anything about parent


Don't flush where you don't need to.

Flushing is expensive, so don't use std::endl unless you need it.
Nearly always, the shorter '\n' suffices, which can be merged with any bordering string-literal.

Still, that advice seems to be for your teacher, not you ;-)
return 0; is implicit in main if control reaches the closing brace }.
The same is true for C since C99.

This also seems to be one for your teacher.
I see you corrected your formatting since posting on SO.

Still, 6 spaces is unusual. Either use the standard tab-stop (8), or if that's too much for your tastes, 4 is a common choice.

Automatic formatting-tools exist which will do this and much additional formatting for you, which gain importance with the size of the project, especially the number of contributors.
There is no reason to write the member-functions of the template out-of-line.

Even if you later divide your projects in multiple files, and thus have headers and implementation-files, templates are always (with really few exceptions) implemented in the header anyway, due to technical constraints.
There is absolutely no reason to explicitly implement the copy-constructor.
Let the compiler provide a default one.
Since C++11, one can also explicitly default it, preferably at the point of declaration: = default;.

Additional benefit: Doing so re-enables move-ctor and move-assignment.
The 2-argument-ctor should be templated to accept any assignable types and use perfect forwarding:

template <typename T3, typename T4, typename = decltype(T1(std::declval<T3&&>()),
    T2(std::declval<T4&&>()), void())>
Calculator(T3&& a, T4&& b) : number1(std::forward<T3>(a)), number2(std::forward<T4>(b)) {}

The setters should accept any assignable type and use perfect forwarding for optimal performance.

template <typename T3>
auto setValue1(T3&& x) -> decltype(number1 = std::forward<T3>(x), void())
{ number1 = std::forward<T3>(x); }
template <typename T3>
auto setValue2(T3&& x) -> decltype(number2 = std::forward<T3>(x), void());
{ number2 = std::forward<T3>(x); }

add and multiply should use a deduced return-type, and be const.
This transfers to avoiding explicit types in the implementations:

Use decltype(std::declval<T1&>()+std::declval<T2&>()) for C++11.

decltype(std::declval<T1&>()+std::declval<T2&>()) add() const;
decltype(std::declval<T1&>()*std::declval<T2&>()) multiply() const;

Or since C++14, just auto for letting the compiler deduce it.

auto add() const {
    auto answer = number1 + number2;
    return answer;
}

Or shorter:

auto add() const {
    return number1 + number2;
}

Putting it all together:

template <class T1, class T2>
class Calculator {
    T1 number1;
    T2 number2;
public:
    template <class T3, class T4, class = decltype(T1(std::declval<T3&&>()),
        T2(std::declval<T4&&>()), void())>
    Calculator(T3&& a, T4&& b) : number1(std::forward<T3>(a)), number2(std::forward<T4>(b)) {}
    // implicit: copy-ctor, move-ctor, copy-assignment, move-assignment, dtor

    template <class T3>
    auto setValue1(T3&& x) -> decltype(number1 = std::forward<T3>(x), void())
    { number1 = std::forward<T3>(x); }
    template <class T3>
    void setValue2(T3&& x) -> decltype(number2 = std::forward<T3>(x), void());
    { number2 = std::forward<T3>(x); }

    auto add() const { return number1 + number2; }
    auto multiply() const { return number1 * number2; }
};


Implementing a Trie in Python - follow-up

You could easily extent __init__ to take a list of strings to add to your Trie from the get go.

def __init__(self, *args):
    self.child = collections.defaultdict(Trie)
    for arg in args:
        self.insert(arg)

Now you could pass an arbitrary number of strings to Trie and they'll all be added in initialisation.

Also, if you wanted to you could still make the string representations equivalent by sorting the list before you return it.

def __str__(self, depth = 0):
    s = []
    for i in self.child:
        s.append( '{}{} {}'.format(
            ' ' * depth, i or '#', '\n' + self.child[i].__str__(depth + 1)))
    s.sort()
    return ''.join(s)

If you're concerned with running time, you can make it flaggable and off by default. Speaking of defaults, you should use depth=0 (no spaces, PEP8 reference) as that's the commonly accepted syntax.


You can access the data by simply passing it into your method call. So instead of passing an event to getroles, just pass the value.

Replace your template:

                {{ user[0] }}

Then update your function:

$scope.getroles = function(uid){
    $http({
        "method": "GET",
        "url":"/api/rolesbyuser/",
        "params": {"user_dn": uid}
    }).success(function(data){
        console.log(data);
        $scope.roles = data;
    });
    // returns {ldapuser: ldapusername, direct_roles: [r1, r2], inheritedroles: [ir1ir2]}
};

Using a Service

Sometimes it's good to separate your $http calls to a service. This allows you to re-use your $http calls in other controllers. It seems like overkill, but it helps with re-use. Alternatively, you could use the $resource, which will build the service for you automatically. Unfortunately, in your case, your endpoints are different, so you'll need to roll your own service.

Each method in the service will return a promise so that future controllers can customize the success conditions.

The bonus of this is that it makes it easier to test your controller as you can easily mock out the service. You could've mocked out the $http service, but then your implementation would start to leak into your tests.

I would also recommend having the userSearch being passed into getUser as a parameter. This reduces the amount of state that your controller needs to maintain.

angular.module("UserRoles")
.service("UserRolesService", function($http) {

    this.getUsers = function(userId) {
        return $http.get("/api/finduser/" + userId);
    }

    this.getRoles = function(uid) {
        return $http.get("/api/rolesbyuser/", { params : { "user_dn" : uid } });

    }
})
.controller("UserRolesController", function($scope, UserRolesService) {

    $scope.usersearch = "";
    $scope.users = [];
    $scope.roles = {};

    $scope.getUsers = function(userId) {
        UserRolesService.getUsers(userId).success( function(data) {
            $scope.users = data;
        });
    };

    $scope.getRoles = function(uid) {
        UserRolesService.getRoles(uid).success(function(data) {
            console.log(data);
            $scope.roles = data;
        });
    };

});


Should this container be a struct or a class?

Keep it a class

The linked MSDN guideline says so itself:

  X AVOID defining a struct unless the type has all of the following characteristics:

  it has an instance size under 16 bytes

It should be pretty clear that DataContainer is going to be much larger than 16 bytes.

One of the reasons this is a concern is that structs are stored on the stack.  The default .NET thread stack size is 1MB, so in an extreme case, a struct which is too large could get you a StackOverflowException without any recursion required.


There's a simple linear solution.

You don't have to check all substrings. If an [l, r] substring is a palindrome and r - l > 2, so is [l + 1, r - 1]. Thus, it's sufficient to check only substrings of length 2 and 3.

One can do with a single pass over the input string:

for i in [0 .. s.length() - 2]:
     if s[i] == s[i + 1]:
         return true
     if i != 0 and s[i - 1] == s[i + 1]:
         return true
return false


What comes to performance, it will degrade drastically if you pass a LinkedList (which implements java.util.List interface accepted in your heap sort): for such a list, get(int) operation runs not in constant time, but rather \$O(n)\$. In order to deal with it, check in your sort that the input list is not a linked list, and if it is, copy all the elements to an ArrayList, sort it, and load back to the input list.

The second point concerns the sifting algorithm. If the indices of the sifting operations are \$i_1, i_2, ..., i_n\$, you first swap \$i_1\$ with \$i_2\$, then \$i_2\$ with \$i_3\$ and so on until the element is in its proper place \$i_n\$. You can do better: save the element at \$i_1\$, then move \$i_2\$ to \$i_1\$, \$i_3\$ to \$i_2\$, and so on. Finally, just set the saved element at index \$i_n\$. This optimization does not improve the time complexity of heap sort, yet it reduces the constant factors hidden by the big-O notation.

The last, but not least: sometimes we do not need to sort the entire array/list. For this, it makes sense to code up a sorting routine, which can sort particular ranges. Then, in order to sort the entire array/list - as you do - you can just do:

sort(List<T> list) {
    sort(list, 0, list.size());
}


Divide a set of strings into those which contain "a" and those which don't

This usecase is actually covered by one of the itertools recipes. itertools is a package in the Python standard library that supplies fast and efficient tools for iterating over things or creating certain iterable things (like the combination of all pairs and such). It is an often used library and well worth it to get acquainted with.

The recipe is as follows:

from itertools import filterfalse, tee

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

In your specific case you would use it like this:

if __name__ == "__main__":
    cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
    no_a_city, a_city = map(list, partition(lambda city: "a" in city, cities))
    print("a_city:", a_city)
    print("no_a_city:", no_a_city)

The map(list, ...) part is needed because what the partition function returns are generators that generate values on the fly. They can be consumed into a list.

The predicate used is a lambda function, an anonymous function which in this case returns truthy or falsy values. It is used to test each element of the iterable.

Instead of manually iterating over each name (even worse, over each index of each name, have a look at Loop Like A Native), I used the fact that strings support the in operator.

I also added a if __name__ == "__main__": guard to allow importing from this script from another script.

One thing you could have used in your code is the fact that for loops have an optional else clause which is run if no break statement interrupted the loop:

a_city, no_a_city = [],[]
for city in cities:
    for char in city:
        if char == "a":
            a_city.append(city)
            break
    else:
        no_a_city.append(city)

As for complexity, this has the same complexity as your code. You have two nested for loops, making this on average \$\mathcal{O}(nk)\$ with \$n\$ being the number of cities and \$k\$ being the average length of the city names.

The in operator for strings is \$\mathcal{O}(k)\$ (it is just the same loop you wrote, but probably written in C) and it is used once per city. However, due to the tee my code iterates twice over the cities, so would be \$\mathcal{O}(2nk)\$, which in terms of algorithmic complexity is also \$\mathcal{O}(nk)\$.


Yes
Blowfish is a great algorithm for storing passwords, it makes generating a hash slow such that brute force attacks are unviable. It's also php's recommended means of storing passwords.
But
The salt for blowfish is supposed to be:

22 digits from the alphabet "./0-9A-Za-z".

This applies to the salt string which in the question is:
'HfuPgoDY94nHJssqQeVLmH' . $salt . '$'

That's 22 chars + 32 chars + '$', which is 65 characters long and contains an illegal '$'. The consequence of that is that the salt actually used is a fixed string, the first 22 characters and is the same for all generated hashes.
The salt should be random, and for example you could use something as simple as this:
$salt = '$2y$12$' . substr(md5(time()), 0, 22);
return crypt($str, $salt);

Note however that this code is simple for brevity and can be significantly improved upon since the salt will only be made up of hexadecimal (0-9a-f) characters. Here's an example implementation that could be used to generate a better salt.
Make cost a parameter
A cost of 12 is fine for passwords, but you may wish to make it a parameter so that e.g. unit tests are not needlessly slow whenever they generate a password.


Change the background color of each section of the page when the user scrolls

Heres your code slimmed down, the problem you were having with the loop was that you weren't getting offset().top of your sectionTop[i].

var myScope = zeus = false;
var colors = ['blue','yellow','green','purple','brown'];
var sectionId = '#section';
var sections = 5;

$(window).on('scroll', function() {
myScope = $(window).scrollTop() + 300;

for (var i = sections; i >= 0; i--) {
   var sid = i > 0 ? i : 1;
   var css = 'white';
   if(myScope >= $(sectionId + sid).offset().top
   && myScope < $(sectionId + sid).offset().top) {
    css = colors[i];
   }

   $(sectionId + sid).css('background-color', css);
}

});


If you want to avoid replace, a faster method would just split and join. This is faster simply because .split and .join are fast:

"20%".join(string.split(" "))

For a more thorough review, I'll point out that your functions aren't equivalent. The first strips whitespace and the second doesn't. One of them must be wrong!

In the second case:

def replace_token_inplace(s, token=" "):
    for index, char in enumerate(s):
        if ord(char) == ord(token):
            s[index] = '20%'
    return s

you are doing several non-idiomatic things. For one, you are mutating and returning a list.
It's better to just not return it if you mutate:

def replace_token_inplace(s, token=" "):
    for index, char in enumerate(s):
        if ord(char) == ord(token):
            s[index] = '20%'

Secondly, it'll probably be faster to do a copying transform:

def replace_token_inplace(s, token=" "):
    for char in s:
        if ord(char) == ord(token):
            yield '20%'
        else:
            yield char

which can also be written

def replace_token_inplace(s, token=" "):
    for char in s:
        yield '20%' if ord(char) == ord(token) else char

or even

def replace_token_inplace(s, token=" "):
    return ('20%' if ord(char) == ord(token) else char for char in s)

If you want to return a list, use square brackets instead of round ones.


Javascript velocity converter, fully chainable

Here's a fairly cryptic rewrite, focussing mostly on extensibility and minimal repetition. The trick I'm using is to pick one unit as our "base" unit from which all others are derived. The base-unit value (m/s in this case) is carried through the chain.

var convert = (function () {
  var conversions = {
    ms:    1, // use m/s as our base unit
    kmh:   3.6,
    mph:   2.23693629,
    knots: 1.94384449
    // feel free to add more
  };

  function Unit(unit, ms) {
    this.value = ms * conversions[unit];
    this.to = {};
    for(var otherUnit in conversions) {
      (function (target) {
        this.to[target] = function () {
          return new Unit(target, ms);
        }
      }).call(this, otherUnit);
    }
  }

  Unit.prototype = {
    yield: function () {
      return this.valueOf();
    },

    toString: function () {
      return String(this.value);
    },

    valueOf: function () {
      return this.value;
    }
  };

  return function (value) {
    var units = {};
    for(var unit in conversions) {
      (function (unit) {
        units[unit] = function () {
          return new Unit(unit, value / conversions[unit]);
        };
      }(unit));
    }
    return units;
  }
}());

Edit: Just for fun, here's an ultra-convoluted version that handles different measurement types. Couldn't get temperature conversions in there, as simple multiplication/division isn't enough to deal with C/K/F conversions. Boo.

Really though, the code's pretty dense, and I can't recommend coding like this. But again, this was just for fun.

Anyway, the usage would be something like

convert.speed(60).mph().to.kmh();  // ~97km/h
convert.distance(100).m().to.ft(); // ~330ft
convert.mass(1000).g().to.lb();    // ~2.2lb

And here's the hairy code:

var convert = (function () {
  var conversions = {
    speed: {
      ms:    1, // use m/s as our base unit
      kmh:   3.6,
      mph:   2.23693629,
      knots: 1.94384449
    },

    distance: {
      m:      1, // use meters as our base
      inches: 39.3700787402, // can't use "in" as that's a keyword. Darn.
      ft:     3.280839895,
      mi:     0.000621371192,
      nm:     0.000539956803 // nautical miles, not nanometers
    },

    mass: {
      g:  1, // use grams as our base
      lb: 0.002204622622,
      oz: 0.0352739619
    }
  };

  function Unit(type, unit, base) {
    this.value = base * conversions[type][unit];
    this.to = {};
    for(var otherUnit in conversions[type]) {
      (function (target) {
        this.to[target] = function () {
          return new Unit(type, target, base);
        }
      }).call(this, otherUnit);
    }
  }

  Unit.prototype = {
    yield: function () {
      return this.valueOf();
    },

    toString: function () {
      return String(this.value);
    },

    valueOf: function () {
      return this.value;
    }
  };

  // my god, it's full of scopes!
  var types = {};
  for(var type in conversions) {
    (function (type) {
      types[type] = function (value) {
        var units = {};
        for(var unit in conversions[type]) {
          (function (unit) {
            units[unit] = function () {
              return new Unit(type, unit, value / conversions[type][unit]);
            }
          }(unit));
        }
        return units;
      };
    }(type));
  }

  return types;
}());


Convert UTF8 string to UTF32 string in C

There are two main things to talk about: checking the input, and buffer handling (your malloc question).

It's a very bad idea to do things like array[i + 1], unless you're absolutely, 100% sure that this refers to memory that is both allocated and part of the string. If it's not allocated, your program is begging for a crash; if it's not part of the string, it's a vulnerability issue and every script kiddie will be able to read your process' memory.

Checking the input

Unless you're absolutely, 100% sure that your user will be supplying you with a valid, NULL-terminated UTF-8 string, you definitely need to do some checking. Note that when I say "user", I mean the developer who will be using your functions.

When writing APIs, it really helps to write, or at least think about, some usage code first, in order to get an idea of what developers would need and how your code will be used. This will help again later, when discussing your malloc question.

Now, think about your general use cases. The developer gets some input through a socket, file, hardware device, form field, whatever. Sockets, files and hardware are prone to losing some bytes due to many different reasons. Forms are generally safe, but you will come across a library that will leave off bytes of the last UTF-8 character when you give it a too small buffer, or not null-terminate the string when the last character fits exactly in the buffer (some C standard lib functions are guilty of the latter). Malicious users may also try to exploit the form input field.

Out of all these, only the form field will be naturally NULL-terminated (probably). With all the others, you get a stream of data that simply ends at some point. So you're forcing the user to manually add the NULL byte, which could possibly lead to reallocation... you can see it's not a good idea.

The developer, however, knows exactly how many bytes he got. Why not exploit this? Rewrite your utf8_strlen function like this:

size_t utf8_strlen(uint8_t* text, size_t nb_text, size_t* nb_valid);

Do pretty much the same thing you were doing, however:

Do not blindly increment i without testing whether i + NUM_BYTES_IN_NEXT_CHAR <= nb_text
Stop immediately if that fails
Stop immediately at a null byte, even if you've used less than nb_text bytes
Stop when you've used nb_text bytes
You may check that every single byte conforms to the UTF-8 standard.
Depends on how thorough you want to be.  Best to do it anyways.
In short, only increment i when you're sure that you've got enough bytes left for the next character, and all bytes of the next character are valid UTF-8. Don't increment i at the terminating null byte and immediately stop.
In the end, set *nb_valid = i. This allows the user to check how many bytes were valid UTF-8. Note that text + *nb_valid would point to the byte immediately after the last valid UTF-8 character. If the string ended with a null byte, text + *nb_valid would point to it instead.
Be nice, and allow nb_valid to be a NULL pointer if the developer doesn't care about this information.
Return the number of valid characters parsed.

Now that you're sure you're only going through valid UTF-8, your utf8_to_utf32 can remain the same. Just add the needed parameters:

uint32_t* utf8_to_utf32(uint8_t* text, size_t nb_text, size_t* nb_valid) {
    size_t num_chars = utf8_strlen(text, nb_text, nb_valid);
    /* ... rest is the same ... */
}

... but do consider what the previous answers mentioned, especially the portability issue of left-shifts, if you plan to program arduinos or other microcontrollers.

Buffer handling

is the reason C is hard. But again, let's think about the use cases. At first, allocating the buffer for the user may seem very helpful, but actually it's rarely something that the user wants. Besides, it burdens them with freeing the buffer, which sucks.

Let's say I'm reading a file or some socket line by line. I'd actually want to allocate just one buffer, and re-use it for each line (reallocating or doing partial reads if I get a very long line). Thus, I'd like for utf8_to_utf32 to write to a particular buffer that I give it. Much better than having many, many allocations and deallocations.
Let's say I'm updating some user input. In most cases I'd already have a UTF-32 buffer where the old user input is stored, and I want to update it. Again, I'd like for utf8_to_utf32 to write to a particular buffer.
I may wish to concatenate or append text. Again, writing to a particular buffer.

So it seems you don't want to actually allocate the buffer, which is just dandy, since the best memory management is none at all. (Side note: the more experienced a C developer, the less you'll see them messing around with memory and allocations, for example see Casey Muratori [1] [2]
[3], a very experienced C developer).

The function signature changes to:

void utf8_to_utf32(uint8_t* text, size_t nb_text, uint32_t* out_buf, size_t* nb_valid) {
    /* don't allocate c, replace c with out_buf */
}

Great, but how will you ensure that there's enough space in out_buf? Two options, each with its pros and cons.

A. Let the user worry about it

You're already providing a function - utf8_strlen, that will let the developer know how many characters to allocate for the buffer (plus one more for the NULL-terminator). If they don't, then that's their problem. Many standard lib functions operate like this: for example mbstowcs.

B. You worry about it

Add another parameter to the function that tells you the size of out_buf. You should never write more than this number of characters. This is a bit safer, though the programmer can of course still lie. This will make your code a bit more complicated, and will allow for partial conversions, though this usually falls under the YAGNI principle. Again, many standard lib functions operate like this too: for example strncpy, snprintf

Pick your poison and keep it consistent

People are familiar with both styles, so choose whatever you prefer and keep it consistent if you decide to add more functions later.

Now the only question that remains is what to do with the return value, which is currently void. Looking at the standard lib functions, you'll see that they would usually return the number of characters written to out_buf.

Another reasonable thing to do would be to return 1 or 0, based on whether the input UTF-8 string was valid all the way through, or there was some invalid data. I'm suggesting it because the check would be

is_utf8_valid = (nb_text == *nb_valid) || (text[*nb_valid] == '\0');

which is something you don't want to bother the user with getting right.


Usage of state machine to model lifetime of an IP address

Better late than never.

Yes, a state machine makes sense here.  You've chosen good names and your coding style is good.

A few comments:

The "puts" lines appear to be for debugging.  If that is so, and they are going to remain in the code, I would consider writing to an IO object rather than $stdout.  This will make tests much nicer to run, since when passing, you won't be bothered by all the debugging information.  For example:

attr_accessor :debug_io
...
after_transition any => any do |ip, transition|
  @debug_io.puts "after_transition -> state was: #{transition.from}, state is: #{transition.to}"
end

And because you want it to still work even if the caller has not set debug_io, give it a default.  "No output" is a good default:

class NullIO
  def puts ; end
end

def initialize
  super
  @debug_io = NullIO.new
end

The return value of is_protected? depends only upon the state, being true if in the bound or protected state.  Remove:

before_transition any => :protected, :do => :activate_firewall_rules
before_transition any => :unprotected, :do => :deactivate_firewall_rules

and the methods they call, and change is_protected? to:

def is_protected?
  [:protected, :bound].include?(state)
end

Similarly, remove:

before_transition any => :bound, :do => :bind_to_server
before_transition any => :unbound, :do => :unbind_from_server

and the methods they call, and change is_bound? to:

def is_bound?
  [:bound, :unprotected].include?(state)
end

Ruby predicates usually leave off the "is_" prefix.  Consider changing is_bound? to bound? and is_protected? to protected?.  The is_ prefix comes from languages which do not allow question marks in identifiers.

Mark as "private" methods which are for the use of the class only, and should not be called by the class's user.  This will help prevent accidental misuse of the class, but more importantly, document the class's public signature, which helps in understanding and is a big help when refactoring.  Methods such as bind_to_server and unbind_from_server are private (or were, before they were removed).

It's not clear what this line is for:

throw :halt unless ip.send("is_#{transition.to}?")

If it's not for debugging, it seems like an odd bit of hidden coupling between the class and the rest of the program; I would try to find another way to do this that makes it clearer why the :halt is being thrown.


Boolean constant for assert in if..else block

Throwing an assert error is probably heavier than throwing an Exception (as Groovy will parse the assert inputs to give you a pretty output string)

And unless you are going to be running this hundreds of times per second, I wouldn't worry about it either way...

A way of using assert that gets round the warning (and provides a nice error message) might be to do:

assert condition_1 || condition_2, 'Expected at least condition_1 or condition_2 to be true'


There are dozens of possible optimizations. The most obvious -- why are you multiplying i by itself every pass in the loop?! Just calculate the loop cut off once.

And why i++?! After you test 2, there's no reason to test 4, 6, or 8. You can test 2, and then start from 3 adding 2 each time instead of one.

Also, since you need to find all the primes up to a given point, you should be using a sieve rather than testing each number.


The one major problem is the lack of synchronisation between processes,
even if you randomise the sleep interval, this is still an invitation
for race conditions (unless you can somehow proof that the randomisation
is good enough).

Using a library like
lockfile or directly
using e.g. fcntl.lock will take care of that.  If you are worried
about the performance, well you are using Python, with cPickle (good
point that).  Otherwise some IPC mechanism, maybe a shared semaphore
between processes, would suffice.

Next, I think you can leave the file simply open and rewind to the
start, the read again instead of constantly closing and opening.  I'm
also not sure, but you could investigate file (region) locking via
fcntl instead to provide the necessary synchronisation.

The turn_on/turn_off seems very complicated if you could just write
out a dict, sequence, whatever, instead of doing bit manipulation.
If, however, you really want that part, then be consistent and simply
write two bytes to the file instead of using pickle.  The mixture of
very high-level serialisation and low-level composition of four bits
doesn't seem necessary at all.

Otherwise looks fine.  Some common expressions could be shared and the
written data structure is mostly used without any abstraction (like you
did with new_state, a updated_state function to create the new
dict could be nice), but I guess for a small script that hardly
matters.


You haven't provided cs50.h, so I have to guess its contents. I guess that it contains

int get_int(); // probably { int k; scanf("%d", &k); return k; }

for this review, since this is the only unknown function in your code.

Either way, let us get started. While completely up to you, the innards of a function are usually indented, just like they are for a conditional construct. So all of your main would be indented:

int main(void)
{
    printf("How many numbers do you want to enter? ");
    int len = get_int();

    int input[len]; // creating an array to store values

    /* .. */

While your program only uses a single large main, where it doesn't seem to matter, it's tremendously helpful if your program consists of multiple functions. for example, you could have split your functionality into several, reusable functions:

void read_n_numbers(int * destination, size_t n);
void count_digits(const int * source, size_t n, int min, int max, int * digits);
void print_digit_count(const int * digits, int min, int max);

By the way, those additional min and max parameters? They already show a flaw with your algorithm. But more on that later.

Instead, let us focus on some things to be wary of.

Know what variable length arrays are

int input[len]; // creating an array to store values

This lines uses two C99 features: C++-style comments and variable length arrays. The comments don't pose any problem. The VLA on the other hand may. VLAs are often stored in an area close to your other variables, like len above. That area is rather limited in size, which can lead to problems if len is too large. Also, with C11, they got optional. Your compiler might or might not support those.

They're sufficient for a small toy program, but you have to make sure that things don't get too large.

Give a variable the correct type and make it constant if it shall not change

We're still just in the first few lines of your program. But did you check whether len is negative? Let's say the user inputs -1. We end up with

int input[-1];

Uh oh… If this was a program you want to use in a productive environment, you would check the sign of len, and, after the discussion above, also check that tit doesn't get too large (or dismiss VLA).

We can provide a small little helper to make sure that we get only positive integers:

size_t get_positive_int() {
    int k = get_int();
    while(k <= 0) {
        printf("Number must be positive, please try again: ");
        k = get_int();
    }
    return k;
}

Now we have an ease of mind when we get our len:

const size_t len = get_positive_int();

What? Why is len now size_t? Why is it const? Well, it's a size_t because that is the proper data type to measure the size of something. You can think of it as a unsigned long, but it's size depends on your system.

And why is len now const? Because it prevents accidental errors like this:

for( int i = 0; i < len++; ++i)
//                     ^^
//                  whoops

It seems unlikely that you accidentally change len. But why take a risk? const puts an ease on your mind.

Make exclusive branches exclusive

We're still following your function top-to-bottom. And while your for finding the minimum and maximum of the range works, it's not really friendly to our PC:

for (int i=1; i<len; i++)
{
    if (input[i]>max)
    {
        max = input[i];
    }
    if (input[i]<min)
    {
        min = input[i];
    }
}

You start with max = min. However, throughout your program, the following property will hold: min <= max. So if the input[i] is greater then max, it will certainly not be lesser than min. We can reflect that with an else:

for (int i=1; i<len; i++)
{
    if (input[i] > max)
    {
        max = input[i];
    }
    else if (input[i] < min)  // << here
    {
        min = input[i];
    }
}

Now we only check whether input[i] is smaller than min if it wasn't aleady greater than max.

An error in disguise

Now we come to the part where your code is actually wrong. Sorry.

Let's say your user inputs the following numbers:

-3
-2
-1
0
1

What can go wrong with the following declaration?

// creating an array for all the digits needed
int digits[max+1];

You will have only memory for exactly two digits. That's not enough! You have to calculate the actual number of possible digits. Luckily, that is simple:

const int number_of_possible_digits = max - min + 1;

size_t digits[number_of_possible_digits]; // size_t because we're counting things again

// use `memset(digits, 0, sizeof(digits));` alternatively

for(int i = 0; i < number_of_possible_digits; ++i)
{
    digits[i] = 0;
}

"But wait", I here you say. "If I have now the following input, I would not have enough space for my digits:"

  10
  11
  12

"I would have only space for three digits, but in my assignment I use digits[input[i]]!" But we're not done yet. Keeping the example with negative numbers from above in mind, what goes wrong in your actual counting?

for (int i=0; i<len; i++)
{
    digits[input[i]] = digits[input[i]] + 1; // increasing the value of default digit element (default is 0) by 1 each time
}

You've probably guessed it. With our negative values, we end up with digits[-3]. This doesn't work. We have to use another technique for our access. Luckily, that's easy again:

for (int i=0; i<len; i++)
{
    digits[input[i] - min]++;
    // digits[ -3 - (-3)] = digits [-3 + 3] = digits[0]. All is well.
}

We have to adjust your algorithm slightly:

for (int i = 0, j = 0; i < number_of_possible_digits; i++)
{
    while (digits[i] != 0)
    {
        input[j] = i + min; // min now added here
        j++;
        digits[i]--;
    }
}

All we had to do is to add min to our index in our digits. Let's check that with an example:

-5
-2
1
1
1
1
1
1
1
1
10

The number of possible digits is 16 (10 - (-5) +1). After counting them, we end up with a digits array that looks like this:

{1,0,0,1,0,0,8,0,0,0,0,0,0,0,0,1}

Does input[0] get the correct value?

input[0] = 0 + -5

Yes it does.

To simplify a condition/loop

Allright, I changed a lot here, I have to admit. But the most important change is input[j] = i + min. What other changes did I do?

I've reduces j's scope. It is only available in the loop, so that you don't accidentally use it at some other point
I've removed all unecessary if and else.

I will show how I did the latter, so it gets easier to understand. First, if we do nothing in an if, but everything in an else, it makes sense to exchange those, e.g. go from

if (digits[i] == 0)
{
}
else
{
    // other stuff
}

to

if (digits[i] != 0)
{
    // other stuff
}

Next, if we look at our do-while, we will see that the conditions are the same:

if (digits[i] != 0)
{
    do
    {
        // other stuff
    }
    while(digits[i] != 0);
}

This means we can change it to a while loop, since the condition olds true. That's guaranteed by the if:

if (digits[i] != 0)
{
    while(digits[i])
    {
        // other stuff
    }
}

Now we remember that a while loop will not even get entered once, if the condition doesn't hold. So we can get rid of the if and we end up with simply

while(digits[i])
{
    // other stuff
}

Don't repeat yourself

You print the sorted number twice. And maybe you want to print the digits at some point, too. Create a function for that:

void print_numbers(const int * source, size_t length) {
    for (size_t i = 0; i<length; i++)
    {
        printf("%i ", source[i]);
    }
}

Keep in mind that that function won't work with digits if they are a size_t array.

To put things together

So, was your algorithm correct? For positive numbers, the answer is yes. But as soon as the user is allowed to input negative numbers, the answer was "no". However, the greatest weak point of your program is that it is a single large function. You don't need to split it into too small functions, but the actual counting algorithm kind of gets lost in the noise of the rest.

So for a future exercise, try to write

void counting_sort_inplace(int * values, size_t length){
    // ...
}

so that

counting_sort_inplace(input, len);

does exactly what your second part of the main did before.


img = "#{row[0]}".downcase
part = "#{row[2]}"
loc = "#{row[5]}"
country = "#{row[4]}"
focus =  "#{row[3]}"
desc = "#{row[8]}"
link = "#{row[9]}"

The only difference between writing "#{ expression }" (without anything else in the string) and just writing expression is that the former converts the result of the expression to a string. If that is your intent, you should write expression.to_s instead because that way it's clearer what's going on.

However in your case the values in row are already string, so there's no need to convert them to strings, so using "#{}" here is just redundant. You can just write img = row[0].downcase, part = row[2] etc.

Instead of taking each column out of the row array individually, you can also write this:

CSV.foreach(@file) do |img, _, part, focus, country, loc, lat, lon, desc, link|
  img = img.downcase
  file.puts("[#{lat}, #{lon}, #{img}, #{part}, #{loc}, #{focus}, #{country}, #{desc}, #{link}],")
end

Note that I've used the variable name _ to denote a variable we're not going to use because you never used row[1] in your code (_ is conventionally used in Ruby to denote variables that aren't used and is in fact the only variable name that's allowed to appear multiple times in a parameter list).

I've also replaced write with puts which automatically inserts a newline after the string, so you don't have to include the newline in the string.

A couple of more general design notes:

I think open_csv is rather misleadingly named. It does a lot more than just opening the csv file.

I also think it's a bad idea to call open_csv in your constructor. Generally the constructor should only set up the object, so that it's in a usable state. It should not do any actual work. The way you designed it, everything the object is ever going to do is done in the constructor. That's why when you use it, you create the object with ArrayGenerator.new and then never do anything with the object - because everything that can be done with the object has already been in the constructor. Another sign of this is that the only public method in your class is initialize. This is a very strange way to use objects.

On a related note there's no point in creating a g variable if you're not going to use it.

You should either redesign your class to behave more like an actual class, with a usage more like this:

g = ArrayGenerator.new( file )
g.generate

Or you could get rid of your class altogether and instead define a stand-alone method that could be used like this:

generate_array( file )


Suggestions for improving collection of related PHP functions?

Just an idea, but maybe this will help you from a manageability point of view:

 public function process($command, $parameters) {
      $method = 'MinteCommand_' . $command;
      $methodFile = dirname(__FILE__) . 'commands/' . $method . ".php";
      if (file_exists($methodFile)) {
            require_once($methodFile);
            if (function_exists($method)) {
                 return $method($parameters);
            } else {
                 throw "invalid function";
            }
      } else {
            throw "invalid function file";
      }
 }

The only benefit to this is that you simply create a new file with the new command (function) inside of that file and it'll automatically search for it if the command is issued.  One caveat will be the limit on the number of commands you can have is a limit on the number of files you can have in a single directory on the filesystem...

Note The code may not be perfect from a syntax point of view.  It's just to give you the general idea / concept.


Merging key-value sets as specified by a command

Abstract as much as possible over type: List instead of ArrayList.
Use OO where appropriate: List<String> operations should clearly be some
class MoveOperation(String to, String from).
It's not clear why you are using LinkedHashSet instead of List.
The algorithm is ill-defined: what happens if there are numerous
foo's or bar's.

I implemented something below, but it is in functional style, so it might be hard to read.  There are three implicit loops: two for the filters and one for the map.  You might also notice that I never modify a collection, but always create a new one.  Again, this is the functional style.  In your algorithm, you can actually shoot yourself in the foot if you modify some collections at the wrong moment.

private List<List<String>> merge2(List<String> operations, List<List<String>> listOfSentences) {
    Stream<List<String>> sentencesWithTo = listOfSentences.stream()
                                           .filter(sentence -> sentence.contains(toMerge));
    Stream<List<String>> sentencesWithFrom = listOfSentences.stream()
                                             .filter(sentence -> sentence.contains(fromMerge));

    long nTo = sentencesWithTo.count();
    long nFrom = sentencesWithFrom.count();

    if (nTo == 0  || nFrom == 0) {
        return listOfSentences;
    } else if (nTo > 1 || nFrom > 1) {
        // what to do here??
    } else {
        List<String> sentenceTo = sentencesWithTo.collect(Collectors.toList()).get(0); // should only be one element ?
        List<String> sentenceFrom = sentencesWithFrom.collect(Collectors.toList()).get(0); // should only be one element ?
        Stream<List<String>> updatedSentences = listOfSentences.stream().map(sentence -> {
            if (sentence.equals(sentenceTo))
                return Stream.concat(sentenceTo.stream(), sentenceFrom.stream()).collect(Collectors.toList());
            else if (sentence.equals(sentenceFrom))
                return new ArrayList<>();
            else
                return sentence;
        });
        return updatedSentences.collect(Collectors.toList());
    }
}


Generating .xml files based on .csv files

Minor stuff:

Remove the last import - etree is not used anywhere.
Merge the two first imports

Possibly speed-improving stuff:

Avoid converting the csv.reader output before returning unless absolutely necessary.
Skip indent unless the output must be readable by a human with a non-formatting editor.
If you need to indent the output, existing solutions are probably very efficient.
Use reader.next() to skip the header line in generate_xml, then you don't need to keep checking the value of i.


Redirecting arriving customers to the nearest empty queue

I see some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.

Check for errors

It may not be part of your assignment, but you should know that real programs should check for errors and handle them appropriately.

Use a function

Right now, everything is in main but we could make things a little more clear by creating a function.  Specifically, as each customer arrives at a register, they need to find the nearest open register.  This suggests a function: findNearestOpenRegister which could take a proposed register as an argument.  However, this function would have to get a number of other things passed to it which suggests a further refinement, described in the next suggestion.

Use an object

We can make the main code cleaner by using an object to represent the array of cashiers at a store.  I'd probably write it like this:

// represents a linear array of checkout registers at a store
class Checkout {
public:
    Checkout(int registerCount)
    : unoccupied(registerCount, true)
    {}
    int arrive(int r) {
        int lo, hi;
        for (lo = hi = r; lo >= 0 || hi < unoccupied.size(); --lo, ++hi) {
            if (lo >= 0 && unoccupied[lo]) {
                unoccupied[lo] = false;
                return lo;
            } else if (hi < unoccupied.size() && unoccupied[hi]) {
                unoccupied[hi] = false;
                return hi;
            }
        }
        return ERROR;   // this is an error condition!
    }
    int leave(int r) {
        if (unoccupied[r])
            return ERROR;
        unoccupied[r] = true;
        return r;
    }
    static constexpr int ERROR = -1;
private:
    std::vector <bool> unoccupied;
};

Now the main function can use the object:

int main () {
    int n;
    int m;

    std::cin >> n >> m;
    Checkout reg(n);

    for (int i = 0; i < m; ++i) {
        int checkout;
        char action;
        std::cin >> action >> checkout;
        --checkout; // checkout is 1-based in input, zero-based internally
        switch(action) {
            case 'C':  // someone comes to the register
                checkout = reg.arrive(checkout);
                if (checkout == Checkout::ERROR) {
                    std::cout << "Error: no free registers in line " << i+2 << ".\n";
                    return 1;
                }
                std::cout << ++checkout << '\n';
                break;
            case 'L':  // someone leaves the register
                checkout = reg.leave(checkout);
                if (checkout == Checkout::ERROR) {
                    std::cout << "Error: attempt to leave free register in line " << i+2 << ".\n";
                    return 1;
                }
                break;
            default:
                std::cout << "Error: unknown action '" << action << "' in line " << i+2 << ".\n";
                return 1;
        }
    }
}

Note that error checking has been added, as per the earlier suggestion.  Also note that rather than storing the output, this version simply emits it as it's generated, avoiding the additional data structure that is otherwise needed.

Profile the program

If you find that the program is not performing as fast as you need, the first step should be to try to find out where the program is spending its time.  This can be done by several different methods.  I tend to use gprof.  Among the possibilities are using a different data structure.  See this question for an example.  Another possibility is to execute std::ios_base::sync_with_stdio(false);, but whether that speeds thing up or not is uncertain until you measure.


C++ vs D - Algorithm Optimization/Conversion (Using vectors/arrays)

How about: using res.length = 64; and then in your loop replace

res ~= cast(int)log2(bitboard & ~(bitboard-1));

by:

res[n] = cast(int)log2(bitboard & ~(bitboard-1));

But to be honest this type of code will be completely dominated by allocations, which is not entirely interesting as a language benchmark. Try to reuse the same array instead.

And there is much faster ways of locating bits (see core.bitop).

tl;dr you're optimizing a slow program.


Tower of Hanoi: graphical representation of optimal solution

Very nice code!

Herea are a few small things:

Since your function hanoi is a generator, you don't need to save it to a variable, you can use it directly in the for loop:

for position in hanoi(pegs, 0, 2, number_of_pegs):

According to PEP8:

  Compound statements (multiple statements on the same line) are
  generally discouraged.

reversed(range(1, number_of_pegs+1)) is the same as range(number_of_pegs, 0, -1)
You calculate 255-pegwidth three times in a row, just use (255 - pegwidth,)*3 and use that.


Applying different equations to a Pandas DataFrame

You don't want to use an awkward lambda to do the addition.  You can use the add method with a parameter axis=0 that specifies which axis to match the lower dimensional argument.

I bundled the two Series you are adding into one so you only have to broadcast across the index once.

Next, I just changed to match my style and improve my readability

Finally, the finding where not zero and filling in with exp, I'm assuming exp is numpy's exp via some import from numpy import exp or something.  Otherwise, replace with np.exp.  This is much more vectorized.  result is a dataframe and mask makes anything that evaluates to True from the passed condition statement into np.nan. I then chain a fillna with a vectorized call to np.exp(result)

result = result.add(
    np.log(socio.ser_emp.add(1)).mul(.36310718).add(
        socio.hhpop.div(socio.acres).mul(-.07379568).fillna(0)
    ), axis=0)

avgtt, dist = matrices['avgtt'], matrices['dist']
result += avgtt.T * -0.05689183 + ((dist > 1) & (dist <= 2.5)) * 1.5

result = result.mask(result != 0).fillna(exp(result))


Project Euler #4 - Finding the largest palindrome that is the product of two three-digit numbers.

using namespace std; is a bad practice.  You should should spell out either what you are using, or spell out explicitly the std:: when you are using something.  You are doing the latter already with std::to_string and std::cout, just not with string.

Your palindromeCheck function should return a bool, instead of an int with specific integers having certain meanings.

temp is not used.

You are checking both 100 * 101 and 101 * 100.   Multiplication is commutative, so you can cut your work in half by adjusting your inner y loop to only use number from a range which hasn't been checked yet (from x to 999, inclusive).

newDigit is an odd variable name for the product of x * y.

palindromeCheck(newDigit) is an expensive operation.  newDigit > highestPalindrome is a relatively cheap test.  Consider reversing the order of these tests to avoid calling an expensive function when the result will never be used.


For each name, the current logic checks the type. That's ugly.
It's better to rewrite this without a switch,
which turns out to be shorter too:

private function auto_register() {
    global $autoload;

    foreach ($autoload['libraries'] as $name) {
        $this->{$name . '_library'} = call_user_func_array(array($this->load, "library"), array($name));
    }
    foreach ($autoload['models'] as $name) {
        $this->{$name . '_model'} = call_user_func_array(array($this->load, "model"), array($name));
    }
    foreach ($autoload['helpers'] as $name) {
        call_user_func_array(array($this->load, "helper"), array($name));
   }
}


Let me make sure I understand the problem.  You have a number of fields on the page where a value is required; when the user submits the page, and any of the fields are blank, you'd like the page to display a Javascript alert instead of submitting the form.  Yes?

I'd suggest you use an unobtrusive technique as follows:

If a field is required, it is marked with a "required" css class.  This can be a dummy class if you like.
Each field that is required is associated with a data attribute which specifies its human-readable name in the appropriate language
The submit button inspects all fields that are marked with the style and displays the names.

So to mark up a required field, use this pattern:

<input ID="login" class="required" data-name="login"/>

Then include this bit of code in your common script.  There's nothing page- or field- specific in it, so you can include it in every page if you want (e.g. in "common.js" or whatever):

$(document).ready(function(){
    var validate = function(e){
        var emptyFields = [];
        $(".required").each(function(){
            if ($(this).val().trim() == "") emptyFields.push($(this).data("name"));
        }
        if (emptyFields.length != 0) {
            e.preventDefault();
            var message = "You forgot these fields: " + emptyFields.join(",");
            alert(message);
        }
    }

    $(":submit").click(validate);
})

This ought to cover any additional fields or really any additional pages that require this sort of validation.


I have some notes on how you structured this, note that some are a bit Python specific.

Your attribute names should not have the class name in them. It's redundant because you'll always be accessing them from something else, ie. Item.name is simpler than Item.itemname. Also you shouldn't use double underscores to prefix the name. A Pythonic style is to use a single underscore to denote an attribute that should be treated as private and not directly accessed. But very often it's Python style to leave out any concept of setters and getters, instead just access them directly. Like this:

>>> apple = Item('apple', 7.8)
>>> print apple.name
apple
>>> apple.price = 7
>>> print apple.price
7

You could almost not have Item be a class, but your spec seems to require it so I wont suggest you change that.

Also you misspelled newitemprice as newitemprcie. You managed to make it consistent between the two (by copy pasting I assume) but keep an eye on little errors like that. They'll only cause headaches.

Your Cart is a little underdeveloped. All it does is subclass dict and then return itself when ShowCart is called? This is redundant since the Cart itself could be passed to places it's needed.

You mentioned in a comment you want to be able to do Cart['apple'] to get the count of apples, but an easier way to do that is to just have an attribute of cart that's a dictionary. For example:

class Cart:
    def __init__(self, items):
        self.items = items

Cart({"apple": 5, "pear": 7})
Cart.items["apple"]

This is a much clearer way to get at the items without needing to inherent a dictionary into the Cart itself.

Maybe the cart could more directly manage items so you could have useful features like counting how many of each item is there. As it stands, you don't do anything special with a cart that has multiple instances of the same item. Why not keep track of that so you could easier print to the user what they have, rather than expecting them to just read a list of items.

While we're on it. Why not implement a method or two to print the contents of a Cart nicer? Maybe the Cart should be where the user actually purchases things? You need to think about what a cart does, and create those functions.

Why make cartlist a dictionary? You should make it a list instead. You can still do cartlist.remove(cart_to_remove). Also don't name it cartlist especially if it's not a list, carts is better. Types don't need to be in names unless it's hard to tell what type a variable is.


I think this is mistake:

self.iterable = list(iterable)

It requires loading the entire iterable into memory. Being able to avoid this and work with large collections efficiently is one of the big benefits of iterators.
It won't work on non-ending iterators like itertools.count()

If instead, you make an iterator from the iterable, you can avoid both those problems and simplify your code by depending on the iterator's own StopIteration exception:

class myEnumerate:
    def __init__(self, iterable):
        self.iterable = iter(iterable)
        self.index = -1

    def __iter__(self):
        return self

    def __next__(self):
        self.index += 1
        return self.index, next(self.iterable)

// this now works:

from itertools import count, islice
c = count()
for (i, ch) in islice(myEnumerate(count()), 1, 10):
    print(i, ch)


The code looks pretty good. There are only a few suggestions I have about it.

While it doesn't depend on Babeljs, it appears that Array.from() is part of the Ecmascript 2015 (6th edition) Standard1. So if you really wanted to make this code ES-5 compliant, you would need to remove that. For example, this example suggests using .slice.call:

So instead of

Array.from(selectorList)
  .forEach(function (selector) {

You would need to do something like

[].slice.call(selectorList)
    .forEach(function (selector) {

The naming of selectorList is a little misleading, since querySelectorAll returns a NodeList. A more appropriate name would be selectedNodes or something similar. Similarly, selector is misleading, since it is typically passed a DOMNode object.

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Specifications


[This answer comes a couple of years after the question was posted. The Community User keeps bumping the question because there is an answer without upvotes, not worth up-voting. It also has 2k+ views. So maybe a good review is in order.]

This priority queue implementation has an \$O(1)\$ push operation, and an \$O(n)\$ pop operation, but with \$n\$ being the size of the container (500) rather than the number of elements in the queue. However, the push complexity increases once there have been 500 elements in the queue, because the two data arrays will be reallocated when pushing more elements. Note that this is not 500 elements currently in the queue, but 500 elements having gone through the queue. Used array elements are not re-used.

Code review:

Variable names are excellent: it is clear what they mean without any comments.

The class has no documentation. Documentation on how to use a class or a function is as important (IMO) as the code working correctly.

There are a few statements that could be more concise: NaN*ones(500,1) is the same as NaN(500,1). thePQueue.valueList{500} = [] is better written as thePQueue.valueList = cell(1,500). thePQueue.nElements is set to 0 twice in the constructor.

The constructor PQ2() could take an optional input argument specifying how many elements one expects will go through the queue, to give the queue an appropriate initial size.

Timing:

This is a very fast implementation of a priority queue (as long as it is not used for too long, because performance degrades after 500 elements have been pushed. I wrote the following script to time it, and try to improve on it:

t_push = 0;
t_pop = 0;
for jj=1:100
   pq = PQ2;
   tic;
   for ii=1:500
      pq.push(ii,randi(10000));
   end
   t_push = t_push + toc;
   tic;
   for ii=1:500
      pq.pop;
   end
   t_pop = t_pop + toc;
end
t_push
t_pop

Sure, it's a little simplistic, but so be it. It pushes 500 elements, then pops 500 elements. This is repeated, with a fresh queue, 100 times. The OP's priority queue implementation gives me t_push = 0.1822 and t_pop = 0.2930. I could not make this significantly faster.

I compared this against the classical \$O(\log n)\$ priority queue as implemented in the link provided by the OP. That one gave t_push = 5.9049 and t_pop = 28.1718. No wonder OP thinks it's slow. That implementation has many problems, one is that it tries to do memory management. If we let MATLAB do the memory management (MATLAB will double the storage when appending elements to an array, and does so much more efficiently than this user's code), and store the priorities in a numeric array rather than a cell array, I get t_push = 0.5715 and t_pop = 1.8866, 10 times faster for pushing and 15 times faster for popping. But still nowhere near the speed of the code in this question.

Next, I increased the size of the queue to 5000, and changed the test code to run 10 iterations of pushing and popping 5000 elements. Push times remained similar for both queues, and pop times increased to 0.9861 for OP's code, and 2.8028 for the other implementation. Here one can see the \$O(n)\$ vs \$O(\log n)\$ characteristic of these two implementations. But it is clear that n times a small number is much less than log(n) times a large number.

For very large queues, with millions of elements, I'd stick to one of the other solutions proposed in the Stack Overflow question (the built-in Java queue or a C++ MEX-file implementation).


Potential bug #1

The problem of using a class variable mIteratedIndex that is modifiable in every new Iterator instance created is simply, multiple such instances cannot iterate through the contents reliably.

Potential bug #2

This is also related to Iterator in the hasNext() method: calling it twice without a next() effectively skips one element. Usually, the iteration state should not be modified when doing a hasNext(), but you have a index++ inside it.

Potential bug #3

The other problem with having index++ inside the hasNext() is that callers cannot reliably retrieve the next() element without calling hasNext() first.

Illustrating all bugs

public static void main(String[] args) {
    BucketArray<String> instance = new BucketArray<>(String.class, 3);
    instance.addAll("first", "middle", "last");
    Iterator<String> i1 = instance.iterator();
    i1.hasNext();
    i1.hasNext();
    System.out.println(i1.next());
    Iterator<String> i2 = instance.iterator();
    i2.hasNext();
    System.out.println(i2.next());
    System.out.println(i2.next());
    i2.hasNext();
    System.out.println(i2.next());
}

Output:

middle
first
first
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

i1.hasNext() has to be called before i1.next(), else there will be an ArrayIndexOutOfBoundsException: -1 error. When i1.hasNext() is called twice in succession, "middle" is returned from calling i1.next(), skipping the first element.

When we have a new i2 Iterator, it starts from where i1 left off, which bizarrely returns "first" since that was stored as the final element of the internal array - is this expected? Regardless, calling i2.next() twice returns the same value, when it shouldn't. Finally, calling the pair of hasNext()/next() methods triggers the ArrayIndexOutOfBoundsException: 3 error as i2 would have iterated past the contents of the array.


Counting the number of continuous palindromic substrings

First off, you should organize your code by using functions as it will help you simplify it and is better for reusability and testing. As I see it, you can use a function to generate the various substrings of the word, and a function to count the amount of palindromes in a string. You could also organize the remaining top-level code in a main() function and guard it with if __name__ == '__main__'::

def palindrome(s):
    if s==s[::-1]:
        return True

def substrings(letters):
    subs = []
    for i in range(len(letters)):
        for k in range(i+1,len(letters)+1):
             sub=('').join(letters[i:k])
             subs.append(sub)
    return subs

def count_palindromes(word):
    letters=[]
    psub=[]
    for l in word:
        letters.append(l)
        if l not in psub:
            psub.append(l)

    for sub in substrings(letters):
         if palindrome(sub) and sub not in psub:
             psub.append(sub)

    return len(psub)

def main():
    noTest=int(input())
    s=[]
    for _ in range(noTest):
        s.append(input())

    count=[]
    for word in s:
        count.append(count_palindromes(word))

    for c in count:
        print (c)

if __name__ == '__main__':
    main()

Now we can start tidying things up. For starter, apply PEP8 to make it look like other Python code and simplify main() as we don't need all those intermediate lists anymore:

def main():
    tests_count = int(input())
    for _ in range(tests_count):
        print(count_palindromes(input()))

Apply the same kind of improvements to the palindrome function:

def is_palindrome(string):
    return string == string[::-1]

Second, use a better datastructure than lists in count_palindromes as checking l not in psub or sub not in psub is an \$\mathcal{O}(n)\$ operation compared to \$\mathcal{O}(1)\$ for the same kind of check in a set. Besides, sets guarantee that each element added in is only added once, so you can get rid of these checks yourself.

def count_palindromes(word):
    palindromes = set(word)
    for sub in substrings(word):
        if is_palindrome(sub):
            palindromes.add(sub)
    return len(palindromes)

Note that I passed the whole word to substrings instead of a list of letters, as len or slicing ([i:k]) would work on both. Also, you could use the filter builtin instead of an explicit check which will allow you to write:

def count_palindromes(word):
    palindromes = set(word)
    palindromes.update(filter(is_palindrome, substrings(word)))
    return len(palindromes)

Lastly, you can optimize substring generation by:

getting rid of the join call as you already have strings when slicing a string;
using a generator rather than building a list and appending to it.

def substrings(word):
    word_length = len(word)
    for i in range(word_length):
        for k in range(i + 1, word_length + 1):
            yield word[i:k]

Full code:

def substrings(word):
    word_length = len(word)
    for i in range(word_length):
        for k in range(i + 1, word_length + 1):
            yield word[i:k]

def is_palindrome(string):
    return string == string[::-1]

def count_palindromes(word):
    palindromes = set(word)
    palindromes.update(filter(is_palindrome, substrings(word)))
    return len(palindromes)

def main():
    tests_count = int(input())
    for _ in range(tests_count):
        print(count_palindromes(input()))

if __name__ == '__main__':
    main()

You could also use the itertools module and adapt a bit the pairwise recipe to make substrings a bit more efficient:

import itertools

def substrings(string, size):
    iterators = itertools.tee(string, size)
    substrings_generator = (
            itertools.islice(i, start, None)
            for start, i in enumerate(iterators)
    )
    return map(''.join, zip(*substrings_generator))

def is_palindrome(string):
    return string == string[::-1]

def count_palindromes(word):
    palindromes = set(word)
    for sub_size in range(2, len(word) + 1):
        palindromes.update(filter(is_palindrome, substrings(word, sub_size)))
    return len(palindromes)

def main():
    tests_count = int(input())
    for _ in range(tests_count):
        print(count_palindromes(input()))

if __name__ == '__main__':
    main()


Maybe this one : #^[^-=+*\w]{2}\s*#um (that is ~500% faster than yours):

<?php
$list = '
== Category one
→ feature 1
++ feature 2
-- feature 3
==-
! feature 4
% feature 5
** feature 6
feature 7';

$list = preg_replace('#^[^-=+*\w]{2}\s*#um', '', $list);
print_r($list);

Whose output is:

== Category one
feature 1
++ feature 2
-- feature 3
==-
feature 4
feature 5
** feature 6
feature 7

Subsidiary question

You can complete the regexp #^[^-=+*\w]{2}\s*#um by the regexp
#^([-=+*])(?!\1|\s)#um to refuse +|-|=|* without whitespace after.

It is possible to combine the two regexps but at the expense of performance.

<?php
function printResult($label, $list, $start, $end) {
  printf(
    "%s: %F s\n%s\n\n",
    $label,
    $end - $start,
    print_r($list, true)
  );
}

$list = '== Category one
→ feature 1
++ feature 2
-- feature 3
==-
! feature 4
% feature 5
** feature 6
feature 7
-line1
-- line2';

// Case 1: regrouping the regexps
$time_start = microtime(true);
$list = preg_replace('#^[^-=+*\w]{2}\s*|^([-=+*])(?!\1|\s)#um', '', $list);
$time_end = microtime(true);
printResult('With one regexp', $list, $time_start, $time_end);

// Case 2: a faster way
$time_start = microtime(true);
$list = preg_replace('#^[^-=+*\w]{2}\s*#um', '', $list);
$list = preg_replace('#^([-=+*])(?!\1|\s)#um', '', $list);
$time_end = microtime(true);
printResult('In two pass, a faster way', $list, $time_start, $time_end);

Whose output is:

With one regexp: 0.000151 s
== Category one
feature 1
++ feature 2
-- feature 3
==-
feature 4
feature 5
** feature 6
feature 7
line1
-- line2

In two pass, a faster way: 0.000024 s
== Category one
feature 1
++ feature 2
-- feature 3
==-
feature 4
feature 5
** feature 6
feature 7
line1
-- line2

Note: preg_replace replaces the overall catch, therefore it is useless to try to capture the full line.