jquery.readmore plugin I'm working now on project, which is need some read more functionality and I tried to write this jquery plugin and share it in my github account.

Here is the full listing of code:

;(function ( $, window, document, undefined ) {

function get_link(readmore_wrap_class, readmore_class, readmore_text ) {
    return $('<a/>')
                .addClass(readmore_wrap_class)
                .prop('href', '#')
                .html(
                    $('<span/>')
                        .addClass(readmore_class)
                        .text(readmore_text)
                    );
}

function get_first_p(text, sentences_number) {
    var paragraph = text.find('p:first-child').clone();

    return paragraph
            .text(
                paragraph
                    .text().split('.', sentences_number)
                    .join('. ') + '. '
            );

}

$.fn.readmore = function (options) {
    var settings = $.extend({
        sentences_number: 3,
        readmore_text: 'Read more.',
        readmore_toggle_text: 'Read less.',
        readmore_wrap_class: 'readmore_link_wrap',
        readmore_class: 'readmore_link',
        bidirectional: false
    }, options);

    return this.each(function(index) {

        var text = $(this),

            // replace default settings with per text data attributes
            sentences_number     = text.data('sentences_number')     || settings.sentences_number,
            readmore_text        = text.data('readmore_text')        || settings.readmore_text,
            readmore_toggle_text = text.data('readmore_toggle_text') || settings.readmore_toggle_text,
            readmore_wrap_class  = text.data('readmore_wrap_class')  || settings.readmore_wrap_class,
            readmore_class       = text.data('readmore_class')       || settings.readmore_class,
            bidirectional        = text.data('bidirectional')        || settings.bidirectional;

            link = get_link(readmore_wrap_class, readmore_class, readmore_text),
            first_p = get_first_p(text, sentences_number);

        /*
        Copy first paragraph
        Save only first `sentences_number` sentences
        Add link `read more`
        Hide Original paragraphs
        On click on `read more` link delete rirst extra paragraph
        Show original paragraphs
        if bidirectional
            add 'readless' link to whole text
            On click to it delete it and run readmore again (go to 1 step)
         */
        text.find('p').hide();

        link
            .appendTo(first_p)
            .on('click', function(event) {
                first_p.remove();
                text.find('p').show();

                if (bidirectional) {
                    get_link(readmore_wrap_class, readmore_class, readmore_toggle_text)
                        .appendTo(text)
                        .on('click', function(event) {
                            $(this).remove();
                            text.readmore();

                            event.preventDefault();
                        });
                }

                event.preventDefault();
            });

        text.prepend(first_p);
    });
};

($('.readmore').length !== 0) && $('.readmore').readmore();

// end of jquery plugin wrap
})( jQuery, window, document );

Codereview goals:

What I have missed?
What can I improve?

The code is good, only a few ignorable pointers :

lowerCamelCase is the standard for JavaScript, so

get_link -> getLink
get_first_p -> getFirstParagraph
readmore -> readMore ?

The code could be more DRY for the retrieval of settings.
I would counter-propose something like this:

    var defaultSettings = {
        sentences_number: 3,
        readMoreText: 'Read more.',
        readMoreToggle_text: 'Read less.',
        readMoreWrapClass: 'readmore_link_wrap',
        readMoreClass: 'readmore_link',
        bidirectional: false
    };

   var settings = $.extend({}, defaultSettings, options);

   return this.each(function(index) {

        var text = $(this),
        var elementSettings = {};

        //Optionally replace settings with per text data attributes
        for( key in defaultSettings )
          elementSettings[key] = text.data( key ) || settings[key];

        //Then you could either
        link = get_link( elementSettings ),
        //Or you could
        link = get_link(elementSettings.readmore_wrap_class,
                        elementSettings.readmore_class,
                        elementSettings.readmore_text);

($('.readmore').length !== 0) && $('.readmore').readmore(); this is a bit too Golfic ( reminds me of code golf ) and has a repeated constant  which should be extracted and part of your readMore object in my mind.
Finally, your commenting is very un-even, one part has a lot, the rest has close to nothing. I'd say that your functions deserve each a /* One liner */.


Google Code Jam: Store Credit Java Solution It would be great if I could get this code reviewed.
I would love tips on how I could improve my code.

Problem
You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).
Input
The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:
One line containing the value C, the amount of credit you have at the store.
One line containing the value I, the number of items in the store.
One line containing a space separated list of I integers. Each integer P
indicates the price of an item in the store.
Each test case will have exactly one solution.
Output
For each test case, output one line containing "Case #x: " followed by the indices of the two items whose price adds up to the store credit. The lower index should be output first.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.stream.IntStream;

public class StoreCredit {

    private static int case_num = 0;
    private static int num_cases, credit_value, item_cnt;
    private static ArrayList<Integer> prices;
    private static Scanner reader;
    private static ArrayList<String> output;

    public static void main(String... args) throws FileNotFoundException{
        output = new ArrayList<String>();
        reader = new Scanner(new File("src/store_credit/input.txt"));

        num_cases = reader.nextInt();
        for(int i = 0; i < num_cases; ++i){
            prices = new ArrayList<Integer>();
            credit_value = reader.nextInt();
            item_cnt = reader.nextInt();
            IntStream.range(0, item_cnt).forEach((j) ->  prices.add(j, reader.nextInt()));
            solution();

        }
        for(String s : output)
            System.out.println(s);
    }

    public static void solution(){
        for(int i = 0; i < item_cnt; ++i){
            if(prices.contains(credit_value - prices.get(i))){
                output.add("Case #" + ++case_num + ": " + (i + 1) + " " + (prices.lastIndexOf(credit_value-prices.get(i)) + 1));
                return;
            }
        }
    }
}

Input Information

Performance is bad. List.contains() runs in linear time, driving it to quadratic. Recommendation: prepare the list of {price, index} pairs, and stable sort it by prices. The solution is then found in a single scan, along the lines of

    while (head < tail) {
        total = head->price + tail->price;
        if (total < credit) {
            ++head;
        else if total > credit) {
            --tail;
        else {
            return {head->index, tail->index};
        }
    }


Add the number of descendants for each li node A web page has a nested list.  The goal is to insert the number of descendants for each li node (except for leaf nodes).

Here is an example of the expected output:

Animals [9]
    Mammals [4]
        Cows
        Donkeys
        Dogs
        Tigers
    Other [3]
        Snakes
        Birds
        Lizards
Fishes [5]
    Aquarium [2]
        Guppy
        Angelfish
    Sea [1]
        Sea trout

Here is the javascript I wrote:

function isLeaf(elem) {
    if(elem.firstElementChild === null) {
        return true;
    }

    else {
        return false;
    }
}

function countDescendants(elem) {
    if(isLeaf(elem)) return 0;

    else {
        let children = elem.firstElementChild.children;
        let count = 0;

        for(let child of children) {
            if(isLeaf(child)) {
                   count++;
            }

            else {
                count = count + 1 + countDescendants(child);
            }

        }
        return count;
    }
}

function insertCount(elem) {
    let count = countDescendants(elem);
    let text = elem.firstChild.textContent.trim();
    text = text + " [" + count + "]";
    elem.firstChild.textContent = text;
}

function traverseDOM(root) {
    let children = root.children;

    for(let child of children) {
        if(!isLeaf(child)) {
            if(child.tagName === "LI") {
                insertCount(child);
            }
            traverseDOM(child);
        }
    }
}

//traverse DOM tree
//try catch is for debugging only
try {
    if(document.body.firstElementChild !== null) {
        traverseDOM(document.body.firstElementChild);
    }
}  catch (err) {
    console.log(err);
}

The code works.  I get this nagging feeling it could be done better.  For example, is there a way to improve the countDescendants function?

I think functional coding style is best suited here, because it will significantly reduce amount of code. Also, you will have clearly separated structure consisting of functions with single responsibility.

Suggested solution

function insertCounts(root) {
    forEachElement(root, (el) => el.innerHTML = countText(count(el)) + el.innerHTML, el => !isLeaf(el) && (el.tagName === 'LI'));
}

function countText(count) {
     return `[${count}]`;
}

function forEachElement(root, apply, predicate = () => true) {
    Array.from(root.children).forEach(el => { predicate(el) && apply(el); forEachElement(el, apply, predicate) });
}

function count(root) {
    return Array.from(root.children).reduce((acc, el) => isLeaf(el) ? acc + 1 : acc + count(el), 0);
}

function isLeaf(elem) {
    return (elem.firstElementChild === null);
}

try {
    if(document.body.firstElementChild !== null) {
        insertCounts(document.body.firstElementChild);
    }
}  catch (err) {
    console.log(err);
}


Feedback on my bash backup script I have this little server at home, which is hosting some websites, school stuff and a minecraft server. I made this backup script and I would like some feedback since I'm not very good at scripting.

#!/bin/bash
# declare folders to backup
dirs=(
    "/home/ferre/Minecraft"
    "/var/lib/automysqlbackup/daily"
);

# backup names
names=(
  "Minecraft"
  "Mysql"
);

# backup folder
backupdir="/mnt/backup";

# backup algorithm
for (( i=0; i<=$(( ${#dirs[*]} -1 )); i++))
do
  # info
  echo "starting backup of ${names[i]}";

  # create folder
  path="${backupdir}/${names[i]}";
  $(mkdir -p "$path");

  # create backup
  file="${path}/$(date +%F).tar";
  $(tar -czf "$file" --absolute-names "${dirs[i]}");

  # reporting
  result=$?;
  if [ $result -eq 0 ]; then
    echo "SUCCESS";
  elif [ $result -eq 1 ]; then
    echo "WARNING some files where changed while copying!";
  else
    echo "FATAL ERROR";
  fi
done

There is not a lot to say, the script is fairly simple.

For the date format:

file="${path}/$(date +%F).tar";

I think I would define a constant variable at the top of the code. You might want to change the pattern latter (use something different than YYYY-MM-DD).

This:

$(mkdir -p "$path");

can simply be written as:

mkdir -p "$path"

unless you want to save the output of the bash command to a variable but this is not the case here.

You have some key/pair values to define your backup sources:

dirs=(
    "/home/ferre/Minecraft"
    "/var/lib/automysqlbackup/daily"
);

# backup names
names=(
  "Minecraft"
  "Mysql"
);

I would combine both into an associative array.

declare -A sources=(
    ["Minecraft"]="/home/ferre/Minecraft"
    ["Mysql"]="/var/lib/automysqlbackup/daily"
)

for item in "${!sources[@]}"; do
  echo "Name: $item => Directory: ${sources[$item]}"
done

Output:

Name: Mysql => Directory: /var/lib/automysqlbackup/daily
Name: Minecraft => Directory: /home/ferre/Minecraft

Thus you can easily loop on the array and extract name and target directory. Warning: please check the syntax. Bash has many pitfalls and I may have made mistakes.

Logging: I think it is important to retain a trace of script execution. Especially when the script is unattended. The console can quickly fill up and you could miss critical messages.

You have a few options like:

define a variable for a log file then use tee -a next next to each command, so that you get output to console and to a file at the same time. But this is tedious and not flexible.
Call your script like this: /path/to/your/script.sh > backup.log (use >> to append) or: /path/to/your/script.sh | tee backup.log
or better yet /path/to/your/script.sh 2>&1 | tee backup.log to capture the output of stderr.

Last but not least, your script could return an exit code. This is useful if your script is going to be handled by another script or even set up as a service.

Suggestions:

Have the script send you the log file by E-mail after execution. Or archive the log file somewhere for later review if desired.
Add error handling to make your script more reliable and more robust. If something wrong happens, or at least a fatal error, the script should stop and alert you. Here is an intro: Bash Error Handling

A backup script is usually critical, it has to perform reliably. One day, you may need to restore some important files, or recover from a system crash. There is nothing more tragic than useless/incomplete backups.

So you should also test your backups manually from time to time. Attempt to restore a random file and verify the result.


Multithread to print odd and even numbers I recently started on C++ multithreading. Here is my code to print odd and even numbers in two different thread. Can somebody please review this code?

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

int x = 1;
mutex m;
bool evenready = false;
bool oddready = true;
condition_variable cond;
void printEven()
{
    for (; x < 10;) {
        unique_lock<mutex> mlock(m);
        cond.wait(mlock, [] {
            return evenready;
        });
        oddready = true;
        evenready = false;
        cout << "Even Print" << x << endl;
        x++;
        cond.notify_all();
    }
}

void printOdd()
{
    for (; x < 10;){
        unique_lock<mutex> mlock(m);
    cond.wait(mlock, [] {
        return oddready;
    });
    oddready = false;
    evenready = true;
    cout << "Odd Print" << x << endl;
    x++;
    cond.notify_all();
}
}

int main()
{
    thread t1(printOdd);
    thread t2(printEven);
    t1.join();
    t2.join();
    return 0;
}

Multiple threads are usually used to compute things in parallel.
In this example nothing is computed in parallel:
while one thread is running,
the other is waiting.
With no practical value,
it's not a great demonstration of multithreading.
I suggest to look for more practical targets in the future.

Since evenready and oddready always have opposite values,
one of them would be enough, and less error-prone.

Instead of for (; x < 10;) { it's more natural to use while (x < 10) {.

using namespace std; is considered bad practice.


Tampermonkey script to check and replace youtube's subscriptions to show all videos Just wanted a general review of the code to make sure I'm doing it properly/efficently. New to JS and don't use RegEx too often.
// ==UserScript==
// @name         Youtube Subscriptions Redirect
// @namespace    https://github.com/spacegIider
// @version      1.0
// @license      MIT
// @description  Shows all subscribed videos in subscription feed.
// @author       Spaceglider
// @match        *://www.youtube.com/feed/subscriptions
// @grant        none
// @homepageURL  https://github.com/spacegIider/Youtube-Subscriptions-Redirect
// @supportURL   https://github.com/spacegIider/Youtube-Subscriptions-Redirect/issues
// @downloadURL  https://raw.githubusercontent.com/spacegIider/Youtube-Subscriptions-Redirect/redirect.js
// @updateURL    https://raw.githubusercontent.com/spacegIider/Youtube-Subscriptions-Redirect/redirect.js
// ==/UserScript==

var BadDumbYoutubeURL = window.location.pathname;

if ( ! /\?flow=1$/.test (BadDumbYoutubeURL) ) {
    var ActuallySeeAllVideosURL = window.location.protocol + "//"
                                + window.location.host
                                + BadDumbYoutubeURL + "?flow=1"
                                +window.location.search
                                +window.location.hash
                                ;

    window.location.replace (ActuallySeeAllVideosURL);
}

A short review;

BadDumbYoutubeURL should be lowerCamelCase and perhaps is a bit silly

the ; does not deserve it's on own line

My understanding is that location.search already starts with ? so you probably want to do something about that, like
 const search = window.location.search ? '&' + window.location.search.substring(1) : 0;

Other than looks fine, perfectly maintainable


Die-rolling for ordering I have a little experience with Python and am trying to become more familiar with it. As an exercise, I've tried coding a program where the ordering of a list of players is determined by the roll of a die. A higher number would place the player ahead of others with lower numbers. Ties would be  broken by the tied players rolling again.

Here is an example:

                           player 1, player 2, player 3
                            rolls 6, rolls 6, rolls 1
                                 /           \
                                /             \
                       player 1, player 2    player 3
                        rolls 5, rolls 4
                         /       \
                        /         \
                   player 1    player 2

Final order: player 1, player 2, player 3

I'm interested in how I could have done this better. In particular, I'm not familiar with much of the Python style guide so making it more pythonic would be nice. Also, I'm not that familiar with unit testing. I've used unittest instead of nose since I was using an online IDE that supports it.

from random import randint
from itertools import groupby
import unittest

def rank_players(playerList, die):
    tree = [playerList]
    nextGeneration = []
    keepPlaying = True
    while keepPlaying:
        keepPlaying = False
        for node in tree:
            if len(node) == 1:
                nextGeneration.append(node)
            else:
                keepPlaying  = True
                rolls = [die.roll() for i in range(len(node))]
                turn = sorted(zip(rolls,node), reverse=True)
                print 'players roll:', turn
                for key, group in groupby(turn, lambda x: x[0]):
                    nextGeneration.append(list(i[1] for i in group))
        tree = nextGeneration
        nextGeneration = []
    return [item for sublist in tree for item in sublist]

class Die:
    def __init__(self,rolls=[]):
        self.i = -1
        self.rolls = rolls

    def roll(self):
        self.i = self.i + 1
        return self.rolls[self.i]

class RankingTest(unittest.TestCase):

    def testEmpty(self):
        die = Die()
        players = []
        self.assertEquals(rank_players(players,die),[])

    def testOnePlayer(self):
        die = Die()
        player = ['player 1']
        self.assertEquals(rank_players(player,die),['player 1'])

    def testTwoPlayer(self):
        die = Die([6, 1])
        players = ['player 1', 'player 2']
        self.assertEquals(rank_players(players,die),['player 1', 'player 2'])

    def testThreePlayer(self):
        die = Die([6, 6, 1, 4, 5])
        players = ['player x', 'player y', 'player z']
        self.assertEquals(rank_players(players,die),['player x', 'player y','player z'])

    def testRunAll(self):
        self.testEmpty()
        self.testOnePlayer()
        self.testTwoPlayer()
        self.testThreePlayer()

if __name__ == '__main__':
    unittest.main()

from random import randint
from itertools import groupby
import unittest

def rank_players(playerList, die):

Python convention is to use names like player_list for arguments/local variables

    tree = [playerList]

This isn't really used to hold a tree. Its only ever two levels deep, so its a list of lists. You also shouldn't name variables after datastructures, you should name after the meaning in the code.

    nextGeneration = []

You should move this into the loop. That way you won't have to repeat it later

    keepPlaying = True
    while keepPlaying:
        keepPlaying = False

Its best to try and avoid boolean logic flags. They tend to make code harder to follow. If you can, try to structure code to avoid their use.

        for node in tree:
            if len(node) == 1:
                nextGeneration.append(node)
            else:
                keepPlaying  = True
                rolls = [die.roll() for i in range(len(node))]

I'd have done:

  rolls = [ (die.role, item) for item in node]

This avoids the pointless call to len/range, and also handles the zipping in the next line

                turn = sorted(zip(rolls,node), reverse=True)
                print 'players roll:', turn
                for key, group in groupby(turn, lambda x: x[0]):
                    nextGeneration.append(list(i[1] for i in group))

Joel's recursive solution is much nicer, I think.

        tree = nextGeneration
        nextGeneration = []
    return [item for sublist in tree for item in sublist]

class Die:
    def __init__(self,rolls=[]):

In general, don't assign mutable objects as defaults. Here I don't even see why you would have a default since the object is useless with the default constructor.

        self.i = -1

I'd use index, just to be more explicit

        self.rolls = rolls

    def roll(self):
        self.i = self.i + 1
        return self.rolls[self.i]

But here's how I'd write your function

def rank_players(player_list)
    random.shuffle(player_list)

All you are doing in the end is shuffling the list of players, and python has a function for that. Unless you really want to simulate dice, there isn't a lot of point in doing it.

Another approach, I'm not sure a good one, would be:

class Die(object):
    def __init__(self, player):
        self.player = player
        self.rolls = []

    def __getitem__(self, index):
        # if you don't provide an __iter__
        # python will use __getitem__

        # whenever an attempt is made to access
        # past the end, we just roll a new number
        if index == len(self.rolls):
            roll = random.randrange(6)
            print "Player: %s Rolls a: %d" % (self.player, roll)
            self.rolls.append(roll)
            return roll
        else:
            return self.rolls[index]

    def __cmp__(self, other):
        # the only Die I am equal to is myself
        if self is other:
            return 0

        # look at the rolls in both die to
        # find first one that's different
        for a, b in itertools.izip(self, other):
            if a != b:
                return cmp(a,b)

        assert False

def rank_players(player_list):
    decorated = [(Die(player), player) for player in player_list]
    decorated.sort(reverse = True)
    print [die.rolls for die, player in decorated]
    return [player for die, player in decorated]


WinForms typing speed game I've been writing a simple code just for fun:

This is a simple WinForms application with which you can measure your typing speed. There are three controls on it, doing the following:

rtbResults - The one where you need to be as quick as possible.
textBox1 - The one where you submit the reference text.
tbBestTime - The one storing the best time of a "contestant".

Fields:

Stopwatch sw = new Stopwatch();
long bestTime = long.MaxValue;

One handler:

private void rtbResults_TextChanged(object sender, EventArgs e)
{
    if (rtbResults.Text.Length == 1)
    {
        sw.Restart();
    }
    else
    {
        if (rtbResults.Text == textBox1.Text)
        {
            sw.Stop();
            if (sw.ElapsedMilliseconds < bestTime)
            {
                bestTime = sw.ElapsedMilliseconds;
                tbBestTime.Text = (bestTime / 1000.0).ToString();
            }

            MessageBox.Show("Your time: " + sw.ElapsedMilliseconds / 1000.0 + "s.");
            sw = null;
            rtbResults.Text = "";
        }
    }
}

Another handler:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    bestTime = long.MaxValue;
    tbBestTime.Text = bestTime.ToString();
}

Now I'm looking for techniques to optimize the performance to get more precise results.
The point is not the memory consumption, but the length of the source code and the performance, and of course it must result the same as it does now (I mean the mentioned code).

I would like you to consider the following issues:

Is the...

Stopwatch
TextChanged event
type long
if/else (instead of if/return)

... the best way to do this?

Your code seems to me to be as efficient as reasonable for the application you are writing...

... but what you want/intend to do with it is unreasonable.... but first:

The method resetting the time is not very practical

private void textBox1_TextChanged(object sender, EventArgs e)
{
    bestTime = long.MaxValue;
    tbBestTime.Text = bestTime.ToString();
}

This method is setting the text to a value that the typical user will have no frame of reference for.... why is that 'big' number meaningful. Why not just set the tbBestTime.Text to be 'None yet' or something? This is especially significant since all other times the tbBestTime is set, you set it to a floating-point time/1000.0 value.
In your messageBox you do a simple /1000.0 for your time display. This is not going to always be 'pretty' since not all floating point values have a neat representation in binary. You should be using a Number formatter to ensure that the presentation of the value is consistent.... consider Custom Numeric Format Strings.

Finally, lets talk about accuracy and precision....

precision is reporting values to a large number of significant figures. In your case, reporting the time to (an intended) millisecond precision seems like a good idea, but, is that accurate?

Your intention with this question is to improve the accuracy of the results by reducing the overhead of the code when compared to the typing.

Unfortunately there is so much happening between your code and the keyboard that any attempt to increase the code performance will be outweighed by the simple operations happening on the system.... The following are things that may/will affect the accuracy of your timing:

Key debouncing
Interrupt handling
OS event notification
OS Thread scheduling
Clock granularity
TextBox listener notification

I would wager that each of these will be significantly more time than the per-cycle cost of your code.

Optimizing your code will make no difference to the accuracy of your timing, and, as it is, your reported precision is probably far more than the actual accuracy. In fact, I would suggest that anything within 1/10th of a second (instead of 1/1000th) is a 'tie'.


Integer to string or wstring converter I can't use std::to_string and std::to_wstring function, so I have written a converter:

///@struct ParseInt
///Contains function that parses integer.
template<typename Char_T> struct ParseInt{
    static std::basic_string<Char_T> toString(int x);
};

///Converts integer to std::string
///@param x the integer to convert
///@return std::string from the integer
template<> inline std::string ParseInt<char>::toString(int x){
    int length = 2; //most ints coming here are 2 digits long.
    char* buf = 0;
    do{
        delete[] buf;
        buf = new char[++length + 1];
    }while(sprintf(buf, "%d", x) < 0);
    std::string str(buf);
    delete[] buf;
    return str;
}

///Converts integer to std::wstring
///@param x the integer to convert
///@return std::wstring from the integer
template<> inline std::wstring ParseInt<wchar_t>::toString(int x){
    int length = 2; //most ints coming here are 2 digits long.
    wchar_t* buf = 0;
    do{
        delete[] buf;
        buf = new wchar_t[++length + 1];
    }while(swprintf(buf, length + 1, L"%d", x) < 0);
    std::wstring str(buf);
    delete[] buf;
    return str;
}

I am not sure how efficient it is. Is there any solution that is more efficient?

I am not sure how efficient it is. Is there any solution that is more efficient?

Very inefficient.

First, you allocate buffers with new/delete. You should not do that. Second, you allocate in a loop. You shouldn't do that either.

Consider this code instead (function renamed to to_string, as what you do is not parsing - parsing would be the inverse operation - taking a string and extracting an integer from it):

auto print(char * buffer, int x)
{
    return sprintf(buffer, "%d", x);
}

auto print(wchar_t * buffer, int x)
{
    return wsprintf(buffer, "%d", x);
}

///Converts integer to std::string
///@param x the integer to convert
///@return std::string/std::wstring from the integer
template<typename C,
    typename T=std::char_traits<C>,
    typename A=std::allocator<C>>
std::basic_string<C,T,A> to_string(int x)
{
    C buffer[ 64 ] = { 0 }; // no new/delete required
                            // no loop required
                            // max int on 32bit architectures is
                            // 2,147,483,647; 64 bytes is "big enough"

    auto written = print(buffer, "%d", x);
    assert(written > 0); // should always be true
    return std::basic_string<C,T,A>{ buffer, buffer + written };
}

Advantages:

there is no code repetition (easier to maintain)
efficiency is linear in to_string (no loops)
code is simpler and more straight-forward


Sleeping and invoking a task in Python 2.X and Python 3.X I'm writing a program that needs to be compatible for both Python 2.X and Python 3.X. My problem is that, because of the differences between these two versions, I'm duplicating code.

try:
        ### Python 2.X part
        time.sleep(iterator.next())
        if len(arguments) >= len(inspect.getargspec(task).args):
            task(*arguments)
        else:
            print("ERROR: There is a mismatch between the number of"
                  " arguments provided in `arguments` and the ones"
                  " needed by the task function.")
except AttributeError:
        ### Python 3.X part
        time.sleep(next(iterator))
        if len(arguments) >= len(inspect.getfullargspec(task).args):
            task(*arguments)
        else:
            print("ERROR: There is a mismatch between the number of"
                  " arguments provided in `arguments` and the ones"
                  " needed by the task function.")

It can be seen that both versions only differ in the usage of next(), inspect.getargspec() and inspect.getfullargspec(), while the other logic remains the same. Is there any way to optimize the execution of the tasks, in tasks(*arguments), and the printing of the error messages, so that I don't have to repeat the same code? This is just sample working code, but I mean my question in a more broader and general case.

You can use next() function in both Python 2.6+ and 3.x. If you need to support Python < 2.6, you can have your own next() function. You can, for instance, check if referring to next throws a NameError and define it if it does:

try:
    next
except NameError:
    _sentinel = object()
    def next(it, default=_sentinel):
        try:
            return it.next()
        except StopIteration:
            if default is _sentinel:
                raise
            return default

Even though getargspec() got deprecated since 3.0, it still can be used and imported. In this case, you can import getfullargspec() and catch the ImportError:

try:
    from inspect import getfullargspec as get_args  # Python 3
except ImportError:
    from inspect import getargspec as get_args  # Python 2

Taking these both points into account, the code would look like:

time.sleep(next(iterator))
if len(arguments) >= len(get_args(task).args):
    task(*arguments)
else:
    print("ERROR: There is a mismatch between the number of"
          " arguments provided in `arguments` and the ones"
          " needed by the task function.")

As far as generally supporting multiple Python versions in a single codebase, six is a must use package.

Also note that instead of using inspect to pre-validate the number of arguments, you can follow the EAFP approach, call the function and handle a TypeError:

>>> f = lambda x, y: 'test'
>>> f(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 2 arguments (3 given)


Java inheritance and generics Today i had discussion with my colleague about casting.

Our case:
We have root class

abstract class RootFoo<R extends RooFoo> {
   ...
   abstract R getThis();
}

and we implement method getThis in subclasses.

To save (in my opinion) unnecessary implementation getThis method in every subclass i showed my solution:

abstract class RootFoo<R extends RooFoo> {
   ...
   R getThis() {
       return (R) this;
   }
}

Could you help me understand why my idea is wrong?

I think that both approaches are incorrect.

Why would you need to cast an object to its own type, while it is already typed to a type that inherits from its parent abstract type?

The method getThis() is absolutely senseless, because if you have an instance of an object, it is typed by definition.


Function for rendering custom fonts I have a function that converts any normal true-type font to my own font file .bff
That function works correct and am not going to post that function for that matter
(the function is also only compatible with a specific engine you may not hear about).

If I post the .bff file and you have an environment in which you could use putpixel(x, y) to put a pixel (for e.g a red one) on the x and y spot, then you can also test my rendering function.

Let me first explain my custom compression method:

I call "Arlo compression" vername "Arlo1" with compression level over 60%. You have to understand the compression before take a look at the rendering function.

Standart characters (dec 48+) to represent whitespaces.
5 will represent 5 spaces and so forth
After each space a pixel is placed. So if there is 00 it puts two pixels right next to each other if there is 20 it puts 1 pixel after 2 spaces and one pixel as a next.
Important: to prevent a vertical line after each character the rendering function is made to not put pixel after the last space-representing character of the line determined (that is what causes problems - some characters needs a pixel at the end and it renders them cropped (without these last pixels) thanks to the vertical-line prevention condition.
# character found in the bff means new line of the character
& character found in the bff means offset for next character
Characters are with ascii sequence, dec32-126

The function:

typedef unsigned char BYTE;

void
bitfox_render_text
(char *FONTNEX, char *STRING, int X_OFFSET, int Y_OFFSET)
{
    FILE* fp = fopen(FONTNEX, "r");
    char *buffer = STRING, *font;
    int fontsize, buffsize = strlen(buffer), strl;
    int line = 0, linep = 0, colp = 0;

    fseek(fp, EOF, SEEK_END);
    fontsize = ftell(fp);
    font = malloc(fontsize);
    rewind(fp);
    fread(font, sizeof(BYTE), fontsize, fp);
    fclose(fp);

    for(strl=0; strl<buffsize; strl++)
    {
        int chrOffset, chr = 32;

        // In-line code for finding the current index of characters
        for(chrOffset=0; chr != buffer[strl]; chrOffset++) { if(font[chrOffset] == '&') { chr++; }} // <--

        do
        {   linep++;
            if
            (font[chrOffset+linep] == '#') { colp++; line = 0; }
            else if
            (font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:
            {
                // there is a function that describes size and color of the brush here
                putpixel(X_OFFSET+(line+=(font[chrOffset+linep]-48)+1), Y_OFFSET+colp);
            }
        } while(font[chrOffset+(linep+1)] != '&');
    }
    free(font);
}

The function currently reads successfully only one character passed as a string. Don't mind the arguments currently not used. Despite the fact that this function is not fully functional.. the only problem is the condition:
(font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement
It prevents for putting pixels at the end of each line.
If i remove that condition.. there will be a vertical line at the end of each character.. if it remains, some characters that need these pixels will be rendered cropped.

I will be doing constant edits to improve the level of clarification. Here is the download link of the .bff that response for the .ttf file "arial.ttf size 11 Normal".

Summary: The .bff file or "Bitfox Font File" is a custom font file, with custom compression method impiled ("Arlo1"). Each character from the ascii in the range of 32 to 126 in sequence is represented in raster-type where # determines there is a new line and & determines next character. To indicate where is a pixel placed, the current character's data consists of ascii characters (dec48-126) that represent whitespaces. The pixel is placed after the sapce is determined with chr-48. For the sake of the unrequired pixels prevention, the rendering function won't place pixels when the last character of the line is readed. That causes some characters to be cropped with 1 pixel at their end.

I'm not going to comment on the algorithm or functionality, however, there are several aspects in this code that make it very hard to read and understand.

Strange variable naming:

Most programmers associate names in ALL_CAPS with macros and constants (Windows programmers might also like that notation for typedefs), which makes them very unsuited for variable and parameter names. X_OFFSET, STRING, and the others would be much better as x_offset, string, and so on.

Unused parameter:

BYTE CLRSPACE[][3] is not used by the function. Should be removed or at least referenced with a (void) to suppress compiler warnings:

{
    (void)CLRSPACE;
    ...

Too many things in a line:

You have no idea how these lines combining several statements can hurt readability. A few instances:

char *buffer = STRING, *font; int xo = X_OFFSET, yo = Y_OFFSET;
...
fseek(fp, EOF, SEEK_END); fontsize = ftell(fp); font = malloc(fontsize); rewind(fp);

A much clearer layout:

char *buffer = STRING, *font;
int xo = X_OFFSET, yo = Y_OFFSET;
...
fseek(fp, EOF, SEEK_END);
fontsize = ftell(fp);
font = malloc(fontsize);
rewind(fp);

Inconsistent statement layout:

You have different ways of indenting and positioning your control statements.
This one in particular is very awkward:

if
(font[chrOffset+linep] == '#') { colp++; line = 0; }
else if
(font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:
{
    ...
}

Re-arrange that to a more natural way an be consistent with all your code:

if (font[chrOffset+linep] == '#')
{
    colp++;
    line = 0;
}
else if (font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:
{
    ...
}

Here, at the end of the function, another strange arrangement:

    } free(font);
    return;
}

free(font) should be in its own line. The return is not necessary, as this is a void function.

Mysterious statement:

It seems that in here:

int chrOffset, chr = 32; _ = chrOffset;

You have declared (or re-assigned) a variable named _. I have no idea what that is supposed to mean, as there are no further references to _. A variable named _ is already pretty bad by itself. This code here, I'm not even sure if it would compile...

There are probably more aspects to consider, but that's all I can tell you for now. Hope the advices are useful.


Assign key name based on row while loop Is it possible to automate the array inside the while loop and automatically assign the key name based on the row so I don't have to spell out each one?

$stmt = $conn->prepare("SELECT * FROM tickets_info WHERE ticket = ?");
$stmt->execute(array($_POST['ticket']));

if ($stmt->rowCount()) {

    while ($row = $stmt->fetch()) {

        $ticket = [
            'name'      => $row['name'],
            'company'   => $row['company'],
            'email'     => $row['email'],
            'phone'     => $row['phone'],
            'address'   => $row['address'],
        ];

    }

}

There is no identifiable difference between your table's column names and your preferred keys, but if you want to alter the keys, just build that into your SELECT clause -- this is what "aliases" are for.

Suppose you wanted to capitalize each column name, here's how that could look:

$stmt = $conn->prepare("SELECT name AS Name,
                               company AS Company,
                               email AS Email,
                               phone AS Phone,
                               address AS Address
                        FROM tickets_info
                        WHERE ticket = ?");
$stmt->execute([$_POST['ticket']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

Note, I am not using a loop.  Your snippet is overwriting itself in the loop, so I am interpreting that to mean that ticket is a PRIMARY/UNIQUE column.

If you want to extract all columns from your table and use the column names as keys, you don't need to change your original query.

$stmt = $conn->prepare("SELECT * FROM tickets_info WHERE ticket = ?");
$stmt->execute([$_POST['ticket']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];


Python molar mass calculator I created the following program which takes a molecular formula as an input, eg CH3COOH and returns the molar mass of the compound:
#! /usr/bin/env python3
element_weights = {
    'H': 1.00794,
    'He': 4.002602,
    'C': 12.011,
    'O': 15.999,
    'Ts': 294.0,
    'Og': 294.0,
}

def tokenize(string):
    position = 0
    tokens = []
    striter = iter(string)

    character = next(striter)

    while True:
        try:
            token = character

            if character in "()":
                character = next(striter)
            elif character.isnumeric():
                while (character := next(striter)).isnumeric():
                    token += character

            elif character.isupper():
                while (character := next(striter)).islower():
                    token += character
            else:
                raise ValueError("Can't parse")

            tokens.append(token)

        except StopIteration:
            tokens.append(token)
            tokens.append("EOF")
            return tokens

def get_composition(tokens_list):
    composition = {}

    tokens = iter(tokens_list)
    token = next(tokens)

    while True:
        if(token == "EOF"):
            break

        num_parens = 0

        if token == "(":
            num_parens = 1
            substr_tokens = []

            while num_parens > 0:
                token = next(tokens)

                if token == "EOF":
                    raise ValueError(f"Unbalanced Parens, tokens: {tokens_list}")
                elif token == "(":
                    num_parens += 1
                elif token == ")":
                    num_parens -= 1

                if (num_parens > 0):
                    substr_tokens.append(token)

            substr_tokens.append("EOF")

            substr_composition = get_composition(substr_tokens)

            if (token := next(tokens)).isnumeric():
                substr_composition = {k: int(token) * v for k,v in substr_composition.items()}

            for k,v in substr_composition.items():
                if k in composition:
                    composition[k] += v
                else:
                    composition[k] = v
            break

        if token == ")":
            raise ValueError(f"Unbalanced Parens, tokens: {tokens_list}")

        if token not in element_weights:
            raise ValueError(f"Can't find element {token}, tokens {tokens_list}")

        element = token

        if (token := next(tokens)).isnumeric():
            element_count = int(token)
            token = next(tokens)
        else:
            element_count = 1

        if element in composition:
            composition[element] += element_count
        else:
            composition[element] = element_count

    return composition

def convertToAMU(element_count):
    return sum(element_weights[k] * v for k,v in element_count.items())

if __name__ == "__main__":
    import sys

    if(len(sys.argv) > 1):
        print(convertToAMU(get_composition(tokenize(sys.argv[1]))))
    else:
        print(f"Usage: {sys.argv[0]} [chemical_formula]")

For such a simple parsing job, I'd use a regular expression and re.findall()` to split the string into a list of tokens.  It's just one line instead of over 20 lines. The tokens are an element (an upper case letter possibly with a lower case letter), a repeat count (1 or more digits), or a bracket. The "{}[]" matches any of the brackets.
    tokens = re.findall(r"[A-Z][a-z]|[0-9]+|[](){}[]", string)

collections.Counter() is useful for counting the elements. Lists used as simple stacks help keep track of bracketed sub-compounds.
    composition = Counter()
    match = []
    stack = []

Using a list of tokens may be less optimal for large parsing tasks, but is sufficient for this command line calculator.  Plus, it lets you "peek" at the next token to see if its a number, greatly simplifying the handling of the numbers in a formula.  (I used an if-expression in the final code)
        if tokens[0].isalpha():
            element = tokens.pop(0)

            if tokens[0].isdigit():           # <-- peek at next token to see if
                repeat = int(tokens.pop(0))   #     there is a count
            else:
                repeat = 1

            compound[element] += repeat

When an opening bracket is encountered, save the current state (the Counter) on a stack and start a new state.  Save the matching bracket on a stack too.
        elif tokens[0] in ('(', '[', '{'):
            match.append(MATCH[tokens.pop(0)])
            stack.append(composition)
            composition = Counter()

When a closing bracket is encountered, see if it matches the one on top of the bracket stack.  Pop the saved state from the stack and combine it from the one for the bracketed sub-compound.
        elif tokens[0] == match[-1]:
            tokens.pop(0)
            match.pop()

            repeat = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1
            for element in composition.keys():
                composition[element] *= repeat

            composition.update(stack.pop())

Any other token is an error.
        else:
            if token in (')', ']', '}'):
                raise ValueError(f"Error, mismatched bracket: "
                                 f"expected {match[-1]} got {tokens[0]}.")

            else:
                raise ValueError(f"Error, unrecognized token "
                                 f"in formula: '{tokens[0]}'.")

If there are any brackets left on the stack at the end, then there are mismatched brackets.
    if match:
        brackets = ', '.join(f"'{b}'" for b in match[::-1])
        raise ValueError(f"Error, missing bracket(s): {brackets}.")

The full parser:
import re

from collections import Counter

MATCH = {'(':')', '[':']', '{':'}'}

def parse(molecule):

    tokens = re.findall(r"[A-Z][a-z]?|[0-9]+|[]{}()[]", molecule)

    composition = Counter()
    match = []
    stack = []

    while tokens:
        # element with optional count
        if tokens[0].isalpha():
            element = tokens.pop(0)
            count = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1
            composition[element] += count

        # start a sub-compound
        elif tokens[0] in ('(', '[', '{'):
            match.append(MATCH[tokens.pop(0)])
            stack.append(composition)
            composition = Counter()

        # matching close bracket ends a sub-compound with an optional count
        elif tokens[0] == match[-1]:
            tokens.pop(0)
            match.pop()

            repeat = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1
            for element in composition.keys():
                composition[element] *= repeat

            composition.update(stack.pop())

        # "syntax" error in the formula
        else:
            if token[0] in (')', ']', '}'):
                raise ValueError(f"Error, mismatched bracket: "
                                 f"expected '{match[-1]}' got '{token[0]}'.")

            else:
                raise ValueError(f"Error, unrecognized token in "
                                 f"formula: '{token[0]}'.")

    # left over, unmatched brackets
    if match:
        brackets = ', '.join(f"'{b}'" for b in match[::-1])
        raise ValueError(f"Error, missing bracket(s): {brackets}.")

    return dict(composition)


Suggested parameter names for utility class function During our internal code review process, my following code raised some eyebrows:

public class MySuperUtil {
    public static List<Long> updateAndSubtract(List<Long> first, List<Long> second) {
        List<Long> updated = updatePlaceholdersWithLargestIds(second, first);
        Collection<?> difference = CollectionUtils.subtract(first, updated);
        return castCollectionToListUsingClass(difference, Long.class);
    }

(the castCollectionToListUsingClass is not related to this problem; it is from this SO answer)

The main feedback is the names of parameters: first and second.

My reviewer suggests using names more informative to the caller, e.g. inDB instead of first, inUI instead of second.

My main points (of using first and second) are:

this is a Util class (although probably there will be only one occasion for it to be used)
this is similar to what CollectionUtils.substract() has

I guess my question really is:
what context do we use when naming those two parameters?

do we name them in the context of the callee MySuperUtil (thus
something like first and second, or probably minuend and subtrahend), OR,
do we name them in the context of the caller (thus inDB and inUI)?

Any suggestion is appreciated.

public class MySuperUtil {
    public static List<Long> updateAndSubtract(List<Long> first, List<Long> second) {
        List<Long> updated = updatePlaceholdersWithLargestIds(second, first);
        Collection<?> difference = CollectionUtils.subtract(first, updated);
        return castCollectionToListUsingClass(difference, Long.class);
    }

My assessment of the code is that, as a Util method, it is poorly named too. The methods are not self-documenting.

I read updatePlaceholdersWithLargestIds, and with two lists as inputs, where is the Id? What does 'updated' look like? I am at a loss.

What I can say is that there is some black-box function that does some update, but, does it manipulate the data in first, or second? Why is 'second' specified first? Why is it not: updatePlaceholdersWithLargestIds(first, second);

Also, why does an update* function return a value, and not update something? it should be called get* or just largestIds. Or, does the function do both? Does it update values and also return values? Yuck!.

The subtract function. Does it subtract the first value from the second, or the other way around?

castCollectionToListUsingClass I presume this method has the signature:

public static <U> List<U> castCollectionToListUsingClass(Collection<?> collection, Class<U> clazz);

Why all the redundancy? That method name duplicates all the signature components. It is tautology. Also, why does it take a collection, and return a List? It should return a Collection too, or it should be parameterized too.... at minimum, just rename the method to something like (I like the word coerce):

public static <U> List<U> coerceMembers(Collection<?> collection, Class<U> clazz);

So, I would agree that naming is a concern in your code, but it extends beyond just your method.

Your method does not tell me what it does, and the code in the method does not help much either. The code in the method does not help me help you rename the method.


Rotate string counterclockwise Here is the function I have come up with. Any improvements possible?

E.g LeetCode -> rotate by 2 -> deLeetCo

public static String rotateAntiClockWise(String s, int offset){
    int i = offset%s.length();
    StringBuffer prefix = new StringBuffer();
    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }
    return prefix.append(s.substring(0, s.length()-i)).toString();
}

for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }

An easy optimization is to change this to

    for (int j = 1; j <= i; j++) {
        prefix.append(s.charAt(s.length() - j));
    }

You can go further if you like, e.g.

    for (int j = s.length() - 1, m = s.length - i; j >= m; j--) {
        prefix.append(s.charAt(j));
    }

But if you're doing that, you might as well change

public static String rotateAntiClockWise(String s, int offset){
    int i = offset%s.length();
    StringBuffer prefix = new StringBuffer();
    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }
    return prefix.append(s.substring(0, s.length()-i)).toString();
}

to

public static String rotateAntiClockWise(String s, int offset){
    int i = s.length() - (offset % s.length());
    StringBuffer prefix = new StringBuffer();

    for (int j = s.length() - 1; j >= i; j--) {
        prefix.append(s.charAt(j));
    }

    return prefix.append(s.substring(0, i)).toString();
}

Now we only subtract from s.length() twice.  Before we subtracted from it i + 1 times.

But I actually think that the best version is

public static String rotateAntiClockWise(String s, int offset){
    int i = s.length() - (offset % s.length());
    StringBuffer prefix = new StringBuffer(s.substring(i));

    return prefix.reverse().append(s.substring(0, i)).toString();
}

Now I can easily read this and see that we are reversing the last part of the string and appending the first part.

I'm not really feeling the rotateAntiClockWise name.  That's not really what we're doing.  We're more mirrorSuffixToPrefix or something.


Adding/Removing Colors to Lists I would like the program to ask the user if they want to add a color.  If they say yes, then ask what color to add. Then after that happens, once the program would ask if you want to, run it again. If they say no to add a color, the program ask if you want to remove a color from the list. If they say yes, it would then ask what color to remove, with error handling built in if the color wasn't in that list. Then after that happens once the program would ask if you want to run it again.

Just wanted to point out I do not know a lot about Python, so please don't be harsh, but I can take constructive criticism.

import socket # imports the socket module
import sys # imports the sys module
import console # imports the console module

usr = raw_input('What is your name? \n').title() # asks for users name for the hostname information
sname = socket.gethostname() # sets sname to gethostname
print '\nThis program is being run by', usr, 'on machine name', sname # displays host information

mylist = ['Red', 'White', 'Blue', 'Yellow', 'Green', 'Orange'] # sets mylist to colors
templist = list(mylist) # sets templist as mylist
runagain = 'y' # sets runagain to a y values

while runagain == 'y': # for looping
print '\nThe current colors are:', templist # print out list so user knows what colors are already there

clradd = raw_input('\nWould you like to add any colors to the list? y or n\n')

while clradd == 'y':
    colors = raw_input('\nWhat colors would you like to add to the list? Please type one color. \n').title()
    templist.append(colors) # appends color to the list

    print templist # prints out new list
    print '\nAscending and Descending'  # print out ascending and descending lists
    print '-' * 30
    print '\nAscending (high to low): ', sorted(templist, reverse=True)
    print '\nDescending (low to high): ', sorted(templist, reverse=False)

    clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n')

while clradd == 'n':
    clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n')

    while clrdel == 'y':
            try:
                removecolor = raw_input('\nWhat colors would you like to remove? ').title() # asks user color to remove
                templist.remove(removecolor) # removes color from the list
            except ValueError:
                print 'Looks like that color was not in the list, try again.'
                continue

            print 'Updated list\n', templist # prints out updated list

            runagain = raw_input('\nWould you like to run this program again again? y or n')

            if runagain == 'n': # if runagain is n
                console.hide_output() # hide the output

    while clrdel == 'n':
        runagain = raw_input('\nWould you like to run this program again again? y or n') # asks user to run again

        if runagain == 'n': # if runagain is n
            console.hide_output() # hide the output
            sys.exit() # stops the program

import socket # imports the socket module

The comment is completely pointless. But I cannot help it, my eyes naturally read it, my brain processes it, only to realize it says nothing new. Let your code speak for itself, avoid comments as much possible.

print '\nThis program is being run by', usr, 'on machine name', sname

Maybe it's somewhat more readable if you use standard Python formatting like this instead:

print '\nThis program is being run by %s on machine name %s' % (usr, sname)

runagain = 'y'

Instead of setting this to a string, and later using == 'y' to evaluate, it would be better to use proper booleans for this kind of thing. For example:

Similarly, instead of:

clradd = raw_input('\nWould you like to add any colors to the list? y or n\n')

while clradd == 'y':

You could write like this:

clradd = raw_input('\nWould you like to add any colors to the list? y or n\n') == 'y'

while clradd == 'y':

Try-catch block writing style:

try:
    removecolor = raw_input('\nWhat colors would you like to remove? ').title()
    templist.remove(removecolor)
except ValueError:
    print 'Looks like that color was not in the list, try again.'
    continue

It's better to keep the try block as small as possible. For example, the removecolor assignment should be moved out from it. Also, since you simply want to check if the given color is in the list of colors, it would be cleaner to write that exactly:

removecolor = raw_input('\nWhat colors would you like to remove? ').title()
if removecolor in templist:
    templist.remove(removecolor)
else:
    print 'Looks like that color was not in the list, try again.'
    continue

There are couple of other things too, globally:

Incorrectly indented code
Incorrectly using while instead of a simple if
Duplicated code blocks
sys.exit is a bit harsh way to exit, try to avoid if possible

Suggested implementation

Putting the above suggestions together:

import socket

usr = raw_input('What is your name?\n').title()
sname = socket.gethostname()
print '\nThis program is being run by %s on machine name %s' % (usr, sname)

mylist = ['Red', 'White', 'Blue', 'Yellow', 'Green', 'Orange']
templist = list(mylist)
runagain = True

while runagain:
    print '\nThe current colors are:', templist

    clradd = raw_input('\nWould you like to add any colors to the list? y or n\n') == 'y'

    if clradd:
        colors = raw_input('\nWhat colors would you like to add to the list? Please type one color. \n').title()
        templist.append(colors)

        print templist
        print '\nAscending and Descending'
        print '-' * 30
        print '\nAscending (high to low): ', sorted(templist, reverse=True)
        print '\nDescending (low to high): ', sorted(templist, reverse=False)

    clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n') == 'y'

    while clrdel:
        removecolor = raw_input('\nWhat colors would you like to remove? ').title()
        if removecolor in templist:
            templist.remove(removecolor)
        else:
            print 'Looks like that color was not in the list, try again.'
            continue

        print 'Updated list\n', templist
        break

    runagain = raw_input('\nWould you like to run this program again again? y or n\n') == 'y'


Parsing XML documents with LXML I'm new to LXML, and parsing XML documents in general. I have written a small section of code that appears to do what I need it too do, but it feels like I have overly complicated it. Is there any way I can simplify this?

Method:

def importFromXML(self, filename):
    tree = etree.parse(filename)
    for child in tree.getroot():
        if child.tag != 'SLOT':
            print('Tag:', child.tag, ', Text', child.text)
        elif child.tag == 'SLOT':
            for slot, index in child.items():
                for attribute in child:
                    print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Item>
<ActiveState>drop</ActiveState>
<Location>Left Wrist</Location>
<Realm>All</Realm>
<ItemName>Band of the Dream Conqueror</ItemName>
<ItemQuality>100</ItemQuality>
<Equipped>1</Equipped>
<Level>50</Level>
<TYPE>Wrist</TYPE>
<SOURCE>Drop</SOURCE>
<DBSOURCE>kscraft</DBSOURCE>
<SLOT Number="0">
    <Type>Resist</Type>
    <Effect>Crush</Effect>
    <Amount>6</Amount>
</SLOT>
<SLOT Number="1">
    <Type>Resist</Type>
    <Effect>Thrust</Effect>
    <Amount>6</Amount>
</SLOT>
<SLOT Number="2">
    <Type>Resist</Type>
    <Effect>Slash</Effect>
    <Amount>6</Amount>
</SLOT>
</Item>

I just want to make sure I'm doing this right. I'm using Python 3.x. Eventually I will be doing more with the data I pull, but for right now I'm just trying to pull the information, and figure out the most optimized way of doing this.

The code isn't actually doing much, there's little to review to be honest, it's not looking complicated for what it is.  Of course don't just have everything in a couple of loops, perhaps have some handlers to dispatch on the tags or so (handlers[child.tag](child) ...).

I suppose if you wanted a relatively quick way to write the importer code, consider XPath.  If you wanted quick processing (by not building up the full DOM in memory), consider using a SAX handler.

Finally, there might be a library to automatically map the XML to a class structure, or even parse it directly into dict instances or something, if you prefer that, but I don't any off the top of my hat.


Automata theory, state reachability in Haskell I wrote a small library to learn Haskell while studying Automata theory. I have some concerns on my algorithm to evaluate state reachability. That is, I think it might be improved if I can avoid checking paths already excluded in other branches of the search for a valid path. This one recursively checks each path separately.

I hope I didn't forget anything. Other suggestions are obviously welcome!

Automaton data type

-- | Represents an automaton in the form
--   /G = (X, E, f, Gamma, x_0, X_m)/
--
--   NB: we're not including Gamma in the definition of Automaton
data Automa st ev = Automa {
    states     :: [st],             -- ^ /X/, set of states
    events     :: [ev],             -- ^ /E/, set of events
    mapTrans   :: M.Map (st,ev) st, -- ^ not /f/, but a map of
                                    --   transitions (see 'trans')
    initial    :: st,               -- ^ /x_0/, initial state
    marked     :: [st]              -- ^ /X_m/, set of marked states
} deriving (Show, Read)

Reachability function

-- | True if a state can reach another for some string of events.
canReach :: (Ord st, Ord ev)
    => st                   -- ^ starting state 's'
    -> st                   -- ^ arrival state 's''
    -> Automa st ev
    -> Bool
canReach s s' au = canReachExcluding s s' au []

-- | True if a state can reach another for some string of events,
--   excluding passing from specified states.
canReachExcluding :: (Ord st, Ord ev)
    => st                   -- ^ starting state 's'
    -> st                   -- ^ arrival state 's''
    -> Automa st ev
    -> [st]                 -- ^ the states to be excluded
    -> Bool
canReachExcluding s s' au ex = s == s' || any (== s') rs
    || any (\x -> canReachExcluding x s' au (s:ex)) rs
        where rs = reach1From s au \\ ex

-- | Returns states reachable from specified state in one step.
reach1From :: (Ord st, Ord ev) => st -> Automa st ev -> [st]
reach1From s au = [ trans' (s,e) au | e <- gammaL s au ]

Accessory functions

-- | Indicator function of active states for an automaton
gamma :: (Ord st, Ord ev)
    => (st,ev)                 -- ^ state-event pair of interest
    -> Automa st ev
    -> Bool                    -- ^ 'True' if 'ev' is active for 'st'
gamma (s,e) au = M.member (s,e) $ mapTrans au

-- | Returns a list of active events for a state of a given 'Automa'
gammaL :: (Ord st, Ord ev) => st -> Automa st ev -> [ev]
gammaL s au = [ e | e <- events au, gamma (s,e) au ]

-- | Transition function: where do I get if 'ev' happens when in 'st'?
trans :: (Ord st, Ord ev) => (st, ev) -> Automa st ev -> Maybe st
trans (s,e) au = M.lookup (s,e) $ mapTrans au

-- | Like 'trans', but to be used if you're sure it's a valid
--   transition (i.e. saves you a 'fromJust').
trans' :: (Ord st, Ord ev) => (st, ev) -> Automa st ev -> st
trans' (s,e) au = fromJust $ M.lookup (s,e) $ mapTrans au

This is neat, methinks.

A couple of questions/points:

Is the || any (== s') rs part of canReachExcluding necessary?
In the same definition, the part rs = reach1From s au \\ ex takes time linear in the size of ex. Using a set (or hash) instead of a list for ex would probably improve your running time significantly in practice. But of course, that'd likely be at the expense of the clarity of your beautiful program.
You are of course right that your program checks "states excluded in other branches". What you are "really" implementing is depth-first search (DFS) on the graph defined by the automaton, and so you might want to look for a more efficient (functional) implementation of DFS. In that case, you could either look at the Haskell Library implementation, or maybe just this quick-and-dirty approach.


Cumulative sum of the smallest neighbors in the previous row in a Numpy array I have the following code snippet, which essentially does the following:
Given a 2d numpy array, arr, compute sum_arr  as follow:
$$sum\_arr[i, j] = \begin{cases}
    arr[i, j] + min(sum\_arr[i - 1, j-1:j+2]), &i > 0\\ arr[i, j], &i = 0\end{cases}$$
(reasonable indices for j - 1 : j + 2 of course, all within 0 and w)

Here's my implementation:

import numpy as np

h, w = 1000, 1000 # Shape of the 2d array
arr = np.arange(h * w).reshape((h, w))

sum_arr = arr.copy()

def min_parent(i, j):
    min_index = j
    if j > 0:
        if sum_arr[i - 1, j - 1] < sum_arr[i - 1, min_index]:
            min_index = j - 1
    if j < w - 1:
        if sum_arr[i - 1, j + 1] < sum_arr[i - 1, min_index]:
            min_index = j + 1
    return (i - 1, min_index)

for i, j in np.ndindex((h - 1, w)):
    sum_arr[i + 1, j] += sum_arr[min_parent(i + 1, j)]

And here's the problem: this code snippet takes way too long to execute for only 1e6 operations (About 5s on average on my machine)

What is a better way of implementing this?

first, your problem is example of dynamic programming. Here some tips how to approach problem in python
your solution calculate each table cell separately. But function min_parent() use data only from previous row, so you can calculate row by row (and numpy is designed to fast operations on vectors)
i am using like you range <j - 1 : j + 2) but check if task don't need <j - 1, j + 2>

Example code

assert(w >= 2) # if not, you should handle w == 1 in special way

def vectorized_solution(arr, h):
    sum_arr = arr.copy()
    for i in range(1, h):
        parent = sum_arr[i - 1, :]
        sum_arr[i, 0] += min(parent[0], parent[1])
        sum_arr[i, 1:-1] += np.minimum.reduce([parent[0:-2], parent[1:-1], parent[2:]])
        sum_arr[i, -1] += min(parent[-2], parent[-1])
    return sum_arr


Merge Sort optimization I was looking at other people code and I realized that mine is not so neat after all.

In this version, I included a base case for the merge part (when there is only 2 elements to merge, just sort it normally). I do not know this is a good idea or not, never seen it in other people' codes.

This is the first time I implemented this algorithm.  I hope you can help me out with this code so it could look more readable.

class MergeSort
{
    public static void Standard() {
        int[] A = new int[] {234, 31, 41, 59, 26, 41, 58, 90, 103, 14, 1235, 2134, 12, 673, 234, 234, 64, 23, 132, 432, 123};
        int last_Index = A.Length-1;

        SplitMerge(A, 0, last_Index);
        foreach (int i in A)
            Console.Write(i + " ");
    }

    //Here is the recursive split merge
    private static void SplitMerge(int[] A,int iBegin,int iEnd) {
        //Base case. Every  recursive has a base case
        if (iBegin == iEnd) return;

        //Calculate the middle index here. This work for odd number array.
        int Middle = (int)Math.Floor((double)(iEnd + iBegin)/2);

        //split left
        SplitMerge(A, iBegin, Middle);

        //split right
        SplitMerge(A, Middle+1, iEnd);

        //merge left and right
        MergeLeftRight(A, iBegin, Middle, iEnd);

    }

    //This is the merge
    private static void MergeLeftRight(int[] A, int iBegin, int iMid, int iEnd) {
        //If we are comparing just 2 numbers, just compare them already xD
        if (iBegin == iMid) {
            int temp_Num = A[iBegin];
            if (A[iBegin] >= A[iEnd]) {
                A[iBegin] = A[iEnd];
                A[iEnd] = temp_Num;
            }
            return;
        }

        //Create a temporary list to store numbers
        List<int> temp = new List<int> {};

        //Declare the last index of left array, we will go to this but will not pass this
        int left_End = iMid;

        //Same as above. This is for the right array
        int right_End = iEnd;

        //Left array start from iBegin, but Right array must start fron left_End+1
        iMid++;

        //Check the number in left and right arrays and sort them while both array still has elements inside
        while ((iBegin <= left_End) && (iMid <= right_End)) {
            if (A[iBegin] <= A[iMid]) {
                temp.Add(A[iBegin]);
                iBegin++;
            }
            else {
                temp.Add(A[iMid]);
                iMid++;
            }
        }

        //If right array is empty, add all leftover elements from left array to the list
        while (iBegin <= left_End) {
            temp.Add(A[iBegin]);
            iBegin++;
        }

        //Same as above loop. Add all leftover elements from right array to the list.
        while (iMid <= right_End) {
            temp.Add(A[iMid]);
            iMid++;
        }

        //Put everything back in the original array, merge everything. Since we are going from right to left
        //We need to reverse the List.
        temp.Reverse();
        foreach (int i in temp) {
            A[iEnd] = i;
            iEnd--;
        }
    }
}

Since you're asking for a readability review, here's my input:

Way too many comments. Comments should say why, not what - the code itself should describe what it's doing.
Use XML comments to describe methods. // regular comments only work if you're looking at the method's code. When you're using the code, XML comments are picked up by Visual Studio and you get tooltips to help you correctly use the method. For example:

/// <summary>
/// A recursive split merge method.
/// </summary>
/// <param name="A">The array to be sorted.</param>
/// <param name="iBegin">The lower bound index for the sub-array to be sorted.</param>
/// <param name="iEnd">The upper bound index for the sub-array to be sorted.</param>
private static void SplitMerge(int[] A, int iBegin, int iEnd)

Avoid Hungarian Notation. Prefixing i for int types is useless in .net, and hinders readability. iBegin and iEnd should simply be begin and end to be correct, startIndex and endIndex to be meaningful.
Use camelCase for parameters and locals. Parameter A should be a... but that's an awfully bad name. unsortedArray, or simply unsorted, would be much more descriptive.
Avoid snake_case. C# naming conventions don't encourage the use of an underscore (_) in the middle of an identifier's name. Use camelCase for parameters and locals, and PascalCase for types and public members (actually, exposed is more accurate, since internal and protected members should also be PascalCase).
Avoid Java-style curly braces. Not to start any flamewars, but C# conventions put the opening brace { on the next line.
Method names should start with a verb. Standard() isn't a good method name. Since it's a member of a class named MergeSort, Sort() would probably be best, and should take the array in as a parameter to be any useful...


Calculator in FORTRAN This is my first step into Fortran. The program aims to provide a simple way of calculating numbers. Just looking for improvements in general.

program Calc
    real :: a, b, additionAnswer, subtractionAnswer, multiplicationAnswer, divisionAnswer
    print *, "George Gibson's Calc"
    print *, "Type the first number: "
    read *, a
    print *, "Type the second number: "
    read *, b
    additionAnswer = a + b
    subtractionAnswer = a - b
    multiplicationAnswer = a * b
    divisionAnswer = a / b
    print *, a, " + ", b, " = ", additionAnswer
    print *, a, " - ", b, " = ", subtractionAnswer
    print *, a, " * ", b, " = ", multiplicationAnswer
    print *, a, " / ", b, " = ", divisionAnswer
    read *
end program Calc

Functions
A more "Fortrany" way to do this might be to put calculations in their own functions,
program Calc
   implicit none
   ...
    print *, a, " + ", b, " = ", AddTwoNums(a,b)
    print *, a, " - ", b, " = ", SubTwoNums(a,b)
    print *, a, " * ", b, " = ", MultTwoNums(a,b)
    print *, a, " / ", b, " = ", DivTwoNums(a,b)
 contains
    pure function AddTwoNums(a,b) result(c)
       real, intent(in) :: a,b
       real :: c
       c = a + b
    end function AddTwoNums
    ...
 end program

where the ellipses (...) mean I'm skipping over the other details. The pure specifier gives details to the compiler that can optimize/vectorize it in some cases (probably not much it can do here, but for some more complex cases it might be useful).
Output
You might also want to specify formats for the output. Since you're using single-precision, you probably want to output the first 6-7 decimal digits,
print '(f12.6,a3,f12.6,a3,f12.6)', a," + ", b, " = ", AddTwoNums(a,b)

The f12.6 means it's a floating-point type number with 12 total digits and 6 after the decimal, a3 means it is a character string of length 3 (you can make this one simply a and let the compiler figure it out).
Precision
Single precision is nice, but you can do better; and there's a few ways how:
-ISO_FORTRAN_ENV (needs Fortran 2008 or later compiler)
Within this big module is the real32, real64, and real132 types

Kind type parameters to specify a REAL type with a storage size of 32, 64, and 128 bits. It is negative if a target platform does not support the particular kind. (Fortran 2008 or later.)

and would be used as
program Calc
   use iso_fortran_env
   real(kind=real64) :: a, b
   ...

-ISO_C_BINDING (need Fortran 2003 or later compiler)
This module is for improved compatibility with C programs/functions. Within it are C_double and C_long_double types that will match the equivalent C types. This would be used as
program Calc
   use iso_c_binding
   real(kind=c_double) :: a, b
   ...

-Kind specifier (part of the 1990 standard)
This is the default way to specify the precision without useing a module. This is done as
program Calc
   integer, parameter :: wp = selected_real_kind(15,307)
   real(kind=wp) :: a, b
   ...

where wp is typically short for "working precision" (some people choose to append an underscore in case they want to use wp as a variable). The first number in selected_real_kind is the decimal precision and the second number is the exponent range (-307 to +307). You are also not restricted to using integers associated with any particular precision (single or double) here, you can choose to use selected_real_kind(10,40), for instance. Fortran 2003 standards specify that absent values for the precision & radix are assumed to be zero.
Comments
This is general and not specific to Fortran, but I'm a big fan & proponent of comments. Even when it's absolutely trivial & blatantly obvious what is being done on the line below, it benefits you (as practice for the more complex computations) and potential future readers (so that they know what is being done & why).


Wrapping types with alignment requirements Visual Studio 2013 still doesn't support the alignas keyword in C++11. This causes some problems with alignment of types in various situations. Thankfully the compiler will generate an error when it can't guarantee the alignment or at least give a warning.

To solve these errors and warnings I'm implementing a wrapper type that will wrap another type with some alignment restriction regardless of how the wrapper is aligned. Consider two wrapper objects A and B that themselves have arbitrary alignment. Let the wrapped datum be a and b respectively. Then A=B will assign a=b while still keeping a aligned regardless of how B was aligned because b in itself is aligned.

I'm looking for a review on the code on the account of syntax and possible weaknesses in the design and implementation.

template< typename T, std::size_t Align = 16>
class aligned_wrapper{
public:
    typedef T value_type;

    template<typename... Args>
    aligned_wrapper(Args&&... args){
        std::size_t space = sizeof(m_storage);
        auto raw_ptr = reinterpret_cast<void*>(&m_storage);
        auto ptr = std::align(Align, sizeof(T), raw_ptr, space);
        new (ptr)T(std::forward<Args>(args)...);
        m_object = reinterpret_cast<T*>(ptr);
    }

    ~aligned_wrapper(){
        get().~T();
    }

    aligned_wrapper& operator = (const aligned_wrapper& that){
        get() = that.get();
        return *this;
    }

    template<typename U>
    aligned_wrapper(const aligned_wrapper<U>& that)
        : aligned_wrapper(that.get())
    {}

    template<typename U>
    aligned_wrapper(aligned_wrapper<U>&& that)
        : aligned_wrapper(std::move(that.get()))
    {}

    inline T& get(){ return *m_object; }
    inline const T& get() const { return *m_object; }

    void swap(aligned_wrapper& that){
        using std::swap;
        swap(get(), that.get());
    }

    friend void swap(aligned_wrapper& lhs, aligned_wrapper& rhs){
        lhs.swap(rhs);
    }
private:
    std::aligned_storage_t<sizeof(T) + Align - 1, 1> m_storage;
    T* m_object{ nullptr };
};

Although it may look a bit funky, one of the key ideas is that once the aligned_wrapper is constructed, m_object will never change for that instance as the address of this will not change, this guarantees alignment. In other words, not assigning m_object in the assignment operator is intentional.

The class is missing a copy constructor and a move constructor. These can never be created by instantiating a template. Right now, the compiler will generate a defaulted copy constructor for you (and no move constructor, because you have a user-defined destructor). Since you obviously don't want that, you have to define the copy (and probably move as well) constructor yourself.
You're also missing a move assignment operator which you should probably add. Otherwise, your class wouldn't be fully usable with move-only types.
Your code is missing comments (there aren't any). You even had to explain an invariant in the question:

  ... once the aligned_wrapper is constructed, m_object will never change for that instance as the address of this will not change, this guarantees alignment. In other words, not assigning m_object in the assignment operator is intentional.

This type of information must go into comments. The next maintainer (which can be you in 6 moths' time) will need knowledge like this to understand the code.
You should add noexcept specifications to your functions. They affect efficiency of some operations (like storing in a std::vector), and since this is a very generic class, you should not limit its use in any way. An example for the assignment operator would be:

aligned_wrapper& operator = (const aligned_wrapper& that) noexcept(std::is_nothrow_copy_assignable<T>::value) {
    get() = that.get();
    return *this;
}

It would probably be a good idea to introduce a way to query Align out of an aligned_wrapper object, e.g.

static const std::size_t alignment = Align;

You don't need reinterpret_cast to convert an object pointer to void*, a static_cast is sufficient for that. Don't use stronger casts than necessary.
You can simplify the assignment to m_object and make it more obvious by assigning the result of the placement-new into it:

m_object = new (ptr) T(std::forward<Args>(args)...);

16 looks like a rather arbitrary number for the default template argument for Align (it's actually a magic number). There is even no guarantee that 16 is a valid alignment value. I would probably choose something less arbitrary such as sizeof(void*).
There is no reason to use std::aligned_storage for the type of m_storage. You don't actually care about alignment of m_storage at all (which is emphasised by you passing 1 to its Align parameter). All you need is a buffer of suitable size, and for this usigned char[sizeof(T) + Align -1] (or a std::array) would work just as well.

As a side note, be aware that std::aligned_storage_t was only introduced in C++14. Visual Studio 2013 supports some C++14 bits, but using it makes your code non-C++11-compliant.
You might want to swap the order of the data members, it might prevent need for padding between an oddly-sized m_storage and aligned m_object.
You might consider overloading the pointer operators * and -> for your class as syntactic sugar for get(), it simplifies usage. Other generic classes which store a single object sometimes do so as well; an example is boost::optional.


Simple JavaScript precondition checking implementation I am writing a JavaScript application and would like to validate function arguments in many places.  Most of these checks will be for correct argument types, or numeric values within specific ranges.

Here is a simple function I came up with to check any number of preconditions:

function requires(conditions)
{
    for (var cond in arguments)
    {
        if (typeof cond !== "boolean") throw "Preconditions must be boolean expressions {" + cond + "}";
        if (cond !== true) throw "Precondition failed {" + cond + "}";
    }
}

It would be used like this:

function alertChar(message, index)
{
    requires(
        typeof message === "string",
        typeof index === "number",
        index >= 0,
        index < message.length);

    alert(message.charAt(index));
}

Is there anything conceptually wrong with this simple implementation?  Is there a way I can make it lazily evaluate each precondition expression?  Is accessing the arguments array inefficient?

function requires(conditions)
{
    for (var cond in arguments)

Don't use for-in. The problem with for-in is that it runs over prototype properties as well. You might loop through more properties than you expect. Either use a regular loop or convert your iterable into an actual array to access array method.

If you can write in ES6, you can use the rest operator. What it does is put the rest of the arguments into an array. Much like arguments but it's a real array. You have access to all array methods.

function requires(...args){
  args.forEach(...)

if (typeof cond !== "boolean") throw "Preconditions must be boolean expressions {" + cond + "}";
if (cond !== true) throw "Precondition failed {" + cond + "}";

The second condition is overly verbose. The first check weeds conds that are not boolean. Therefore, if it passes that part, cond is a boolean. That means you can simplify if (cond !== true) as if (!cond).

requires(
    typeof message === "string",
    typeof index === "number",
    index >= 0,
    index < message.length);

If you go on with this route of manual type checks, at least hide away the complexity by abstracting the checks away. The following would be more like it. Checks the arguments against the type, and in that order.

require(args, ['string', 'number']);

Additionally, the last 2 checks there are not type checks but more like app-specific logic. Your type checker should not concern itself with those anymore.

Runtime type checks should be avoided as they incur performance penalties as well as cause bloated code. Common practice is to offload this responsibility to development-time and/or build-time tools.

TypeScript and Flow are typed supersets of JS that will let you write in a typed language and whose compilers do type checks for you.

If you prefer vanilla JS, using an editor or IDE that utilizes JSDoc to do basic checks is also an option. I know Visual Studio's Intellisense or Intellij IDEA with the right plugins do this.


Making a grid for collision detection in a game that wraps I'm making a 2D game which wraps (when you move off the right edge, you appear on the left, etc). The game area is square, all objects are circles (with AABB smaller than the game area, and in most cases, much smaller).

I'm dividing the game area into a grid to perform collision checks. I need to determine which cell(s) an object's AABB lives in.

Right now I have this awkward code to deal with cases when the object passes the left/right boundary... I feel like there must be a better way to write it.

gridX is x-dimension of the grid
x1 is the x-coord of the cell the object's left boundary lives in (before taking into account wrap)
x2 " " right boundary

if (x1 < 0) {
  for (let j = x1 + gridX; j < gridX; j++) someFunction(j)
  for (let j = 0; j < x2; j++) someFunction(j)
} else if (x2 >= gridX) {
  for (let j = x1; j < gridX; j++) someFunction(j)
  for (let j = 0; j < x2 - gridX; j++) someFunction(j)
} else {
  for (let j = x1; j <= x2; j++) someFunction(j)
}

someFunction would then contain the y coord version of the above and add to the grid.

Bear in mind I don't want to lose performance (as it will be run multiple times per second).

I want to write out someFunction instead of actually declaring a function so I hope there is a better way to do this - especially if I wanted to make my game 3 dimensional in future. That would be 25 pastes.

Some style points first.

Always wrap statement and loop blocks in {} eg you wrote for (let j = 0; j < x2; j++) someFunction(j) to avoid maintenance headaches use the curlies for (let j = 0; j < x2; j++) { someFunction(j) }
Don't declare the same variable over and over. There is no advantage to locally scoping variables to code blocks unless you are writing very long functions, and you should avoid writing functions more than a page long.
In this case j is not the best choice of variable name for the loop counter. x would be far better.

Rewriting your function with the above points

var x;
if (x1 < 0) {
    for (x = x1 + gridX; x < gridX; x++) { someFunction(x) }
    for (x = 0; x < x2; x++) { someFunction(x) }
} else if (x2 >= gridX) {
    for (x = x1; x < gridX; x++) { someFunction(x) }
    for (x = 0; x < x2 - gridX; x++) { someFunction(x) }
} else {
    for (x = x1; x <= x2; x++) { someFunction(x) }
}

The remainder operator %

  "I feel like there must be a better way to write it."

You can simplify the solution by using the remainder operator %. First ensure that x1, and x2 are positive by adding the grid width (or height)
Then use remainder as you loop over the items to get the wrapped coordinate.

Example replaces your function

// Assumes x1 is never less than -gridX and that x2 is always > x1
const end = x2 + gridX;
var x = x1 + gridX;
while (x <= end) { someFunction((x++) % gridX) }

More detailed example of wrapped play-field

The example below demonstrates using remainder and has two functions that take a x,y gird coordinated and map it to an array. setGrid(x, y, val) as long as the grid coordinates are greater than gridSteps (same as your gridX) * -gridMin

const AABB = { x: 0, y: 0, w: 90, h: 90 } // values in pixels
const gridSteps = 10;  // same as your gridX
const gridMin = 100; // min number of grids below origin 0,0. Used to translate
                     // coordinates to positive values
const grid = new Uint8Array(gridSteps ** 2); // grid array

function setGrid(x, y, val) {
    x += gridSteps * gridMin; // translate to positive space
    y += gridSteps * gridMin; // translate to positive space
    const idx = (x % gridSteps) + (y % gridSteps) * gridSteps;
    grid[idx] = val;
}

// version 2
const gridMinC = gridSteps * gridMin;
function setGrid(x, y, val) {
    const idx = ((x + gridMinC) % gridSteps) + ((y + gridMinC) % gridSteps) * gridSteps;
    grid[idx] = val;
}

requestAnimationFrame(update);
const scaleMouse = 0.05; // scales mouse to add movement
const inset = 3, inset2 = inset * 2;
var w = 1, h = 1;
const gridImg = createImage(w, h);
const ctx = canvas.getContext("2d");
const mouse  = {x : 0, y : 0};
document.addEventListener("mousemove", mouseEvents);
function fillGrid(AABB, gridSteps, col = "#9998") { // Draw wrapped collision boxes
    var x, y, xs = w / gridSteps, ys = h / gridSteps;
    const yStart = AABB.y / ys | 0, yEnd = (AABB.y + AABB.h) / ys | 0;
    const xStart = AABB.x / xs | 0, xEnd = (AABB.x + AABB.w) / xs | 0;
    ctx.fillStyle = col;
    ctx.beginPath();
    for (y = yStart; y <= yEnd; y += 1) {
        const yy = y % gridSteps;
        for (x = xStart; x <= xEnd; x += 1) {
            const xx = x % gridSteps;
            ctx.rect(xx * xs + inset, yy * ys + inset, xs - inset2, ys - inset2);
        }
    }
    ctx.fill();
}
function drawBox(AABB, col = "#000") {  // draws AABB box wrapped
    ctx.strokeStyle = col;
    ctx.lineWidth = 2;
    const x = AABB.x % w;
    const y = AABB.y % h;
    ctx.strokeRect(x, y, AABB.w, AABB.h);
    var corner = 0;
    if (x + AABB.w > w) {
        ctx.strokeRect(x- w, y, AABB.w, AABB.h);
        corner ++;
    }
    if (y + AABB.h > h) {
        ctx.strokeRect(x, y - h, AABB.w, AABB.h);
        corner ++;
    }
    if (corner === 2) { ctx.strokeRect(x - w, y - h, AABB.w, AABB.h) }
}
function update() {
    if (w !== (innerWidth / 2 | 0) || h !== innerHeight) {
        w = gridImg.width = canvas.width = innerWidth / 2 | 0;
        h = gridImg.height = canvas.height = innerHeight;
        drawGridLines(gridImg.ctx, gridSteps);
    }
    ctx.globalCompositeOperation = "copy";  // copy transparent pixels to destination
    ctx.drawImage(gridImg, 0, 0);
    ctx.globalCompositeOperation = "source-over"; // default comp mode

    //Use mouse dist from center to scale speed of AABB
    AABB.x = (AABB.x + (mouse.x - w / 2) * scaleMouse + w) % w;
    AABB.y = (AABB.y + (mouse.y - h / 2) * scaleMouse + h) % h;
    fillGrid(AABB, gridSteps);
    drawBox(AABB);
    requestAnimationFrame(update);
}
function mouseEvents(e){
    const bounds = canvas.getBoundingClientRect();
    mouse.x = e.pageX - bounds.left - scrollX;
    mouse.y = e.pageY - bounds.top - scrollY;
}
function createImage(width, height) {
    const img = document.createElement("canvas");
    img.width = width, img.height = height;
    img.ctx = img.getContext("2d");
    return img;
}
function drawGridLines(ctx, gridSteps, col = "red") {
    var i, xs = w / gridSteps, ys = h / gridSteps;
    ctx.lineWidth = 2;
    ctx.strokeStyle = col;
    ctx.beginPath();
    for (i = 0; i <= gridSteps; i ++) {
        ctx.moveTo(0, i * ys);
        ctx.lineTo(w, i * ys);
        ctx.moveTo(i * xs, 0);
        ctx.lineTo(i * xs, h);
    }
    ctx.stroke();
}
canvas { position : absolute; top : 0px; left : 0px; cursor: crosshair;}
<canvas id="canvas"></canvas>

Last point

  "especially if I wanted to make my game 3 dimensional in future."

You would never use a 3D grid for collisions as their size can grow very quickly, a 1024 cube would require a minimum or 1Gig of RAM. What you want are Quad Trees or even Octrees and the many variations, as they provide fast data structures for all sorts of spacial related problems 2D, 3D, and more :D

Collision grids are great for lowres 2D and limited 3D uses but you will need to consider alternatives when resolutions grow.


Shopping cart program in Java with a text menu I wrote this program to implement a shopping cart.  It supports adding/removing items to the cart, viewing the current order, and completing the checkout process.

import java.util.Scanner;

public class Keychains1 {

    public static Scanner keyboard = new Scanner(System.in);
    public static boolean stay = true;

    public static void add_keychains() {
        System.out.println("ADD KEYCHAINS");
    }

    public static void remove_keychains() {
        System.out.println("REMOVE KEYCHAINS");
    }

    public static void view_order() {
        System.out.println("VIEW ORDER");
    }

    public static void checkout() {
        System.out.println("CHECKOUT");
        stay = false;
    }

    public static void main(String[] args) {

        int choice;

        while (stay) {

            System.out.println("Ye Olde Keychain Shoppe");
            System.out.println();

            System.out.println("1. Add Keychains to Order");
            System.out.println("2. Remove Keychains from Order");
            System.out.println("3. View Current Order");
            System.out.println("4. Checkout");
            System.out.println();
            System.out.print("Please enter your choice: ");

            choice = keyboard.nextInt();

            System.out.println();

            if (choice == 1) {
                add_keychains();
            }
            else if (choice == 2) {
                remove_keychains();
            }
            else if (choice == 3) {
                view_order();
            }
            else if (choice == 4) {
                checkout();
            }
            else {
                System.out.println("Error. Please choose again.");
            }
            System.out.println();
        }

    }
}

Naming
I can't begin with another topic.
You use 2 different approaches to name your variables:

someName -> it's a camelCase
some_name -> it's a snake_case

Read this article to understand the difference
Java has own code style and you should use only camelCase for your variable name, class name, method name
I'll provide more examples about naming in Java.
Let's start with simple variable (not final, because final variable has own name convention)

someName - for variable (not final variable) name
someMethod - for method name
SomeClass - for class name

You may have final variable, it's commonly use in case when you need the property that will be general for all objects of the class and this property will not change.
private static int SOME_IMMUTABLE_VARIABLE = 10;

You need to fix names for your variables and methods:
remove_keychains -> removeKeyChains() // in the same manner for others