Searching for a value from one CSV file in another CSV file

What you want is a mapping from the product code (the key) to a stock level/result code (the value). In Python this is known as a dictionary. The way to do it is to go through your check file at the start, and use the information in it to create a dictionary containing all the stock level details. You then go through your input file, read in the product code, and retrieve the stock code from the dictionary you created earlier.

I've rewritten your code to do this, and it works for the example files you gave. I have commented it fairly thoroughly, but if there is anything unclear in it just post a comment and I'll try to clarify.

import csv

# Open the check file in a context manager. This ensures the file will be closed
# correctly if an error occurs.
with open('checkfile.csv', 'rb') as checkfile:
    checkreader = csv.DictReader(checkfile)

    # Create a function which maps the stock level to the result code.
    def result_code(stock_level):
        if stock_level > 0:
            return 3746
        if stock_level == 0:
            return 3745
        return " "

    # This does the real work. The middle line is a generator expression which
    # iterates over each line in the check file. The product code and stock
    # level are extracted from each line, the stock level converted into the
    # result, and the two values put together in a tuple. This is then converted
    # into a dictionary. This dictionary has the product codes as its keys and
    # their result code as its values.
    product_result = dict(
        (v['ProductCode'], result_code(int(v[' Stock']))) for v in checkreader
    )

# Open the input and output files.
with open('infile.csv', 'rb') as infile:
    with open('outfile.csv', 'wb') as outfile:
        reader = csv.DictReader(infile)

        # Use the same field names for the output file.
        writer = csv.DictWriter(outfile, reader.fieldnames)
        writer.writeheader()

        # Iterate over the products in the input.
        for product in reader:
            # Find the stock level from the dictionary we created earlier. Using
            # the get() method allows us to specify a default value if the SKU
            # does not exist in the dictionary.
            result = product_result.get(product['SKU'], " ")

            # Update the product info.
            product['ChannelProfileID'] = result

            # Write it to the output file.
            writer.writerow(product)


Creating an insert at front function for a circular doubly linked list

Here are some things that will help you improve your code.

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.

Consider how your code is used

When somebody uses this code, they will probably want to insert a value into a data structure, and have the data structure handle all of the messy details, such as memory management. However, this code only seems to store successive integers (from a global variable) and requires the caller to allocate memory for the entire structure.  So instead of an interface like this:

void add_to_list( struct TCB_t **ptrBlock, struct TCB_t **addQ)

a better interface would probably be this:

void add_to_list(struct TCB_t *node, int value)

This interface would allocate space for an additional TCB_t, add the passed value to it and link it appropriately to the existing node.

Provide convenience functions for testing

In order to test your function, it would be useful to be able to do things like print out the contents of the list.  One way to do that is to provide a convenience functions such as this one:

void print_list(const struct TCB_t *n)
{
    if (n == NULL) {
        printf("empty list\n");
        return;
    }
    printf("%d", n->val);
    for (struct TCB_t *p=n->next; p!=n; p = p->next)
        printf(", %d", p->val);
    printf("\n");
}

Consider providing a whole interface

Instead of providing just one function, it is often more useful to provide a couple of related functions to deal with a particular structure.  For example, in the case of a circular doubly-linked list, node insertion, node deletion, printing, initialization and destruction are all reasonable things to expect from an interface.  Providing only one fails to provide a sufficient spectrum that makes the data structure actually usable.


Add many objects to a collection in a JavaScript object

Before I answer your question, I want to clean some things up first.

this[listField]={
    'formField':formField,
    'fieldType':fieldType
}

Whoa. You are creating an entire new property here based on input a caller gave you. Then, you are setting this to a uniformly designed object every time.

Not good practice
We can OOP this up.

Every time this method is called, an object is created with a certain "shape" (certain properties, etc.)

For that, we create a new class:

function ListField(name, formField, fieldType) {
    ... fill in the rest with property setting ...
}

Now our data is more easily help together.

Time to fix the bad practice mentioned above.

Instead of modifying the very structure of the parent object every time add is called, you should instead push the new ListField object into an array.

This will keep all the added ListField objects in one, easy to access place. This all removes all bad practices.

  Is there a more efficient way to do this?

Sure.

Considering you know that you are going to be sending in a large amount of ListFields, then why not let add take an array?

FieldMap.prototype.add = function(arr) { // use better name
    for(var i = 0; i < arr.length; i++) {
        this.listFields.push(arr[i]);
    }
}

Then, to call, just pass in an array of the various FieldMaps.

No, this will not making typing more easily (well, it will by a little bit). However, since the data you are providing is arbitrary, then there is no way you can do this with patterns and loops.

However, this will speed up your code. Instead of calling a method 20+ times in a row, you are calling this method a single time and this method is using a loop 20+ times; a much more efficient task.


A tiny mistake is not quoting $EXT1 in for f in *.$EXT1.
If it contains a space, the script won't work as expected.
I agree it's an unrealistic corner case,
but it's easy enough to protect against with proper quoting: for f in *."$EXT1".

The rename Perl script is famous for this purpose.
Since you asked about its advantages:

Stood the test of time
You don't have to write it
It has more features (full regex support)

The equivalent usage to simulate the behavior of your script would be:

rename -v 's/EXT1$/EXT2/' *.EXT1

A feature I like is the -n flag for dry run, to verify the renames that would be performed before actually performing them.


Does the hideMenu and showMenu fall under the view or controller?

UI only changes could definitely be put in the view.

  Have I put viewNewPage in the correct block?

I would put data changing code in the controller, so no.

  Should I bind elements to functions in the controller or model?

I would bind elements to events in the view.

  Have I made any other blunders here when trying to follow the MVC pattern?

The view is a combination of the view javascript and the corresponding html. The html selectors shouldn't exist outside of the view, and absolutely not in the model.

model.elements => view.elements

hideMenu, showMeny, setElementBindings => view

viewNewPage => controller


Use variable for element, toggle can take multiple classes, use minimal selector.

var voteButton;
if(type === 'down'){
    voteButton = $('.i-down-' + commentid);
    voteButton.toggleClass('active-color opacity-initial');
} else {
    voteButton = $('.i-up-'+commentid);
    voteButton.toggleClass('primary-color opacity-initial');
}
if(voted === 'True'){
    voteButton.css('opacity', '0.2')
}

or you could stack functions

$('.comment-item .down-vote .i-down-'+commentid+'')
  .toggleClass('active-color opacity-initial')
  .css('opacity', '0.2')


Content aggregator using bs4 and requests

Your linesplit is... strange? I'm going to ignore that message and pretend it makes sense.
Whenever there's an API, prefer it. In this case Google has a Custom Search API that allows you to skip past all of the scraping insanity. You'll need to get an API key and configure an engine instance to search the whole web. The front-end of such an application, without including your second "scrape all of the paragraphs" step, looks like:
from typing import Iterable
from requests import Session

# To set a custom search engine to search the entire web, read
# https://support.google.com/programmable-search/answer/4513886
API_KEY = '...'
ENGINE_ID = '...'

def api_get(session: Session, query: str) -> Iterable[str]:
    with session.get(
        'https://customsearch.googleapis.com/customsearch/v1',
        headers={'Accept': 'application/json'},
        params={
            'key': API_KEY,
            'cx': ENGINE_ID,
            'q': query,
        }
    ) as resp:
        resp.raise_for_status()
        body = resp.json()

    for item in body['items']:
        yield item['link']

def main():
    topic = input('Enter the topic: ').lower()

    with Session() as session:
        urls = api_get(session, topic)

    print('\n'.join(urls))

if __name__ == '__main__':
    main()


Try-catch flow to handle two failing services

First, any async function should end with Async, ie MyFunctionAsync. You can see examples of this in the other async functions you're calling throughout your code.
As to your requirements, the exception you throw at the end is devoid of any useful information. It has no exception origination information (line number etc) and no correct stack trace. Either save the exception you're handling in the top try when it happens, or even better rethrow it on the spot.
I very much question your updating the item even though the first part errored out, so rethrowing the first set of exceptions on the spot is what I'd do, but if you want to update it even in an error case, bring the update function with you in the catch and then rethrow.
The second part is fine, you're rethrowing as you should.


Filter leading zeroes from numbers using only character operations for input and output

I see a number of things that could be improved here.

Include the appropriate headers

The code as posted is just a fragment, but only a few additional lines would make it into a complete program.  It's usually best to provide a complete program for review.  With that said, the missing headers are these:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>

Check for EOF

The code currently looks for the & character, but that's not in the specification.  It would probably make more sense to look for the end of file which is EOF.

Restructure your code

Any time you find yourself writing while (true) and then putting a conditional break within the loop, this should be a strong indication that something is not quite right. Also, lines like this:

if (curr_char=='0'); else break;

are really quite awful.  That could easily have been written instead as:

if (curr_char != '0')
    break;

which makes it much easier to understand.  Even better would have been to write the loop as:

while (cur_char != '0')
    curr_char = getchar();

Eliminate unneeded variables

The code defines curr_char, prev_char and flag but it's possible to rework the algorithm to eliminate at least one of these.  Also, curr_char and prev_char are good names, but flag is not.  It's entirely too generic and doesn't say what it's intended to flag.

Fix your algorithm

If we feed a03+0.0g to this code, it should print a3+0.0g but what it actually prints is a30.0 which is clearly not correct.  Part of the problem here is that the implementation of the algorithm is quite convoluted and difficult to follow.  For that reason, I would recommend a different approach.

Start with a state machine

Starting with a state machine is a very good way to work out what a program should do in advance of writing any code.  Having a design first and then writing code is essential to good programming practice.  For example, this state machine can be easily implemented in code.  I used an enum to represent the state and then a switch statement to drive the code.  In it, each transition is labelled as condition/action.

As an example of how to code this, here's the first part of the code including the code for the nonNum state:

int main()
{
    enum { nonNum, inInt, inDec, zeroSupp } state = nonNum;
    int ch;
    while ((ch = getchar()) != EOF) {
        switch (state) {
            case nonNum:
                if (ch == '0') {
                    state = zeroSupp;
                } else if (ch > '0' && ch <= '9') {
                    state = inInt;
                    putchar(ch);
                } else {
                    putchar(ch);
                }
                break;
      /* the rest of the state machine goes here */


Finding the max subset of non-overlapping intervals

I see three points of improvement:

The isEmpty check is redundant can be removed. The contains will handle the scenario your are checking for.
The Comparator really clutters things up, and since you already have a SortedSet coming in, I know you have another compareTo method somewhere else.  If Pair is one of your classes, go ahead and make it implement Comparable so you don't have to worry about rewriting comparison logic everywhere.
Your conditional block could be simplified if you only look for your failure cases. In cases like this, I usually step back and start by writing our pseudo code for these complex boolean constructs and let loose with DeMorgan's law.

Here's a pastebin with my changes. It takes you down from 35 loc to 19 loc.  http://pastebin.com/NpSHemqP

--edit-- Wrong sleep deprived academic reference.


According to whether regex is None, you run code segment A or B. This feels like a copy-n-paste "bolt-on" to add the regex feature.

I suggest that you may be able to refactor A & B into a common piece of code that pays attention to regex and Does The Right Thing.

You didn't publish any automated unit tests that exercise this code. Putting together some unit tests would help you to refactor while verifying that functionality is unchanged.

You have some KPIs, and you mentioned 9s wall clock time, but did not mention how many directory entries were parsed in those 9 seconds. It would be interesting to know what sort of inputs this code expects, and where a profiler says the code spends most of its time.


Program that reads a string from the keyboard and tests whether it contains a valid date

First, a few comments about style.

You shouldn't start variable names with a capital letter, that's used for constants and class names.  So instead of Smonth and Sday, use monthStr and dayStr.
If you put braces around the statement after an if, put them around the else as well.  Your last if/else doesn't do that.
Instead of saying leap == false, say !leap.

I think the one thing that could make your code look cleaner and clearer would be to move repeated code off into a separate method.  For example, you're repeatedly opening a JOptionPane, getting a value and then converting it to an integer.  Why not put that in a separate method, so you could call:

int month = getValue("Month");

This would reduce the clutter in your main method and have the added advantage that if you wanted to change how you ask the user for values, you would only have to do it in one place.  Do that with your error checking as well and your code improve quite a bit.


Evaluation of insert method from within a class using PDO

Your design is flawed in the following way:

DO NOT USE GLOBAL.

It is not OO programming and you shouldn't be calling it if you are using PDO - pass your PDO through your function or as part of your user constructors. (see SOLID design patterns)

class User
{
     //private attributes
     private $_db;
     public function __construct(PDO $pdo)
     {
         $this->_db = $pdo;
     }
}

your function pdo_create
is too couple with pdo - if you decide to switch off from pdo - you will need to re-write that function call to reflect what you change to - use convention a bit more general: creatingUser(PDO $pdo) for example or even better creatingUser(DBInterface $db) (as part of SOLID

Now as for the function itself:

+1 for using prepare statement however ? is more used for mysqli - it better to use place handler instead. such as VALUES(:first_name, :last_name). When you pass the array you can then use the place handler to effectively assign to which variable its value. It is best for readability later.

Finally: you defeat the purpose of the class if your attributes are PUBLIC. Ideally functions receives parameters by the function itself OR by the constructor of the class which initializes the attributes of the class.


Pandoc filter to allow embedding arbitary HTML in latex documents

I think it's clearer to just merge all those functions into one since you only really care about one case:

convertCode :: String -> Maybe [Block]
convertCode code =
  case strip codeHead of
    ('%':'%':'%':' ':typeName) -> matchType $ strip typeName
    _                          -> Nothing
 where
   (codeHead, codeTail) = splitWhen (== '\n') $ strip code

   matchType "html" = Just [RawBlock (Format "html") codeTail]
   matchType _      = Nothing

Does this do the same thing? I cant test it without too much effort on my part.


Return the number of unique ways you can climb the staircase

Dynamic programming approach

My main advice is to prefer bottom-up iteration to top-down memoization. These are the two main approaches to dynamic programming as described on Wikipedia. Now, while there is nothing absolutely wrong with top-down approaches, bottom-up is, at least for this problem

cleaner to code
does not take up space on the stack
runs faster if method calls are slower than iteration

Finally, your code may re-compute the same values multiple times. This is not true of all top-down approaches, but is easy to avoid using bottom-up dynamic programming.

Bugs

incorrect if X is not sorted
incorrect if X does not contain 1 due to unnecessary memory[1] = 1

Minor style points

use more descriptive class and variable names
instead of N - X[i] >= 0 use N >= X[i]
prefer enhanced for loops

static int solution(int totalStairs, int[] stepSizeOptions) {
    int[] numberWays = new int[totalStairs+1];
    numberWays[0] = 1;

    for (int numStairs = 1; numStairs <= totalStairs; numStairs++) {
        for (int stepSize : stepSizeOptions) {
            if (numStairs >= stepSize) {
                numberWays[numStairs] += numberWays[numStairs - stepSize];
            }
        }
    }

    return numberWays[totalStairs];
}


Better way to do multiple try/except in Python

Firstly, consider whether these shouldn't be None, but instead should be empty lists. Most of the time None is better replaced by something else like an empty list.

If that's not an option, you can use a list:

for item in [self.download_links, self.case_name...]:
    if item is not None:
         length.append( len(item) )

or a function

def add_length(obj):
   if obj is not None:
            lengths.append(len(obj))

add_length(self.download_links)
add_length(self.case_name)
...


Binary search tree in C++ 17 using iterator pattern

BinarySearchTree

Since the tree isn't balanced, worst case insertion complexity is \$\mathcal{O}(n)\$ (and not \$\mathcal{O}(\log n)\$ as likely intended). (Same for lookup, if such a method were to be added).
Calling left() or right() will create a copy of the whole left/right subtree. This is very likely not intended.
This class could profit a lot from a move constructor and a move assignment operator overload. (And while we're at it, add a copy assignment operator overload and a destructor to complete the rule of five.)
Is it really necessary to name the lambda the same as the enclosing function in BinarySearchTree::insert(T key)?
Also of note, only types that can be copied can be inserted into the BinarySearchTree. This means it is currently not possibly to store a move-only type (like std::unique_ptr) in the tree. (This capacity could be added with an overload accepting a T&&.
BinarySearchTree::insert(T key) creates unnecessary copies of key for each recursive call. Consider taking a const T& instead.`
left_ and right_ are often dereferenced without checking them for nullptr beforehand! This results in undefined behavior if they are nullptr!

BinarySearchTreeIterator

This iterator doesn't provide any iterator_traits or an end iterator. This means using it with standard library algorithms (or even a range based for loop) is not possible. More info on iterators and iterator_traits.
There are lots and lots of unnecessary copies (basically every time std::make_unique or bst_->left() or bst_->right() are called).
current_ will always have a value with this implementation, so making it std::optional<T> is misleading. Also, any modifications done to the value returned by operator*() won't be propagated to the original BinarySearchTree entry (as it returns an independent copy and not a reference).
This iterator traverses the tree in-order. Since there are also other traversal methods, like pre-order, post-order or level-order, it would be nice to indicate that in the name.

std::unique_ptr usage

Normally, a std::unique_ptr is used to express "I own this". So a signature like std::unique_ptr<BinarySearchTree<T>> BinarySearchTree::left() says "Call me, and you become the new owner of whatever I return".

Is this necessary in this case? No! After all, the caller just wants to access the existing object, and not acquire a new one.

So, how can this be expressed?

There are two variants:

Return a non-owning BinarySearchTree<T>*.

Pros:

Very lightweight.
Very simple (can still use std::unique_ptr for internal storage, so resources get cleaned up properly).

Cons:

If the BinarySearchTree<T> gets destroyed, but someone still has the pointer stored, the pointer is dangling.
Someone could prematurely call delete on the pointer (so the internal std::unique_ptr would be dangling).

Return a std::shared_ptr<BinarySearchTree<T>>.

Pros:

As long as the std::shared_ptr exists, the object will be valid.

Cons:

Might keep the tree (or subtrees) alive for far longer than intended.
Has a slight overhead.
Requires using std::shared_ptr for internal storage.
Might leak in case of cycles (not a problem here, just for the general case).

Of course, some of those problems can be avoided by appropriate use of std::weak_ptr.

Some more resources:

CppCon 2014 talk about smart pointers
CppCon 2016 talk about memory management (even talks specifically about trees and graphs)


What is the fastest way to record the listed files in a directory in C?

OP poses 2 approaches

Iterate twice through opendir(), readdir(), closedir() with one malloc().

Iterate one through opendir(), readdir(), closedir() with multiple realloc().

For performance, I would use a 3rd option: linked list instead of using an array of struct dirent

Iterate once through opendir(), readdir(), closedir() with one malloc() per entry.

As with such performance issue: strive for reduced big O, not linear ones.


Generally, the Python style is to indent by one tab, or four spaces. Functions and variables should be named in snake_case, and classes should be in PascalCase. See PEP8 for more style information.

You should also use docstrings to describe what your functions do. Here's an example of how docstrings are used.

def my_func( ... ):
    """
    Describe what your function does and
    it's arguments in this docstring.
    """
    ...

Other than that, your code looks pretty nice! Good work!


I propose this:

internal ILink Parse(Uri endpoint) {
    ...
    foreach (LinkXPath source in sources) {
        UpdateIfNecessary(document, ref result.Title, () => GetFragment(document, source.Title));
        UpdateIfNecessary(document, ref result.Description, () => GetFragment(document, source.Title));
        UpdateIfNecessary(document, ref result.Article, () => GetFragment(document, source.Article));
    }
    ...
}

private static void UpdateIfNecessary(Document document, ref string field, Func<string> getValue) {
    if(!string.IsNullOrEmpty(field)) {
        return;
    }
    field = getValue();
}

UpdateIfNecessary receives a lambda so it only evaluates the new value if necessary.

The field is passed by reference, so any change to the parameter in the method is reflected in the underlying argument variable in the calling method.


Just a few if statements will do.
Your answer to the problem is rather strange.
To find out if an apple or orange is between s and t is just a simple if statement.
if(apple[index] + appleTreePos >= s && apple[index] + appleTreePos <= t){
    // Apple is on the house.

// Same for the orange.

So you only need to loop over the apples and oranges once. Best is to have a single loop that does both the apples and oranges at the same time, then a second loop to do the remaining (if any) fruit.
There is no need to create any arrays. Your solutions is exponentially lots more work than is needed. For speed aim to reduce the number of times your code loops. Note that Array.map is the same as doing a for loop over each item, but much slower in this case.
NOTE I struck out exponentially and added "lots" as some have complained, I used it in the common vernacular (increasing rate of change) and not as in CS time complexity.
Your code loops over the length of the house, then the number of apples and oranges, and then you loop the length of the house times the number of apples plus oranges.
If the house is 5 units wide and there are 5 of each fruit you iterate over them a total of (house pos to array) 5 + (map each fruit array) 5 + 5, (counting) 5 * (5 + 5) for a total of 65 iterations. This is 60 times too many.
Example
I have not run this code so there could be a few typos, but the general structure is as described above.
This is faster than your solution, If it is fast enough to pass the test I do not know.
function countApplesAndOranges(houseLeft, houseRight, appleTreePos, orangeTreePos, apples, oranges) {
    var appleCount = 0;
    var orangeCount = 0;
    var i = 0;

    // find smallest group
    const len = Math.min(apples.length, oranges.length);

    // do apples and oranges
    while (i < len) {
        let pos = apples[i] + appleTreePos;
        appleCount += pos >= houseLeft && pos <= houseRight ? 1 : 0;
        pos = oranges[i++] + orangeTreePos;
        orangeCount += pos >= houseLeft && pos <= houseRight ? 1 : 0;
    }

    // if same number of fallen then return result
    if (apples.length === oranges.length) {
        console.log(`${appleCount}${'\n'}${orangeCount}`);
        return;
    }

    // if more apples have fallen the do remaining apples
    if (apples.length > len) {
        while (i < apples.length) {
            const pos = apples[i++] + appleTreePos;
            appleCount += pos >= houseLeft && pos <= houseRight ? 1 : 0;
        }
        // all done return result
        console.log(`${appleCount}${'\n'}${orangeCount}`);
        return;
    }

    // must be more oranges so do the rest of them and return result
    while (i < oranges.length) {
        const pos = oranges[i++] + orangeTreePos;
        orangeCount += pos >= houseLeft && pos <= houseRight ? 1 : 0;
    }
    console.log(`${appleCount}${'\n'}${orangeCount}`);
 }


Tweeting NASA's Astronomy Pic of the Day

Instance and class variables.

I think tw should be an instance variable, made in the constructor.  Same for web and soup - not having to remake those every time will probably help you with your runtime issues (at least a little).

Then, I'd make all of your constants class-level variables.  This includes self.url, self.app_key, self.app_sec, self.token_key, self.token_sec, and self.img_path.  Really, the only one of the instance variables you set there that wouldn't be constant is the time.'

After that, you should probably add a few constants - "http://apod.nasa.gov/apod/" and "Imagen astronómica del día. (vía: NASA). ~Alfred" come to mind.

Then I'd go one step further and put all of the constants into a config file.  If you aren't interested in doing that, skip the rest of this section.

I assume that these may eventually change, or you might want to share/open-source your code and you probably don't want this out there publicly with all those values. Luckily, Python provides ConfigParser to handle config files.  I'd suggest the following structure for your config file

[TwitterBot]
url: http://apod.nasa.gov/apod/astropix.html
app_key: XXX
app_sec: XXX
token_key: XXX
token_sec: XXX
img_path: static/img/

Pretty standard, Windows INI file style config file.  This should either be in the same directory the file is in, or in the user's home directory.  Then you can get the parser object pretty easily - I encapsulated the behavior in a class, you can do whatever works for you.

from ConfigParser import SafeConfigParser

class Configuration(object):
    _parser = None
    _url = None
    _app_key = None
    _app_sec = None
    _token_key = None
    _token_sec = None
    _img_path = None

    def __init__(self, filepath=None):
        self.filepath = filepath

    @property
    def parser(self):
        if self._parser is None:
            self._parser = self._get_config_file(self.filepath)
        return self._parser

    @property
    def url(self):
        return self._get_config_value("url")

    @property
    def app_key(self):
        return self._get_config_value("app_key")

    @property
    def token_key(self):
        return self._get_config_value("token_key")

    @property
    def token_sec(self):
        return self._get_config_value("token_sec")

    @property
    def img_path(self):
        return self._get_config_value("img_path")

    def _get_config_value(self, value_name):
        """Gets a configuration value

        Parameters
        ==========
        value_name : str
            The name of the value you want.

        Returns
        =======
        value : str
            The value you want.
        """

        value = getattr(self, "_{}".format(value_name))
        if value is None:
            return self.parser.get("TwitterBot", value_name)
        return value

    def _get_config_file(self, filepath=None):
        """Gets the config file for the twitter bot

        Parameters
        ==========
        filepath: string, optional
            The path to the desired file.  If omitted, the function first
            looks in the local directory for a file named ".twbot.config",
            then looks in the user's home directory.

        Returns
        =======
        parser: SafeConfigParser
            A parser object with the config file loaded.
        """

        if filepath is None:
            true_filepath = ".twbot.config"
            if not os.path.isfile(true_filepath):
                true_filepath = os.path.expanduser("~/.twbot.config")
                if not os.path.isfile(true_filepath):
                    raise OSError("Couldn't find '.twbot.config' either "
                                  "locally or in the user directory")
        else:
            true_filepath = filepath

        parser = SafeConfigParser()
        with open(true_filepath, 'r') as config_file:
            parser.readfp(config_file)

        return parser

Use new style classes

Python allows you to use new-style classes (in 2.7) by inheriting from object - this is almost always something you want to be doing.

class Alfred(object):

Naming

I don't like the name start - it isn't very descriptive to me.  What are you starting?  It might be better with a more descriptive class name, but I think you can change it to something like startTweetingImages and be fine.

Break up your start function

Right now there are three distinct functions happening here - getting the image, deleting old files, and then tweeting the image.  I'd make a function for each of them.

def _get_image(self):
    img = self.soup.find("img")
    img_src = img.get("src")
    return img_src, img_src[11:]

def _remove_old_files(self):
    for file_name in os.listdir(self.img_path):
        os.remove(os.path.join(self.img_path, file_name))

def _send_tweet(self, img_src, img_name):
    img_url = self.base_nasa_url + img_src
    image_path = os.path.join(self.img_path, img_name)
    urllib.urlretrieve(img_url, image_path)
    with open(image_path, 'rb') as photo:
        response = self.tw.upload_media(media=photo)
        self.tw.update_status(
            status=self.status, media_ids=[response['media_id']])

def start(self):
    while True:
        if self.time[3] < 5:
            img_src, img_name = self._get_image()

            if not (os.path.isfile(os.path.join(self.img_path, img_name))):
                self._remove_old_files()
                self._send_tweet(img_src, img_name)

You'll notice I did a few other things - I removed the unnecessary else blocks, and then negated the condition of the if block so we could remove that else as well.  I also used a context manager, safely closing the file when I'm done with it.  Lastly, I used os.path.join to safely join together parts of a filepath so that it is operating system independent.

The above implementation assumes that you've made things constants that I mentioned should be constants, and that tw, web, and soup are each instance variables.

Sorry, I got lazy adding docstrings but you should always have them for functions. Sometimes you can omit them for private functions (prepended with a _) but I like them for the convenience of the implementor.  I've used the numpydoc style here.

Lastly, please put things that run (i.e. a = Albert(); a.start()) inside of an

if __name__ == '__main__':

block - this lets people import your module safely and do other stuff with it.


Convert a double to a string containing rational and surd

This is not a good question because the objective is unrealistic. The code (or perhaps the problem statement) is also flawed since √1 is considered a surd, which - if I am not mistaken - is wrong. (A surd is an "irrational nth root of a positive integer (n > 1)", i.e. it has a non-recurring floating point representation.)

Here is why the objective needs sorting out

Reasonably performant algorithms exist to express floating point numbers as irrational numbers (all of which may be expressed as x / y * √1).  Here's an example (E&OE):

static string Frac(double value)
{
  const double compareTolerance = 1.0E-12;
  bool isNegative = value < 0;
  value = Math.Abs(value);

  long numerator = 1L;
  long denominator = 1L;
  double fraction = (double)numerator / denominator;

  while (Math.Abs(fraction - value) > compareTolerance)
  {
    if (fraction < value)
      numerator++;
    else
    {
      denominator++;
      numerator = (long)(value * denominator);
    }
    fraction = (double)numerator / denominator;
  }
  return $"{numerator} / {denominator} ~= {fraction}, error = {value - fraction}";
}

Given Console.WriteLine(Frac(2.0 / 3 * Math.Pow(7, 1.0/3)));

One gets 1238109 / 970847 ~= 1.27528745518089, error = 7.04103442217274E-13

Reducing the "tolerance" leads to finding bigger (numerator, denominator) pairs giving "increasingly accurate" rational equivalents (within the significant digit limit of the floating point type of course). Taking the floating point representation of any rational, multiplying (or dividing) by a (floating point approximation to a) surd, just gives another floating point number which can be (approximately) represented by a rational. Every floating point number therefore has virtually unlimited rational * surd representations, so you need to specify how you want to limit the search range and/or output possibilities.


Java converter from Arabic to Roman Numerals

private final Map<Integer, String> BASE_VALUES_MAP

This is missing static modifier

private StringBuilder romanNumeralString;

I don't think that should be a member, just pass it as argument where necessary. That way you code will be thread-safe, without any additional effort.

private int findNearestBaseValue(int arabicNumberToConvert) {

If you use TreeSet instead of HashSet you could just use ceiling()/floor() instead of manual iteration.

buildRomanNumeralString()

This method looks unnecessary, just inline it.

  Are there Java 8 features that I should be using but not using.

I would say it is the opposite - there is no real point in using Stream in repeatBaseValue(), normal for loop would be fine.


Moving a bot through a maze with Depth First Search

I cleaned up your code, but it appears like your code performs a depth-first search.  It's more common to use a graph to represent the different paths than a queue, but your code works, as best as I can tell.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

public class DFSMaze {

    public static int[][] maze = {
            { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 },
            { 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9 },
            { 9, 1, 0, 1, 0, 1, 1, 0, 0, 0, 5, 9 },
            { 9, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 9 },
            { 9, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 9 },
            { 9, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 9 },
            { 9, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 9 },
            { 9, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 9 },
            { 9, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 9 },
            { 9, 1, 0, 0, 0, 0, 1, 0, 0, 0, 3, 9 },
            { 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9 },
            { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }
            };

    public static Deque<Coordinate> deadEnd =
            new ArrayDeque<Coordinate>(10);
    public static Deque<Coordinate> deq =
            new ArrayDeque<Coordinate>(10);

    public static void main(String[] args) {
        printMaze();
        dfs(2, 10);
    }

    public static boolean isDeadEnd(Coordinate coord) {
        Iterator<Coordinate> it = deadEnd.iterator();
        while (it.hasNext()) {
            if (it.next().equals(coord)) {
                return true;
            }
        }
        return false;
    }

    public static Coordinate setCoord(int i, int j) {
        return new Coordinate(i, j);
    }

    public static boolean checkCoord(Coordinate coord) {
        Iterator<Coordinate> it = deq.iterator();
        while (it.hasNext()) {
            if (it.next().equals(coord)) {
                return true;
            }
        }
        return false;
    }

    public static int dfs(int i, int j) {
        if (i == 9 && j == 9) {
            maze[9][10] = 4;
            printMaze();
            System.out.println("You're Free!");
            return 0;
        }
        Coordinate coord = new Coordinate();

        if (!checkCoord(coord) && !isDeadEnd(coord)) {

            if (maze[i + 1][j] == 0 || maze[i + 1][j] == 3) {
                coord = setCoord((i + 1), j);
                deq.push(coord);
                maze[i + 1][j] = 4;
                printMaze();
                return dfs(i + 1, j);
            } else if (maze[i - 1][j] == 0) {
                coord = setCoord((i - 1), j);
                deq.push(coord);
                maze[i - 1][j] = 4;
                printMaze();
                return dfs(i - 1, j);
            } else if (maze[i][j + 1] == 0) {
                coord = setCoord(i, (j + 1));
                deq.push(coord);
                maze[i][j + 1] = 4;
                printMaze();
                return dfs(i, j + 1);
            } else if (maze[i][j - 1] == 0) {
                coord = setCoord(i, (j - 1));
                deq.push(coord);
                maze[i][j - 1] = 4;
                printMaze();
                return dfs(i, j - 1);
            }
        }

        deadEnd.push(deq.pop());
        int n = deq.peek().getX();
        int m = deq.peek().getY();
        // maze[m][n] = 0;
        return dfs(n, m);
    }

    public static void printMaze() {
        String chars = " XeEbb";
        for (int i = 0; i < 12; i++) {
            for (int j = 0; j < 12; j++) {
                int k = maze[i][j];
                if (k < 9) {
                    System.out.print(" " + chars.charAt(k));
                    if (maze[i][j] == 5) {
                        maze[i][j] = 1;
                    }
                }
            }
            System.out.println();
        }
    }

}

class Coordinate {
    private int x;
    private int y;

    public Coordinate() {
        x = 0;
        y = 0;
    }

    public Coordinate(int i, int j) {
        x = i;
        y = j;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof Coordinate) {
            Coordinate test = (Coordinate) obj;
            if (test.x == this.x && test.y == this.y) {
                return true;
            }
        }
        return (this == obj);
    }

}


Find pairs in an integer array whose sum is equal to 10

The O(n²) approach

The first algorithm is indeed O(n²), because, for every element in the array, the array is traversed again to see whether an element after the current element is equal to 10 minus it. It is quite clear, and there is not much to change. Comments are:

There is a bug: you're checking the same element twice in a row, since j, in the inner loop, starts at i. Therefore, if you consider the array { 1, 5, 2 }, the pair (5,5) will be considered a solution, when 5 only appeared once in the input array. To fix this, j should start at i + 1.
Indent properly the code. As written, the curly braces are not aligned correctly, making it more difficult to read than it needs to be. A quick reformat by an IDE will produce

int[] array = new int[] { 10, 3, 4, 6, 1, 9, 10, 0 };
int sum = 0;

for (int i = 0; i < array.length; i++) {
    for (int j = i; j < array.length; j++) {
        sum = array[i] + array[j];
        if (sum == 10) {
            System.out.println(array[i] + " " + array[j]);
        }
    }
}

which is easier to go through.
There is no need to declare the sum variable outside the two for loops. This variable is only used inside to calculate the sum of two elements of the array. As a usual guideline, local variables should have the smallest possible scope, so in this case, you would prefer to have:

int sum = array[i] + array[j];

and remove the int sum = 0 before the loop.

The O(n) approach

The second algorithm is, as you say, O(n). The difference in approach with regard to the first, is that instead of traversing the array a second time for each element, we memorize along the way the difference between 10 and the current element. This means that we don't need to go through every element again, for each element, to check whether one satisfies; we can just continue and if we find one that we memorized, it means we just found a pair. A couple of comments again:

There is a bug in the boundary of the while loop: why mandate i < sum? Because of this, not every element in the array will be considered (only the first sum ones), and pairs will be missed. A simple example is the array { 0, 1 } with a sum to search of 1. Once fixed, you can even turn this into a classic for loop, with an index going from 0 to nums.length excluded.
Hashtable is considered an obsolete class. Not officially deprecated, but it has been superseded with faster solutions, like HashMap and ConcurrentHashMap. Since thread-safety is not a concern here, you can safely switch to HashMap.
Remove the unused code. The variable count is declared, and incremented, but never used. In the same way, the variable temp is declared and never used.
Notice how you're not using the value of the map. The code is doing reqNoList.put(key, i);, but then the stored i is never used. You could accomplish the same with a just HashSet instead of an HashMap.

They are not equivalent

But be careful, because there is a fundamental difference between the two algorithms, namely in how they handle duplicate pairs. Consider the array { 4, 4, 1, 0 }, and a sum to search of 5. The first algorithm will print two solutions, whereas the second one will just print one. So depending on what you want, there might be adjustements.

In you want to print them all using the second approach, you could do it by utilizing the value of the HashMap, and make it store the number of times a given element has been encountered.

As a final note, you should consider extracting each approach into their own method, like printPairsHavingSum(int[] array, int sum). It would clarify even more the code.


Your code is very clean, easy to understand and well written. My only comment for improving it would be to take advantage of a framework that does some of this lifting for you, such as:

KnockoutJS
BackboneJS
AngularJS

As well, coming from an OO background, you might be interested at looking at CoffeeScript, which is a higher level language that provides class constructs and such that compiles down into regular JavaScript.


Is there currently anything wrong with my custom authentication and authorization?

I can't help with the security aspect of it because I don't know enough about it. So just same general code review things:

It seems odd that your CookieHelper class contains two methods which seem like they should be complementary operations however they are named inconsistently and their parameter/results don't really match up:

The MergeIntoString accepts a bunch of parameters which are all taken from some kind of user object.
The DecodeFromString splits up a string which was generated by MergeIntoString but returns a dictionary instead which you then seemingly have to parse back into a user.

I would suggest to rename the first method to UserToCookie and pass the user as single parameter returning a string and rename the second one to CookieToUser which accepts a string and returns a user object.

Alternatively keep the dictionary for the second method but then also pass in a dictionary in the first. You could then have helper methods which convert users to/from dictionaries.
You have some magic constants without a unit and therefore had to write a comment of what it means.

   var timeout = model.RememberMe ? 525600 : 2880; // 365 days or 2 days

.NET has a TimeSpan type which is ideal to store this kind of information and it become obvious what unit it is and works nice with DateTime as well. So something along these lines:

var timeout = model.RememberMe ? TimeSpan.FromDays(365) : TimeSpan.FromDays(2);

....

    Expires = DateTime.Now + timeout,

Doesn't require a comment and it's immediately visible what the timeout could be.


Can someone review my implementation of a Queue?

You should not name your interface Queue, since java.util.Queue already exits.

Also it would be helpful if you post the source of SingleLinkedListNode.

The source looks fine to me, you could however add two methods like (append/en-queue, remove/de-queue):

SingleLinkedListNode<E> append(SingleLinkedListNode<E> newNode) that will replace

 this.rear.setNextNode(new SingleLinkedListNode<E>(value, null));
 this.rear = this.rear.getNextNode();

and returns the next node.


Toggle button that will hide/unhide columns within a range

You use ActiveWorkbook.Sheets("Notes") 5 times, throw that into a variable or use CodeName property - View Properties window (F4) and the (Name) field can be used as the worksheet name. This way you can avoid Sheets("mySheet") and instead just use mySheet.

You don't need to Call subs, it's obsolete. Instead just use Sub argument, argument

As far as troubleshooting the second, that's not really on topic here because it's not working. But what is -

Call ActiveWorkbook.Sheets("Notes").All_Sheets_UnProtect("Notes")

You were using

Application.ActiveSheet.Columns(xAddress).Hidden

and then changed to

Range("NAMED_RANGE").Columns.Hidden

It works for me. If your sheet is changing, it might fail because you don't specify the sheet.


A prime numbers enumeration optimized for speed

There are many, many problems with this implementation, but they pretty much all come down to two major problems: first, you do a linear-time operation when a constant-time or log-time operation would suffice, and second, your code is chock-full of expressions that are useful for both their values and their side effects, which makes for code that is confusing.

return PrimeNumbers.Contains(value);

PrimeNumbers is a sorted list, but you check to see if a value is in it by starting from the beginning and searching every element in it. Do a binary search.

public static long IndexOfPrime(this long value) =>
  IsPrime(value) ? Primes().TakeWhile(p => p < value).LongCount() : -1;

This is bizarre. You use IsPrime for its side effect, and then do a linear search of the primes in a list to get their index. You have a list.  Just search the list for the index!

This was a good attempt but it has turned into an object lesson in what not to do. The fundamental strategy here is very sound and you should keep it, but the details around that strategy are confusing and inefficient. This is not a good use of LINQ.

What I would do here is refactor the program so that it does a smaller number of things and does them better. For example, suppose instead of this business of constantly enumerating Primes, you instead made two methods:

EnsureUpTo(n) -- makes sure that the list is filled in up to n.
NearestIndexOf(n) -- uses an efficient search to return the index of n, or, if n is not prime, the index of the nearest prime to n.
Prime(i) returns the ith prime.

From this simple interface you can answer all your questions:

You can determine if n is a prime by running EnsureUpTo(n) and then i = NearestIndex(n) and then m = Prime(i).  If n == m then n is prime, otherwise it is composite.
You can get the next or previous prime similarly; run i = NearestIndex(n) and then Prime(i-1) and Prime(i+1) are the next and previous.

Your routine for computing primes you don't already know also could use some work:

  var max = (int)Math.Sqrt(++MaxValue);

A number of problems here. Computing square roots is expensive; it is always better to do p * p <= m than p <= Sqrt(m).

The increment is also suspicious. Fully half the time you will be incrementing it to an even number! After you are at 3, increment it by 2.  Or, even better, notice that once you are above 5, you can pick any six numbers in order and at most two of them will be prime. That is, of 5, 6, 7, 8, 9 and 10 we know that 6, 8 and 10 are divisible by 2. We know that 6 and 9 are divisible by 3, so we only need to check 5 and 7. But that also goes for 11, 12, 13, 14, 15, 16:  12, 14, 15 and 16 cannot be prime, so we only have to check 11 and 13.  And then 17, 18, 19, 20, 21, 22 we only check 17 and 19. And so on.

So what you can do is increment MaxValue by 6 every time after you get to 5, and then check MaxValue and MaxValue + 2 for primality, and you do much less work.

if (PrimeNumbers.Where(p => p <= max).All(p => MaxValue % p != 0))

Again, this is really bad because LINQ does not know that the list is sorted.  You check the entire list, which is O(n) in the size of the list, for elements smaller than max, but you could be bailing out once you get to the first that is larger than max.  Where is not the right sequence operator here.  You want Until(p => p > max).


It's probably not reliable except if your XML data is simple.

XML is tricky!

You forgot the .tail attribute, which contains any text after a given attribute.
Whitespace is significant, so you won't be able to go back to the same XMl document.
And everything else I don't know about.

The way Python represents dictionary is different from JSON. For example, JSON only allows " for quoting, not '. You can use json.dumps to solve this problem.
More obviously, if you were representing this data using JSON, your data would look like:

"records": [
    {"him": "Maldonado, Gavin G.",
     "her": "Veda Parks"}
]

or something like that. That's very different from what you're outputting, so your progrem does not really represent your data using JSON, but represents the XML representing your data using JSON. But converting to "real JSON" is much more difficult except for some very specific XML, and would not be useful as a general purpose converter.

This program may be useful to you in some specific scenarios, but you'd better explicitly state what kind of data you accept and reject anything else. Also, what's the point of this?


The thing with bash is more often then not... there is a tool that you can leverage to do what you want. When writing bash scripts, I try write as little bash as possible, and to leverage these tools where best possible to avoid bash (seems counter intuitive, but is the nature of bash to write as little bash as possible).  For example have you heard of the command tuptime?  (https://manpages.debian.org/testing/tuptime/tuptime.1.en.html)

This is what it looks like after a reboot (is packaged with apt):

$ sudo apt-get install tuptime
$ tuptime | grep "System downtime"
System downtime:    0.15 %   -   32 seconds

Is not a complete answer because does not cover the >5 hrs case above.

For reference, here is a run of tuptime

$ tuptime
System startups:    2   since   11:02:34 AM 02/05/2020
System shutdowns:   1 ok   <-   0 bad
System uptime:      99.85 %   -   5 hours, 56 minutes and 45 seconds
System downtime:    0.15 %   -   32 seconds
System life:        5 hours, 57 minutes and 17 seconds

Largest uptime:     5 hours, 45 minutes and 12 seconds   from   11:02:34 AM 02/05/2020
Shortest uptime:    11 minutes and 33 seconds   from   04:48:18 PM 02/05/2020
Average uptime:     2 hours, 58 minutes and 23 seconds

Largest downtime:   32 seconds   from   04:47:46 PM 02/05/2020
Shortest downtime:  32 seconds   from   04:47:46 PM 02/05/2020
Average downtime:   32 seconds

Current uptime:     11 minutes and 33 seconds   since   04:48:18 PM 02/05/2020

If wanting something more specific, I would also consider last command which gives you information about when people logged in or out (using http://man7.org/linux/man-pages/man1/last.1.html).

$ last reboot --time-format iso
reboot   system boot  4.15.0-76-generi 2020-02-05T16:48:22-0800   still running
reboot   system boot  4.15.0-76-generi 2020-02-05T11:02:38-0800 - 2020-02-05T16:47:57-0800  (05:45)
reboot   system boot  4.15.0-76-generi 2020-02-04T14:30:53-0800 - 2020-02-05T16:47:57-0800 (1+02:17)
reboot   system boot  4.15.0-76-generi 2020-02-03T15:28:38-0800 - 2020-02-04T14:30:29-0800  (23:01)
reboot   system boot  4.15.0-76-generi 2020-02-03T10:55:02-0800 - 2020-02-03T15:28:13-0800  (04:33)


As you wrote in your comments, (.contains "str" "sub") is perfectly fine. it is indeed java interop - it runs the method contains on String object "str".

two more comments, first, passing str as a var name isnt so good, since str is a function, so you should consider giving it a different name. Second, in your implementation, its quite redundant to write

(defn substring? [sub st]
  (if (not= (.indexOf st sub) -1)
   true
   false))

You could simply write

(defn substring? [sub st]
 (not= (.indexOf st sub) -1))


Non-recursive BFS Maze Solving with Python

Feedback in mostly top-down order

"""Doc strings""".  You should get in the habit of adding these at the top of your file, the top of every class, and the top of every (public) function.

class Queue.  I'm certain you know that Python comes with everything including the kitchen sink, so it should come as no surprise that there exists a deque already builtin.  I'll assume you implemented your own for practice.  ;-)

self.list The list member should not be accessed outside of the Queue class; it is an internal private detail.  To indicate this, you should name the member with a leading underscore, referencing it as self._list.  Python does not enforce public/private semantics, but many code-review tools (such as pylint) will check for and complain about these violations.  Also, leading underscores can "hide" members from autogenerated documentation.

You actually do reference it outside the Queue class, to print the queue's contents.  You should instead implement the method which converts the object to a string, for printing.  It is called __str__, and you could implement it like:

class Queue:
    # ... your other methods here

    def __str__(self):
        return str(self._list)

Then instead of .format(q.list), you could write .format(q).

    def dequeue(self):
        temp = self.list[0]
        del self.list[0]
        return temp

This is verbose code to retrieve an item from the start of a list, remove the item from the list, and return the item.  The list has a builtin method to do this: pop(0).

    def dequeue(self):
        return self.list.pop(0)

    maze = []
    for row in range(n):
        row = []
        ...
        maze.append(row)

The variable row is created in the for loop, and assigned the value 0 (an integer).  Then, the next statement reassigns row to [] (a list).  Fortunately, when the loop returns for the next value, it doesn't try to add 1 to row, but rather retrieves the next value from the range(n), and the loop works properly.  But this is still poor coding.  pylint will complain that the type of row (not that python has typed variables) changes between an int and a list.

Better would be to use a different variable names, or since the int value of row is never used, to use no variable name at all.  A single underscore is by convention the "throwaway" variable, used when you need a variable but will never use it.

    maze = []
    for _ in range(n):
        row = []
        ...
        maze.append(row)

row.append(0)
row.append(1)
maze[n-1][n-1] = 2
maze[row][col] = 3

Magic numbers!  What is 0?  What is 1?  What is 2?  What is 3?

Help maintain the code by giving names to these numbers.  For example, you could add:

EMPTY = 0
BLOCKED = 1
GOAL = 2
VISITED = 3

at the top of your program, and then use:

maze[n-1][n-1] = GOAL

Readers/maintainers of your program will understand more quickly what is meant by GOAL than by 2.

But, just assigning values to variable names is slightly dangerous.  They are variables can therefore can be changed.  Better would be to create an Enum:

from enum import Enum
class Position(Enum):
    EMPTY = 0
    BLOCKED = 1
    GOAL = 2
    VISITED = 3

Then you can write:

maze[n-1][n-1] = Position.GOAL

And the value of Position.GOAL cannot be changed.

def is_valid_pos(tup):
    (col, row) = tup
    if col < 0 or row < 0 or col >= MAZE_SIZE  or row >= MAZE_SIZE :
        return False
    return maze[row][col] == 0 or maze[row][col] == 2

You always call is_valid_pos((..., ...)), constructing a tuple to pass to the function, which immediately unpacks the tuple into col and row.  Why not simply use col and row as parameters?

The tests for whether row and col are within the valid range is more complex than it needs to be.  Python allows for chained comparisons.  The compound test:

if 0 <= row  and  row < MAZE_SIZE:

can be written as:

if 0 <= row < MAZE_SIZE:

Python evaluates 0 <= row, then row < MAZE_SIZE, then the and of the two values.  So the function may be rewritten as:

def is_valid_pos(col, row):
    if  0 <= col < MAZE_SIZE  and  0 <= row < MAZE_SIZE:
        return (maze[row][col] == Position.EMPTY  or
                maze[row][col] == Position.GOAL)
    return False

As of Python 3.6, we have "f-strings".  This means instead of:

print('Enqueueing ({},{})'.format(col,row))

where you need to match the format() arguments to the correct {} codes positions, we can write:

print(f'Enqueueing ({col},{row})')

which is shorter and may be simpler to understand.

    if is_valid_pos((col+1, row)): q.enqueue((col+1, row))
    if is_valid_pos((col, row+1)): q.enqueue((col, row+1))
    if is_valid_pos((col-1, row)): q.enqueue((col-1, row))
    if is_valid_pos((col, row-1)): q.enqueue((col, row-1))

This code style is error prone.  You probably copied the first line, and pasted it 3 times, and then changed the +1's to -1's, and moved them from col to row.  Did you make the same change to corresponding the is_valid_pos() and q.enqueue() calls?

Better might be:

    enqueue_if_valid(q, col+1, row)
    enqueue_if_valid(q, col, row+1)
    enqueue_if_valid(q, col-1, row)
    enqueue_if_valid(q, col, row-1)

and write an enqueue_if_valid() function:

def enqueue_if_valid(q, col, row):
    if is_valid_pos(col, row):
        q.enqueue((col, row))

  I notice that there are duplicate values in the Queue. I understand that I should avoid visiting already visited positions. However the queue contains only "prospective" positions which are yet to be visited. Should I modify the algorithm to not enqueue positions which it already contains?

Since we have moved the 4 enqueue operations into a call to one function, it would now become easier to implement this improvement.  One way would be to search the queue for the tuple you are about to add, but an easier way would be to mark maze[col][row] with Position.ENQUEUED, if it was Position.EMPTY.  Then the next time you are about to enqueue that position, instead of that position being valid, it would return invalid and not be enqueued a second time.

What is maze?  Is it a local variable, and passed to solve(maze, ...) and print_maze(maze)?  Or is it a global variable that is_valid_pos() automatically knows about?

Pick one.

MAZE_SIZE is also a global.  Do you need it?  Or could you just use len(maze) when it is required?


Assuming monthlyRows and dailyRows are both IEnumerable<ExcelDataRow>, a first step could be to extract a method (assuming return type here, I only skimmed through your code):

private Dictionary<DateTime, List<DataPoint>> GetDataDictionary(IEnumerable<ExcelDataRow> data)
{
    var result = data.Where(r => r[KeyCol] != null && ConfigMap[0].ContainsKey((string)r[KeyCol]))
                                   .GroupBy(r => (string)r[KeyCol])
                                   .ToDictionary(g => g.Key,
                                                 g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
                                                       .ToDictionary(c => c.Key,
                                                                     c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
                                                                           .ToList()));
    return result;
}

Your ParseData method's body could then look like this:

    // Extract the information from the excel file
    var excelData = file.GetWorksheetData(sheet: 0, rowStart: 2);

    var monthlyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days > 1);
    var monthlyData = GetDataDictionary(monthlyRows);

    var dailyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days == 1);
    var dailyData = GetDataDictionary(dailyRows);

    return new Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] { monthlyData, dailyData };

That solves one issue.

Next step would be to break down the LINQ query and make the code self-explanatory as far as why you need to have a dictionary of dictionaries of lists.. and then make that simpler.


Mainly I would like to know if I should be sanitizing any strings?

Assuming that the only unsafe input is in $_GET['url'],
you're safe: junk that doesn't match a defined route will be ignored.
The routes work effectively like a white list.

  How could I handle paths that don't match any defined routes?

Return a 404 error page (and correctly set status code in the header).

This seems quite redundant:

function __construct()
{
    if (isset($_GET['url']))
        $this->req_path = $_GET['url'];

    // Build the requested path.
    $this->req_path = is_null($this->req_path) ? "/" : "/" . $this->req_path;
}

This should be equivalent and shorter:

function __construct()
{
    // Build the requested path.
    $this->req_path = '/' . @$_GET['url'];
}

Instead of iterating over the list of routes and stop when you find a match,
why not use an associative array instead? Like this:

function route($path, $handler)
{
    $this->routes[$path] = $handler;
}

function run()
{
    if (is_null($this->routes))
        throw new RuntimeException("No routes have been defined");

    if (isset($this->routes[$this->req_path])) {
        $this->routes[$this->req_path]();
        return;
    }
}


I see two major issues when you want to use this code for a MMORPG game.

Exception Handling

Make your code robust against connection hick-ups (when connection goes down for a fraction). It's up to be the client to reconnect asap on connection loss (out of scope of your code). The server should dispose client connections on error in order to clean up resources.

Resource Management

The server does not care about the number of clients connected, nor does it own the life time scope of these connections.

I would expect the code below to close the connections.

public void Stop()
{
    _listener.Stop();
    // _connectedClients.ForEach(Disconnect); // cleanup resources
}


I am new to C# and have coded a database abstraction class that I
  would like to get comments on.  It uses prepared SQL statements.

No, it doesn't. If you want it to use prepared statements then you have to call Prepare() on the SqlCommand instances.

Whether you really want actual prepared statements or whether you just want to leave escaping to the library is, as you say, up to you.

class DatabaseAccess
{
    private SqlCommand alreadyDownloadedCommand;
    private SqlCommand markedDownloadedCommand;

Both SqlCommand and SqlConnection are IDisposable. Best practices would require you to make DatabaseAccess implement IDisposable by disposing of all three.

        SqlConnection myConnection = new SqlConnection("user id=username;" +
                                   "password=password;server=serverurl;" +
                                   "Trusted_Connection=yes;" +
                                   "database=database; " +
                                   "connection timeout=30");

If this is for a throwaway project, hard-coding the connection string like that is acceptable. If it's for a "serious" project then you should really get the connection string from App.config with System.Configuration.ConfigurationManager.ConnectionStrings. That has the benefit of allowing you to have dev and prod configurations, as well as to handle server migrations, password cycling, etc. without recompiling.

        SqlCommand command = new SqlCommand(null, connection);
        command.CommandText = markDownloadedInsert;

Why not this?

     SqlCommand command = new SqlCommand(markDownloadedInsert, connection);

        command.Parameters.Add(new SqlParameter("@FileName", System.Data.SqlDbType.Text, 80));

...

    public void MarkDownloaded(String filename)
    {
        markedDownloadedCommand.Parameters[0].Value = filename;

If filename is longer than 80 characters, it will be silently truncated. I would think it advisable to check the length and throw an ArgumentOutOfRangeException if it's too long. Similarly in the other method.

    public Boolean AlreadyDownloaded(String filename)
    {
        Int32 rowCount;

Finally, some debatable points of style. I think it's quite unusual to use Boolean, String, Int32 instead of the aliases bool, string, int. And it's fairly conventional that a method (or property) which tests a condition and returns a bool should have a name beginning Is: here IsAlreadyDownloaded.


You can try editing your BaseHandler like this

class BaseHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.user_email = self.get_secure_cookie('trakr')
        self.user_db = self.application.db.users

and then call the  following in your other Handlers

self.userdb.update({'email_id': self.user_email},

Basically the prepare function is called right at the beginning of the request
for more information you can look at the tornado docs


The only thing you are getting out of this inheritance is which directory should be used to access the executable. And you are only using that to define a number of (what should be constant) strings. The fact that you have an error in your value for _capinfos in the seconds case should be an indication that this is not the best way to perform this action.

To accomplish the task of initializing the strings, I would instead do something like this.

public void initializeCommands(String path) {
    _capinfos = path + "_capinfos.exe";
    _dumpcap = path + "_dumpcap.exe";
    _editcap = path + "editcap.exe";
    _mergecap = path + "_mergecap.exe";
    _rawshark = path + "_rawshark.exe";
    _text2pcap = path + "_text2pcap.exe";
    _tshark = path + "_tshark.exe";
    _wireshark = path + "_wireshark.exe";
}

You can wrap this in something that determines the path or even support non-standard paths.

But what this really comes down to is that you are using inheritance just so you have easy access to some constants you might want to use. You are not defining any methods that would specify actual code used between multiple classes that execute Wireshark processes. If Editcap were passed in the path to the executable, it would no longer have a need to the parent class. If the coupling is this loose, inheritance is generally not the best idea.


Get the tail of a file (the last 10 lines)

Obviously the tail of the file is harder to do. This is a much more challenging situation than getting the first 10 lines. You have chosen a system that requires complicated byte manipulation to get bytes in to chars, and I don't believe the system will work for non-ascii files where the character encoding of the data may have a second-byte of 0x0A causing a mis-parse of a new-line.

For simplicity sake I would still recommend you use a forward cursor, and a circular buffer. This will work for all files regardless of the size, but the performance will be related to the size. On my system though, even 20MB files were done within moments (0.3 seconds according to the bash 'time' command). So that are not too large (a couple of megabytes), and is easy:

String[] lines = new String[10];
int count = 0;
String line = null;
while ((line = bufferedReader.readLine()) != null) {
    lines[count % lines.length] = line;
    count++;
}

That will load as many as possible lines in to the lines array, limited to 10. It will have the 10-most-recent lines.

Then you can dump those with:

int start = count - 10;
if (start < 0) {
    start = 0;
}

for (int i = start; i < count; i++) {
    System.out.println(lines[i % lines.length];
}

The above code will always work, but for larger files will be slow.

For practical purposes though, I don't believe you will run in to problems, and you should be fine.

I worked a little Java 8 in to the following code as well. Consider the RingBuffer class which allows you to collect the data in to it:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Tail {

    private static final class RingBuffer {
        private final int limit;
        private final String[] data;
        private int counter = 0;

        public RingBuffer(int limit) {
            this.limit = limit;
            this.data = new String[limit];
        }

        public void collect(String line) {
            data[counter++ % limit] = line;
        }

        public List<String> contents() {
            return IntStream.range(counter < limit ? 0 : counter - limit, counter)
                    .mapToObj(index -> data[index % limit])
                    .collect(Collectors.toList());
        }

    }

    public static final List<String> tailFile(final Path source, final int limit) throws IOException {

        try (Stream<String> stream = Files.lines(source)) {
            RingBuffer buffer = new RingBuffer(limit);
            stream.forEach(line -> buffer.collect(line));

            return buffer.contents();
        }

    }

    public static void main(String[] args) throws IOException {
        tailFile(Paths.get(args[0]), 10).forEach(line -> System.out.println(line));
    }
}


Critique my JSON-optimizing Python script

digest = defaultdict(lambda: defaultdict(set))

It's pretty rare that we have a good reason for such a nested data structure in python.

    for element in data:
        if not isinstance(element, dict) or len(element) != 2:
            break
        for key, value in element.items():
            digest[key][type(value)].add(repr(value))

Why are we adding the repr of the value? I assume you do it to avoid taking the hash of unhashable objects. But what if somebody puts some strange object in your list that has a repr which always returns the same thing. Besides you are only interested in strings.

    else:
        if len(digest) == 2:

This is an unintuive way to check for your requirement. Your requirement is actually that all elements have the same keys. Check for that instead.

            pool = {k for k in digest if len(digest[k][str]) == len(data)}

Your actually checking to see if that key was always a string. Perhaps you should check that more directly.

            if pool:
                if len(pool) > 1:
                    meta = input("Which key (%s)? " % "|".join(pool))

Its deeply suspicious if you need to ask the user for instructions.

                else:
                    meta = next(iter(pool))
                infra = (digest.keys() - {meta}).pop()
                return {d[meta]: optimize(d[infra]) for d in data}
    return [optimize(x) for x in data]

Here is my reworking of it.

def optimize(data):
    """
    Dispatcher, figure out which algorithm to use to compress the json
    """
    if isinstance(data, list):
        if len(data) == 1:
            return optimize(data[0])
        else:
            keys = determine_key(data)
            if keys is None: # unable to determine tkeys
                return [optimize(element) for element in data]
            else:
                return optimize_list(data, keys)
    elif isinstance(data, dict):
        if len(data) == 1:
            return optimize(next(iter(data.values())))
        else:
            return optimize_dict(data)
    else:
        return data

def optimize_dict(data):
    """
    Optimize a dict, just optimizes each value
    """
    return {key : optimize(value) for key, value in data.items()}

def can_be_key(data, key):
    """
    return true if key could be a key
    """
    if not all( isinstance(element[key], str) for element in data):
        return False
    return len(set(element[key] for element in data)) == len(data)

def determine_key(data):
    """
    Determine the key, value to compress the list of dicts
    or None if no such key exists
    """
    for element in data:
        if not isinstance(element, dict):
            return None
        if len(element) != 2:
            return None
        if element.keys() != data[0].keys():
            return None

    key1, key2 = data[0].keys()
    key1_possible = can_be_key(data, key1)
    key2_possible = can_be_key(data, key2)

    if key1_possible and key2_possible:
        meta = input("Which key (%s|%s)? " % (key1, key2))
        if meta == key1:
            return key1, key2
        else:
            return key2, key1
    elif key1_possible:
        return key1, key2
    elif key2_possible:
        return key2, key1
    else:
        return None

def optimize_list(data, keys):
    key_key, key_value = keys
    return {element[key_key]: optimize(element[key_value]) for element in data}

But... I must question the wisdom of the entire approach. The function is actually rather useless. Suppose that you use it on web service that returns a json object. It gives you

{"results" : [
     {"name" : "foo", "age": 42}
     {"name" : "bar", "age": 36}
}

Which optimize to

{"foo": 42, "age": 36}

So you write:

for name, age in optimize(the_json).items():
    print(name, age)

But then in another request, the server returns

{"results" : [
     {"name" : "foo", "age": 42}
}

which optimizes to:

42

So when you run:

for name, age in optimize(the_json).items():
    print(name, age)

You get an error.

Or the server adds extra data to the json:

{
 "salinity" : "high",
 "results" : [
     {"name" : "foo", "age": 42, "status" : "sad"}
     {"name" : "bar", "age": 36, "status" : "happy"}
}

Which should be backwards compatible using json, but will break your code or anything doing the same job.

This is not to say that can't or shouldn't simplify the json. But don't try to do it by analyzing the data like this. You should do it by some external record of the schema.

class Fetch(object):
    """
    Fetch one element from a dictionary
    """
    def __init__(self, name, inner):
        self._name = name
        self._inner = inner

    def __call__(self, data):
        return self._inner(data[self._name])

class KeyValue(object):
    """
    Given a list of dicts, convert to a dictionary
    with each key being taken from the `key` on each element
    and each value being taken from the `value`
    """
    def __init__(self, key, value, inner):
        self._key = key
        self._value = value
        self._inner = inner

    def __call__(self, data):
        return {element[self._key] : self._inner(element[self._value]) for element in data}

class Literal(object):
    def __call__(self, data):
        return data

schema = Fetch("recipes",
    KeyValue("name", "ingredients",
        KeyValue("ingredient", "quantity", Literal())
    )
)

That's actually simpler then what you were doing, and its much more robust. Its also very flexible as you can write code to perform just about any transformation on the data.


Here is a solution using the Command Pattern.

Each action will live in its own class. I'm using some mixins so we don't have repeated code.

nursing_formulas.rb

require_relative "formulas/mass_for_mass"
require_relative "formulas/mass_for_liquid"
require_relative "formulas/iv_ml_rate"
require_relative "formulas/iv_drop_rate"

class NursingFormulas
  def initialize
    show_instructions

    @instructions = {
      1 => MassForMass.new,
      2 => MassForLiquid.new,
      3 => IvMlRate.new,
      4 => IvDropRate.new
    }

    choice = gets.chomp.to_i

    @instructions.key?(choice) ? @instructions[choice].do : exit(0)
  end

  def show_instructions
    puts "What do you want to do?"
    puts "1) How many tablets should I administer?"
    puts "2) How many ml should I administer?"
    puts "3) What's the ml per hour rate of my IV?"
    puts "4) What's the drop rate of my IV?"
    puts "5) Exit"
  end
end

mass_for_mass.rb

require_relative "mixins/mass_actions"

class MassForMass
  include MassActions

  def do
    result = ask_for_prescribed_mass / ask_for_mass
    puts "Administer #{result} tablets"
  end
end

mass_for_liquid.rb

require_relative "mixins/mass_actions"

class MassForLiquid
  include MassActions

  def do
    prescribed = ask_for_prescribed_mass
    mass = ask_for_mass
    ml = ask_for_ml

    result = (prescribed / mass) * ml
    puts "Administer #{result} ml"
  end

  def ask_for_ml
    puts "How many mL do you have?"
    gets.chomp.to_f
  end
end

iv_ml_rate.rb

require_relative "mixins/iv_actions"

class IvMlRate
  include IvActions

  def do
    volume = ask_for_volume
    time = ask_for_time

    result = (volume / time).round
    puts "The rate is #{result} ml per hour"
  end
end

iv_drop_rate.rb

require_relative "mixins/iv_actions"

class IvDropRate
  include IvActions

  def do
    volume = ask_for_volume
    time_in_min = ask_for_time * 60
    factor = ask_for_drop_factor

    result = ((volume / time_in_min) * factor).round
    puts "The drop rate is #{result} drops per minute"
  end

  def ask_for_drop_factor
    puts "What's the drop factor?"
    gets.chomp.to_f
  end
end

MIXINS

mass_actions.rb

module MassActions
  def ask_for_prescribed_mass
    puts "What's the prescribed mass in mg?"
    gets.chomp.to_f
  end

  def ask_for_mass
    puts "What's the mass you've got in mg?"
    gets.chomp.to_f
  end
end

iv_actions.rb

module IvActions
  def ask_for_volume
    puts "What's the volume in mL?"
    gets.chomp.to_f
  end

  def ask_for_time
    puts "What's the time in hours?"
    gets.chomp.to_f
  end
end


I don't think it's a good idea to rethrow only the first/single exception of a particular type. Often, when done right ;-) each exception may contain different data about what went wrong, like entity validation errors may happen for multiple entities or mutliple files may not have been found etc. If you pick only the first one you won't know about the rest and you'll app crashes agian next time.

The Handle and the ThrowIfNonEmpty are fine but Throw is very harmful.

Additionaly I would change the Handle to be Func<TEx, bool>:

public static AggregateException Handle<TEx>(
    this AggregateException source, Func<TEx, bool> handler)
    where TEx : Exception
{
    var exceptions = source.Flatten().InnerExceptions.OfType<TEx>();
    var handlerExceptions = new List<Exception>();
    foreach (var exception in exceptions)
    {
        try
        {
            if (!handler(exception))
            {
                handlerExceptions.Add(exception);
            }
        }
        catch (Exception ex)
        {
            handlerExceptions.Add(ex);
        }
    }
    return new AggregateException(source.InnerExceptions
        .Except(exceptions)
        .Concat(handlerExceptions));
}

so that I can for example log it and still be able to say I didn't handle it by returning false.

.Handle((ArgumentException ex) =>
{
   Console.WriteLine(ex.Message);
   return false;
})


Initializing a tile-like map such that the edges are marked with an 'X'

switch vs. if

In

        switch (rpgLevelGrid[i][j])
        {
        case 1:
            cout << "X";
            break;
        default:
            cout << "-";
        }

do not use switch when all you need is a regular if. Instead do

        if (rpgLevelGrid[i][j])
        {
            cout << "X";
        }
        else
        {
            cout << "-";
        }

or even better do

        cout << (rpgLevelGrid[i][j] ? "X" : "-");

You could also fill the grid with the characters to print unless there is reason not to do so. Then you only do

        cout << rpgLevelGrid[i][j];

A third option for the output is to define a symbol table like

const char symbols[] = "-X";

and use it like

        cout << symbols[rpgLevelGrid[i][j]];

Initialisation

Also our inner init loop is not consistent. you conditionally init with 1 on i but conditionally overwrite the previously initialized 0 with 1 on j. Wwhy not init all with 0 and overwrite the borders? That is less complex. So

        switch (i)
        {
        case 0: case 19:
            rpgLevelGrid[i][j] = 1;
            break;
        default:
            rpgLevelGrid[i][j] = 0;
            break;
        }

        switch (j)
        {
        case 0:
            rpgLevelGrid[i][j] = 1;
            break;
        case 19:
            rpgLevelGrid[i][j] = 1;
            break;
        }

becomes

        rpgLevelGrid[i][j] = 0;
        if (i==0 || i==19 || j==0 || j==19)
        {
            rpgLevelGrid[i][j] = 1;
        }

Number literals

Still there are some magic numbers. We now define

const int dim = 20;

and replace all literals in the code like

int rpgLevelGrid[dim][dim];

for (int i = 0; i < dim; i++)

case dim-1:

or

        if (i==0 || i==dim-1 || j==0 || j==dim-1)

Functions

Finally we pull out some code from main and provide two functions for init and print and end up in

#include <iostream>

using namespace std;

const int dim = 20;

void init(int grid[dim][dim])
{
    for (int i = 0; i < dim; i++)
    {
        for (int j = 0; j < dim; j++)
        {
            grid[i][j] = 0;
            if (i==0 || i==dim-1 || j==0 || j==dim-1)
            {
                grid[i][j] = 1;
            }
        }
    }
}

void print(int grid[dim][dim])
{
    const char symbols[] = "-X";
    for (int i = 0; i < dim; i++)
    {
        for (int j = 0; j < dim; j++)
        {
            cout << symbols[grid[i][j]];
        }
        cout << endl;
    }
}

int main()
{
    int rpgLevelGrid[dim][dim];

    init(rpgLevelGrid);
    print(rpgLevelGrid);
}

That is a resonable result for a beginner.


Writing FizzBuzz like this makes me feel like a small child

It may be fun watching it type out FizzBuzz, but interacting with the UI directly has its pitfalls. For example, if the user focuses a different application while your script is running, you will now be typing in the wrong place; and if you refocus the application, that could be annoying.

Fortunately, there is a better way. Rather than activating the application, waiting until a window appears, and making the window frontmost, you could just…

tell application "TextEdit" to set text of first document to "Hello, world!"

This is much less problematic. The only issue is if TextEdit is already open, in which case it will overwrite the existing document. In that case, you could use

tell application "TextEdit" to set text of (make new document) to "Hello, world!"

Either way, you’re not interacting directly with the UI any more, which eliminates a lot of potential problems.

The actual meat of the FizzBuzz implementation (barring the use of keystroke) looks fine, although you might consider something like keystroke "FizzBuzz" & return rather than keystroke "FizzBuzz" and separately keystroke return.


It is perfectly normal to attempt to subclass a Tkinter widget to create a custom one. Your choice is valid and justified.

However, as Tkinter does not have a EntryBox() class, it would be better to rename this, in order not to confuse the reader of your code, to rename it to something like: CustomEntry() or, why not, CustomEntryWidget().


Find integer pairs in an array which adds to a given sum

I like your approach with the two-pointer-array. As for the performance: The other answers here use the Big O notation as a basis for comparing the speed of different algorithms, hinting that using a HashMap or a HashSet might be faster than your approach. But this is misleading, since the Big O notation says nothing about the speed of different algorithms compared to each other, but only about how much slower an algorithm will be when \$n\$ increases. For example, you might have an \$O(n)\$ algorithm that takes \$n\$ hours to complete, and an \$O(n^{2})\$ algorithm that takes \$n^{2}\$ milliseconds to complete, and the second algorithm will be faster for all \$n < 3600000\$. Of course, this is an extreme example, I just wanted to make a principle clear.

As for this case, I tried to compare your algorithm with the algorithm suggested by zenwraight. Here is my implementation of that algorithm:

public class FindPairsInAnArrayAddingToASum {
    public static class IntegerPair {
        public final int number1;
        public final int number2;

        public IntegerPair(int number1, int number2) {
            this.number1 = number1;
            this.number2 = number2;
        }
    }

    public static List<IntegerPair> findNumberPairs(int[] items, int prescribedSum) {
        Map<Integer, Integer> frequencies = new HashMap<>();
        for (int item : items) {
            Integer previousFrequency = frequencies.get(item);
            frequencies.put(
                    item,
                    previousFrequency != null
                    ? previousFrequency + 1
                    : 1);
        }

        List<IntegerPair> result = new LinkedList<>();
        for (int item : frequencies.keySet()) {
            int complement = prescribedSum - item;
            Integer complementFrequency = frequencies.get(complement);
            if (complementFrequency != null
                    && (item != complement || complementFrequency > 1)) {
                result.add(new IntegerPair(item, complement));
            }
        }

        return result;
    }
}

First, I benchmarked 10 test cases where every array contains 10,000 random integers, with a different random prescribed sum for every array. Here are the results:

Double pointer array: 0.022 seconds
Hash map: 0.066 seconds

Double pointer array: 0.012 seconds
Hash map: 0.036 seconds

Double pointer array: 0.017 seconds
Hash map: 0.021 seconds

Double pointer array: 0.003 seconds
Hash map: 0.071 seconds

Double pointer array: 0.006 seconds
Hash map: 0.013 seconds

Double pointer array: 0.006 seconds
Hash map: 0.009 seconds

Double pointer array: 0.008 seconds
Hash map: 0.01 seconds

Double pointer array: 0.003 seconds
Hash map: 0.009 seconds

Double pointer array: 0.003 seconds
Hash map: 0.007 seconds

Double pointer array: 0.002 seconds
Hash map: 0.008 seconds

So your code performed slightly better in all test cases listed here (although there also were some 10,000-size array test cases in other benchmark runs where the HashMap performed slightly better). Next, 10 test cases, same as above, but now the arrays contain 100,000 integers:

Double pointer array: 0.064 seconds
Hash map: 0.346 seconds

Double pointer array: 0.068 seconds
Hash map: 0.381 seconds

Double pointer array: 0.03 seconds
Hash map: 0.068 seconds

Double pointer array: 0.032 seconds
Hash map: 0.12 seconds

Double pointer array: 0.032 seconds
Hash map: 0.17 seconds

Double pointer array: 0.037 seconds
Hash map: 0.073 seconds

Double pointer array: 0.014 seconds
Hash map: 0.12 seconds

Double pointer array: 0.013 seconds
Hash map: 0.054 seconds

Double pointer array: 0.016 seconds
Hash map: 0.059 seconds

Double pointer array: 0.014 seconds
Hash map: 0.066 seconds

Your code still wins. The differences are even more significant in some cases than when the arrays only contained 10,000 integers. Next, increase the array size to 1,000,000 integers:

Double pointer array: 0.495 seconds
Hash map: 2.356 seconds

Double pointer array: 0.336 seconds
Hash map: 3.916 seconds

Double pointer array: 0.279 seconds
Hash map: 0.651 seconds

Double pointer array: 0.164 seconds
Hash map: 0.713 seconds

Double pointer array: 0.162 seconds
Hash map: 0.885 seconds

Double pointer array: 0.31 seconds
Hash map: 0.868 seconds

Double pointer array: 0.164 seconds
Hash map: 0.795 seconds

Double pointer array: 0.165 seconds
Hash map: 0.919 seconds

Double pointer array: 0.323 seconds
Hash map: 0.71 seconds

Double pointer array: 0.164 seconds
Hash map: 0.697 seconds

Your double pointer array beats the hash map again. Finally, increase the array size to 5,000,000 (the program ran out of memory when I tried to run it with 10,000,000-size arrays, probably because I generated all 10 test cases in advance instead of only generating one for each benchmark).

Double pointer array: 1.625 seconds
Hash map: 14.116 seconds

Double pointer array: 0.927 seconds
Hash map: 12.554 seconds

Double pointer array: 0.914 seconds
Hash map: 11.51 seconds

Double pointer array: 0.924 seconds
Hash map: 10.654 seconds

Double pointer array: 1.013 seconds
Hash map: 15.335 seconds

Double pointer array: 1.039 seconds
Hash map: 10.512 seconds

Double pointer array: 0.9 seconds
Hash map: 11.928 seconds

Double pointer array: 0.954 seconds
Hash map: 10.16 seconds

Double pointer array: 0.916 seconds
Hash map: 12.326 seconds

Double pointer array: 0.899 seconds
Hash map: 9.881 seconds

I don't know why the HashMap algorithm takes so long here. It could have to do with the need to increase the capacity of the HashMap multiple times, but experimenting with different values for the initial capacity didn't make much of a difference. But anyway, I think this makes it clear that you shouldn't rely on the Big O notation when comparing the speed of different algorithms to each other.

However, apart from the performance, your public method getPairsAddingToSum(int[], int) returns a ResultPair, which is a private class, so whoever calls your method won't be able to do anything with the returned value. But regardless of that, I don't understand why, in your code, you invent something that already exists, namely a linked list. Why don't you just use java.util.LinkedList?

In any case, you also asked whether there would be a better data structure than a linked list to return the found pairs. I think there is, namely a Set. After all, the array might contain duplicates, so it might also contain duplicate valid pairs. Of course, in order to take advantage of a Set, you would have to implement hashCode() and equals(Object) in your ResultPair class (which would then only contain the two integers and no nodes). Seeing as, in your algorithm, the first number in a pair will always be less than or equal to the second number, it would suffice for ResultPair.equals(Object) to compare a and b from both ResultPairs to each other without sorting them first, thereby considering to ResultPairs with the same numbers but in a different order unequal, but this depends on how you want to use the class ResultPair further (in case you do want to use it outside the context of this algorithm). Note that, if you use a Set, the algorithm will naturally take longer than if you use a List, because removing duplicates is an additional task that was not carried out in your original code.

Edit:

Actually, there's a much simpler and more efficient approach for avoiding duplicate number pairs than using a Set: When adjusting the array counters for the next while loop, you could simply in-/decrement them until the integer they point to is different from the integer they previously pointed to, instead of in-/decrementing them only once.


Allocation and freeing

In the while loop of your infinite loop, you are allocating memory for proc only to be completely freeing it by the end of the loop. Why? Considering every loop you reset with memset, why not keep the same allocated memory for the entire time?

Your code would be much faster if you moved the allocation of proc out of both loops, and if you did not free the memory every iteration, too. Also, you seem to be freeing proc in a few other places in the loop; see if you can remove those, too.

Refactor built-in functions

Here you are checking for commands that require special attention:

if(!strcmp(proc->commv[0], "exit")) {
    free(proc);
    exit(EXIT_SUCCESS);
}

if(!strcmp(proc->commv[0], "cd")) {
    proc->exec = 0;
    if (chdir(proc->commv[1]) != 0)
        error_msg("chdir() error");
}

What if you need to add another command to this list for whatever reason? Now, you could just add another if, but then your code starts to look a little  more messy.

To make your code more flexible here, you could try splitting these built-in functions into a struct which stores the name of the built-in function and a pointer to a function to execute if this is come across.

Then, you could create a function that checks if the command entered is a built-in function. If it is, then the function can easily handle the situation using the built-in function's struct.

Here is a short snippet of what I mean:

struct builtin {
    char *name;
    function pointer;
} builtins = {
    "exit", builtin_exit,
    ...
};

Then, all you need is a function to check through builtins to see if the command entered is a built-in function.

From there, if you ever need to add another built-in function, you simply add another one to the array (and create its respective function), and you don't even have to touch the shell's main code.

Exit number

In your error_msg function, you have this:

exit(0);

Well, that doesn't make much sense; if there's an error, the code needs to return a non-zero number to indicate failure. Other than that, the environment in which this program was run will not be able to tell that there was an error.

const int or #define

#define MAX_LEN 4096
#define MAX_ARGS 256

It would be better to use a const int here because that will actually define a type for the variable, where #define simply sticks that literal string after the macro name into the code and leaves it up to the compiler to determine a type for it.