With two tightly related classes like HashTable and HashTableEntry, you should probably nest them inside each other:

public class HashTable<K, V> {
    public static class Entry<K, V> {
        ...
    }
    ...
}

This way, the relationship between the classes is clear.

In your Entry class, you make it mutable. However, why not make it immutable? Immutability wouldn't cost much, but it would make some stuff easier to keep track of, such as providing the user an immutable view of your hashtable (this may be undesired, but it's what I'd do).

public static class Entry<K,V> { // This was nested within HashTable<K, V>
    private final K key;
    private final V value;
    private final Entry<K,V> next;

    public Entry(K key, V value, Entry<K, V> next) {
        this.key = key;
        this.value = value;
        this.next = next; // This could be changed by the user, so we aren't quite immutable yet; we'd have to do a deep copy on `next`
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public Entry<K, V> getNext() {
        return next;
    }

    public Entry<K, V> withNext(Entry<K, V> newNext) {
        return new Entry<>(key, value, newNext);
    }
}

Interestingly, you are combining table entries with a linked-list. This makes sense from the implementation viewpoint of a hashtable, but for readability's sake, I recommend removing the Entry<K, V> next entirely and simply using an array of LinkedList in your HashTable class. If you don't want to use the built-in LinkedList class, I still feel it is clearer if you separate these two unrelated pieces of the hashtable.

This would require some other changes in the code as well.

In getLastEntry and findValue, you return null when the request cannot be met. However, this is a little bit unclear. I'd recommend instead using Optional<Entry<K, V>> and Optional<V> as your return types so you can just do this:

private Optional<V> findValue(HashTableEntry<K,V> entry, K key) {
    if (entry == null) return Optional.empty();

    HashTableEntry<K,V> currentEntry = entry;

    while(currentEntry.getNext() != null) {
        if (currentEntry.getKey().equals(key)) {
            return Optional.of(currentEntry.getValue());
        }

        currentEntry = currentEntry.getNext();
    }

    return Optional.empty();
}

Then to get the value, you'd call optional.get(), but first you should check optional.isPresent(). This speaks more clearly than a null, so I personally find it easier to follow in this case.


Golang - Splitting a string by a separator not prefixed by an escape string

One approach that's simple, but is a bit of a dirty trick: first replace sequences of escape+separator with a string that's never going to occur in your text (for example a NUL byte "\x00"), then do the split, then do the reverse replace on each token. For example (Go Playground link):
func SplitWithEscaping(s, separator, escape string) []string {
    s = strings.ReplaceAll(s, escape+separator, "\x00")
    tokens := strings.Split(s, separator)
    for i, token := range tokens {
        tokens[i] = strings.ReplaceAll(token, "\x00", separator)
    }
    return tokens
}

Your approach of splitting and then re-joining if the last character was an escape works, but it's a bit tricky, and it does more work than necessary. You may also want to name the t function a bit more meaningfully.
An alternative approach would be more of a tokenizer, where you loop through all the bytes in the string, looking for escape and space. Here's the code for that, but note that I've made the separator and escape a single byte to simplify it -- I'm guessing they will be in most cases anyway (Go Playground link):
func SplitWithEscaping(s string, separator, escape byte) []string {
    var token []byte
    var tokens []string
    for i := 0; i < len(s); i++ {
        if s[i] == separator {
            tokens = append(tokens, string(token))
            token = token[:0]
        } else if s[i] == escape && i+1 < len(s) {
            i++
            token = append(token, s[i])
        } else {
            token = append(token, s[i])
        }
    }
    tokens = append(tokens, string(token))
    return tokens
}

The other approach that came to mind is regexes, but you have to be able to say "match space, but only if it's not preceded by this escape", which I think you can only do with lookbehind expressions like ?<, and Go's regexp package doesn't support those.


It is already a good attempt at making better-looking code.  Just a few improvement:

Declare all private functions one-by-one with declaring that individual just like you declare your variable (see jQuery code).
There is no need for the updateOptions() method; we don't need it.

var myDialog = myDialog || (function () {

    var options = {
        title: 'Attention',
        msg: 'Message Here',
        focusOn: ''
    }

    var show = function(opts) {
            options = $.extend({}, options, opts);
            $('<p>' + options.msg + '</p>').dialog({
                title: options.title,
                modal: true,
                draggable: false,
                show: {
                    effect: "fade",
                    duration: 500
                },
                hide: {
                    effect: "fade",
                    duration: 200
                },
                buttons: {
                    'Close': function() {
                        $(this).dialog("close");
                    }
                },
                close: function() {
                    if (options.focusOn.length !== 0) {
                        $(options.focusOn).focus();
                    }
                    $(this).dialog("destroy");
                }
            });
        },

        updateOptions = function(opts) {
            options = $.extend({}, options, opts);
        };

    return {
        fire: show,
        options: updateOptions
    };

}());


protected $people = array();

public function __construct() {
    $this->people = $people;

This may not be doing what you want.  After doing that, I would expect $this->people to equal null, as you just overwrote the previous value of array() with the value of a previously undeclared variable.

                $this->people[] = $new_person;

Which makes that line create an array the first time that it is reached.

$this->model = $options['model_type'];
$this->type = $options['post_type'];

This is bad style.  You should always declare class properties before using them so that you can give them the proper scope.  This also makes them quicker to access (it checks for declared variables first).

                $new_person = new Person( $person->ID, $person->post_title, get_post_meta($person->ID, '_email_address', true) );

This looks suspicious to me.  Is the post title really a person's name?  If so, you should comment and explain why this would be true.  Otherwise, someone will later create a bunch of posts whose titles aren't people and wonder why posts are showing up under a list of people.

Alternately, if post titles are not names of people, then this type is misnamed.

You also might want to consider extending your class rather than using a switch in get_people.  Then you could have a People class and a Post class, and each could define its own get_people.


Yes, there is at least one way to increase the performance of the adding loop. You should have as few bytecode instructions in that loop as possible. Right now, you are accessing the attribute of a variable. Such an operation can be eliminated by only assigning to that attribute once all of the additions have been run in the given time limit. By starting another thread waiting on a barrier, you can signal the main threading with a keyboard interrupt when the time limit has expired. When handling the exception, that is when you can assign the total number of addition operations to the number's value attribute.
import _thread
import multiprocessing
import threading
import time

def main():
    numbers = tuple(multiprocessing.Value('Q', 0, lock=False) for _ in range(multiprocessing.cpu_count()))
    signal = multiprocessing.Barrier(len(numbers) + 1)
    processes = tuple(multiprocessing.Process(target=count, args=(number, signal)) for number in numbers)
    for process in processes:
        process.start()
    time.sleep(10)
    signal.wait()
    for process in processes:
        process.join()
    print(sum(number.value for number in numbers))

def count(number, signal, temp=0):
    threading.Thread(target=terminate, args=(signal,)).start()
    try:
        while True:
            temp += 1
    except KeyboardInterrupt:
        number.value = temp

def terminate(signal):
    signal.wait()
    _thread.interrupt_main()

if __name__ == '__main__':
    main()


In real code, I would consider this to be too much naming for this little code. Most of this would probably be used only once and could thus be inlined. Since the exercise required implementations for all these, it's okay.

(concat .) . map is foldMap.

\x y -> compare (length x) (length y) is comparing length.

Did you try compiling this? ind /= Nothing means that ind + 1 shouldn't work, and elemIndex takes the Char before the String.

look keys c = case asum $ zipWith (fmap . (,)) [0..] $ map (elemIndex c) keys of
  Nothing -> []
  Just (n, ind) -> [(head $ show n, ind + 1)]


Make all additional threads return from a method using Interlocked.Increment

Yes, your code should work. Though the first part can be simplified to:

if (Interlocked.CompareExchange(ref _threadsCount, 1, 0) != 0)
{
    return;
}


Merge sort implementation: sorting feels clunky

That merge would be clearer as a while (index1 < subArray1.length && index2 < subArray2.length), while bot arrays have elements to be merged in. And you can do 2 System.arraycopys for the remainder afterwards.

while (index1 < subArray1.length && index2 < subArray2.length){
    if (subArray1[index1] <= subArray2[index2]) {
        sorted[i++] = subArray1[index1++];
    else {
        sorted[i++] = subArray2[index2++];
}

System.arraycopy(subArray1, index1, sorted, i, subArray1.length - index1);
i+=subArray1.length - index1;

System.arraycopy(subArray2, index2, sorted, i, subArray2.length - index2);

At the end either subArray1.length - index1 or subArray2.length - index2 would be 0 but then the arraycopy will be a no-op.


More efficient version of an ID calculator in JavaScript

Here's a better implementation.

Used the unary + operator for number conversion.

Used null instead of undefined since it's shorter and produces the same result because of type coersion.

Avoid performing a substring operation by starting to iterate from index 4.

Cached num.length into len so that we save on property lookups when the condition is evaluated for every loop iteration.

Removed uneeded parenthesis.

Took advantage of the += operator.

Made sure that every variables were locally scoped. The _local1 variable in the selected answer isin't properly scoped.

Used a single var statement; it's a better practice to declare variables at the top of the function for readability.

Stole the % 10 idea from the other answer since I thought it was great ;)

 function getidnumber (num, ts) {
    var i = 4,
        len = num.length,
        res = '@user';

    ts = ts == null? '3452' : ts;

    for (; i < len; i++) {
        res += (+num[i] + +ts[i - 4]) % 10;
    }

    return res;
}


Yes, this isn't the canonical way. My solution is to not use Self and to instead focus on shared.
That is:
protocol ImageCacheProtocol {
    func getCache() -> NSCache<AnyObject, UIImage>
}

final class ImageCache: ImageCacheProtocol {
    var cache: NSCache<AnyObject, UIImage> = NSCache<AnyObject, UIImage>()
    static var shared = ImageCache()

    private init() {}

    func getCache() -> NSCache<AnyObject, UIImage> {
        return cache
    }
}

Then the mocks can be altered:
final class MockImageCache: ImageCacheProtocol {
    var cache: NSCache<AnyObject, UIImage> = MockNSCache(shouldReturnImage: true)
    public static var shared: ImageCacheProtocol! = MockImageCache()
    func getCache() -> NSCache<AnyObject, UIImage> {
        return cache
    }
}


Refer to other cells besides the one in the Cells.Find

Firstly, I think you could use VLOOKUP or INDEX & MATCH functions. You code could always fill column A of the Data sheet with the MATCH function and then read down the rows, using the result of the function, instead of the Find method.

Your code currently only finds the first match found, if you want to check for other matches you will need another loop.

If you want to keep this in "traditional" VBA, rather than use ADODB as suggested by @RubberDuck, then there are a couple things you can try:

Try to avoid using ActiveSheet, ActiveCell and Select at all times. I did some testing and this didn't produce much of an imporvement in speed although it makes your code more robust.
Not a performance issue, but in your code you currently have these lines of code:

sEff = rFound.Offset(0, 3).Value
sTerm = rFound.Offset(0, 4).Value

immediately after the Find method but before you have tested if rFound Is Nothing so these lines will throw an error when the Find doesn't return a Range object.
Do you need to search the whole of the User sheet for a matching entry or can you search a single column? Reducing the number of cells through which the Find method must check will give you a big performance increase. So, for example, you could use:

Set rFound = Sheets("User").Range("A1:A26000").Find(What:=sCat, _
                                               LookIn:=xlValues, _
                                               LookAt:=xlPart, _
                                               SearchOrder:=xlByRows, _
                                               SearchDirection:=xlNext, _
                                               MatchCase:=False, _
                                               SearchFormat:=False)

In VBA, the AND and OR operators are not "lazy" and will always test both expressions. You might get some improvement if you split the following line into several If .. Then tests:

If (sDate >= sEff And sDate <= sTerm) Or sTerm = "" Then


Fragile parsing of query parameters

For example, the implementation will silently convert a url like /bbq=grill&pagefilter=foo into /q=grill&filter=foo.

Inappropriate use of query parameters

The example urls use some sort of illegal form of query parameters.
Query parameters should come after ? in a url.
(The part of a url after ? is called the query string.)

Unclear purpose

It seems that encodedVal is the encoded value of q=.
If that's the case, it's not clear from the posted code.
If that's not the case,
then the posted code ignored the value of q=,
and it's not clear why.

On the other hand, the value of filter= is left untouched.

Why not encode all the query values?
It's puzzling.

Complicated parsing of query parameters

The chain of conditions is complicated,
fragile,
and it won't scale if you need to add something else later.
It's hard to understand and to modify.

It would be better to properly tokenize the query parameters into key-value pairs (so an object in JavaScript).
Let's call this object query.
Then, the implementation to build the url fragment can be written a simple straightforward way that's easy to understand and to extend.

var encodedUrl = "";

if (query.q) {
    encodedUrl += "&q=" + encodeURIComponent(query.q);
}

if (query.filters) {
    encodedUrl += "&filters=" + encodeURIComponent(query.filters);
}

// chop off any excess leading "&"
if (encodedUrl) {
    encodedUrl.substr(1);
}

// let's make this a proper query string
this.props.history.push("?" + encodedUrl);


Saving array values for a secondary foreach loop

Your approach seems fine, assuming that the entries in $child_pages are the correct order. I mention that because you mentioned the ordering requirement in the description, but I don't see any supporting logic in the posted code.

If you need to sort the entries yourself, another solution can be sorting using usort() and a custom comparator function:

if the second post is empty, then the first is smaller
else if the first part is empty, then the second is smaller
else perform regular alphabetic comparison

Using such comparator, empty posts will get sorted to the end.


Both of your solutions have efficiency issues, but at least your original list comprehension has the advantage of being short and readable. Your revised solution is arguably worse.

The problem with replicate is that each string is rebuilt from scratch.

The problem with the second solution is that you are using ++, which appends to the end of a list. That requires traversing to the end of the list, which gets more and more time-consuming as the lists get longer. Anytime you write ++, you should try hard to find a better approach.

This is the solution that your professor probably had in mind (note the use of : rather than ++):

aStar :: [String]
aStar = aStar' 'a' ""
  where
    aStar' c s = s : aStar' c (c : s)


Finding whether a number of the form 1444....4 is a perfect square

I suggest you modularize your code writing a function to check for perfect squares:

public static boolean isPerfectSquare(int n) {
    return Math.pow((int) Math.sqrt(n), 2) == n;
}

And you then you can call it:

if (isPerfectSquare(num)) {
                System.out.println(num + " is a perfect square with root "
                    + Math.sqrt(num));
            }

You should also take care of always putting braces, namely

    if (i % (Math.pow(10, power_of_ten) / 100) == 0)
        System.out.println("--- Progress "
                + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");

should become

    if (i % (Math.pow(10, power_of_ten) / 100) == 0) {
        System.out.println("--- Progress "
                + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");
    }

typing braces takes  a fraction of a second, fixing bugs caused by not writing them may take hours.

And make sure you get your indentation correct, after some tweaking in my ide I your code looks like this:

public class OneFours {
    public static boolean isPerfectSquare( int n) {
        return Math.pow((int) Math.sqrt(n), 2) == n;
    }
    public static void main(String args[]) {
        final int power_of_ten = 8;
        int num = 14;
        for (int i = 0; i <= Math.pow(10, power_of_ten); i++) {
            if (isPerfectSquare(num)) {
                System.out.println(num + " is a perfect square with root "
                    + Math.sqrt(num));
            }
            if (i % (Math.pow(10, power_of_ten) / 100) == 0) {
                System.out.println("--- Progress "
                    + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");
            }
            num = num * 10 + 4;
        }
    }
}


Can I simplify this recursive grid search?

It seems to me that most of the body of the first GetNeighbours is extraneous. Wouldn't this be enough ?

public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
    var neighbours = new List<Cell<int>>();

    GetNeighbours(cell, direction, neighboursToGet, neighbours);

    return neighbours;
}

Also, it is redundant to accept neighbours as a read/write parameter and to return it. However, if you are going to do it, you could as well write:

public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
    return GetNeighbours(cell, direction, neighboursToGet, new List<Cell<int>>());
}


Creating Extension Method to map entity with subentities object to Poco object

For this task, i would use AutoMapper, it does exactly what you need, and can work with complex entities.

If you are writing this mapper yourself, consider using expression compilation feature.
Such code will execute at the speed of a custom written code, with all reflection interpretation done beforehand. See the code example for Expression.MemberInit

As for the sub-objects in your code, you will figure out the recursive procedure, as soon as you rewrite your extension to work with a Type argument, not a generic argument. This way you can easily call the procedure for the properties, knowing their type from PropertyInfo.


Read lines from file, calling a consumer function for each line

You are conflating bytes with characters.  An InputStream produces bytes, but you implicitly interpret each byte as a character when you do character=stream.read() followed by the cast lineBuild.append((char)character).  To be clear:

Strings consist of chars, not bytes.
InputStreams and OutputStreams deal with bytes.
Readers and Writers deal with characters.

To read lines as strings, first convert stream to a Reader using InputStreamReader.

BufferedReader br = new BufferedReader(new InputStreamReader(stream, "ISO-8859-1"));

Then, BufferedReader offers a .readLine() method.  Or, since you seem to be interested in a stream-based approach, call .lines(), which produces a Stream<String>.


Smelly code

The parent method smells:

public void setDataSource(DataSource dataSource) {
    this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}

You ask a DataSource, but in fact you need a SimpleJdbcTemplate. this smells...
Let's assume I need to test your code. I run my unit tests and pass in a DataSource, It somehow throws this really weird exception class SimpleJdbcTemplate not found.

This smells because now, your DAO classes are tightly coupled with your SimpleJdbcTemplate class. What if the constructor changes? what if you whant to use something different then SimpleJdbc? ... If you need a class, ask for it.

the fix

public void setSimpleJdbcTemplate(SimpleJdbcTemplate template) {
    this.simpleJdbcTemplate = template;
}

I don't trust my parent

The override in the child classes smell even harder. Your setDataSource method does exactly the same, but yet you @override ? But the only thing you do is delegate everything to the parent. why? what is the logic here?

public, static, private, mess

Some methods are declared public, some are not. And whats it with those private statics? what is the point of those?

Wouldn't it be better to have just one private variable called table that holds the table where you DAO class is looking for persons? And then simply create 2 Objects, one for your new table and one for you historical table?

What happened to this?

Sometimes you use this. in your code, and sometimes you don't? smelly

public PersonDao() {
    final String tableName = getTableName(); // what happened to this?
    fieldNamesCSV = getFieldNames(); // what happened to this?
    String select = String.format("SELECT %s FROM %s ", fieldNamesCSV, getTableName()); //again, where is this?
}

What does your class need

Looking at your constructor, Your class needs nothing. Not even a datasource, or table name or ...

Again, if you need it, ask for it.

The best code quality analysis tool is 'grandparents'

Code should read like poetry. You know what is going on, but it doesn't feel like perfectly written English. If your code is readable, it's good. If it reads a little bit weird, it smells...

for instance your setDataSource method:

  The public returns void method setDataSource needs a DataSource
  object. this simepleJdbcTemplate is now a new SimpleJdbcTemplate that
  needs a DataSource object.

smells right?

Or your @Override method:

  I override the parrent method setDataSource. The new method needs a
  DataSource and passes it to the parent.

hmmm...


Using properties efficiently in inheritance

Accessors in C#
You should read on accessors in C# - your setter does not do what it should - it should set the value if Cname. If this has no meaning (you can't change the value of Cname - you should drop the set altogether.
Correct use of accessors:

public string Name
{
   get
   {
      return name;
   }
   set
   {
      name = value;
   }
}

For read only properties:

public static string Cname
{
   get
   {
      return HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
   }
}

Inheritance and static members
You are asking about efficiency in inheriting properties. I don't know what do you mean by "efficiently inheriting", but static members are not really inherited, you simply get some allowance from calling them in the inherited class...

  Inheritance in .NET works only on instance base. Static methods are
  defined on the type level not on the instance level. That is why
  overriding doesn't work with static methods/properties/events...

Use of properties
When using properties, you imply state of the object you are writing the property on (in this case - Mailer class). From looking at your code, it does not look like its the class's state, but rather a calculation made.
A better choice would be to write it as a utility method, which makes it clear that you are calculating something in it:

public static string ExtractCNameFromCurrentRequest() {
    return HttpUtility.HtmlDecode(
       HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
}

Or you could use an extension method, which will result in a cool usage syntax, and make clear from where you are extracting the CName:

public static class HttpContextExtension {
    public static string GetCName(this HttpContext context) {
        return HttpUtility.HtmlDecode(context.Server.UrlDecode(context.Request["cname"]));
    }
}

And its usage will be:

string cname = HttpContext.Current.GetCName();


Map is not guaranteed to impose or preserve any order for its entries.  For example, if I change Factors to …

private final val Factors = Map(3 -> "a", 5 -> "b", 6 -> "c", 7 -> "d", 8 -> "e", 9 -> "f")

… I get:

⁞
89
bcfa
d
92
a
94
b
cae
97
d
fa
b

So, the fact that you get "fizzbuzz" rather than "buzzfizz" is based on luck, not skill.  If you want to guarantee "fizzbuzz", you need a scala.collection.immutable.SortedMap.


Returning a new object reference when mutation happens

Mutants are not evil.

I am not going to give a line by line review as I do not see this code as having any useful value. Rather is see it as dangerous as it gives a air of safety when none is present, thus much worse than the supposed monsters you wish to banash, as now you say there are none to worry about (in fact there are more).

First some basics..

Mutation

Object mutation is not a bad thing. In javascript it is a fundamental part of the language and contributes much to what makes it such an enjoyable language to use.

Mutation has turned into a cover all term referring to any change to an object, its structure, or content of its properties. The term is synonymous with bad practice, even assigning a variable is considered mutation and bad these days.

The term "Mutation" should be used to only when changes are made in such a way as to result in a state that can not be trusted to work.

Good and bad mutants

Consider the following simple object

var myNum = {
    valueOf : 0,
    add(num) { this.valueOf += num.valueOf; return this },
    toString() { return Number(this.valueOf).toFixed(2) }
};

// created as follows
var numA = {...myNum, valueOf: 1};
var numB = {...myNum, valueOf: 2};

// use it
console.log(numB.add(numA).valueOf); // >> 3
element.textContent = numB;  // >> 3.00

Good mutants

We can mutate it in a variety of ways that do not effect its operational quality. These mutations must be consciously implemented and as long as all involved are aware of the mutation there is no problem

numA.message = "Foobar"; // add a property
numA.toString = function() { return Number(this.valueOf).toFixed(4) }; //instance output format
myNum.toString = function() { return Number(this.valueOf).toFixed(3) }; //default output format
myNum.value = 2; // change its default state

Bad mutants

However there are mutations that are not deliberate, or there is error in understanding that make the object or template untrustable.

numA = 1; // reassignment
numA.add(1); // improper use
numA.value = "2"; // improper type
numA.add = (num) => { this.valueOf += num; return this }; // ambiguous closure use
myNum.toString = function() { return this.valueOf.toFixed(3) }; // missing procedural logic

Does your code protect against mutants?

const numAO = NObject(numA); // original instance remains
const numA = NObject({...myNum, value: "3"}); // already mutated
// next assigns a mutant property
const numAA = numAO.set("toString",function() { return this.valueOf.toFixed(3) });
// There are many more

So... Does your code protect against mutants? No it does not.

The original reference still remains and can be used. Duplication does not stop mutation
The internal state is not protected and manipulated without using the wrappers methods.
Using the wrappers does not stop mutant assignment that can result in untrusted state.
Each wrapper call creates a new instance, yet does not delete old and likely in use references.

And quite franckly you have added another level of procedure that will have a very negative effect on the source code quality and the coders workload. You will stop using it within a few hundred lines of a project as it is cumbersome.

In terms of readability, massive bloat in source size
In terms of comprehension as it does not provide a clear semantic understanding via its naming and how it is used.
Striking at the heart of a coders need to be lazy (AKA succinct, efficient, and elegant) to much overhead and typing.

Trust is not an option.

To protect against bad mutation you can not rely on trust (trust that the object is used correctly). One mistake at any point in using your wrapper and the whole house of cards falls.

Protection MUST be enforceable. Protection against mutation means that you simply can not create bad mutations.

How to protect against mutants

JavaScript is particularly prone to mutation, it is neither type nor object (class) safe.

Mutation has long been a problem in programming, and there are many ways devized to protect against them. Some good some not so good.

Not so good, Functional programing, relies on trust and is next to useless in my view.
Good, Encapsulation. The best ever as it is enforced by fundamental language constructs.

JavaScript provides a strong encapsulation mechanism that can ensure state safety no matter how much the coder wishes to break the rules.

Closure, encapsulates private properties safe from outside mutation.
Constants const as declared variables are immutable
Object methods to help protected properties eg myNum.toString protect against mutation Object.defineProperty(myNum,"tostring",{value : function() { return Number(this.valueOf).toFixed(2) }})
Getters and Setters create read and write only properties, and define a method of vetting state changes to prevent bad mutation.

Example

Taking the myNum example from above and turn it into an immutable object with enforced state safety and trust

const MyNum = (value) => {
    const error = () => { throw new ReferenceError("value is not a number") }
    const vet = (v, suppressError = true) => // vet state
        typeof (v = Number(v)) === "number" ? v : (
            suppressError ?
                0/0 : // creates trusted NaN
                error()
        );
    value = vet(value, false); // vet new internal state
    const add = num => value += num; // encapsulated method safe from mutation
                                     // and can run in trust (no vetting)
    return Object.freeze({ // Frozen object ensures no tampering
        set valueOf(num) { value = vet(num) },
        get valueOf() { return value },
        toString() { return value.toFixed(2) },
        add(myNum) {
            add(vet(myNum.valueOf, false))
            return this;
        },
    });
}


Blockquote

What if nums1's size is small compared to nums2's size? Which
algorithm is better? (The original algorithm problem is from Leetcode
and this is a follow up question to the problem)

It feels like the pointer method always win, but I can't articulate why.

Granted, in many cases, the pointer method might be faster because it might break out of the while after exhausting the elements of the smaller list without having to consider the vast majority of the elements of the larger list.
However, think of a pathological worst case where max(nums1) > max(nums2) such as nums1 = [1_000_000] and nums2 = list(range(100_000)). The pointer approach as shown would have to examine all 100_000 elements of nums2.
What are some ways you can mitigate this?
Taking advantage of the fact that nums1 and nums2 are sorted, you can get the min and max of each list in O(1) and use those values as additional conditions to break out of the while loop earlier.
Given that the input is sorted, binary search might speed things up considerably. bisect.bisect_left is python's own implementation of binary search. Given that sorted input, binary search would allow you to potentially skip over larges swaths of the input as follows:
while p1 < len(nums1) and p2 < len(nums2):
    if nums1[p1] < nums2[p2]:
        # advance p1 to an index s.t. nums1[p1] >= nums2[p2]
        p1 = bisect.bisect_left(nums1, nums2[p2])
    elif nums1[p1] > nums2[p2]:
        # advance p2 to an index s.t. nums2[p2] >= nums1[p1]
        p2 = bisect.bisect_left(nums2, nums1[p1])
    else:
        inter_arr.append(arr_one[p1])
        p1 += 1
        p2 += 1

P.S.:
bisect_left has two optional keyword arguments, lo and hi which might be useful here as well.


Recursive Implementation of Merge Sort C++

First off, I'd use typedef rather than #define.

You don't really need to reference vec.end(); you know mid <= right <= vec.end() and the fact that you're copying the same number of elements back in as you copied out, means you don't need to compare vec_itr to vec.end(). What this really means is that you don't need the vec parameter to MERGE.

vector<T> has a constructor that copies from an iterator. Your push_back for loop could be simplified to

vector<int> left_vec(left, mid);
vector<int> right_vec(mid, right);

The push_back of max() as a sentinel is not strictly needed. Instead, you can just loop until you hit the end of either left_vec or right_vec and then copy the remainder of the vectors to the left to right range.

Your variable names might be easier to understand.

typedef itr vector<int>::iterator;

void MERGE(itr left, itr mid, itr right){
    //Make vector left with elements from left to mid-1 inclusive
    vector<int> left(left, mid);

    //make vector right with elements from mid to right-1 inclusive
    vector<int> right(mid, right);

    // Now concurrently loop over the left and right vectors
    // and add the values back to left to right. Stop when
    // either iterator runs out of elements.
    itr left_src=left.begin();
    itr right_src=right.begin();
    itr dest = left;
    while (left_src != left.end() && right_src != right.end()) {
        // pick the iterator with the smallest current value
        itr& least_src = (*left_src < *right_src) ? left_src : right_src;
        *dest = *least_src;
        least_src ++;
        dest ++;
    }

    // copy remainder of left (maybe 0 elements)
    copy(left_src, left.end(), dest);

    // copy remainder of right (maybe 0 elements)
    copy(right_src, right.end(), dest);
}


You have a docstring and some doctests, which is great! The docstring needs some work, though, as described below.
The docstring needs to mention that the returned function has an add method, and explain what this method does.
The docstring needs to explain how the multiple dispatch works: that is, by exact match on the types of the arguments against the types of the annotations of the function instances. You ought to make it clear that arguments without annotations are ignored by the dispatcher.
The docstring says, "The returned function doesn't allow keyword arguments" but you might want to elaborate on exactly what this means.
The example code in the docstring is not very motivating. Why would I want to want to write a function foo like this? It would be very helpful to the reader if you could come up with an example that more closely resembles a real use case.
A group of multi-dispatch functions is a persistent data structure with two methods (add and __call__) and so would be clearer, I think, if it were implemented as a class.
The introspection code would be much clearer if you used inspect.signature. (This was introduced in 3.3, but since you're using function annotations, you probably don't mind this.)
The function that is decorated with @multi_dispatch is only used for its name, module, and docstring (the items that are copied by functools.update_wrapper). The function body is ignored. This seems like a waste: why not add this function to the registry too?
If you wrote return decorated instead of return func at the end of adder, then you wouldn't have to respell the names of the method instances.

Update: What I mean by this is that you have to spell your method instances _foo rather than foo, to avoid overwriting the multi-method in the variable foo. With my suggestion, you wouldn't have to do this.
Dispatching on the exact types of the arguments limits the usefulness of multiple dispatch. In languages like Common Lisp that have multiple dispatch, dispatching can be performed on subclass matches (not just on exact matches). This makes for more natural fallback code, for example:

@find.add
def find(needle: str, haystack: str):
    # When both arguments are strings, Python has a built-in efficient
    # search operation.
    return haystack.find(needle)

@find.add
def find(needle: Sequence, haystack: Sequence):
    # Otherwise, for generic sequences, use Boyer–Moore–Horspool.
    h = len(haystack)
    n = len(needle)
    skip = {needle[i]: n - i - 1 for i in range(n - 1)}
    i = n - 1
    while i < h:
        for j in range(n):
            if haystack[i - j] != needle[-j - 1]:
                i += skip.get(haystack[i], n)
                break
        else:
            return i - n + 1
    return -1

With your implementation one would have to provide separate method instances for (list, list), (tuple, tuple), (list, tuple) and other combinations of sequence types.

Update: In comments you express concern about the speed of doing the subclass lookups. But you can deal with that by maintaining a cache of the actual argument types and the method instance that was found corresponding to those types. The revised dispatch logic would be something like this:

arg_types = tuple(type(i) for i in args)
try:
    method = cache[arg_types]
except KeyError:
    method = ... # slow subclass dispatch logic here
    cache[arg_types] = method
return method(*args)

(When adding a new method instance, this might invalidate some of the cached lookups, so you'd need to clear the cache in the add method.)
You probably want to look at Guido van Rossum's multimethod implementation for other ideas (like "stacking" of multimethod decorators).


I'll assume the indentation is an artifact of pasting the code here.

The big problem here is that long series of if statements.  A simple improvement is to make use of the else clause, along with knowledge of what values you've tested for already, it can be simplified to

if (sensorValue <= 10)
    UVLevel = 0;
else if (sensorValue <= 46)
    UVLevel = 1;
// etc.

But we can do better.  Since the range of values you're checking with is contiguous, and the result (UVLevel) is linear, we can set up an array to hold the data, then just use a loop to find the right place.

static values[] = { 10, 46, 65, /* ... */, 240 };
UVLevel = std::size(values);    // 12
for (int i = 0; i < std::size(values); ++i)
    if (values[i] <= sensorValue) {
        UVLevel = i;
        break;
    }
}

We initially set UVLevel the the maximum value so that if the sensor value is greater than 240 we get the correct result without having to check after the loop.

For a larger range of possible values, the for loop used here can be replaced with a more complicated binary search.


This won't do much for the performance, but maintaining this kind of T-SQL is painful, so proper formatting is essential.

The FROM clause is hidden, and one has to pay very close attention to notice the ORDER BY clause as well. Consider:

WITH cte (Execution_ID,Intake_Generic_ID, [File_Name],F1,Report_Attributes) AS (
    SELECT
         Execution_ID
        ,Intake_Generic_ID
        ,[File_Name]
        ,F1
        ,CONVERT(XML,
            '<Report><Attribute>' +
            REPLACE(F1,'~', '</Attribute <Attribute>') +
            '</Attribute></Report>') AS Report_Attributes
    FROM [dbo].[Intake_Generic]
)
SELECT
     Execution_ID
    ,Intake_Generic_ID
    ,[File_Name]
    ,LTRIM(RTRIM(Report.value('Attribute[1]','varchar(50)'))) AS [TransactionDate]
    ,LTRIM(RTRIM(Report.value('Attribute[2]','varchar(50)'))) AS [TransactionNum]
    ,LTRIM(RTRIM(Report.value('Attribute[3]','varchar(50)'))) AS [Interchange]
    ,LTRIM(RTRIM(Report.value('Attribute[4]','varchar(50)'))) AS [Gantry]
    ,LTRIM(RTRIM(Report.value('Attribute[6]','varchar(50)'))) AS [GantryDirection]
    ,LTRIM(RTRIM(Report.value('Attribute[7]','varchar(50)'))) AS [GantryEntryExit]
    ,LTRIM(RTRIM(Report.value('Attribute[8]','varchar(50)'))) AS [RTCID]
    ,LTRIM(RTRIM(Report.value('Attribute[9]','varchar(100)'))) AS [Vehicle_Classification_Cd]
    ,LTRIM(RTRIM(Report.value('Attribute[10]','varchar(100)'))) AS [VehicleClassification]
    ,LTRIM(RTRIM(Report.value('Attribute[11]','varchar(100)'))) AS [Txn_Iden_Cd]
    ,LTRIM(RTRIM(Report.value('Attribute[12]','varchar(100)'))) AS [TransactionIdentification]
FROM  cte S
    CROSS APPLY Report_Attributes.nodes('/Report') AS Tbl(Report)
ORDER BY Intake_Generic_ID

XQuery is slower than "normal" T-SQL querying, pretty much by definition.

If the results don't need to be sorted, or if they can be sorted by whoever is consuming this data, then removing the ORDER BY clause should give you a little boost, but I suspect the CROSS APPLY is much more expensive than the sorting.

Looking more closely at what the query is doing, I'd say the XQuery isn't required for this to work - it was clever, but as you saw, a total performance killer.

    ,F1
    ,CONVERT(XML,
        '<Report><Attribute>' +
        REPLACE(F1,'~', '</Attribute <Attribute>') +
        '</Attribute></Report>') AS Report_Attributes

You're building the XML from the contents of F1, by replacing occurrences of ~ within the varchar value.

If the data is shaped anything like a list of comma tilde-separated values, you could write a table-valued function that returns a table with 12 records given that F1 string:

declare @result as table (
     AttributeIndex int
    ,AttributeValue varchar(50)
);

Your CTE could be CROSS APPLY-ing that function with the contents of Intake_Generic, and the actual SELECT wouldn't have much work left to do. And without XML involved, I'm willing to bet that you'd get the results much, much faster.


Scraper to grab a Stack Overflow profile name

IMO the answer highly depends on how you are planning to extend the functionality of your class.
If its only function is fetching the username, it's probably better to transform it into a function. Class is an overkill.

A few thoughts if you're going to expand it:

You can take a look at the Stack Exchange API and see if it matches your needs if you haven't already.
You can cache user data in the class fields.
If you don't care too much about making one extra request, you can make one when you call get_profile. For this, you'll probably need to store the session credentials.
You can try using HEAD method instead of GET when you don't need the body (dunno though if the site will handle it as intended).

Also, in Python 3 there is no reason to extend object for new classes.


Efficiency

The algorithm is suboptimal. Selecting a min is linear in the number of ranges. Arranging them in a priority queue would make it logarithmic.
Correctness

Testing for (min->first != min->second) is done too late. min->first == min->second means that the empty range participated in the comparison. Which in turn means that the end of that range was dereferenced. UB is imminent.

Since

inputs.erase(std::remove_if(std::begin(inputs), std::end(inputs), is_empty_range<I>{}),
std::end(inputs));

guarantees that there are no empty ranges at the beginning, I recommend to rewrite the loop as

while (inputs.size() != 1) {
    auto min = std::min_element(std::begin(inputs), std::end(inputs), range_compare<I, Compare>{comp});
    *output = *min->first;
    ++min->first;
    ++output;

    if (min->first != min->second) {
        inputs.erase(min);
    }
}


Your what variable would be more accessible if it was just an JavaScript Object (w3school javascript objects), instead of list of lists.

var what_object = {
    "what": [
        [
            {
                "link": "http://validator.w3.org/unicorn/",
                "text": "Unicorn"
            },
            {
                "link": "http://validator.w3.org",
                "text": "W3C Validation Service"
            },
            {
                "link": "http://jigsaw.w3.org/css-validator/",
                "text": "W3c CSS Validator"
            },
            {
                "link": "http://text-compare.com/",
                "text": "Text Compare!"
            }
        ],
        [
            {
                "link": "https://imgflip.com/",
                "text": "Imgflip.com"
            },
            {
                "link": "http://jpillora.com/base64-encoder/",
                "text": "Base64 Encoder"
            },
            {
                "link": "http://www.showmycode.com/",
                "text": "Adobe Flash Decompiler"
            },
            {
                "link": "http://jsbeautifier.org/",
                "text": "Beautify Js"
            }
        ]
    ]
};

I have only done indexes 0, and 1.

jQuery.fn.loadWhatList = function(list_location) {

    if (Number(list_location) >= 0) {
        var selected_list_section = what_object.what[list_location];
        if (typeof(selected_list_section) === 'undefined') {
            return false;
        };
        for (var y = 0; y < selected_list_section.length; y++) {
            var selected_link = selected_list_section[y]; // The selected link
            var compiled_link = jQuery("

");
            compiled_link.find('a').attr('href', selected_link.link);
            compiled_link.find('a').html(selected_link.text);
            // Can also do all of your Click Events in here too...
            compiled_link.click(function(e) {
                jQuery(this).toggle();
            });
            // Load the compiled_link to the ELEMENT
            jQuery(this).append(compiled_link);
        };
        return true;
    };

    return false;
};


I am assuming you are used to getters/setters because you are experienced in another language, please don't do this. Performance matters, there is no good reason to download all those functions for no good reason, model-person.js should be

var ModelPerson = (function () {
    'use strict';

    var ModelPerson = function (name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    };

    ModelPerson.prototype.getAge = function () {
        var dateDifference = new Date(Date.now() - this.birthDate.getTime());
        return Math.abs(dateDifference.getFullYear() - 1970);
    };

    return ModelPerson;
}());

Also, updateView does not belong in the controller, it should be part of your view class which should contain all view related logic.

Furthermore, I think in the original pattern, the model actually updates the view, meaning that the controller should not be done the one doing controller.updateView();, that should be handled implicitly by controller.modelPerson.setName(this.textContent);

Personally, I like your approach better, I think the controller should decide when the UI gets updated.

Finally, there is the matter of the element id's like person-name, you use them more than once so you should use a constant. Now the question is, should this constant be defined in Model, View or Controller ? I personally define these id's in the View class and then the controller asks the View what the element is, so that it can attach the listener. I dont think the MVC pattern goes into this detail, so it's up to you.

Other than that, your code is very readable and easy to follow.


Advent of Code Day 6: toggling lights in a grid with Powershell

I assume the Write-Host commands are to view progress/status of the script? I would remove these if you are confident the script is reliable and accurate. Maybe one status (write-host $lightson.Count) after every instruction line.

When you add a light to the list, you don't need to check if it's already in the list. Add will return True/False for its success. Either way, you won't need to check before or after. Just know that if it was on the list already, it will simply return False and carry on. Likewise when removing it from the list.

while ($x -le $maxX){
    while ($y -le $maxY){
        $light = "$x,$y"
        [void]$lightson.Add("$x,$y")
        $y +=1
    }
    $x += 1
    $y = $miny
}

You will also no longer need $light.

When toggling a light, you can again use the return value of Add or Remove:

while ($x -le $maxX){
    while ($y -le $maxY){
        If ($lightson.Remove("$x,$y")) { }
        Else {[void]$lightson.Add("$x,$y")}
        $y +=1
    }
    $x += 1
    $y = $miny
}

Every loop of ForEach is evaluating all three If conditions. You can combine these into an If/ElseIf/ElseIf so subsequent conditions are not evaluated when the first has already succeeded.

For slightly less verbose loops, you could change While loops to For loops. This didn't make a large difference in times though.

I entered the number into the website you linked, and your algorithm did give the correct answer.

$lightson = New-Object Collections.Generic.HashSet[string]
$strings = Get-Content C:\test\lights.txt

foreach ($string in $strings){
    $numbers = [regex]::matches($string,"\d+")
    $minX = [convert]::ToInt32($numbers[0],10)
    $minY = [convert]::ToInt32($numbers[1],10)
    $maxX = [convert]::ToInt32($numbers[2],10)
    $maxY = [convert]::ToInt32($numbers[3],10)

    if ($string -like "turn on*"){
        For ($x = $minX; $x -le $maxX; $x++) {
            For ($y = $minY; $y -le $maxY; $y++) {
                [void]$lightson.Add("$x,$y")
            }
        }
    } ElseIf ($string -like "turn off*"){
        For ($x = $minX; $x -le $maxX; $x++) {
            For ($y = $minY; $y -le $maxY; $y++) {
                [void]$lightson.Remove("$x,$y")
            }
        }
    } ElseIf ($string -like "toggle*"){
        For ($x = $minX; $x -le $maxX; $x++) {
            For ($y = $minY; $y -le $maxY; $y++) {
                If ($lightson.Remove("$x,$y")) { }
                Else {[void]$lightson.Add("$x,$y")}
            }
        }
    }
    write-host $lightson.Count
}


Is this program susceptible to a buffer overflow exploit?

Your program parses the Content-Length header and stores its value in an int called length:

length = atoi (getenv ("CONTENT_LENGTH")))

Then it increments this value and uses it as the argument of a call to malloc():

result = malloc (length + 1))

Suppose I were to post 232−1 bytes of data to your program (about 4 GB in other words). If it's running in a 32-bit environment, the value of length + 1 will overflow to zero. The subsequent call to malloc() will probably succeed, but the call to fread() will crash the program immediately.


File archiver, archive files into a zip file

Code organization

The Main method should be very short, and have almost no logic at all, simply call other methods and create very few objects. Something like this:

static void Main(string[] args)
{
    string filename = archiveCreator.GenerateRandomFilename();

    string userName = Environment.UserName;
    string startDir = $"c:/users/{userName}/test_folder";
    string zipFile = $"c:/users/{userName}/archive/{finalString}.zip";
    string dirName = $"c:/users/{userName}/archive";

    Say("Starting file extraction..");

    var archiveCreator = new ArchiveCreator();
    if (archiveCreator.CreateDirIfNotExists(dirName)) {
        archiveCreator.CreateArchive(startDir, zipFile);
    }

    Say("Press enter to exit..");
    Console.ReadLine();
}

Printing messages

This and the similar methods simply print messages:

public string Success(string input)
{
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine(input);
    return input;
}

As such, these have nothing to do with the logic of creating archives,
so these methods would be better in another class.
Or, you could keep them within this class, but make them static.

Also, I don't see a point in return input,
it would be better to make these methods void.

Error handling

Consider this piece:

try
{
    ZipFile.CreateFromDirectory(startDir, zipDir);
}
catch (Exception e)
{
    info.Warn($"Error: {e}");
}
info.Success($"Extracted files successfully to: {zipDir}");

If an exception occurs in the try block,
the program prints a warning,
but it also prints "Extracted files successfully",
which is just not true.
Probably you want to move that line inside the try block.

Also, the program doesn't check that the directory could be created. It should.

Naming

Symbols in a program should have good names,
to make it easier for readers to understand the program and how the different elements work together.
For example, stringChars, Program, info don't describe well what they are:

var stringChars = new char[8];

Program info = new Program();

I recommend renaming them, for example:

stringChars -> filename or randomFilename
Program -> ArchiveCreator
info -> archiveCreator


Fastest Windows script to move files from one did to a network dir

Okay, I'll start by trying to answer your questions first.

If there is a lot of files and you should look into using runspaces to run several copy-jobs in separate threads. Just be careful, you are still limited by the bandwidth of the network.
We need to see some kind of error to be certain, but I would start by using PowerShell commands instead of old dos commands.

Which leads me to the second part of this answer. The actual code review :)

First thing; if you are going to write a script in PowerShell, use PowerShell commands :) Replace echo with Write-Host and replace mv with Copy-Item.

Second: you don't need | select fullname, lastwritetime. It probably just adds (a little bit of) latency to the execution of the script.

As others have pointed out, you should add some error handling and thinking about what would happen if the destination folder already have a file with the same name. Using -Force is one way, but would overwrite the existing file. So if you don't want this, you will have to handle it differently.

Lastly, if you are new to PowerShell, start commenting your code. You'll thank yourself when you go back to review your scripts 6 months from now :)

Oh, by the way, If you read up on Copy-Item, there is a -Filter parameter that might make the whole Get-ChildItem part of the script redundant.


Merge sort implementation using divide-and-conquer

To expand on CiaPan's answer. Your solution might look like:

result = mergeAndSort([8,4,17,2,1,32]);

You would write code that would do:

let a = mergeAndSort([8,4,17]);
let b = mergeAndSort([2,1,32]);
return merge(a, b);

This would be recursive, so mergeAndSort([8,4,17]) would do:

let a = mergeAndSort([8,4]);
let b = mergeAndSort([17]);
return merge(a, b);

Now mergeAndSort would be called with [8,4] which would be:

let a = mergeAndSort([8]);
let b = mergeAndSort([4]);
return merge(a, b);

Now lastly you have mergeAndSort([8]) which is trivially implemented as

return [8]

Or alternatively, in pseudocode:

function mergeAndSort(array) {
  if (array.length <= 1)
    return array;
  let a = mergeAndSort( leftHalfOfArray(array)  );
  let a = mergeAndSort( rightHalfOfArray(array) );
  return merge(a,b);
}


Optimize LINQ search with custom fixed ranking

Distinct

Take a look at the documentation for Distinct.

A couple things from the remarks should stand out for you:

  The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values.

I know that the order of the sequence is preserved when using Distinct but that's an implementation detail - there's no gaurantee.

  The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you must implement this interface and provide your own GetHashCode and Equals methods for the type.

Your custom type Counterpart does not do this. It should implement IEquatable<Counterpart> and additionally override both GetHashCode and Equals.

public class CounterPart : IEquatable<Counterpart>
{
    // ...
    public bool Equals(Counterpart other)
    {
        // left for you.
    }

    public override bool Equals(object other)
    {
        return Equals(other as Counterpart);
    }

    public override bool GetHashCode()
    {
         // http://stackoverflow.com/a/263416/1402923
    }
}

Now you have a type that is safe for use with Distinct!

AddRange

As far as I know, AddRange only throws when the collection is null. You don't need to check for items before you call it. That elminates a whole heap of code:

rankedItems.AddRange(items1.Select(x => new CounterPartRanking { Rank = 1, CounterPart = x }));
rankedItems.AddRange(items2.Select(x => new CounterPartRanking { Rank = 2, CounterPart = x }));
rankedItems.AddRange(items3.Select(x => new CounterPartRanking { Rank = 3, CounterPart = x }));
rankedItems.AddRange(items4.Select(x => new CounterPartRanking { Rank = 4, CounterPart = x }));
rankedItems.AddRange(items5.Select(x => new CounterPartRanking { Rank = 5, CounterPart = x }));
rankedItems.AddRange(items6.Select(x => new CounterPartRanking { Rank = 6, CounterPart = x }));
rankedItems.AddRange(items7.Select(x => new CounterPartRanking { Rank = 7, CounterPart = x }));

Other comments

As I mentioned previously, this isn't gauranteed to be correct (but is in every instance I know of):

var items = rankedItems.OrderBy(x => x.Rank).Select(x => x.CounterPart);
var distinct = items.Distinct();


Is this actually a good alternative to the second version that uses indexing? And if so, how could it be improved?

I'm not sure what you're asking here. Obviously the first version is fine; obviously the second version is pretty silly (because it does the same thing as the first version but in a more confusing and verbose way).

As for "using indexing", doesn't the first version also use indexing? What do you think argv[i] is, if not "indexing"? It sure seems like you've got the hang of "indexing" well enough. :)

Your second program is also silly in that it uses a while loop instead of a for loop, even though you have all three pieces of a for-loop (initialization, condition, and increment) in close proximity. Why didn't you use a for loop? Just for practice with different kinds of loops? In that case, I'd dock you points for not using a do-while loop! ;)

To nitpick as long as I'm here:

Everyone will tell you (so you might as well start listening now) that using namespace std is a bad habit. Write std::cout and std::endl explicitly.
You have a stray ; on line 1 — a transcription error, since the compiler wouldn't accept it if you actually tried to compile that.
Your second program uses saner loop index names: i and j. Naming a loop control variable number is more likely to confuse the reader than help them.
Explicit return 0 from main is unnecessary in C++ (and also in C, as of 18 years ago). Omitting it from simple programs like this can help the reader focus on the important stuff instead of the boilerplate.

Putting it all together:

#include <iostream>

int main(int argc, char **argv)
{
    for (int i = 1; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}


IEnumerable extension method that ingests SqlCommand and returns query results

You are never using b in the method. Why make it an extension method if you are going to completely ignore the first argument? In order to use this code, you need to create a new instance that is immediately thrown away. That is unneeded waste.

Instead, you can just specify the generic type in the function call.

public static IEnumerable<T> FromCommand<T>(SqlCommand command)
{
    // ...
}

[Description("Selects and returns all rows.")]
public static IEnumerable<MyType> SelectAll()
{
    SqlCommand command = new SqlCommand(QueryRepository.SELECT_MyType_ALL, Conn.ConnectionString) { CommandTimeout = 0 };

    return FromCommand<MyType>(command);
}

The expression that assigns to properties is over 100 characters. That doesn't count the indentation or the variable declaration. That is going to be hard to follow. I suggest that you extract the lambda being passed to Where() into a static function with a descriptive name. That way I don't need to think about what is being filtered out.

You are adding extra blank lines after opening curly brackets and before some closing curly brackets. This is just inflating the file size and not helping readability.


I like the simplicity of just using unquote at the module level to generate the defs, such as:

defmodule MyModule do
  def do_map_stuff(method, arg) do
    IO.inspect([method, arg])
  end

  Enum.each [:method1, :method2, :method3], fn method ->
    def unquote(method)(map) when is_map(map) do
    do_map_stuff(unquote(method), map)
  end

    def unquote(method)(arg)  do
    do_map_stuff(unquote(method), arg)
    end
  end
end


Here are a few tips:

Do not use select *, instead type out all the columns you need to insert into. It should be done in both your select and insert statements.
For the subquery in the where clause, you can store the result from that query in a temp table and then use that temp table for the where clause so it does not need to check while inserting the data.
Try to add an index to your tables which are unique so you can do faster and more efficient queries.


You say that using itemgetter is better than using choices.get, as you don't have to call get multiple times,
however this is wrong.

If we look at itemgetter it says that it uses __getitem__.
Python's function get also uses __getitem__ but allows a default value.
And so the following give the same:

print(itemgetter(3, 5)(choices))
print(tuple(map(choices.get, [3, 5])))

As you say using the above is bad, as it doesn't print things on new lines, you could use str.join.
As you want to join each one with a newline or '\n'.

print('\n'.join(map(choices.get, [3, 5])))

In both examples this won't give the same output as your inefficient code.
As there are no numbers before the choice.

To improve your inefficient code, you could alternately make an options dictionary,
and use options.get but with a supplied default value.

options = {
    1: "Welcome to Staff Payments",
    2: "Welcome to Finance"
}
print(options.get(option, "Error."))

Alternately to your current code pattern, you can make a dictionary holding users with places they are allowed to.
This would be by supplying user-names, and the allowed places in a dictionary.

# Access control list
ACL = {
    "Mike": [3, 5],
    "Joe": [1]
}

places = ACL[user_name]
options = dict(enumerate(map(choices.get, places)))
print("-Managing Menu-")
for option, num in choices.items():
    print("{} {}".format(option, num))

option = int(input("Option Choice (1-2): "))
while option not in range(1,2):
    option = int(input("Option Choice (1-2): "))

if option == 1:
    print("Welcome to Staff Payments")
elif option == 2:
    print("Welcome to Finance.")
else:
    print("Error.")

As you can see, whilst we took advantage of a new dictionary to print the allowed places,
you would still need boilerplate for all the locations.
Instead you could use str.format to display the places, just like I did for the menu.

choices = {
    1: "Student Details",
    2: "Student Grades",
    3: "Finance",
    4: "Staff Details",
    5: "Staff Payments"
}

def managing_menu(user_name):
    places = ACL[user_name]
    options = dict(enumerate(map(choices.get, places)))
    print("-Managing Menu-")
    for option, place in choices.items():
        print("{} | {}".format(option, place))

    option = int(input("Where do you wish to go: "))
    while option not in options:
        option = int(input("Where do you wish to go: "))

    location = options.get(option, None)
    if location is None:
        print("Error.")
        return

    print("Welcome to {}.".format(location))

There are some other ways that you can improve the code:

don't use raw int(input())'s instead use them with a try and except.
This will cause the program to not crash if you enter Finance, rather than 2.
You also are probably calling a function after printing "Welcome to Finance",
and so you would need to add that functionality to the options dictionary.
(It's not hard)
You should change the place you define option to become a function,
this is as you are likely to need the function in more than that one location.


You should decide if your functions modify the object they receive or if the return a modified object. Doing both is just asking for disaster. After your code has finished, file_1, file_2 and file_3 are all identical.

The usual convention is to return None (implicitly or explicitly) if you mutate any of the inputs. In the rest of this answer I have decided to mutate the inputs.

Besides that, pandas is most effective if you use its vectorized functions. For columns with strings, it has a whole lot of methods which are vectorized. You can access them with df.col_name.str. You can find some examples in the documentation.

Your appends_address_before_name function could be simplified a lot because string addition is vectorized:

def appends_address_before_name(file):
    file["parentID"] = address + file["parentID"]
    file["ID"] = address + file["ID"]

And your create_parent_name function could be:

def create_parent_name(file, column_name: str):
    file["parentID"] = file[column_name].str.split(".").str[:-1].str.join(".")

With a csv file like this:

ID
99.99.9
100.42.3
101

This produces

df = import_file(file_name)
create_parent_name(df, 'ID')
appends_address_before_name(df)
print(df)
#                     ID           parentID
# 0   New_Jersey_99.99.9   New_Jersey_99.99
# 1  New_Jersey_100.42.3  New_Jersey_100.42
# 2       New_Jersey_101        New_Jersey_

Note that the order of the calls has changed, so that ids without a . are handled correctly.

As for general structure:

Seeing docstrings is very nice (I omitted them here for brevity)
Python has an official style-guide, PEP8. It recommends writing x = some_thing(a=3), so surround equal signs with spaces when assigning but not when setting keyword arguments.
You should wrap the main calling code in a if __name__ == "__main__" guard.


Rails guestbook with new, index, and Kaminari pagination in the same method

Yes, there's a lot that can be done differently.

Firstly, Ruby convention is 2 spaces of indentation. Not 4, not tabs.

Secondly, Guestbook isn't a great name for your model. You're modelling entries in a guestbook, not multiple guestbooks.

Mostly, though I fail to understand the structure of your pages. If you go to index you load all the entries. If you go to new you... also load all the entries. But then you do some pagination, which, in effect, discards all but 5 of the records you just loaded from the database. Imagine how well that'll work if you have thousands of entries...

But why is the new action listing and paginating anything? That's the job of the index action; to list things, to be an index. Sure, you can combine the two by having a form and a list on the same page, but in that case it should be on the index view.

I'd cut the controller down to this (keeping, for now, the Guestbook model name):

class GuestbooksController < ApplicationController
  before_action :load_guestbooks

  def index
    @guestbook = Guestbook.new
  end

  def create
    @guestbook = Guestbook.new(guestbook_params)

    if @guestbook.save
      redirect_to guestbooks_url, notice: "Thanks for taking the time to write us! We greatly appreciate it!"
    else
      flash.now[:alert] = "Your message failed to post, please try again"
      render :index
    end
  end

  private

  def load_page
    @guestbooks = Guestbook.page(params[:page])
  end

  def guestbook_params
    params.require(:guestbook).permit(:name, :email, :message)
  end
end

No new action whatsoever. I haven't used kaminari, but just going to its github page I see several examples of usage that are much cleaner than loading everything. The whole point of pagination is not do that.

For your view (which should be the index view), I would read up on class naming, semantics, and HTML in general, I'm sorry to say. For instance, the hr tag could save you a few dozen hyphens, and span1, span2 etc. are not useful names for anything - certainly not divs. And don't use br for layout; use CSS.

Also, look into partials, aka partial views. If a partial is properly used, the whole entries list can be rendered as just:

<%= render @guestbooks %>

Lastly for the view, simple_form does not need a url or method argument if they can be derived from the record. Which they can in this case.

For your routes, you only need this:

resources :guestbooks, only: [:index, :create]

The paths in your question do not look strange: Two of them are both called guestbooks_path because they do indeed have the same path - but the action they invoke depend on the method (POST or GET) used. If you POST to /guestbooks it'll invoke the create action; if you simply GET /guestbooks, it'll invoke the index action. That's the basic premise of routing in Rails.


_logTooBig: function(obj, limit) {
  if (limit > 200) {
    console.log('Object too big, memory leak? [size: ' + limit + ']')
    console.log(obj)

Naming: Surely the parameter you've called limit ought to be named size! The word "limit" implies an upper bound, as in "speed limit". In this case, the "limit" on object size is 200. The parameter you've currently called limit is the thing you're supposed to be comparing to the size limit. What it actually represents is just a size.

Separately, are you at all worried that repeatedly console.logging (only) huge objects will be a bad debugging experience? Or do good browsers already handle huge objects just fine?

var self = MemoryLeak;
self.checked++

Syntax nit: missing semicolon after ++. This is legal of course, but I think many linters will flag it as an inconsistency.

Why do you do this thing with self = MemoryLeak instead of just saying this.checked++? I might be exposing my own lack of knowledge here, but I thought this was supposed to do the right thing in "member" functions called with the MemoryLeak.foo() syntax. Is your use of self actually working around a problem with this, or is it just an idiosyncrasy that could be cleaned up?

try {
  return obj instanceof Array
}
catch(e) {
  return false;
}

Again I may be exposing my own lack of knowledge, but I'm about 75% sure that instanceof cannot possibly throw an exception. What case are you worried about here?

  _keys: function(obj) {
    var rval = [], prop
    for (prop in obj)
      rval.push(prop)
    return rval;
  };

This should at least be rewritten

  _keys: function(obj) {
    var rval = [];
    for (var prop in obj)
      rval.push(prop);
    return rval;
  };

and (unless I'm missing something) it should simply be

  _keys: function(obj) { return Object.keys(obj); }

if(!obj || (typeof obj == 'function') || self.checked > 20000)
  return;

I see where you initialize checked = 1 and where you checked++, but I don't see anywhere that checked's value decreases or is reset. So do you only ever check 20000 entities and then stop checking forever? That doesn't seem like super useful behavior, since memory leaks typically manifest only after a fairly long time. What's the point of the checked counter? (If you keep it, then it would be a good idea to add a //code comment explaining why it's desirable. Code comments are great for explaining the "why" of code.)

Speaking of "explain the why": it would have been nice to see an example of how you expect the user to use this leak checker. I gather that he'd just insert a call to MemoryLeak.checkLeaks(mySuspiciousObject) after initializing the object, and that would trigger the checking of mySuspiciousObject every 5 seconds for 20000 iterations?

Certainly exposing my ignorance: I wasn't aware that all your };s were legal. I thought you'd have to make them },.


Pairing Labels with Images when building a UI

A HashMap does not guarantee any order whatsoever, so that is a bad idea to use.

Your Image and Label belongs together, so make a class where they actually do belong together.

public class StarView {
    private final Label label;
    private final Image colorImage;
    // constructor and stuff...
}

private void createContents() {
    this.contents = new ArrayList<StarView>();

    for (Star star : this.game.getPlayerStars()) {

        Image starImage = new Image(this.libGDXGame.starTextures.get(star.type));
        starImage.addListener(new StarClickListener(star) {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                StarScrollPane.this.gameScreen.playerClickedStar(star);
            }
        });

        Label starLabel = new Label(star.type.name(), this.libGDXGame.skin);

        this.contents.add(new StarView(starLabel, starImage));
    }

    for (StarView starView : this.contents) {
        this.starTable.add(starView.label);
    }

    this.starTable.row();

    for (StarView starView : this.contents) {
        this.starTable.add(starView.image).width(width).height(height);
    }
}

This could be combined with @Vogel's suggestion about changing the layout manager. Or you could make the StarView extend Actor and put it in a horizontal group.


Work in Unicode and encode at the last moment:

def entry2html(**kwargs):
    """ Format feedparser entry """
    template = u"""

{title}

    {title}
    {description}
    """
    return template.format(**kwargs)

def convert_feed(**kwargs):
    """ Main loop """
    out = u'\n'.join(entry2html(**entry)
                    for entry in parsefeed(kwargs['url']).entries)
    return out.encode('utf-8')

You can pass entry directly as format does not mind extra keyword arguments. StringIO is not necessary for simple concatenation of strings.


Better way of setting input scope on text box in WP7

I'm not really sure what you want from this, if all you want is to make it more readable, then a few well placed new-lines will make a world of difference. If you want to reduce the amount of code, I don't think there is much room for that other than switching constructors for InputScopeName.

txtBox.InputScope = new InputScope
{
    Names =
    {
        new InputScopeName(InputScopeNameValue.Text)
    }
};

Note: Text does not appear to be a valid member of InputScopeNameValue, but ill keep it for the sake of consistency with the question.


preferably into one-liner with high-order-functions.

Machines execute code the same way, minified or not. But a human doesn't read or understand minified code the same way as verbose JS. Write for a human, don't one-line code.

Now one thing about your code. You do NOT compare booleans. if statements evaluate booleans. If your expression is already a boolean, then just use that boolean. If you need to negate it, use !.

case DrivesPageActions.DrivesPageActionTypes.AddCustomGroup:
  if (!state.customGroups.includes('A1')) {
    return {
      ...state,
      customGroups: [...state.customGroups, 'A1']
    };
  } else if (!state.customGroups.includes('A2')) {
    return {
      ...state,
      customGroups: [...state.customGroups, 'A2']
    };
  } else {
    return {
      ...state,
      customGroups: [...state.customGroups, 'A3']
    };
  }

Looks like your code is looking for A1, A2 and A3 in that order and adding the first one that's not found. You could just create an array of the three, then filter it by the array in the state, removing the ones already present. The first item in the filtered array is the item you want.

const inserts = ['A1', 'A2', 'A3']
const defaultInsert = inserts[inserts.length - 1]

function reducer(state, action){
  switch (action) {
    case 'AddCustomGroup':
      const missing = inserts.filter(v => !state.customGroups.includes(v))
      const insert = missing[0] || defaultInsert
      return { ...state, customGroups: [...state.customGroups, insert] }
    default:
      return state
  }
}

console.log(reducer({ customGroups: [] }, 'AddCustomGroup'))
console.log(reducer({ customGroups: ['A1'] }, 'AddCustomGroup'))
console.log(reducer({ customGroups: ['A1', 'A3'] }, 'AddCustomGroup'))
console.log(reducer({ customGroups: ['WORD', 'A2'] }, 'AddCustomGroup'))


You're looking for the First Monoid instance for Maybe. Used like—

import Data.Foldable (foldMap)
import Data.Monoid (First(..))

fractionParse :: String -> FractionParse
fractionParse s = fromMaybe Rubbish . getFirst
                $ foldMap First [ maybeFraction s
                                , maybeWhole s
                                ]

It doesn't make sense to encode your own failure values in your datatypes, so I'd remove the Rubbish Constructor.

data FractionParse = Fraction Int Int | Whole Int
  deriving (Show, Eq)

fractionParse :: String -> Maybe FractionParse

Use Control.Monad.guard instead of manually sending up your own sentinel values (as in maybeNumDenom).

maybeNumDenom s = do
  guard $ containsExactlyOneSlash s
  -- ...

Take advantage of incremental parsing to implement maybeNumDenom, then you won't have to do so much extraneous filtering, counting, and finger crossing. And by removing the Rubbish constructor, at the point you have a correct parse you know you can return a Fraction, so—

import Data.Maybe (listToMaybe)

maybeFraction :: String -> Maybe FractionParse
maybeFraction s = listToMaybe $ do
  (n, '/':s') <- reads s
  (d, "") <- reads s'
  return (Fraction n d)

The above function operates in the list monad. listToMaybe converts a list to a Maybe value by returning Just the first element of the list, or Nothing in the case of an empty list. reads :: Read a => String -> [(a, String)] produces possible parses from a given string, returning the remainder of the unparsed string as the second element of each tuple. Binding to (d, "") ensures that only parses that consume the whole string will be returned.


Dependencies: right now your makefile will let changes in .h to remain unnoticed.

DEPS := $(SOURCES:.c=.d)

.c.d:
    $(CC) -o $< -MM $(CFLAGS)

-include $(DEPS)

PS: it is highly recommended to remove -c from CFLAGS and mention it explicitly in the .c.o rule.


I would use a library that is designed for this, such as Moment.js.  It is a lot more flexible, and has internationalization support also.


Version A is definitely better, as it employs a more familiar pattern to get the job done, and it makes use of bit of trivial code (boolean lIsFirstIteration = lBbox == lPreviousBbox) to save you from duplication of non-trivial code. (lIndexFromBbox.put(lPreviousBbox, lCurrentIndex))

I would trivialize the trivial code even more, by saying bool IsFirstIteration = true right before entering the loop, and IsFirstIteration = false as the last instruction of the loop. Note that even though this is two lines of code instead of one, its complexity is smaller, because it deals with constants, not with variables.

I could perhaps give more advise if you explained what you mean by 'algorithm to position boxes in a grid'.  A grid is generally thought of as a two-dimensional structure, but I only see operations in one dimension, on variables which are defined outside of the code fragment that you provided, so... what is this code trying to accomplish?


Aggregation of a collection of object's nested array-properties

From a once over :

This is a problem : var search = JSON.stringify(obj); because JSON.stringify() does not guarantee any order.. To be completely correct I think you are going to need to pass the properties to arrayObjectIndexOf that need to get compared ( that is, if uniqueness is determined by only comparing the provided properties, otherwise you are in a world of trouble )
"Inner property is not a collection!" <- Perhaps props[l-1] + " is not an array!", then you will provide which property is not an array, and be clear that you are expecting an array
"Property doesn't exist!" <- "Property " + props[j] + "does not exist" will give a better feedback as to which part is not working
JSHint.com could only find semicolon issues, which is good


Code to find value into a table by 2 criteria (x,y)

First step:

Write down your assumptions

These would be mine;

This data table has a header row in row 1 and a header column in column A.
The values in the headers could be any legal text.
The values in the headers are unique

What's the fastest way to find an exact match in a list?

My answer: A dictionary (or any other Linked-List object)

Dim rowList as Scripting.Dictionary, columnList as Scripting.Dictionary
    Set rowList = New Scripting.Dictionary
    Set columnList = New Scripting.Dictionary

    finalrow = Cells(Rows.Count, 1).End(xlUp).Row
    finalColumn = Cells(1, Columns.Count).End(xlToLeft).Column

Dim cellText As String

    For i = 1 To finalrow
        cellText = Cells(i, 1).Text
        rowList.Add cellText, i
    Next i

    For i = 1 To finalColumn
        cellText = Cells(1, i).Text
        columnList.Add cellText, i
    Next i

Now we have 2 dictionaries, where each row/column (i) is referenced by its cell value.

rowList.item("0") will return row "5", "100" returns row "6" and so on. This will work with any size of table and any possible values for the headers, so long as there are no repeated values.

Now you just take your 2 input values, access the associated items, and either they exist and you have your co-ordinates, or they don't exist, and you can tell your user.

For added speed, read your row/column into an array before iteratively adding them to your list.

Bonus: Aside from the initial time to create the lists, searches are effectively instant for any size of list and any number of searches.


Passing Array into Unmanaged Code for Modification

You must definitely call handle.Free() when finished using it so GC can do the cleaning.

Note that GCHandle.Alloc(objects, GCHandleType.Pinned); only works for structs with pure primitive or to be more precise: blittable types. String fields etc. must be handled differently.

A little optimization:

You repeatedly calculate this

  var offset = Marshal.SizeOf<MyObject>() * i;

Instead you can calculate offset once:

var offset = Marshal.Sizeof<MyObject>();

and in the loop do:

ptr = IntPtr.Add(ptr, offset);

If you are willing/allowed to run in unsafe mode you can do:

unsafe public void RunUnsafe()
{
  var objects = new MyObject[3];

  var handle = GCHandle.Alloc(objects, GCHandleType.Pinned);
  var ptr = GCHandle.ToIntPtr(handle);

  ArrayTest(ptr, objects.Length);
  MyObject* pobj = (MyObject*)ptr;

  for (int i = 0; i < objects.Length; i++, pobj++)
  {
    Console.WriteLine((*pobj).X);
  }

  handle.Free();
}

If you are entitled to modify the signature of ArrayTest, you can changed it to:

    public extern static void ArrayTest([In, Out] MyObject[] objects, int length);

The [In, Out] attributes determines that the array should be marshaled both ways so that ArrayTest can work on the provided instances in the array [In], and changes made in ArrayTest are reflected in the objects when the function returns [Out].

Then your method can be simplified to:

  var objects = new MyObject[3];

  ArrayTest(objects, objects.Length);

  foreach (var obj in objects)
  {
    Console.WriteLine(obj.X);
  }


Computation for finding the largest prime factor of 600851475143 is slow

Your algorithm doesn't scale.  In this answer, I've outlined the three common strategies for finding the largest prime factor of a number, only one of which is reasonably efficient.  You've chosen Option 2 (testing largest candidates first, then check for primality).  However, you start at \$\lfloor\frac{n}{2}\rfloor\$ rather than \$\lceil\sqrt{n}\rceil\$, which is even less efficient, and furthermore it incorrectly produces Nothing whenever n is already prime.

Here's a Haskell implementation of Option 3 (testing smallest candidates first):

largestPrimeFactor :: Integer -> Maybe Integer
largestPrimeFactor n
  | n <= 1    = Nothing
  | otherwise = Just $ largestPrimeFactor' n (2 : [3, 5..])
  where
    largestPrimeFactor' n pseudoprimeCandidates@(c:cs)
      | c * c >= n = n
      | m == 0     = largestPrimeFactor' d pseudoprimeCandidates
      | otherwise  = largestPrimeFactor' n cs
      where
        (d, m) = divMod n c

Personally, I'd avoid contaminating the output with Maybe, since Nothing will only result from obviously illegal input anyway.

largestPrimeFactor :: Integer -> Integer
largestPrimeFactor n
  | n <= 1    = error "largestPrimeFactor n where n <= 1"
  | otherwise = largestPrimeFactor' n (2 : [3, 5..])
  where
    largestPrimeFactor' n pseudoprimeCandidates@(c:cs)
      | c * c >= n = n
      | m == 0     = largestPrimeFactor' d pseudoprimeCandidates
      | otherwise  = largestPrimeFactor' n cs
      where
        (d, m) = divMod n c


Is there a cleaner way of building a list of the previous, next months than this?

Based on this answer, I would do something like :

from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
months = [today + relativedelta(months = +i) for i in range(2,-3,-1)]

It's always better not to have to play with the dates manually as so many things can go wrong.

(I don't have access to a machine with relativedelta here so it's not tested but I'm pretty confident it should work)


LINQ isn't a silver bullet. It stands for Language-INtegrated-Query, which allows querying objects.

Querying objects isn't something that's supposed to have side-effects. However this is precisely what you loop's body is doing.

Therefore, refactoring it to use LINQ, if at all possible, would make it much less readable than the foreach loop you have here.

You could always create a Task object for each notification, and then run that.

Now the loop body you have, is using AddRange to add what appears to be a single value. Unless notification.ID is an IEnumerable<whatever>, you should be using the Add method to add a single value to your successNotificationIDs.


Download file and connect: if one of them fails, go to step one

Globals & Public Static Fields

public class Globals
{
    public static int sockConn = 0;
    public static bool sockRetry = false;
}

You put a beginner tag on your post, so I'm going to try do be gentle: please kill this, with fire! :)
A non-static class that's called Globals, that only contains public static fields, smells. Why? Because in an object-oriented paradigm language, globals stink and make everything more complicated than need be.

Side note: naming.
C# coding standards recommend using camelCase for local variables and parameters. Public members should be PascalCase.

OOP Basics #1: Encapsulation
Avoid exposing public fields. Always. Not because they're static - because they're fields. Fields belong to a class instance (or, when they're static, they belong to a type), and should be considered implementation details that the outside world never needs to know about. Consider systematically encapsulating fields with properties:
private int sockConn = 0;
public int SocketConnectionCount { get { return sockConn; } set { sockConn = value; } }

In this case, there isn't really a gain with the backing field - so you can have the C# compiler make one for you, leaving you with a cleaner code file:
public int SockConnectionCount { get; set; }

This is called an "auto-property". Compiler magic! :)

Thinking in Objects
Think in terms of responsibilities - what is your code accomplishing?

Creating and sending a web request, receiving a web response.
Streaming the response into a string.
Splitting the string into an array; element 0 being the IP, element 1 being the port.
Connecting to the IP/port and receiving a message through TCP/IP.
Parsing the received message.

Break this down into their own methods/functions that do one thing, so simply that they can't possibly do it wrong. Then regroup the related ones into their own classes, and instantiate them.

Wait, something caught my eye and needs to be addressed:

int serverPort = 5000;
Int32.TryParse(serverPortStr, out serverPort);

out serverPort is an out parameter - the method it's passed into has to initialize it before it returns. In other words, the 5000 is never used. And you're never using the TryParse method's return value either (it's a Boolean that tells you whether the parse succeeded or not). out parameters are the only time you can pass an uninitialized variable into a method and have nothing to worry about. The above lines should read something like this:
int serverPort;
var result = int.TryParse(serverPortStr, out serverPort);
// do something if result is true

Avoid Hungarian-ish postfixes (and prefixes as well); If you need to specify that a variable is a String, it's because you haven't found a truly meaningful name for it. Notice I called the TryParse method on the int type. It's the very same thing as Int32 - in fact, int is a C# language shortcut for System.Int32; both are perfectly interchangeable... but it's better to choose one, and stick to it, for consistency's sake! :)


Is this a good Ruby implementation of Prime Factorization?

Reinventing the wheel

There is an easier solution, considering that you are using the Prime class, which already has a Prime.prime_division() method that does almost the same thing.  The only difference is the output format: your prime_factorization(360) would output [2, 2, 2, 3, 3, 5], whereas Prime.prime_division(360) would output [[2, 3], [3, 2], [5, 1]].  It's just a matter of converting the output by repeating each prime factor the specified number of times.

require 'prime'

def prime_factorization(n)
  Prime.prime_division(n).flat_map { |factor, power| [factor] * power }
end

(Thanks to @Flambino and @tokland for simplifying the transformation.)

Critique

You've asked some very interesting questions.

The big-O complexity of this method is not at all simple to analyze.  You call methods such as Prime.prime?() that in turn make use of a generator.  Then you also call Prime.take_while(), Prime.prime?(factor).  On top of that, there's recursion.   All I will say, though, is that the method can be very inefficient.

The initial call to prime?(n) already does a trial division that resembles the kind of work your method will perform.  Calling prime? is altogether redundant — see Simplification 1 below.

The call to primes ||= Prime.take_while { |p| p < n / 2 } can also be very inefficient.  For example, to calculate prime_factorization(360), you would be asking it to generate primes up to 179, even though no prime factor above 5 exists.

Ruby provides an Integer.divmod() function that lets you avoid having to recalculate n / p immediately after having ascertained n % p == 0.

When you recurse, you test every prime number all over again, starting with 2, 3, 5, ….  Rather, you want to be able to continue by testing the same prime factor that succeeded.

Simplification 1

Assuming that you are deliberately reinventing-the-wheel, you can still improve your method in several ways:

Eliminate calls to prime?
Make early termination work by removing take_while in favour of a break
Use divmod
Replace recursion with looping
Just yield factors as you detect them.  Let to_enum and to_a take care of appending results to the array.

def prime_factorization(n)
  def factor_generator(n)
    Prime.instance.each do |p|
      break if p > n
      begin
        div, mod = n.divmod(p)
        if mod == 0
          yield p
          n = div
        end
      end while mod == 0
    end
  end

  to_enum(:factor_generator, n).to_a
end

Simplification 2

The implementation above is still inefficient, since there is already primality testing hidden inside Prime.instance.each.  To avoid duplication of effort between your code and the Prime class, you should be able to test any increasing sequence of numbers that is not obviously composite.

def prime_factorization(n)
  def factor_generator(n)
    for prime_candidate in Prime::Generator23.new
      break if prime_candidate > n
      begin
        div, mod = n.divmod(prime_candidate)
        if mod == 0
          yield prime_candidate
          n = div
        end
      end while mod == 0
    end
  end

  to_enum(:factor_generator, n).to_a
end