texts:
I have a data synchronisation operation that is observing a database. This is a fairly key piece of code for the system, so I want to make sure I handle the concurrency correctly.

The problem

The operation manipulates sync state flags in the database and should
have zero concurrency
The operation must be cancellable
The operation should repeat an additional time if signals are received while it is running

Behavior

The service is started in response to changes to the underlying data
The service is started in response to changes in connectivity
The service is started periodically

Current design

    bool syncRequired = false;

    private async void StartSynchronisation()
    {
        // the cancellation token operates as the flag to indicate if the operation is running
        if (this.cancellationTokenSource != null)
        {
            syncRequired = true;
            return;
        }

        try
        {
            this.cancellationTokenSource = new System.Threading.CancellationTokenSource();

            // stop the time that periodically prompt the operation
            this.synchronisationTimer.Stop();

            bool dataWasSynchronised = false;

            // Repeated synchronisation and replication until no updates are made
            do
            {
                syncRequired = false;
                // Only attempt synchronisation if the service is actually available
                if (this.connectivityMonitor.IsServiceAvailable)
                {
                    dataWasSynchronised = await DoSynchronisation().ConfiguredAwait(false);
                }
            }
            while (dataWasSynchronised || syncRequired );
        }
        catch (Exception ex)
        {
            // handle exception using injected policy handler
        }
        finally
        {
            this.synchronisationTimer.Start();
            this.cancellationTokenSource.Dispose();
            this.cancellationTokenSource = null;
        }
    }

I bring you this code because it is missing any thread synchronisation and it probably needs it. It currently relies on the atomicity of read/writes to a reference (cancellationTokenSource) and bool (syncRequired) but this doesn't cover anything really. As a critical piece of code, I don't want to miss an event and need to wait for the next timer interval to start the operation. It will continue working, but our test department won't like it. My issue is, thread concurrency isn't my strongest area and I'm already burned out on this feature - I'm struggling to reason about it without tying my head in knots.

What synchronisation primitives do I need to make sure all events are handled as intended? Is there a more favourable pattern using concurrent queues or reactive extensions that I can throw in here? I have been considering some use of Reactive Extension's BehaviorSubject<T>.


texts: Reading input fast in Java for competitive programming

texts:
I have been solving problems on Timus Online Judge. In the beginning, I didn't worry much about I/O operations, so I just took some code from the internet and focused more on the logic. But after going through the helper class that I was using, I created my own class.

This is the original stuff:

import java.io.InputStream;

public class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() throws Exception {
        if (curChar >= numChars) {
            curChar = 0;
            numChars = stream.read(buf);
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() throws Exception {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() throws Exception {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
}

This is what I have written now:

import java.io.IOException;

public class IOUtils {

    public static String readString() throws Exception {
        int c = System.in.read();
        while (isSpaceChar(c))
            c = System.in.read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = System.in.read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public static int readInt() throws IOException {
        int i = 0;
        int c = System.in.read();
        while (isSpaceChar(c))
            c = System.in.read();
        int sign = 1;
        if (c == '-') {
            sign = -1;
            c = System.in.read();
        }
        do {
            i = i * 10 + c - '0';
            c = System.in.read();
        } while (!isSpaceChar(c));
        return i * sign;
    }

    public static int readPositiveInt() throws IOException {
        int i = 0;
        int c = System.in.read();
        while (isSpaceChar(c))
            c = System.in.read();
        do {
            i = i * 10 + c - '0';
            c = System.in.read();
        } while (!isSpaceChar(c));
        return i;
    }

    private static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == -1;
    }
}

Is my code any better than the original? Could someone look into it and let me know about the performance and the pitfalls?


texts: Return a string without the first two characters

texts:
I'm new to Java and am trying to solve a scenario.  Even though I've succeeded and it works, I've just wondered if there was a more practical way of doing this task.  Is there a quicker or more efficient way of solving the task, or is this fine?

  Task:

  Given a string, return a version without the first 2 chars. Except
  keep the first char if it is 'a' and keep the second char if it is
  'b'. The string may be any length.

deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"

Code:

public String deFront(String str) {
  if(str.length() > 0) {
    if(str.substring(0,1).equals("a") && !str.substring(1,2).equals("b")) {
      return str.substring(0,1) + str.substring(2,str.length());
    } else if(str.substring(1,2).equals("b") && !str.substring(0,1).equals("a")) {
      return str.substring(1,2) + str.substring(2,str.length());
    } else if(str.substring(0,1).equals("a") && str.substring(1,2).equals("b")) {
      return str;
    } else {
      return str.substring(2,str.length());
    }
  } else {
    return "";
  }
}


texts: Functional implementation of collecting objects into groups

texts:
Trying to write more functional Javascript with the underscore library. Any thoughts on how to improve this to be more functional than imperative? Also, any way to do this without mapObject?

The first of each pair is a "bucket" and the second is a value, I'd like to iterate over the information and get a unique list of what is in each bucket.

var a = [
  ['A',1],
  ['A',1],
  ['A',1],
  ['A',2],
  ['B',1],
  ['B',2],
  ['B',2],
  ['B',4],
  ['C',6],
  ['D',5]
];

//result should be:
//  {
//     A: [1,2],
//     B: [1,2,4],
//     C: [6],
//     D: [5]
//  }

_.chain(a)
 .groupBy(function (pair) {
    var group = pair[0];
    return group;
 })
 .mapObject(function (val, key) {
    var results = _.chain(val)
                   .map(function (pair) {
                     return pair[1]
                   })
                   .uniq()
                   .value();
    return results;
 })
 .value();


texts:
I have an array of some arbitrary int values; I want to find the array containing the sum of the past elements in the current index.

Example:

int[] myArray = new int[5]{ 5, 7, 8, 2, 6 };

I would attempt to:

myArray[0] = 5
myArray[1] = myArray[0] + myArray[currentIndex] = 5 + 7
myArray[2] = 5 + 12 + 8 and so forth till my finished array is:
[5, 12, 25, 44, 92]

I have 2 solutions, one in Java 7, and the other in Java 8, and I was wondering if it was possible to get critiqued on both of them, specifically on how to make the code more terse and efficient i.e. cutting out unnecessary steps or operations.

Java 7 (or language agnostic) solution:

public static int[] sumifyIn7(int[] array) {
    int length = array.length;
    for(int i = 1; i < length; i++) {
        int sumSoFar = 0;
        for(int j = 0; j <= i; j ++) {
            sumSoFar += array[j];
        }
        array[i] = sumSoFar;
    }
    return array;
}

Side-note: Am I correct in saying this solution is \$O(nlog(n))\$?

Java 8 solution:

I'm very unfamiliar with Java 8, and plan on getting up to date with it during the school year, but this is what I could put together, but I'm sure it could be improved based on how redundant it seems.

public static int[] sumifyIn8(int[] array) {
    int length = array.length;
    for (int i = 1; i < length; i++) {
        array[i] = Arrays.stream(Arrays.copyOfRange(array, 0, i + 1)).sum();
    }
    return array;
}

Test:

public static void main(String[] args) {
    System.out.println(Arrays.toString(sumifyIn8(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })));
    System.out.println(Arrays.toString(sumifyIn7(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })));
}

Test Results:

[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]

[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]


texts: Assistance requested to refactor a section of Typescript code for readability

texts:
Code
if (source.length > 0) {
    if (
        source[0].mandatory === true &&
        this.allInputs.documentsType !== "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    } else if (
        source[0].mandatory === false &&
        this.allInputs.documentsType === "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    }
} else {
    if (
        target[0].mandatory === true &&
        this.allInputs.documentsType === "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    } else if (
        target[0].mandatory === false &&
        this.allInputs.documentsType !== "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    }
}

All is working, the problem I have is that this code is not very readable. Can someone please help me refactor this?
Thanks


texts: Coding Challenge : Build Tower refactoring code is it necessary

texts:
In the interview you are asked to build a tower in a variable input e.g. n=3 .
The output should be as show below.
[
  '  *  ',
  ' *** ',
  '*****'
]

My solution is the following. Is this a good enough answer for the problem because I know people can solve it using Linq with less lines of code.
    public string[] PrintStairs(int n)
    {
        if (n == 1)
        {
            return new []{ " * " };
        }

        var result = new string[n];
        for (int row =0; row < n; row++)
        {
            var level = new StringBuilder();
            var midpoint = ((2 * n - 1) / 2);

            for (int col =0; col < 2 * n - 1; col++)
            {
                if((midpoint-row <= col) && (midpoint + row >= col))
                {
                    level.Append("*");
                }
                else
                {
                    level.Append(" ");
                }
            }
            result[row] = string.Concat(new string(level.ToString()));
        }
        return result;
    }

Linq Solution:
  public static string[] TowerBuilder(int nFloors)
  {
      return Enumerable.Range(1, nFloors).Select(i => string.Format("{0}{1}{0}", i == nFloors ? "" : new string(' ', nFloors - i), new string('*', 2 * i - 1))).ToArray();
  }


texts:
I have this Quicksort implementation that sorts arrays of int (not Integer). It has comparable performance to Java's DualPivotQuicksort, especially when the size of the range is below one million elements or so.
IntegerQuicksort.java
package net.coderodde.util;

import java.util.Arrays;
import java.util.Random;

public class IntegerQuicksort {

    public static void sort(int[] array) {
        sort(array, 0, array.length);
    }

    public static void sort(int[] array, int fromIndex, int toIndex) {
        if (toIndex - fromIndex < 2) {
            return;
        }

        int pivot = array[fromIndex];
        int leftPartitionLength = 0;
        int rightPartitionLength = 0;
        int index = fromIndex;

        while (index < toIndex - rightPartitionLength) {
            int current = array[index];

            if (current > pivot) {
                ++rightPartitionLength;
                int tmp = array[toIndex - rightPartitionLength];
                array[toIndex - rightPartitionLength] = current;
                array[index] = tmp;
            } else if (current < pivot) {
                int tmp = array[fromIndex + leftPartitionLength];
                array[fromIndex + leftPartitionLength] = current;
                array[index] = tmp;

                ++index;
                ++leftPartitionLength;
            } else {
                ++index;
            }
        }

        sort(array, fromIndex, fromIndex + leftPartitionLength);
        sort(array, toIndex - rightPartitionLength, toIndex);
    }

    private static final int SIZE = 500_000;
    private static final int FROM = 100;
    private static final int TO = SIZE - 100;

    public static void main(final String... args) {
        long seed = System.nanoTime();
        Random random = new Random(seed);
        int[] array1 = getRandomArray(SIZE, -1000, 1000, random);
        int[] array2 = array1.clone();

        System.out.println("Seed: " + seed);
        long startTime = System.nanoTime();
        sort(array1, FROM, TO);
        long endTime = System.nanoTime();

        System.out.printf("IntegerQuicksort.sort in %.2f milliseconds.\n",
                          (endTime - startTime) / 1e6);

        startTime = System.nanoTime();
        Arrays.sort(array2, FROM, TO);
        endTime = System.nanoTime();

        System.out.printf("Arrays.sort in %.2f milliseconds.\n",
                          (endTime - startTime) / 1e6);

        System.out.println(Arrays.equals(array1, array2));
    }

    public static int[] getRandomArray(int size,
                                       int minimum,
                                       int maximum,
                                       Random random) {
        int[] array = new int[size];

        for (int i = 0; i < size; ++i) {
            array[i] = random.nextInt(maximum - minimum + 1) + minimum;
        }

        return array;
    }
}

Some performance figures:

Seed: 347202193766632
IntegerQuicksort.sort in 61.21 milliseconds.
Arrays.sort in 131.72 milliseconds.

I am well aware that the current pivot selection rule will make the algorithm degrade to quadratic running-time on sorted input; please ignore this, I wanted to experiment a little bit.
So, is there room for improvement? Naming? Coding style? Please, tell everything that comes to mind.


texts:
Description

  You and your friends are seizing another summer day, passing around the frisbee in the park. You have the most fun when the game is fair, so as much as possible, you would all like to ensure that everyone receives the disc an equal number of times. You also like to challenge yourselves, so when possible, you'll go for the longest pass you can throw.

  So each friend will throw according to the following rules:

  Pass to the friend who has held the frisbee the least amount of times.
  In the event of a tie, pass to the furthest among these friends.
  If there's also a tie for furthest, pass to the one of these friends with the lowest index.

  Given an array friends containing info about each player (where they're standing and how far they can throw), as well as the index of the starting player and the total number of passes, your task is to find which player will be holding the frisbee after all the passes are complete.

  NOTE: Because you and your friends are really good at frisbee, it's safe to assume that all passes will be completed successfully; none of you will fumble a throw or catch.

Example

For friends = [[152, 213, 276], [274, 259, 151], [40, 57, 130], [203, 87, 189], [43, 182, 163]], numberOfPasses = 19, and startingPlayer = 4, the output should be frisbees(friends, numberOfPasses, startingPlayer) = 4

Visual example

Constraints

2 ≤ friends.length ≤ 5000
friends[i].length = 3
0 ≤ friends[i][0] ≤ 400
0 ≤ friends[i][1] ≤ 400
0 ≤ friends[i][2] ≤ 500
0 ≤ numberOfPasses ≤ 2500
0 ≤ startingPlayer < friends.length

Code

def make_player_throws_list(friends):
    distance = lambda f, s: (f[0] - s[0])**2 + (f[1] - s[1])**2
    return [
        [
            (i, distance(f, s))
            for i, f in enumerate(friends)
            if distance(f, s) <= s[2]**2 and f != s
        ]
        for s in friends
    ]

def frisbees(friends, number_of_passes, starting_player):
    frisbee_held = {i: 0 for i in range(len(friends))}
    player_possible_throws_list = make_player_throws_list(friends)

    for _ in range(number_of_passes):
        frisbee_held[starting_player] += 1
        starting_player = min(
                                player_possible_throws_list[starting_player],
                                key = lambda x: (frisbee_held[x[0]], -x[1], x[0])
                             )[0]
    return starting_player


texts: Optimize Cython code with np.ndarray contained

texts:
Can someone help me further optimize the following Cython code snippets? Specifically, a and b are np.ndarray with int value (range(256)) in them.  They are one dimension arrays with dynamic length.  resultHamming is a one-dimension array with float value in it (dynamic length).  bits is an int list (size 256).

The function is to compare two dynamic length bit vector, and return a similarity value as the distance of the two, where the length of each vector is a multiple of 2048-bit (256 bytes). I want to find the best match between these two bit vector by comparing each 2048-bit block, where each bit vector is represented as ndarray (read the bit sequence byte by byte, thus each position is range from 0 to 2^8 = 256). Rule for matching is to find global minimum distance between all block pairs and allow one block in A to be matched with more than one block in B if they have smaller distance. Always compare the smaller size vector against the larger one.

The following code assumes b vector is smaller.  We can limit resultHamming to be smaller than size of numArrayB and only record numArrayB smallest distance value, but need to track the current size when inserting new value into it. Even with current case (record all the pairwise distance), we actually know the final size of resultHamming at the beginning.

def compare(a, b):
    cdef double dis, hammingTotal = 0
    cdef int numArrayA = int(a.size/256)
    cdef int numArrayB = int(b.size/256)
    cdef int i, j, k, l, index
    bits = list(xrange(256))
    # Prepare a bit number table for fast query
    for l in xrange(256):
        # nnz() counts the number of 1s in value
        bits[l] = nnz(l)

    resultHamming = []
    for i in xrange(numArrayB):
        # Count the number of 1-bits in i-th block of B
        onesB = sum(bits[b[k+256*i]] for k in xrange(256))
        for j in xrange(numArrayA):
            # Count the number of 1-bits in j-th block of A
            onesA = sum(bits[a[k+256*j]] for k in xrange(256))
            # Calculate the hamming distance between i-th block of B and j-th block of A
            hammingCur = sum(bits[b[i*256+k] ^ a[j*256+k]] for k in xrange(256))
            dis = (hammingCur) / (onesA + onesB)
            # Insertion current dis to resultHamming with sorted order
            k = len(resultHamming) - 1
            if dis >= resultHamming[-1]:
                resultHamming.append(dis)
            else:
                resulthamming.append(resultHamming[k])
                while k > 0 and resultHamming[k-1] > dis:
                    resultHamming[k] = resultHamming[k-1]
                    k -= 1
                resultHamming[k] = dis

    # Extract k smallest distance from the distance array
    for k in xrange(numArrayB):
        hammingTotal += resultHamming[k]
    return round(hammingTotal/(numArrayB), 3)


texts: Rvalue copy and and assignment for secure array class

texts:
I have a C++03 library with lots of classes. I'm interested in trying to take advantage of Rvalues and move semantics under C++11 for two or three critical classes. Once of the critical classes is a SecBlock, which is effectively a secure array class. It has a secure allocator and deallocator, and its used nearly everywhere.

SecBlock looks like so, where T might be a byte or an int:

template <class T, class A = AllocatorWithCleanup<T> >
class SecBlock
{
   ...
private:
    A m_alloc;
    size_type m_size;
    T *m_ptr;
}

If I am reading Thomas Becker's "C++ Rvalue References" treatise correctly, I can use a simple swap because SecBlock does not have a base class (no need for Base(std::move(rhs)):

template <class T, class A = AllocatorWithCleanup<T> >
class SecBlock
{
   ...

#if CXX11_AVAILABLE
    SecBlock(SecBlock&& t)
    {
        std::swap(*this, t);
    }
    SecBlock& operator=(SecBlock&& t)
    {
        if(this != &t)
            std::swap(*this, t);
        return *this;
    }
#endif

private:
    A m_alloc;
    size_type m_size;
    T *m_ptr;
}

We guard on CXX11_AVAILABLE because the library is a C++03 library at heart.

It's probably obvious I have some open questions. For instance, do I have to guard for self assignment in operator=? (I suspect not, but I think its best to show the code and take the comments).

I'm also interested in knowing if a derived class must implement the semantics also, even if they add no members.

Is the code above correct, or are there gaps that need to be addressed? If there are gaps, what are they?


texts: Designing a public facing Java interface for future extensibility (API evolution)

texts:
I develop an in-house Java framework. I provide an interface so that my end users can provide their own custom implementation (i.e. plugin/SPI).

public interface SomePlugin {
    SomeResponse doSomething(SomeRequest request);
}

There are a number of small configurations to be made, some required and some optional. For example: plugin name, response formatter.

My initial interface looked like this (V1):

public interface SomePlugin { // V1
    String getName();
    default SomeFormatter getResponseFormatter() { return new DefaultFormatter(); }
    SomeResponse doSomething(SomeRequest request);
}

Over time I learned this is not easily extensible, without breaking existing user implementations or abusing the default keyword. Reasons:

What if I want to receive another config value, e.g. plugin description?
What if I need to provide an alternative way to receive response formatting?

V2

Now, this blog post suggests that I may use "argument objects" to better achieve this.

  It is generally a bad idea to have non-void methods in SPIs as you will never be able to change the return type of a method again. Ideally, you should have argument types that accept “outcomes”.

public interface SomePlugin { // V2
    void configure(SomeConfigurator config);
    SomeResponse doSomething(SomeRequest request);
}

public interface SomeConfigurator {
    void setName(String name);
    void setDescription(String description);
    void useFormat(SomeFormatter formatter);
    void useFormat(SomeParser parser, SomeOutputBuilder builder);
}

public class MyPlugin { // Usage example
    void configure(SomeConfigurator config) {
        config.setName("Test plugin");
        config.useFormat(new MyFormatter());
    }
    ...
}

This nicely solves the extension/evolution problem that my initial design (V1) had.

Deprecation and addition are easier.
I can now receive multiple objects at once, i.e. parser and builder, without creating a wrapper object.
I can overload some methods because what was a return type is now a parameter.

I lose the required-ness of mandatory configs, i.e. users may forget to provide name and it will still compile. But I think this is an acceptable trade-off for maintainability, with help of Javadoc and runtime checks.

V3

One concern on the concept of "argument objects" with void return type is that it is a foreign idea. When I showed this prototype to my end users, they didn't grasp how to use it unless an example was provided. This leads me to consider:

public interface SomePlugin { // V3
    SomeConfig getConfig();
    SomeResponse doSomething(SomeRequest request);
}

public final class SomeConfig {
    private String name;
    private String description = "";
    private SomeFormatter formatter = new DefaultFormatter();
    private SomeParser parser;
    private SomeOutputBuilder builder;
    ... getters and setters ...
}

public class MyPlugin { // Usage example
    SomeConfig getConfig() {
        SomeConfig config = new SomeConfig();
        config.setName("Test plugin");
        config.useFormat(new MyFormatter());
        return config;
    }
    ...
}

Now, this feels more like a "traditional" Java and should be more intuitive to my end users. I still get the benefits of V2. It's unlikely that I'd have to worry about deprecating or replacing getConfig() itself.

One small con: SomeConfig is now more verbose with all getters and setters, compared to SomeConfigurator in V2 which looked like a clean "header file". Despite this, I feel like V3 is the way to go.

Does my reasoning make sense? Are there any reasons to favor V2 over V3, or do you have other approaches to suggest? Thanks!


texts:
I have a few servers to fix that repeatedly get their nginx.conf file messed up due to a rogue deploy script.

These are the three sed commands I'm using to fix at present:

sed -i '' 's/^\([[:blank:]]*\)#\([[:blank:]]*\)server_names_hash_bucket_size/\1server_names_hash_bucket_size/g' nginx.conf

The first finds any kind of blank space at the start of a line followed by a pound symbol and the string server_names_hash_bucket_size. Then it replaces it with the original blank space (to honour any indentations) and the string without the pound.

sed -i '' '/^\([[:blank:]]*\)server_names_hash_bucket_size/s/[0-9]//g' nginx.conf

The second gets rid of any numbers:

sed -i '' '/^\([[:blank:]]*\)server_names_hash_bucket_size/s/;/64;/g' nginx.conf

The third finds the semi colon and replaces it with the necessary value 64;

I'm currently testing this in terminal OSX, but ultimately will be used on Linux machines.

Does anyone know how to tidy this up and can point out any potential Linux gotchas with sed?


texts:
An Atbash cipher is a simple substitution cipher wherein a key is used to determine what letters to swap, for example:

Original alphabet: abcdefghijklmnopqrstuvwxyz
Substitute (key):  zyxwvutsrqponmlkjihgfedcba
Original message:  hello world
Altered message:   svool dliow

In my program, I get the key by printing the original letter, and then getting the letter that is to substitute it, and adding it to a key string, for example:

a = <user input>
b = <user input>
c = <user input>
...

Here is the simple code that I use for it:

std::cout << "Key:\n";
std::string key;

for(int i = 0; i <= 25; i++){
    std::cout << static_cast<char>('a' + i) << " = ";
    char inputChar;

    std::cin >> inputChar;
    key += inputChar;

    std::cin.ignore();
    std::cin.clear();
    std::cout << std::flush;
}

How can I improve this code?


texts: Copy object properties without using many if statements

texts:
I have two class:

InputForm.java

public class InputForm {
    private String brandCode;
    private String caution;

    public String getBrandCode() {
        return brandCode;
    }

    public void setBrandCode(String brandCode) {
        this.brandCode = brandCode;
    }

    public String getCaution() {
        return caution;
    }
    public void setCaution(String caution) {
        this.caution = caution;
    }
}

CopyForm.java

public class CopyForm {
    private boolean brandCodeChecked;
    private boolean cautionChecked;

    public boolean isBrandCodeChecked() {
        return brandCodeChecked;
    }

    public void setBrandCodeChecked(boolean brandCodeChecked) {
        this.brandCodeChecked = brandCodeChecked;
    }

    public boolean isCautionChecked() {
        return cautionChecked;
    }

    public void setCautionChecked(boolean cautionChecked) {
        this.cautionChecked = cautionChecked;
    }
}

I want to copy values from an InputForm to another if its corresponding property in CopyForm is true.
This is what I do:

if(copyForm.isBrandCodeChecked()) {
    inputForm.setBrandCode(otherInputForm.getBrandCode());
}
if(copyForm.isCautionChecked()) {
    inputForm.setCaution(otherInputForm.getCaution());
}

The problem is I have many many properties. Writing many if statements seems ugly and bad programming practice.
How to solve it? (I know reflection is not a good choice so I don't think about it)


texts: Fastest fill memory with specified 64-bit value

texts:
I need to fast fill a memory block in C#, so I wrote something like this (in Free Pascal Compiler + Lazarus in 64 bit mode):

//  ECX = Ptr64
//  EDX = Count
//  R8  = Value

PROCEDURE Fill64 (VAR Ptr64; Count: QWord; Value: QWord);
BEGIN
  ASM
    PUSH    RDI
    MOV     RDI, RCX    // Destination Index = Ptr64
    MOV     RAX, R8     // Accumulator = Value
    MOV     RCX, RDX    // Counter Register = Count
    TEST    RCX, RCX    // If RCX is 0, set ZF (zero flag)
    JZ      @Exit       // Exit if ZF is set
    REP     STOSQ       // Fill memory using 64 bit value from RAX register
  @Exit:
    POP     RDI
  END;
END;

And I use it from C#:

[DllImport ("MemUtil64.dll", EntryPoint = "Fill64", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void Fill64 (void* ptr, ulong count, ulong value);

If this code okay, and fastest possible?


texts:
I have a method to replace URL parameters in an URL. It receives url as mandatory parameter and prefix and/or hash as optional parameters. Examples:

url_replace( '/news?b=2', { b: nil } )                     # => '/news'
url_replace( '/news?b=2', { b: 3 } )                       # => '/news?b=3'
url_replace( '/news?a=b', '/bar' )                         # => '/bar?a=b'
url_replace( '/news?a=b&c=d', '/bar', c: nil )             # => '/bar?a=b'

The method:

def url_replace( target, *args )
  uri = URI.parse(URI.escape target)
  if hash = args.last.kind_of?(Hash) && args.last
    query = uri.query ? CGI.parse(uri.query) : {}
    hash.each do |k,v|
      v ? query[k.to_s] = v.to_s : query.delete(k.to_s)
    end
    uri.query = query.any? ? query.map{|k,v| "#{CGI.escape k.to_s}=#{CGI.escape Array(v).join}"}.join('&') : nil
  end
  prefix = args.first.kind_of?(String) && args.first
  uri.path = CGI.escape(prefix)  if prefix
  CGI.unescape(uri.to_s)
end

I would like some refactoring or speed optimizations.

Okay, here's the code I ended up with:

def url_replace( target, *args )
  uri = URI.parse(URI::DEFAULT_PARSER.escape target)
  uri.path = CGI.escape(args.first)  if args.first.kind_of?(String)
  if args.last.kind_of?(Hash)
    query = uri.query ? CGI.parse(uri.query) : {}
    args.last.each{ |k,v| v ? query[k.to_s] = v.to_s : query.delete(k.to_s) }
    uri.query = query.any? ? URI.encode_www_form(query) : nil
  end
  CGI.unescape(uri.to_s)
end


texts:
I have implemented a program in C to crack passwords by generating all possible combinations of words ([A-Z][a-z]) up to the length of 5. While the program works, I would like to receive comments on the efficiency of the algorithm and other design decisions that would improve the code. The exercise is part of the course CS50 by Harvard.

I timed the program using unix's time and the time the program took to print all the combinations was

**real**    14m39.433s;
**user**    0m10.040s;
**sys**     0m36.356s.

CS50.h is a library developed for the course as training wheels for students. String (char*) and Bool are types defined in this library.

#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <cs50.h>

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Usage: ./crack hash\n");
        return 1;
    }

    string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char password[6] = "\0\0\0\0\0\0";
    string hash = argv[1];
    char salt[3];
    memcpy(salt, hash, 2);
    salt[2] = '\0';

    bool flag = false;
    int alphabet_len = 52;

    for(int i = 0; i < alphabet_len; i++)
    {
        password[0] = alphabet[i];
        password[1] = password[2] = password[3] = password[4] = '\0';
        if(!strcmp(hash, crypt(password, salt)))
        {
            flag = true;
            break;
        }
        for(int j = 0; j < alphabet_len; j++)
        {
            password[1] = alphabet[j];
            password[2] = password[3] = password[4] = '\0';
            if(!strcmp(hash, crypt(password, salt)))
            {
                flag = true;
                break;
            }
            for(int k = 0; k < alphabet_len; k++)
            {
                password[2] = alphabet[k];
                password[3] = password[4] = '\0';
                if(!strcmp(hash, crypt(password, salt)))
                {
                    flag = true;
                    break;
                }
                for(int l = 0; l < alphabet_len; l++)
                {
                    password[3] = alphabet[l];
                    password[4] = '\0';
                    if(!strcmp(hash, crypt(password, salt)))
                    {
                        flag = true;
                        break;
                    }
                    for(int m = 0; m < alphabet_len; m++)
                    {
                        password[4] = alphabet[m];
                        if(!strcmp(hash, crypt(password, salt)))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if(flag)
                        break;
                }
                if(flag)
                    break;
            }
            if(flag)
                break;
        }
        if(flag)
            break;
    }

    if(flag)
        printf("Password: %s\n", password);
    else
        printf("Password not found\n");
}


texts:
I've written a linked-list version of something like shared_ptr, which gets destroyed when the last copy of a pointer is destroyed.

Aside from the thread-unsafety, is it a fine implementation? Anything I could improve?

Also, what's the best way to extend it to make it work with HANDLEs, etc., without repeating (or limiting) myself unnecessarily, while avoiding excess verbosity (e.g. auto_<HANDLE, custom_deallocator<HANDLE> > is considered too verbose)?

template<typename T>
class auto_
{
    T *pValue;
    mutable const auto_<T> *pPrev, *pNext;

public:
    auto_()           : pValue(new T()),  pPrev(NULL), pNext(NULL) { }
    auto_(T *pValue)  : pValue(pValue),   pPrev(NULL), pNext(NULL) { }
    auto_(const T &v) : pValue(new T(v)), pPrev(NULL), pNext(NULL) { }
    auto_(const auto_<T> &o) : pValue(o.pValue), pPrev(&o), pNext(NULL) { o.pNext = this; }

    virtual ~auto_()
    {
        const auto_<T> *const pPrev = this->pPrev, *const pNext = this->pNext;
        if (pPrev != NULL) { pPrev->pNext = pNext; }
        if (pNext != NULL) { pNext->pPrev = pPrev; }
        if (pPrev == NULL && pNext == NULL) { delete this->pValue; }
        this->pPrev = this->pNext = NULL;
        this->pValue = NULL;
    }

    auto_<T>& operator=(const auto_<T>& other)
    {
        if (this != &other)
        {
            this->~auto_();
            this->pValue = other.pValue;
            this->pPrev = &other;
            this->pNext = other.pNext;
            if (other.pNext != NULL) { other.pNext->pPrev = this; }
            other.pNext = this;
        }
        return *this;
    }

    operator   T&() /*also const version*/ { return *this->pValue; }
    operator   T*() /*also const version*/ { return  this->pValue; }
    T* operator->() /*also const version*/ { return  this->pValue; }
    T& operator *() /*also const version*/ { return *this->pValue; }
};

Sample usage:

template<typename T>
T recurse(T value, int depth)
{
    if (depth > 0) { T result = recurse(value, depth - 1); return result; }
    else { return value; }
}

auto_<int> test()
{
    printf("Value: %d\n", *recurse(auto_<int>(10), 3));
    auto_<int> p1 = recurse<auto_<int> >(5, 3);
    printf("Value: %d\n", *p1);
    auto_<int> p2 = 3;
    p1 = p2;
    p2 = p1;
    return p2;
}


texts: Recursively pop the last node from a singly linked list

texts:
I am exploring different ways of implementing a linked list in Rust as a learning project.  In one particular place, I've got some code that works properly, but it makes multiple calls to unwrap--I am under the impression this is generally regarded as unsafe/poor style.  I'd like to make it better.

Here are some relevant definitions (I've omitted things not relevant to the question at hand, like push methods).  Note that it is a singly linked list, with owning next pointers.  Note that for clarity I've separate out the most interesting part into a separate section.

type NodePtr<T> = Option<Box<Node<T>>>;

struct Node<T> {
    data: T,
    next: NodePtr<T>,
}

pub struct LinkedList<T> {
    head: NodePtr<T>,
}

pub struct LinkedListError {
    kind: LinkedListErrorKind,
}

enum LinkedListErrorKind {
    Empty,
}

impl<T> LinkedList<T> {
    pub fn pop_back(&mut self) -> Result<T, LinkedListError> {
        if self.head.is_none() {
            Err(LinkedListError { kind: LinkedListErrorKind::Empty })
        } else {
            Ok(LinkedList::pop_last_node(&mut self.head))
        }
    }
    // definition for pop_last_node goes here...
}

In this particular implementation I'm experimenting with recursive functions, and this is my working version of pop_last_node.

fn pop_last_node(node_ref: &mut NodePtr<T>) -> T {
    match node_ref.as_ref().unwrap().next {
        None => {
            let old_tail = node_ref.take();
            old_tail.unwrap().data
        }
        _ => LinkedList::pop_last_node(&mut node_ref.as_mut().unwrap().next)
    }
}

This is working correctly, but since I'm doing this as a learning experiment, I wanted to see if I could cut down on the unwrap calls and use some more pattern matching.  This part of the experiment did not go as well.

Here is my attempt to do so.  Unfortunately, this version is much more verbose (and confusing!) than the original.  I especially don't like the "fall through out of this scope before you can do anything" part, but I haven't been able to come up with an idea on how to make it better.

fn pop_last_node(node_ref: &mut NodePtr<T>) -> T {
    {
        let next_node = match node_ref.as_mut() {
            None => panic!("Error handling will go here..."),
            Some(node_box) => &mut node_box.next,
        };
        match *next_node {
            None => {
                // fall through to code below
            },
            _ => {
                return LinkedList::pop_last_node(next_node)
            },
        }
    }
    // no sense converting this to a match--the "None" case was already checked above
    node_ref.take().unwrap().data
}

And that's where I am now.  The main question is this: Is there a less crazy way to write the pattern matching version?  Are there significant ways to improve the clarity or idiomatic-ness of either version?)


texts: Multiple Pandas Ranking Operations within a Loop - Better Optimization and Performance

texts:
I have implemented the following code which works as intended. However, I would like to improve my code in terms of performance and efficiency
Code in Question
import pandas as pd
from scipy.stats import norm

# data frame of length 40,000 rows, containing 25 columns
for indx in df.index:
    matrix_ordered_first = df.loc[indx].rank(method='first',na_option='bottom')
    matrix_ordered_avg = df.loc[indx].rank(method='average', na_option='bottom')
    matrix_ordered_first.loc[df.loc[indx] == 0] = matrix_ordered_avg
    matrix_computed = norm.ppf(matrix_ordered_first / (len(df.columns) + 1))
    df.loc[indx] = matrix_computed.T

A peak of the dataframe
Here is a part view of my dataframe df:
s            s1     s2           s3         s4      ...     s21        s23        s24  s25
0            NaN   5.406999   5.444658   4.640154  ...  4.633389   5.517850       NaN  6.121492
1            NaN   2.147866   1.758245   1.274754  ...  1.465129   1.200157       NaN  1.789203
2       2.872652   5.492498   2.547415   3.754654  ...  3.686420   1.540947  4.405961  1.715685
3            NaN  46.316837  27.197062  72.910797  ...       NaN  46.812153       NaN       NaN
4       1.365775   1.329316   1.852473   1.208155  ...  1.489296   1.313321  1.462968  1.249645

[5 rows x 25 columns]

Explanation
The code above is the part of a long python script in which this part runs slower than the other parts of the program. So what I am trying to do in the above code is to iterate over the data frame in a row-wise fashion. Then, for each row I have to perform a chain of pandas ranking operations followed by a statistical test equivalent to the "One-tail test”.Finally, transpose the matrix which will then be fed as a row for the data frame.
How can I improve this block of code in terms of efficiency, speed, and performance?
On a separate note, I not experienced in pandas so my code may seem amateur and for that I kindly seek your guidance.
Thank you so much in advance,


texts: Search algorithm to find a point from a given X value

texts:
I implement the following algorithm in order to find a point from a given X value in a sorted list with the same distance between each X values. Here's an example of my list content with a delta of 10:

(687;10)
(12;20)
(24;30)
(10125;40)
(0;50)
(111;60)
(-2;70)

The delta can be any float number;
The list can be up to 2.000.000pts so it needs to be as fast as possible;
I can't change the type of the points container (IPointList from ZedGraph).

Here's the code:

private ZedGraph.PointPair findPoint(ZedGraph.CurveItem curve, double x)
{
    if (curve.NPts == 1)
        return curve.Points[0];

    // Look for the min and max value
    double min = curve.Points[0].X;
    double max = curve.Points[curve.NPts - 1].X;

    double delta = curve.Points[1].X - min;

    // Prevent error if mouse is out of bounds.
    if (x > max)
        x = curve.Points[curve.NPts - 1].X;
    else if (x < min)
        x = curve.Points[0].X;

    double index = (x - min) / delta;
    int nearestIndex = (int)Math.Round(index, 0);

    if (nearestIndex < curve.NPts)
    {
        return curve.Points[nearestIndex];
    }
    return curve.Points[curve.NPts - 1];
}


texts: regex on a log file utilizing stacks and queue's in Java

texts:
This would be for a MUD client, which has elements of a sort of telnet bot.

Here, there's string parsing for a logged file for each line -- starting with the most recent.  Once a "trigger" is invoked the parser and actions should, for the sake of simplicity, stop.

I'm considering a records class for the triggers, but for now have the trigger and result in a map as below.

Not terribly concerned about resource efficiency, as this ultimately deals with text files, but more with extensibility and flexibility.

package net.bounceme.dur.files;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BotActions {

    private final static Logger log = Logger.getLogger(BotActions.class.getName());

    private Map<String, String> triggers = null;
    private boolean triggered = false;

    private BotActions() {
    }

    public BotActions(Map<String, String> triggers) {
        this.triggers = triggers;
    }

    private void pullTrigger(String line, Map.Entry<String, String> entry) {
        log.info(line);
        log.info(entry.toString());
    }

    private void triggers(String line) {
        Pattern pattern = null;
        Matcher matcher = null;

        Iterator<Map.Entry<String, String>> triggerEntries = triggers.entrySet().iterator();

        while (triggerEntries.hasNext() && !triggered) {
            Map.Entry<String, String> entry = triggerEntries.next();
            pattern = Pattern.compile(entry.getKey());
            matcher = pattern.matcher(line);
            if (matcher.matches()) {
                pullTrigger(line, entry);
                triggered = true;
            }
        }
    }

    public void everyLine(List<String> list) {
        ListIterator listIterator = list.listIterator(list.size());
        while (listIterator.hasPrevious() && !triggered) {
            triggers(listIterator.previous().toString());
        }
    }

}

I'm thinking really the text lines are a stack while the triggers are more a queue, although there's more flexibility on the triggers sequence.  But, just because of how the log file is initially parsed, those don't really seem options.

Regardless, interested in all comments.


texts:
Some might not think it's worth asking but I consider good function names quite important. I am not sure what should be the overridable function name in what I think is template design pattern. I am printing a report which has 3 types. There are lots of if-else which is confusing. I replace the long function with the polymorphic class hierarchy with base class below. I have than derived a class from each report type which overrides the PrintCustom() function but this doesn't strike me as a good name.

class CPrintReport
{
protected:
    CPrintReport(void);
public:
    virtual ~CPrintReport(void);

    // template function?
    void PrintReport();

protected:
    void PrintCommon();
    virtual void PrintCustom() = 0;
    virtual void PrintChart();

protected:
    CStringArray pstrData;

    CGraphCtrl * m_GraphCtrl;

};

PrintReport is the main function which is as following:

void CPrintReport::PrintReport()
{
    // prints thte common data
    PrintCommon();

    // prints specialized (verification,identification or regular type)
    PrintCustom();

    PrintChart();

}

Does this implement the template design pattern where PrintReport() is the template function?
As you can see from report, the first section prints common information, and the last section prints a chart, but the middle section varies based on what type of report it is. If it was procedural programming I would be calling this PrintVerificationData()and PrintIdentifcationData() depending on which type of report is being printed. How do we name such methods in the template design pattern so it makes better sense?
It turns out PrintChart is going to be different as well for each type. However, it is the same for 2 types (verification and identification) and different for regular print. Does this mean PrintChartVerifyIdentify() (being lazy but making a point) should reside in the base class so it can be shared, or should I use a visitor pattern or something?


texts: Selecting and copying event log entries for some machine

texts:
I have a PL/pgSQL function with erratic performance:

DECLARE
l RECORD;
events_for_machine integer;
before_event "PRD".events_log;
machines_ids integer[];
island_controller RECORD;
before_order "PRD".events_log;
before_detail "PRD".events_log;
before_pallete "PRD".events_log;
before_operation "PRD".events_log;
timer timestamp;
timer2 timestamp;

BEGIN
machines_ids = string_to_array(machines_ids_g,',')::integer[];
for l in
select m.*
from
    "PRD".machines m
    inner join
    unnest(machines_ids) n(id) on n.id = m.id
where
    m.start_work_date < begin_date_g
order by m.id
LOOP

SELECT * INTO island_controller FROM "STRUCT".island_machines WHERE machine_id=l.id;

RAISE NOTICE 'pobieram zdarzenie before dla maszyny %',l.id;

    SELECT * INTO before_event FROM "PRD".events_log WHERE plc_time < begin_date_g AND (((event_type_id IN (1,51) AND machine_id = island_controller.controller_id AND island_id = island_controller.island_id))
    OR (event_type_id IN (2000,2001) AND machine_id=l.id)) ORDER BY plc_time DESC LIMIT 1;

IF before_event.plc_time IS NOT NULL THEN

RAISE NOTICE 'Getting info about first machine work time struct element';
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 113 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 102 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 111 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 1010 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN NEXT before_event;

END IF;
RAISE NOTICE 'generuje zdarzenia wlasciwe dla maszyny %',l.id;
    RETURN QUERY SELECT * FROM "PRD".events_log WHERE
            (event_type_id = ANY ('{1,51}'::integer[]) AND (machine_id=island_controller.controller_id AND island_id = island_controller.island_id) AND (plc_time BETWEEN begin_date_g AND end_date_g))
            OR (event_type_id = ANY ('{2000,2001,107}'::integer[]) AND machine_id=l.id AND (plc_time >= begin_date_g AND plc_time <= end_date_g))
            OR ((event_type_id = ANY ('{101,102,103,301,1010}'::integer[]) OR ((event_type_id >= 5000) AND (event_type_id <= 5999))) AND machine_id=l.id AND plc_time >= begin_date_g AND plc_time <= end_date_g) ORDER BY plc_time;

RAISE NOTICE 'koniec dla maszyny %',l.id;
END LOOP;

END;

Sometimes the function execution time is ~9 seconds and sometimes ~40 seconds for the same arguments.

What does it depend on?  What could be so inefficient?


texts: Simple calculator which can operate on more than two numbers

texts:
All the calculator programs I have seen so far seem long, complicated and they can only operate on two numbers. Mine is simple, short, and it can operate on as many numbers as you want. Please tell me if there is another way to improve this section of code.

x=[]
amount=int(input("How many numbers?"))
operation=input("(*), (/), (+), (-)")
previous1 = 0
previous2=1
for i in range(amount):
    number=int(input("Number: "))
    x.append(number)
if operation == "+":
    for i in range(amount):
        previous1=x[i]+previous1
elif operation == "*":
    for i in range(amount):
        previous2=x[i]*previous2
elif operation == "-":
    for i in range(amount):
        previous1=x[i]-previous1
elif operation == "/":
    for i in range(amount):
        previous2=x[i]/previous2
if operation == "+" or operation == "-":
    print(previous1)
else:
    print(previous2)


texts: Quasi-random sequences: how to improve style and tests?

texts:
The requirements for this one were (original SO question):

Generate a random-ish sequence of items.
Sequence should have each item N times.
Sequence shouldn't have serial runs longer than a given number (longest below).

The solution was actually drafted by another user, this is my implementation (influenced by random.shuffle).

from random import random
from itertools import groupby # For testing the result
try: xrange
except: xrange = range

def generate_quasirandom(values, n, longest=3, debug=False):
  # Sanity check
  if len(values) < 2 or longest < 1:
    raise ValueError

  # Create a list with n * [val]
  source = []
  sourcelen = len(values) * n
  for val in values:
    source += [val] * n

  # For breaking runs
  serial = 0
  latest = None

  for i in xrange(sourcelen):
    # Pick something from source[:i]
    j = int(random() * (sourcelen - i)) + i
    if source[j] == latest:
      serial += 1
      if serial >= longest:
        serial = 0
        guard = 0
        # We got a serial run, break it
        while source[j] == latest:
          j = int(random() * (sourcelen - i)) + i
          guard += 1
          # We just hit an infinit loop: there is no way to avoid a serial run
          if guard > 10:
            print("Unable to avoid serial run, disabling asserts.")
            debug = False
            break
    else:
      serial = 0
    latest = source[j]
    # Move the picked value to source[i:]
    source[i], source[j] = source[j], source[i]

  # More sanity checks
  check_quasirandom(source, values, n, longest, debug)

  return source

def check_quasirandom(shuffled, values, n, longest, debug):
  counts = []
  # We skip the last entries because breaking runs in them get too hairy
  for val, count in groupby(shuffled):
    counts.append(len(list(count)))
  highest = max(counts)
  print('Longest run: %d\nMax run lenght:%d' % (highest, longest))

  # Invariants
  assert len(shuffled) == len(values) * n
  for val in values:
    assert shuffled.count(val) == n

  if debug:
    # Only checked if we were able to avoid a sequential run >= longest
    assert highest <= longest

for x in xrange(10, 1000):
  generate_quasirandom((0, 1, 2, 3), 1000, x//10, debug=True)

I'd like to receive any input you have on improving this code, from style to comments to tests and anything else you can think of.


texts: Using getopt parse and validate command line arguments

texts:
I am learning getopt in Python to parse and validate command line inputs:

#!/usr/bin/python
'''\nMailing Script
Usage: python script.py -y <year> -c <type_user>"
Arguments:
 -y, --year       any value from 2008 to 2013
 -c, --campaign   any value in:
                    '80c', '80d', 'allowances', 'late_filing',
                    'exempt_income', 'other_sources'
Flags:
 -h      help
'''
import sys, getopt
first_yr, last_yr = (2008, 2013)
campaign_type = (
    '80c', '80d', 'allowances', 'late_filing',
    'exempt_income', 'other_sources',
)

def usage():
    print sys.exit(__doc__)

def parse_arguments(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "y:c:", ["year=", "campaign="])
    except getopt.GetoptError:
        usage()
    for opt, arg in opts:
        if opt == '-h':
            usage()
        elif opt in ("-y", "--year"):
            target_year = arg
            # customized exception
            try:
                if not target_year in map(str, range(first_yr, last_yr+1)):
                    raise Exception()
            except:
                sys.exit("Argument Error: Invalid year passed. \n"
                         "One valid year is within (%s, %s)" % (first_yr, last_yr)
                )
        elif opt in ("-c", "--campaign"):
            campaign = arg.lower()
            try:
                if not campaign in campaign_type:
                    raise Exception()
            except Exception, e:
                sys.exit("Argument Error: Invalid 'Campaign type' passed. \n"
                         "A valid value can be any of %s" % str(campaign_type)
                )

    # to avoid 'UnboundLocalError' Exception when one argument not passed
    try:
        target_year, campaign
    except UnboundLocalError, u:
        usage()

    print 'Year : ', target_year
    print 'campaign: ', campaign

    # return argument values
    return (target_year, campaign)

if __name__ == "__main__":
    target_year, campaign = parse_arguments(sys.argv)

 Presently I didn't learn 16.4. argparse. I will learn it in the next step.

I want to improve my script as follows:

All arguments are mandatory. Presently if the user misses some argument then the script raises an UnboundLocalError exception. I then catch it and call usage(). Is it a correct way? Should I use len(argv) in some ways to handle this?
I check for correct values of arguments. If any argument value is wrong then I explicitly raise an exception and print an error message in the except clause. I am again not sure whether it's a preferable way to write this kind of code. I feel it adds one more level of nested blocks.

Some runs of this script:

$ python opt.py -y 2012 -c 80c
Year :  2012
campaign:  80c

Correct as I want:

$ python opt.py -year=2012
Argument Error: Invalid year passed.
One valid year is within (2008, 2013)

I think I should print message something like "insufficient arguments passed" or "use --year=2012 or -y 2012".


texts: Javascript function to get cellId from map point

texts:
I wrote this, and I would like to know if this code is clean.

It lets me know if a point is in the middle of an isometric cell.

const getMapPointFromCellId = cellId => {

    var {x, y} = getCoordinatesFromCellId(cellId)

    x = x * constants.cellWidth
    if (y % 2) x += constants.offsetWidth

    y = y * constants.offsetHeight

    return {x, y}
}
const getCellIdFromMapPoint = (x, y) => {
   var cellId = 0
   while(cellId < constants.numberCells){

       const cellCoordinates = getMapPointFromCellId(cellId)

       const offsetX = cellCoordinates.x + constants.offsetWidth
       const offsetY = cellCoordinates.y + constants.offsetHeight

       const endX = cellCoordinates.x + constants.cellWidth
       const endY = cellCoordinates.y + constants.cellHeight

       if (cellCoordinates.x < x && x < cellCoordinates.x + constants.cellWidth)
          if (cellCoordinates.y < y && y < cellCoordinates.y + constants.cellHeight){

            if (x < offsetX && y < offsetY)
                if ((offsetY - y) / (cellCoordinates.x - x) > (offsetY - cellCoordinates.y) / (cellCoordinates.x - offsetX)) return cellId
            if (x > offsetX && y < offsetY)
                if ((offsetY - y) / (endX - x) <= (offsetY - cellCoordinates.y) / (endX - offsetX)) return cellId
            if (x < offsetX && y > offsetY)
                if ((offsetY - y) / (cellCoordinates.x - x) <= (offsetY - endY) / (cellCoordinates.x - offsetX)) return cellId
            if (x > offsetX && y > offsetY)
                if((offsetY - y) / (endX - x) >= (offsetY - (constants.cellHeight - constants.offsetHeight)) / (endX - offsetX)) return cellId

        }

       cellId++
   }

  return -1
}


texts: Implementing a stack using a linked-list

texts:
In my intro CS class we're reviewing data structures. I'm currently working on implementing a stack using a linked list (LIFO) in C. I'd appreciate a review of the implementation as well as of my understanding of how a stack should work.

// This program is implementation of stack data structure
// via linked list (LAST IN FIRST OUT STRUCTURE) LIFO

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
   char string[20];
   struct node *next;
} node;

node *push(char *element, node *head);
node *pop(node *head);
void destroy_stack(node *p);

int main(void)
{

    // create new stack
    node *stack = NULL;

    // push 6 "functions" to the stack
    char *function[6] = {"first funct", "second funct", "third funct",
    "fourth funct", "fifth funct", "sixt funct"};
    for (int i = 0; i < 6; i++)
    {
        printf("function is : %s\n",function[i]);
        stack = push(function[i], stack);
        if (!stack)
        {
            fprintf(stderr,"Not enough memory space for new list");
            return 1;
        }
    }

    // display the stack
    for (node *temp = stack; temp != NULL; temp = temp -> next)
    {

        printf("Elements of the stack are: %s\n", temp -> string);
    }

    // pop the elements from the stack
    while (stack != NULL)
    {

        printf("Popped elemet is: %s\n", stack -> string);
        stack = pop(stack);

    }

    destroy_stack(stack);
    return 0;

}

node *push(char *element, node *head)
{
    // create space for new element on stack
    node *temp = malloc(sizeof(node));
    if (!temp)
    {
        return NULL;
    }

    // if stack is empty
    if (head == NULL)
    {
        strcpy(temp -> string, element);
        temp -> next = NULL;
        return temp;
    }

    strcpy(temp -> string, element);
    temp -> next = head;
    return temp;
}

node *pop(node * head)
{
    // create a new head
    node *newHead = head->next;

    // pop the element from stack
    free(head);

    return newHead;

}

void destroy_stack(node *p)
{
    if ( p == NULL )
    {
        return;
    }
    else
    {
        destroy_stack(p -> next);
    }
    free(p);
}


texts:
I wrote a Python script to format plain text to markdown title.

for example, modify multiple lines

['1 Introduction\n',
 'Part I: Applied Math and Machine Learning Basics\n',
 '2 Linear Algebra\n',
 '3 Probability and Information Theory\n',
 '10 Sequence Modeling: Recurrent and Recursive Nets\n',
 '11 Practical Methodology']

to

['# chapter1: Introduction\n',
 'Part I: Applied Math and Machine Learning Basics\n',
 '# chapter2: Linear Algebra\n',
 '# chapter3: Probability and Information Theory\n',
 '# chapter10: Sequence Modeling: Recurrent and Recursive Nets\n',
 '# chapter11: Practical Methodology']

each chapter title in original file starts with only a number, modify them from 1 to "# chapter 1:", namely, insert "# chapter " before the number, append a colon ":" behind the number; finally write the new toc to a file.

here is the code

import re
# f_name = 'data_multi_lines_3.md'
f_name = 'data_multi_lines.txt'
with open(f_name) as f:
    line_list = f.readlines()
res_list = []
for line in line_list:
    res_list.append(re.sub(r'^(\d{1,2})( +.*?)', r'# chapter\1:\2', line))
with open('your_file.md', 'w') as f:
    for item in res_list:
        f.write("%s" % item)

Is there a better approach to do this?

I guess I should be concerned about the for loop although I have no idea how to improve that.


texts:
I am trying to refactor a ViewModel class because it has two methods that are really similar called updateRegions and updateTowns and even another one may end up being made called updateCountries. I basically copy-paste the method and change the variable names. How can this be refactored with maybe an abstract class that has an abstract updateArea function?

class SearchFilterViewModel {
        _regionsList = [];
        _townsList = [];
        _regions = ko.observableArray();
        _towns = ko.observableArray();
        selectedRegion: KnockoutObservable<string> = ko.observable('');
        selectedTown: KnockoutObservable<string> = ko.observable('');
        selectedCategories: KnockoutObservableArray<string> = ko.observableArray([]);

        constructor() {
            this.updateRegions("2186224");
            this.selectedRegion.subscribe(this.updateTowns.bind(this));
        }

        updateRegions(geonameId) {
            var self = this;
            self._regionsList = [];
            $.ajax({
                url: `http://api.geonames.org/children?geonameId=${geonameId}&username=elion`
            }).then(function(allRegionsXML) {
                var allRegionsJSON = xml2json(allRegionsXML);
                var allRegions = JSON.parse(allRegionsJSON);
                if(allRegions.geonames.length) {
                    for (var index = 1; index < allRegions.geonames.length - 1; index++) {
                    self._regionsList.push(allRegions.geonames[index].geoname);
                    }
                } else {
                    if(allRegions.geonames) {
                        self._regionsList.push(allRegions.geonames.geoname);
                    }
                }
                self._regions(self._regionsList);
            });
        }

        updateTowns(geonameId) {
            var self = this;
            self._townsList = [];
            $.ajax({
                url: `http://api.geonames.org/children?geonameId=${geonameId}&username=elion`
            }).then(function(allTownsXML) {
                var allTownsJSON = xml2json(allTownsXML);
                var allTowns = JSON.parse(allTownsJSON);
                if(allTowns.geonames.length) {
                    for (var index = 1; index < allTowns.geonames.length - 1; index++) {
                    self._townsList.push(allTowns.geonames[index].geoname);
                    }
                } else {
                    if(allTowns.geonames) {
                        self._townsList.push(allTowns.geonames.geoname);
                    }
                }
                self._towns(self._townsList);
            });
        }
    }


texts:
I had a thought last night on how I could easily write a Pascal's Triangle generator basically just using partition and map. I tried writing it this morning, and it got slightly more complicated than I originally thought it would, although it's still pretty nice.

My main concern is the wrap "hack" that I'm using. I found two similar, but different ways of writing it. I can either wrap the input to the iteration function in 0s, or I can wrap the result of the iteration function in 1s. Both give the same result, but the need for a wrapping helper pollutes an otherwise nice ->> chain. If anyone can think of how I can avoid a separate anonymous function here, and ideally avoid wrapping the input/output in 0s/1s, I'd appreciate it. I'll take any other critique as well, although there isn't much else going on here.

Usage:

(let [pre-t (pascals-triangle-pre) ; Wrapping pre-processing
      post-t (pascals-triangle-post) ; Wrapping post-processing
      n 5]
  (println (take n pre-t))
  (println (take n post-t)))

([1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1])
([1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1])

(ns minesweeper.irrelevant.pas-tri)

(defn pascals-triangle-post []
  (let [wrap #(vec (concat [1] % [1]))]
    (iterate #(->> %
                   (partition 2 1)
                   (mapv (partial apply +'))
                   (wrap))
             [1])))

(defn pascals-triangle-pre []
  (let [wrap #(vec (concat [0] % [0]))]
    (iterate #(->> %
                   (wrap)
                   (partition 2 1)
                   (mapv (partial apply +')))
             [1])))


texts: Create numerical-key array from existing string-key array, with a given string-key as first item

texts:
I have an array of available languages for my website, with a short ISO country code as the key for each language. I need to create a new array that contains the same info, but with numerical keys and where the first item in the new array is the current language.

I have this, which works fine:

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

$currentLanguage = 'sv';

// Create new numerical-ordered array with current language info as first element
$langugeList = [];
foreach( $allLanguages as $key => $value ){
    if( $key == $currentLanguage )
        array_unshift($langugeList, $value);
    else
        array_push($langugeList, $value);
};

Result:

    array (
        0 =>
            array (
                'locale' => 'sv_SE',
                'code' => 'sv',
                'displayName' => 'Swedish',
            ),
        1 =>
            array (
                'locale' => 'en_US',
                'code' => 'en',
                'displayName' => 'English',
            ),
        2 =>
            array (
                'locale' => 'de_DE',
                'code' => 'de',
                'displayName' => 'German',
            ),
    )

Is there another, more elegant way of doing this?

I first had the idea to copy the array values and then sort them using usort() (keeping the original order except for the current language), but that doesn't seem like an improvement to neither performance nor "elegancy".

I just realized that one option would be

$langugeList = [ $allLanguages[$currentLanguage] ];
foreach( $allLanguages as $key => $value ){
    if( $key != $currentLanguage )
        $langugeList[] = $value;
};


texts:
I'm currently doing the Project Euler challenges to learn C++. The fifth problem is the following.

  2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

  What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

I thought of a loop between 20 and 10 as everything under 10 is a multiple of something under 10. At each iteration, the result is the lcm of the loop variable and the current result.

If I am correct, the complexity of this should be \$\mathcal{O}(n/2)\$. Am I right?

Is there any faster/better/cleaner implementation or another algorithm with a better complexity?

This is my code.

#include <iostream>

long gcd(long a, long b)
{
    long t;

    if (b == 0) return a;

    while (b != 0) {
        t = b;
        b = a % b;
        a = t;
    }
    return a;
}

long lcm(long a, long b)
{
    return (a * b) / gcd(a, b);
}

int main()
{
    long n(20), result(1);
    for (long i = n; i > n/2; --i) {
        result = lcm(result, i);
    }
    std::cout << "Result: " << result << "\n";
}


texts: Is this a valid way of computing autocorrelation?

texts:
I am a beginner in Digital Signal Processing and I was trying to compute and plot an autocorrelation.

I've wrote this piece of code:

r = [zeros(2,1); y(1:98,1)];
r = r.*y;

and I wished to know if this is a valid way of computing an autocorrelation.


texts:
The JSON standard uses double quotes for key names and string values, such as the following:

{"one":1,"two":"two"}

However, the current project I am working on requires JSON-encoded objects to use single quotes instead of double quotes. (In this case {'one':1,'two':'two'}). Right now, there is no reasonable way to get rid of this requirement. I am using the following code to convert a JSON-encoded string from double quotes to single quotes:

var encoded = JSON.stringify(...);
encoded = encoded.replace(/\\"/g, '"')
    .replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
    .replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
    .replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2");

This code replaces double quotes with single quotes on key names and string values, and handles possible quote escaping issues (such as {"\"key\"": "'value'"}, which is replaced with {'"key"', '\'value\''}).

Is this code enough to guarantee that, for any given object, a valid JSON-like string with single quotes will be generated? In other words, is there any way to break this code such that the result is not valid?

P.S: if you are interested, the reason that JSON strings must have single quotes is that I am working with Cassandra's map type, which doesn't accept double quotes.


texts: Class for finding the median of a two-dimensional space

texts:
I have a simple static class that it's purpose is given an RDD of Point to find the median of each dimension and return that as a new Point using Spark's reduce functions.

This is the class:

public class MedianPointFinder {

    public static Point findMedianPoint(JavaRDD<Point> points) {
        Point biggestPointByXDimension = points.reduce((a, b) -> getBiggestPointByXDimension(a, b));
        Point biggestPointByYDimension = points.reduce((a, b) -> getBiggestPointByYDimension(a, b));

        double xDimensionMedian = biggestPointByXDimension.getX() / 2.0;
        double yDimensionMedian = biggestPointByYDimension.getY() / 2.0;

        return new Point(xDimensionMedian, yDimensionMedian);
    }

    private static Point getBiggestPointByXDimension(Point first, Point second) {
        return first.getX() > second.getX() ? first : second;
    }

    private static Point getBiggestPointByYDimension(Point first, Point second) {
        return first.getY() > second.getY() ? first : second;
    }
}

Point class is a simple class for storing an (x, y) point.


texts: Trait accessing variables of classes using it

texts:
I just tried PHP Traits for the first time, to keep my code DRY :

<?php
namespace Acme\DemoBundle\Model;

trait CheckPermissionTrait
{
    protected function checkPermission($object_id)
    {
        $judge = $this->container->get('acme_judge');

        $user  = $this->container->get('security.context')->getToken()->getUser();

        if( !$judge->isPermitted($user, $object_id) ) {
            throw $this->createAccessDeniedException("Brabbel");
        }
    }
}

-

<?php
namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\DemoBundle\Model\CheckPermissionTrait;

class SomeController extends Controller
{
    use CheckPermissionTrait;

    public function someAction(Request $request, $object_id)
    {
        $this->checkPermission($object_id);

        //do other stuff
    }
}

What making me a little nervous, is that the trait is accessing the container of the class using it, which means there is actually the requirement that the class using the trait needs to extend the Controller (Symfony\Bundle\FrameworkBundle\Controller\Controller) for the trait to work.

Is this normal when using traits or is it bad practice?


texts:
How can I make it shorter and cleaner?

using Queries.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace Queries.Persistence.Repositories
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected readonly DbContext Context;

    public Repository(DbContext context)
    {
        Context = context;
    }

    public TEntity Get(int id)
    {
        return Context.Set<TEntity>().Find(id);
    }

    public IEnumerable<TEntity> GetAll()
    {
        return Context.Set<TEntity>().ToList();
    }

    public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
    {
        return Context.Set<TEntity>().Where(predicate);
    }

    public TEntity SingleOrDefault(Expression<Func<TEntity, bool>> predicate)
    {
        return Context.Set<TEntity>().SingleOrDefault(predicate);
    }

    public void Add(TEntity entity)
    {
        Context.Set<TEntity>().Add(entity);
    }

    public void AddRange(IEnumerable<TEntity> entities)
    {
        Context.Set<TEntity>().AddRange(entities);
    }

    public void Remove(TEntity entity)
    {
        Context.Set<TEntity>().Remove(entity);
    }

    public void RemoveRange(IEnumerable<TEntity> entities)
    {
        Context.Set<TEntity>().RemoveRange(entities);
    }
}
}


texts: Most elegant way to copy type alias class to original collection

texts:
Looking for a most elegant way to copy dictionary type alias to original collection.
using System;
using System.Collections.Generic;
public class SmallDictionary: Dictionary<string, JToken>
public class NestedDictionary : Dictionary<string, SmallDictionaly>

using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Adp.Configuration.Events.Entities;
using Newtonsoft.Json.Linq;

public static Dictionary<string, Dictionary<string, JToken>> ToDictionary(this NestedDictionary configurationEntry)
{
   Dictionary<string, Dictionary<string, JToken>> resultDictionary = new Dictionary<string, Dictionary<string, JToken>>();
   foreach (KeyValuePair<string, SmallDictionary> pair in configurationEntry)
   {
      resultDictionary.Add(pair.Key, pair.Value);
   }
   return resultDictionary;
}
```


texts: Templated JSON parsing methods that work with an element or elements array

texts:
Consider the following two Java methods. The first takes a JSON string representing one element, the second representing multiple elements. gson.fromJson() can be called with a Class parameter or a Class[] parameter. The trick is in unifying the method signatures so a caller of creatBean() can call seamlessly with a Class or Class[] parameter. Is there a way these two can be combined?

public <T extends ValidateableBean>T createBean(String json, Class<T> clazz) {
    Gson gson = new Gson();
    T device = gson.fromJson(json, clazz);

    InputValidation inputValidation = new InputValidation();
    if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
        throw new WebApplicationException(Status.BAD_REQUEST);
    }

    return device;
}

public <T extends ValidateableBean>T[] createBeans(String json, Class<T[]> clazz) {
    Gson gson = new Gson();
    T[] devices = gson.fromJson(json, clazz);

    InputValidation inputValidation = new InputValidation();
    for (T device : devices) {
        if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
            throw new WebApplicationException(Status.BAD_REQUEST);
        }
    }

    return devices;
}


texts:
I've tried to take the shortest, simplest path to a C# solution to the Ultimate Tic-Tac-Toe challenge.  This implementation plays in the console.  I admit the game logic could be hived off into a separate method, but I'm not sure that would be an improvement.  I also admit that the fields should be tighter than public, but that's neither here nor there.

I would appreciate feedback on:

How readable people find this solution;
Any suggestions to make the code more succinct;
Any other comments people would care to make.

void Main()
{
    var mb = new MetaBoard();
    var board = -1;
    var player = Who.X;
    while (WinFor(mb) == Who.Neither && mb.Boards.Any(x => WinFor(x) == Who.Neither)) {
        mb.Write();
        Console.WriteLine(player + " to play.");
        // Choose a board if we've just started or the current board is finished.
        while (board == -1 || mb[board] != Who.Neither) board = InputNum("an unfinished board");
        var cell = -1;
        // Choose an empty cell on the board.
        while (cell == -1 || mb.Boards[board][cell] != Who.Neither) cell = InputNum("an empty cell on board " + (board + 1));
        Console.WriteLine();
        mb.Play(board, cell, player);
        // The next board is decided by the cell just played.  Swap turns between the players.
        board = cell;
        player = (player == Who.X ? Who.O : Who.X);
    }
    mb.Write();
    Console.WriteLine(WinFor(mb) + " wins!");
}

static int InputNum(string what) {
    var i = -1;
    do {
        Console.Write("Choose " + what + " [1-9]: ");
    } while (!int.TryParse(Console.ReadLine().Trim(), out i) || i < 1 || 9 < i);
    return i - 1;
}

enum Who { Neither, X, O }

static int[][] Lines = new int[][] {
    new int[] {0,1,2}, new int[] {3,4,5}, new int[] {6,7,8},
    new int[] {0,3,6}, new int[] {1,4,7}, new int[] {2,5,8},
    new int[] {0,4,8}, new int[] {2,4,6}
};

interface IBoard { Who this[int i] { get; } } // Indicate who, if any, has won position i.

static Who Min(Who p, Who q) { return p == q ? p : Who.Neither; }

static Who WinFor(IBoard board) { // X if a line of three Xs, O if a line of three Os.
    return Lines.Select(line => Min(board[line[0]], Min(board[line[1]], board[line[2]])))
                .FirstOrDefault(who => who != Who.Neither);
}

class Board: IBoard { // A 3x3 grid of cells.
    public Who[] Cells = new Who[9];
    public Who this[int i] { get { return Cells[i]; } }
    public void Play(int i, Who who) { Cells[i] = who; }
}

class MetaBoard: IBoard { // A 3x3 grid of boards.
    public Board[] Boards = Enumerable.Range(0, 9).Select(i => new Board()).ToArray();
    public Who this[int i] { get { return WinFor(Boards[i]); } }
    public void Play(int i, int j, Who who) { Boards[i].Play(j, who); }

    public void Write() {
        Action<Who> writeCell = w => { Console.Write(w == Who.X ? 'X' : w == Who.O ? 'O' : '.'); };
        var rg = Enumerable.Range(0, 3);
        foreach (var rr in rg) foreach (var r in rg) foreach (var cc in rg) foreach (var c in rg) {
            writeCell(Boards[cc + 3 * rr].Cells[c + 3 * r]);
            if (c == 2) Console.Write("  ");
            if (c == 2 && cc == 2) Console.WriteLine();
            if (c == 2 && cc == 2 && r == 2) Console.WriteLine();
        }
    }
}


texts: Public Function to remove empty or "" elements from a single dimension array

texts:
I've written a function to remove empty or "" value elements from an array or in other words return an array consisting only of elements containing a value.

Option Explicit

Public Function RemoveBlanksFromArray(ByVal TheArray As Variant) As Variant

    Dim temp As Variant
    ReDim temp(LBound(TheArray) To LBound(TheArray))
    Dim myElement As Variant
    Dim myCount As Long
    myCount = LBound(temp)

    For Each myElement In TheArray
        If myElement <> "" Then
            ReDim Preserve temp(LBound(temp) To myCount)
            temp(myCount) = myElement
            myCount = myCount + 1
        End If
    Next myElement

    RemoveBlanksFromArray = temp

End Function

The Function is passed an Array as an argument. The Array is temp and ReDimed as a single element. It then loops each element of the passed argument and adds the value if it's not "" or Empty.

I've used ReDim Preserve temp(LBound(temp) To myCount) before each element is written to temp to dynamically set the upper bound.

I feel there may be more efficient ways to perform this task.

Are there any inefficiencies in ReDiming the upper bound the way I have done it?

Can the upper bound of the array be set in any other way dynamically?

Have I broken any sacred rules in the formatting of the function or naming conventions etc?


texts:
I'm using VS 2013/EF 6/WEB API 2.

This application of mine which is working on will eventually grow to be big project and I'm in the very beginning stage and need your expertise to make it simple as possible without over-complication.

My goal is to make it KISS solution and I'm trying my best.  After spending a lot of time thinking and researching I have come up with this design.

PS: I'm very open for suggestions and willing to change my design please don't be harsh with me.

//DAL project

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
}

//Impl

public class HostRepository : IRepository<Host>
    {
        public IEnumerable<Host> GetAll()
        {
            using (SRDbContext context = new SRDbContext())
            {
                var hosts = from host in context.Hosts
                            select new Host()
                            {
                                FirstName = host.FirstName,
                                LastName = host.LastName,
                                Email = host.Email
                            };
                return hosts.AsEnumerable().ToList();
            }
            return null;
        }
    }

//UOW

public class UnitOfWork : IDisposable
    {
        private SRDbContext context = new SRDbContext();
        private GenericRepository<Host> hostRepository;

        public GenericRepository<Host> HostRepository
        {
            get
            {
                if (this.hostRepository == null)
                {
                    this.hostRepository = new GenericRepository<Host>(context);
                }
                return hostRepository;
            }
        }
     }

//GenericRepository

public class GenericRepository<T> where T : class
    {
        internal DbContext context;
        internal IDbSet<T> IDbSet;

        public GenericRepository(DbContext context)
        {
            this.context = context;
            this.IDbSet = context.Set<T>();
        }

        public virtual T GetByID(object id)
        {
            return IDbSet.Find(id);
        }

        public IEnumerable<T> GetAll()
        {
            IQueryable<T> query = IDbSet;
            return query;
        }
    }

//Service project

public class HostService
    {
        //HostRepository reqRepo = new HostRepository();
        private UnitOfWork _uow = null;
        protected UnitOfWork UOW
        {
            get
            {
                if (_uow == null)
                {
                    _uow = new UnitOfWork();
                }
                return _uow;
            }
        }
        public IEnumerable<Host> GetAll()
        {
            return UOW.HostRepository.GetAll();
        }
   }

//WebAPI project

[ResponseType(typeof(HostDTO))]
    [Route("hosts")]
    [HttpGet]
    public async Task<IHttpActionResult> Get()
    {
        IEnumerable<HostDTO> host = hs.GetAll();

        if (host == null)
        {
            return NotFound();
        }

        return Ok(host);
    }


texts: Creates a menu and sidebar in Google Spreadsheets

texts:
In an effort to make my code more testable, I'm trying to make use of constructors and prototypes.

Here is a working Google Apps Script (GAS) for creating a new submenu under the Addon main menu in a Google Spreadsheet. If a user clicks the 'Show' menu item, a sidebar will appear.

var UI = function (menuName, menuFunction, sidebarFile, sidebarTitle) {
    this.menuName = menuName;
    this.menuFunction = menuFunction;
    this.sidebarFile = sidebarFile;
    this.sidebarTitle = sidebarTitle;
};

UI.prototype.createAddonMenu = function () {
    try {
        SpreadsheetApp.getUi()
            .createAddonMenu()
            .addItem(this.menuName, this.menuFunction)
            .addToUi();
        Logger.log('onOpen (success): building menu');

    } catch (e) {
        Logger.log('onOpen (fail): ' +  e);
    }
};

UI.prototype.showSidebar = function () {
    try {
        var ui = HtmlService.createTemplateFromFile(this.sidebarFile)
            .evaluate()
            .setTitle(this.sidebarTitle)
            .setSandboxMode(HtmlService.SandboxMode.IFRAME);

        SpreadsheetApp.getUi()
            .showSidebar(ui);
        Logger.log('showSidebar (success): showing sidebar');

    } catch (e) {
        Logger.log('showSidebar (fail): ' + e);
    }
};

var ui = new UI('Show', 'showSidebar', 'index', 'Awesome Title');

// onOpen is a built-in Google Apps Script function that gets called when the spreadsheet is opened
function onOpen(e) {
    return ui.createAddonMenu();
}

// showSidebar is a standalone function and returns the ui showSidebar method. needs to be this way in order to be called from createAddonMenu
function showSidebar() {
    return ui.showSidebar();
}

Questions:

I'd like to be able to write unit tests for both createAddonMenu and showSidebar, but at this moment I don't believe it's possible as I'm not returning a value from either method; I'm simply just calling Google's third party code for creating a menu and showing a sidebar. Would I need to create a wrapper around any code calling a third party's code, and then call that within my method? I know I'm not supposed to test third party code, so how would I go about testing to make sure it gets called and doesn't return an error?
I'd like a sanity check on when I should create a constructor. I feel like maybe I'm trying to shove too many arguments into it and maybe trying to do too much. Should I create two separate constructors (one for createMenu and one for showSidebar)? Should I even be using constructors at all?
Finally, any other feedback?


texts:
I need to compute the max contiguous slice in an array. I wrote this function, but I am not sure if it is correct or I am missing edge cases. I ran several cases.

def max_slice(a)
  max_start,max_end = 0,0
  largest_sum = 0
  curr_start,curr_end = 0,0
  curr_sum = 0
  for i in 0..a.length-1
    if (curr_sum + a[i]  < 0 ) then
      curr_start = i+1
      curr_sum = 0
    elsif (curr_sum + a[i] > curr_sum) then
      curr_sum = curr_sum + a[i]
      curr_end = i
      if (curr_sum > largest_sum) then
        max_start, max_end = curr_start,curr_end
        largest_sum = curr_sum
      end
    end
  end
  a[max_start..max_end]
end

p max_slice([-3,39,2,-1,65]) #> [39, 2, -1, 65]
p max_slice([12,-3,39,2,-1,65]) #> [12, -3, 39, 2, -1, 65]
p max_slice([]) #> []
p max_slice([2,3]) #> [2, 3]
p max_slice([-2,3]) #> [3]
p max_slice([-2]) #> [-2]
p max_slice([12,-3,39,2,-1,102]) #> [12, -3, 39, 2, -1, 102]
p max_slice([-5,-3,39,2,-39,65]) #> [39, 2, -39, 65]
p max_slice([-5,5,39,2,-60,65]) #> [65]
p max_slice([-5,35,39,2,-60,65]) #> [35, 39, 2, -60, 65]
p max_slice([-5,35,39,2,-160,65]) #> [35, 39, 2]


texts:
I've started to go through Node tutorials on nodeschool.io, and the second assignment was to write a program that will count the number of newlines in a file and print it out. My solution looks like this

var fs = require('fs');

var file = process.argv[2];
var buff = fs.readFileSync(file);
var str = buff.toString();
var str_arr = str.split('\n');
var newline_length = str_arr.length-1;

console.log(newline_length);

It's correct, and works. Theirs is

var fs = require('fs')

var contents = fs.readFileSync(process.argv[2])
var lines = contents.toString().split('\n').length - 1
console.log(lines)

// note you can avoid the .toString() by passing 'utf8' as the
// second argument to readFileSync, then you'll get a String!
//
// fs.readFileSync(process.argv[2], 'utf8').split('\n').length - 1

While both are correct, mine is longer (more lines used because I declared variables at every step).

I am wondering, am I wrong in declaring the variables for every step and then working on the code as I go? I mean, it does take more space, but I have the feeling that it's a bit clearer what I'm doing, unlike theirs. Or am I mistaken and haven't really gotten to that level where I can safely write everything in a one line like they did?

Also am I using memory space by declaring too many variables?

This task is rather trivial, and mostly the code I've written so far is for web elements (carousels and whatnot), so I'm used to writing mostly jQuery code instead of pure JavaScript (declaring variables used in events and such). Does this have any impact in real life apps?


texts: Retrieving the most recent posts from the users someone is following

texts:
I have two different implementations for retrieving posts from the users someone is following and I want to know which one you would recommend using. First I'll show you the tables, and then the two implementations.

Post table

  id (PK)| poster_id (FK) | value | created_on

Repost table - necessary for both implementations

  reposter_id (FK) | post_id (FK) | created_on

Following table

  follower_id (FK) | followee_id (FK)

user_feed table - necessary only for second implementation

  user_id (FK) | post_id (FK) | created_on

First implementation:

Requires the repost table, but no user_feed table. Whenever a user posts something I don't have to add a row for each of their followers in the user_feed table, but the query seems much more computationally expensive.

SELECT * FROM (
    SELECT p.id, p.poster_id, p.value, p.created_at
    FROM post AS p
    WHERE p.'user_id'=23 OR (p.'user_id' IN SELECT 'followee' FROM following WHERE 'follower'=23)
    UNION
    SELECT p.id, p.poster_id, p.value, rp.reposter_id, rp.created_at
    FROM post AS p
    INNER JOIN repost AS rp
    ON rp.post_id = p.id
    WHERE p.'user_id'=23 OR (p.'user_id' IN SELECT 'followee' FROM following WHERE 'follower'=23)))
ORDER BY created_at DESC
LIMIT 80;

Second implementation:

Requires the user_feed table and the repost table. I add a record to the user_feed table every time someone posts/reposts something. The record is added for each one of the poster's followers. I only keep, say, 120 records for any particular user in the user_feed table. If a post is made and a user already has 120 records in the user_feed table, the oldest record for that user is deleted and the new one takes its place. If a user requests more records than there are present in the user_feed table for them, then the first implementation is used to retrieve them.

SELECT * FROM (
    SELECT p.id, p.poster, p.value, p.created_at
    FROM post As p
    WHERE p.'id' IN (SELECT 'post_id' FROM user_feed WHERE 'user_id'=23)
ORDER BY created_at DESC
LIMIT 80;


texts: Finding the use of the word 'Cthulhu' in tags on Stack Overflow

texts:
I've written the following SQL to count the number of times the name 'Cthulhu' turns up for each tag on Stack Overflow (original here):

select t.TagName, count (*) 'Tainted'
from Posts p, Tags t, PostTags pt
where p.Body like '%cthulhu%'
and (pt.PostId = p.Id and t.Id = pt.TagId)
group by t.TagName
order by Tainted DESC, t.TagName ASC

It works, but I'm not used to cutting SQL manually; I'm more accustomed to using ORMs.  I tried using CONTAINS instead of LIKE, but apparently Body isn't set up for full-text search.

Could you please provide me some feedback - in particular, are there any best practices I'm missing, and whether there are standard formatting rules for SQL that would make it a bit easier on the eye?


texts: Multiple forms for accessing records in database

texts:
I have a main form for adding and deleting records and a button that opens a child form that displays records from an access database.  Child form will have buttons for moving though the rows like first, last, next, previous and search.  When user selects a record the child form will close and the selected record will be displayed in the main form, from which it can be changed, deleted, etc.  This is the logic behind what I’m doing.  So far I have written a class for accessing the data and is called from the child form to display the records.  Before I move on, I want to get advice on what I have done so far and if it follows best practices.  Any advice would be greatly appreciated.

Main Form:

namespace Test
{
public partial class frmTest : Form
{
    public frmTest()
    {
        InitializeComponent();
    }

    public class myClass
    {
        private static OleDbConnection myConn = new OleDbConnection();
        private static DataSet myDS;
        private static DataRow myDR;
        public static int MaxRows = 0;
        public static int increment = 0;
        public static string name;

        public static void GetConnection()
        {
            myClass.myConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Testing\TestDatabase.accdb";
            try
            {
                myConn.Open();
                myDS = new DataSet();
                string SQL = "SELECT * From Test";
                OleDbDataAdapter myDA = new OleDbDataAdapter(SQL, myConn);
                myDA.Fill(myDS, "People");
                NavigateRecords();
                MaxRows = myDS.Tables["People"].Rows.Count;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                myConn.Close();
            }
        }

        public static void NavigateRecords()
        {
            myDR = myDS.Tables["People"].Rows[increment];
            name = myDR.ItemArray.GetValue(1).ToString();
        }
    }

    private void frmNewForm_Click(object sender, EventArgs e)
    {
        frmNewForm fNew = new frmNewForm();
        fNew.ShowDialog();
    }
}
}

Child form:

namespace Test
{
public partial class frmNewForm : Form
{
    public frmNewForm()
    {
        InitializeComponent();
    }

    private void frmNewForm_Load(object sender, EventArgs e)
    {
        MyAlias.GetConnection();
        txtName.Text = MyAlias.name;
    }

    private void FillTextBox()
    {
        txtName.Text = MyAlias.name;
    }

    private void btnNext_Click(object sender, EventArgs e)
    {
        if (MyAlias.increment != MyAlias.MaxRows - 1)
        {
            MyAlias.increment++;
            MyAlias.NavigateRecords();
            FillTextBox();
        }
        else
        {
            MessageBox.Show("No more rows");
        }
    }
}
}