Return table value based on a primitive "priority queue" I have 2 function in Lua, one to look if a key is present inside a provided table and if true then return the value, else return false. This lookup function is called by another function with a "priority queue". It is not a queue per definition but I don't have a better name for it.

function inTable(tbl, item)
    for key, value in pairs(tbl) do
        if key == item then
          return value
        end
    end
    return false
end

function ReturnString()
local valid = {}

valid[22] = "string1"
valid[13] = "string2"
valid[25] = "string3"
...

  if inTable(valid, "22") then
    return inTable(valid, "22")
  elseif inTable(valid, "13") then
    return inTable(valid, "13")
  elseif inTable(valid, "25") then
    return inTable(valid, "25")
  else
    print("nope not found")
  end
end

Usage:

print(ReturnString())

valid is filled with a lot of different key-value pairs, unordered. My goal is to return the value based on a priority I determine using my nested if-elseif-else construct. If there is a key 22 then return string1, else check if there is a key 13 and so on. I know that there are more real implementation of a priority queue like this but I prefer something simple. What improvement can I do without implementing a complex priority queue?

welcome to Code Review.

I don't understand the purpose of your inTable() function. Lua tables already support immediate lookup of entries in them, just by using square brackets. See the Lua documentation for tables.

So your code:

  if inTable(valid, "22") then
    return inTable(valid, "22")
  elseif inTable(valid, "13") then
    return inTable(valid, "13")
  elseif inTable(valid, "25") then
    return inTable(valid, "25)

is really equivalent to:

if valid[22] then
  return valid[22]
elseif valid[13] then
  return valid[13]
elseif valid[25] then
  return valid[25]

Can we do better than this? Sure! Lua has the or operator which returns the first true value. (See documentation)

return valid[22] or valid[13] or valid[25]

Can we do even better? Definitely. Make up another table with the indexes in order, then iterate over it, returning the first true value.

local priority = {22, 13, 25}
local i
for i in priority do
   if valid[i] return valid[i]
end


Checking whether a game board is full I have a method in Scala that checks if a game board is full or not. To speed this method up, I return inside the nested for loop to break out of both of them and stop execution. How would I achieve this in Scala in an idiomatic way?

def isFull: Boolean = {
  for (x <- getGrid.indices) {
    for (y <- getGrid(x).indices) {
      if (getGrid(x)(y).getState.isInstanceOf[Undecided]) {
        return false
      }
    }
  }
  true
}

You can apply forall to most containers to test if every element in the container satisfies some property. forall will only evaluate x + 1 if x is true. This type of evaluation is known as short-circuit evaluation. So basically we can use this property to perform the same behavior as the if-then statement in the original code.

Notice also that I've used pattern matching to get rid of the isInstanceOf[T].

def isFull: Boolean =
  getGrid.indices.forall(x =>
    getGrid(x).indices.forall(y =>
      getGrid(x)(y).getState match {
        case xyState: Undecided => False
        case _ => True
      }
    )
  )


Return the first word in the image name I just want to return the first word in the image name (before the dash, dog in my example). Now I use it like this but believe it can be done in a simpler way (like one line of code):

$live_site_image = "http://example.net/wp-content/themes/example/images/dog-in-park.jpg";
$live_site_image = substr( strrchr( $live_site_image, '/' ), 1);
$live_site_image = strtok($live_site_image,"-");

If you want to capture part of a pattern,
you can use preg_match, and surround the pattern you want to capture in (...),
like this:

$live_site_image = "http://example.net/wp-content/themes/example/images/dog-in-park.jpg";
preg_match('/images\/([^-]+)-/', $live_site_image, $matches);
// $matches[0] will be "dog"

$matches will get filled with the content matched within each (...) in the pattern. In this case there will be one match.
The pattern I used is "images/" followed by 1 or more non-dash characters followed by a dash. I only capture the part that you want.

This is just one way to extract "dog" from your input string,
there may be a better pattern more suitable for your purpose,
depending largely on the other possible urls and parts to extract.


Remove comments from C-like source code I am working on the problem of removing comments from C-like source code. Here is my code in Python 2.7, and if anyone could advise improvement areas (especially performance), or any functional bugs which I do not discover, it will be great.

Problem statement

Given a file path represented as string, take this input string and remove all the comments in the file, print this file or save this to a new txt file by your choice.

Cases to consider:

// comment
/*

    comment
    */
    foo(); // comment

Source code

code='''// comment
/*
    /* hello python */
    comment
    */
    foo(); // comment
'''

def remove_comment(content):
    index = 0
    comment_line_inside = False
    comment_block_level = 0
    result = []
    while index < len(content):
        if content[index] == '/' and index + 1 < len(content) and content[index+1] == '*':
            comment_block_level += 1
        elif content[index] == '/' and content[index-1] == '*':
            comment_block_level -= 1
        elif content[index] == '/' and index + 1 < len(content) and content[index + 1] == '/':
            comment_line_inside = True
        elif content[index] == '\n' and comment_line_inside == True:
            comment_line_inside = False
        elif not comment_line_inside and comment_block_level == 0:
            result.append(content[index])
        index += 1

    return ''.join(result)

if __name__ == "__main__":
    print remove_comment(code)

First off, as said in the comments, C-style comments matches the first /* with the first */; meaning you can not nest comments:

/* This comment is /* a nested */ comment */

should be interpreted as: comment */

It is also more natural, in Python, to iterate over the elements of a collection rather than their indices. This allows you to write for character in content:. And if you trully need indices, you can use enumerate.

You can also use temporary variables to store characters that may indicate the beginning or the end of a comment without having to look at the character before or after the current one:

def remove_comments(content):
    block_comment = False
    line_comment = False
    probably_a_comment = False
    result = []
    for character in content:
        if not line_comment and not block_comment and character == '/':
            probably_a_comment = True
            continue

        if block_comment and character == '*':
            probably_a_comment = True
            continue

        if line_comment and character == '\n':
            line_comment = False
            result.append('\n')
        elif block_comment and probably_a_comment and character == '/':
            block_comment = False
        elif not line_comment and not block_comment:
            if probably_a_comment:
                if character == '/':
                    line_comment = True
                elif character == '*':
                    block_comment = True
                else:
                    result.append('/')  # Append the / we skipped when flagging that it was probably a comment starting
                    result.append(character)
            else:
                result.append(character)
        probably_a_comment = False

    return ''.join(result)

You can also simplify a bit the memory management by using a generator instead of appending into a list:

def remove_comments(content):
    def gen_content():
        block_comment = False
        line_comment = False
        probably_a_comment = False
        for character in content:
            if not line_comment and not block_comment and character == '/':
                probably_a_comment = True
                continue

            if block_comment and character == '*':
                probably_a_comment = True
                continue

            if line_comment and character == '\n':
                line_comment = False
                yield '\n'
            elif block_comment and probably_a_comment and character == '/':
                block_comment = False
            elif not line_comment and not block_comment:
                if probably_a_comment:
                    if character == '/':
                        line_comment = True
                    elif character == '*':
                        block_comment = True
                    else:
                        yield '/'
                        yield character
                else:
                    yield character
            probably_a_comment = False

    return ''.join(gen_content())

If you want to go crazy, you can also use a state machine approach to simplify the code: no more boolean flags and far less comparisons in average:

def source_code(char):
    if char == '/':
        return comment_begin, ''
    return source_code, char

def comment_begin(char):
    if char == '/':
        return inline_comment, ''
    if char == '*':
        return block_comment, ''
    return source_code, '/'+char

def inline_comment(char):
    if char == '\n':
         return source_code, char
    return inline_comment, ''

def block_comment(char):
    if char == '*':
        return end_block_comment, ''
    return block_comment, ''

def end_block_comment(char):
    if char == '/':
        return source_code, ''
    return block_comment, ''

def remove_comments(content):
    def gen_content():
        parser = source_code
        for character in content:
            parser, text = parser(character)
            yield text

    return ''.join(gen_content())

But, all in all, this is far too complicated for the task at hand. You can get the same job done using a simple regular expression:

import re

COMMENTS = re.compile(r'''
    (//[^\n]*(?:\n|$))    # Everything between // and the end of the line/file
    |                     # or
    (/\*.*?\*/)           # Everything between /* and */
''', re.VERBOSE)

def remove_comments(content):
    return COMMENTS.sub('\n', content)


Random Message Generator using Arrays using System;

namespace Friendly_Bot
{
    internal class Program
    {
        private static string[] Greetings = { "Hello, you have a", "Hey, you have a", "Hi, you have a" };
        private static string[] Compliments = { "cool", "fashionable", "stylish" };
        private static string[] Garments = { "coat.", "dress.", "shirt.", "skirt.", "suit.", "swimsuit." };
        private static string[] Farewells = { "ADIOS!", "BYE!", "BYE-BYE!", "FAREWELL!", "GOODBYE!" };

        private static string Greeting;
        private static string Compliment;
        private static string Garment;
        private static string Farewell;
        private static string Message;

        private static void Main(string[] args)
        {
            GenerateMessage();
        }

        private static void GenerateMessage()
        {
            int i = new Random().Next(1, 11);

            //20% chance of including a farewell in the message.
            if (i < 3)
            {
                Greeting = Greetings[new Random().Next(0, Greetings.Length)];
                Compliment = Compliments[new Random().Next(0, Compliments.Length)];
                Garment = Garments[new Random().Next(0, Garments.Length)];
                Farewell = Farewells[new Random().Next(0, Farewells.Length)];
                Message = Greeting + " " + Compliment + " " + Garment + " " + Farewell;
                Console.WriteLine(Message);
                Console.ReadLine();
            }
            //80% chance of NOT including a farewell in the message.
            else
            {
                Greeting = Greetings[new Random().Next(0, Greetings.Length)];
                Compliment = Compliments[new Random().Next(0, Compliments.Length)];
                Garment = Garments[new Random().Next(0, Garments.Length)];
                Message = Greeting + " " + Compliment + " " + Garment;
                Console.WriteLine(Message);
                Console.ReadLine();
            }
        }
    }
}

This code will piece together a random message with the contents in 4 separate arrays: Greetings, Compliments, Garments, Farewells.

There is a 20% chance of the randomly generated message including a farewell at the end of the message. There is an 80% chance for the message not to include a farewell exclamation in the message.

How can I clean this code up and make it produce the same product, but more efficiently? Any help is greatly appreciated! :)

The difference in the two branches of that if statement is just the Farwell so only this generation is what should happen inisde the if.
the name of the variable i is not choosen very well if you later on need a comment to describe what it should represent.
The GenerateMessage() method is doing more than its name implies. It is generating and outputting the message. This is also violating the single responsibility principle which means that each method should have only one responsibility. So let the method return a string which then can be used in the Main().
you shouldn't create each time a new Random but reuse an existing.
if the range out of which the random numbers should be generated starts at 0 you should use the overloaded Next() method which only takes the exlusive upper bound as a parameter.
by using a List<string> the multiple string variables won't be needed and you can take advantage of the string.Join() method

private static Random random = new Random();
private static string GenerateMessage()
{
    IList<string> subMessages = new List<string>(4);
    subMessages.Add(Greetings[random.Next(Greetings.Length)]);
    subMessages.Add(Compliments[random.Next(Compliments.Length)]);
    subMessages.Add(Garments[random.Next(Garments.Length)]);

    int chance = random.Next(1, 11);
    if (chance < 3)
    {
        subMessages.Add(Farewells[new Random().Next(Farewells.Length)]);
    }

    return string.Join(" ", subMessages);
}

Edit based on the comment

  Why do you have a 4 in the parentheses in this line: IList<string> subMessages = new List<string>(4); I removed the 4 to see if the code would still work and it did...

The 4 is pretty bad code style if another programmer needs to ask. Thats what a magic number is which I should have extracted to a meaningful constant like so

private static readonly int maxMessages = 4;

and then used it like so

IList<string> subMessages = new List<string>(maxMessages);

now you know what it is, but you are still missing what is for. That is shown if you take a look at the documentation for this overloaded constructor of the List<T> you will see that this is the initial capacity of the List<T> which is explained more in the Remarks section.

  The capacity of a List is the number of elements that the List can hold. As elements are added to a List, the capacity is automatically increased as required by reallocating the internal array.

And the reason why I used it is shown here

  If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List.


PHP/Doctrine bootstrap for review Here's my bootstrap.php for my PHP/MySQL/Doctrine app.  It's my first PHP app so I'm interested in learning from the experience of others how this could be improved - security-wise, performance-wise, or otherwise.

//-------------------------------------------------------------------------
// Define global constants
define('ROOT_PATH', dirname(__FILE__) . '/');
define('URL_BASE', 'http://localhost/myapp/public/');
define('LIB_PATH', 'C:\\wamp\\www\\lib\\');
define('OPENID_PATH', 'C:\\wamp\www\\lib\\lightopenid.git\\openid.php');

//-------------------------------------------------------------------------
// Bootstrap Doctrine.php, register autoloader, specify
// configuration attributes and load models.
require_once(LIB_PATH . 'doctrine12/lib/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();

//-------------------------------------------------------------------------
// Define database connection
$dsn = 'mysql:dbname=mydb;host=127.0.0.1';
$user = 'xxx';
$password = 'yyy';
$dbh = new PDO($dsn, $user, $password);
$conn = Doctrine_Manager::connection($dbh);

//-------------------------------------------------------------------------
// Set defaults
$manager->setAttribute(Doctrine::ATTR_DEFAULT_COLUMN_OPTIONS,
  array('type' => 'string', 'length' => 255, 'notnull' => true));
$conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
$manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
// Don't load a model until it's needed (causes problems when this is on)
//$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);

//-------------------------------------------------------------------------
// Import model objects
Doctrine_Core::loadModels(ROOT_PATH . 'app/models/generated'); // have to load base classes first
Doctrine_Core::loadModels(ROOT_PATH . 'app/models');

Here are a few lines that might be useful to add if you would like to use these options:

/**
 * Needed for SoftDelete to work
 */
$manager->setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true);

/**
 * Tell doctrine to look for custom ___Table classes in the models folder
 */
$manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, true);


Dealing with KB, MB, GB and TB and bytes This function is simple, it gets a number of bytes and returns its representation in either Bytes, KB, MB, GB and TB.

As simple as it is, I am sure there are other (and perhaps better ways) to write it.

function kmgtbytes (num) {
    if (num > 0 ){
        if (num < 1024)             { return [num, "Bytes"] }
        if (num < 1048576)          { return [num/1024, "KB"] }
        if (num < 1073741824)       { return [num/1024/1024, "MB"] }
        if (num < 1099511600000)    { return [num/1024/1024/1024, "GB"] }

        return [num/1024/1024/1024/1024, "TB"]
    }

    return num
}

Here's a slightly less repetitive way to write it since we know each unit is 1024 as large as the last:

function kmgtbytes (num) {
    var unit, units = ["TB", "GB", "MB", "KB", "Bytes"];
    for (unit = units.pop(); units.length && num >= 1024; unit = units.pop()) {
        num /= 1024;
    }
    return [num, unit];
}


Automatically scan and resize buffer in C I have a simple function that reads character by character from stdin, while resizing the buffer whenever needed. The implementation will only allow 256 characters to be read, but that can easily be modified. Are there an obvious problems with this function? ie. it relies on undefined behaviour. And how can performance be improved?

void scan(char **buffer) {
char *newBuffer;
unsigned char i = 0;
unsigned char size = 1;
*buffer = malloc(16);
(*buffer)[0] = 0;
while (1) {
    (*buffer)[i] = getchar();
    if ((*buffer)[i] == '\n') {
        (*buffer)[i] = 0;
        return;
    }
    if (i >= (size * 16)) {
        size++;
        newBuffer = realloc(*buffer, size * 16);
        *buffer = newBuffer;
    }
    i++;
}
}

Missing includes

I think you need to include <stdio.h> and <stdlib.h> for successful compilation.

Always check that allocations succeed

Look at

*buffer = malloc(16);
(*buffer)[0] = 0;

If malloc() returns a null pointer, then the assignment to its first element is undefined behaviour.  Your program could crash, destroy your system, or (if you're unlucky) appear to work.

Always check that input succeeds

If getchar() returns EOF, we should stop reading.  Note that by storing the result in a char, we lose the ability to distinguish EOF from valid input.

Avoid output-only parameters

Why do we return void, and instead write our result to a supplied pointer argument?  I could understand accepting an argument if we were to re-use a buffer passed in, but we just discard it.  I'd write this as

/* caller must release allocated memory with free() */
char *scan(void)

Be careful of overflow

If an input line reaches 255*16 = 4080 characters, size++ will overflow to zero.  Then our realloc() acts as free(), and we find ourselves accessing memory out of bounds.  I recommend using size_t for the length of allocated memory - allocation will fail before we reach the limits of size_t.

Consider increasing the allocation increment

This code reallocates every 16 chars.  This makes for a lot of allocations for really long lines.  One technique to avoid that, without hugely over-allocation for short lines, is to increase the increment as the buffer gets larger.  So instead of always increasing by 16, we might double the buffer size instead, or perhaps double it and add 32.  There are various strategies that can be used, with different performance implications (though the differences are likely small compared to the overhead of reading input at all).

Improved version

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

/* Read a line from standard input stream.

   Returns a buffer that must be released with free(),
   or a null pointer if none could be allocated.

   The result will end in a newline character if a
   full line was successfully read.
 */
char *scan(void)
{
    size_t capacity = 16;
    char *buffer = malloc(capacity);
    if (!buffer) {
        return NULL;
    }
    size_t i = 0;

    int c;                      /* current input character */
    while ((c = getchar()) != EOF) {
        if (i + 2 > capacity) {
            /* ensure space for c and terminating NUL */
            capacity *= 2;
            char *newbuf = realloc(buffer, capacity);
            if (!newbuf) {
                /* allocation failed - undo the read, terminate string, and return */
                ungetc(c, stdin);
                buffer[i] = '\0';
                return buffer;
            }

            buffer = newbuf;
        }

        /* We have enough space; now store it */
        buffer[i++] = (char)c;
        if (c == '\n') {
            break;
        }
    }

    if (i == 0) {
        /* we didn't read anything */
        free(buffer);
        return NULL;
    }

    buffer[i] = '\0';
    return buffer;
}

Demo

#include <string.h>
int main(void)
{
    char *s;
    while ((s = scan())) {
        printf("%04zu %s\n", strlen(s), s);
        free(s);
    }
}


Embedding a Text -> Maybe MyDataType function in a Parser to parse JSON into a custom data type I have these types:

data PizzaType = Cheese | Pepperoni | Anchovy

data PizzaOrder = PizzaOrder
    { p_type :: PizzaType
    , p_specialInstructions :: Text
    }

I want to use Aeson to create PizzaOrder instances from this JSON structure:

{
    "type": "pepperoni",
    "specialInstructions": "please cut into nine slices"
}

I have this function to convert from a Text to a PizzaType:

convertPizzaType :: Text -> Maybe PizzaType
convertPizzaType "cheese" = Just Cheese
convertPizzaType "pepperoni" = Just Pepperoni
convertPizzaType "anchovy" = Just Anchovy
convertPizzaType _ = Nothing

(The actual code to convert from a Text to my custom data type is much more involved, but it’s not the main point of my question.) In order to use my convertPizzaType function in the JSON parsing process, I wrote this general function

parseMaybe :: String -> (a -> Maybe b) -> Parser a -> Parser b
parseMaybe err f p = do
    result <- p
    case f result of
      Nothing -> fail err
      Just x -> pure x

which I use like this:

instance FromJSON PizzaOrder where
    parseJSON (Object v) = PizzaOrder <$>
        parseMaybe "Unknown pizza type" convertPizzaType (v .: "type") <*>
        v .: "specialInstructions"
    parseJSON _  = mzero

My question involves my parseMaybe function. It takes the raw input from Aeson, runs the given conversion function, and aborts the parsing if Nothing was returned. This seems to work but I have the sneaking suspicion that I’m reinventing a wheel. Is this a reasonable way to embed my convertPizzaType function in a Parser or should I be doing something simpler?

Complete runnable example

#!/usr/bin/env stack
-- stack --resolver lts-3.14 --install-ghc runghc --package aeson

{-# LANGUAGE OverloadedStrings #-}

import Control.Monad (mzero)
import Data.Aeson
import Data.Aeson.Types (Parser)
import Data.Text (Text)

data PizzaType = Cheese | Pepperoni | Anchovy deriving (Show)

data PizzaOrder = PizzaOrder
    { p_type :: PizzaType
    , p_specialInstructions :: Text
    }

instance FromJSON PizzaOrder where
    parseJSON (Object v) = PizzaOrder <$>
        parseMaybe "Unknown pizza type" convertPizzaType (v .: "type") <*>
        v .: "specialInstructions"
    parseJSON _  = mzero

parseMaybe :: String -> (a -> Maybe b) -> Parser a -> Parser b
parseMaybe err f p = do
    result <- p
    case f result of
      Nothing -> fail err
      Just x -> pure x

convertPizzaType :: Text -> Maybe PizzaType
convertPizzaType "cheese" = Just Cheese
convertPizzaType "pepperoni" = Just Pepperoni
convertPizzaType "anchovy" = Just Anchovy
convertPizzaType _ = Nothing

main :: IO ()
main = do
    let example1 = "{\"type\": \"pepperoni\", \"specialInstructions\": \"none\"}"
        parsedExample1 = decode example1 :: Maybe PizzaOrder
    case parsedExample1 of
      Nothing -> putStrLn "Example 1 couldn't be parsed"
      Just o -> putStrLn $ "The type of example 1 was " ++ (show $ p_type o)

    let example2 = "{\"type\": \"broccoli\", \"specialInstructions\": \"EXTRA BROCCOLI\"}"
        parsedExample2 = decode example2 :: Maybe PizzaOrder
    case parsedExample2 of
      Nothing -> putStrLn "Example 2 couldn't be parsed"
      Just o -> putStrLn $ "The type of example 2 was " ++ (show $ p_type o)

Modern functional programming and pizza are best friends, so I commend the usage of Haskell here.

As  PizzaType is already its own type, it's probably easiest to implement a FromJSON PizzaType instance. We know Parser is a monad, so we can use >>= to sequence parser computations together.

instance FromJSON PizzaType where
  parseJSON (String s) =
    maybe err pure (convertPizzaType s)
    where
      err = (fail . unpack) ("PizzaType: unknown type " <> s)
  parseJSON invalid =
    typeMismatch "PizzaType" invalid

instance FromJSON PizzaOrder where
  parseJSON (Object v) =
    PizzaOrder <$> (v .: "type" >>= parseJSON) <*> v .: "specialInstructions"
  parseJSON invalid =
    typeMismatch "PizzaOrder" invalid

I also recommend using two helpers:

typeMismatch to make the Aeson errors a little better. It's easy, with large JSON input, to quickly run into error hell where you have no idea where an error is coming from. Best to be specific early on.
maybe to convert values from Maybe a to Parser a.


Checking if two numbers have the same sign Is there a more elegant way than the following to check if two numbers have the same sign?

 bool sameSign(int num1, int num2)
    {
        if (num1 > 0 && num2 < 0)
            return false;
        if (num1 < 0 && num2 > 0)
            return false;
        return true;
    }

It could also be written as the not case of all of this (e.g. check the true cases and return false at the end).

By design, the two integers will never contain a zero value.

First up, your code has bugs. What if one of the numbers is 0? 0 should be positive, but your code treats it as negative in some tests, and positive in others. When comparing against 0 you should use >=, not just >.

The actual code is quite readable, though, and the performance is probably not horrible. I would recommend a single return statement though. A single return statement is easier if you check for "the same sign", and not "opposite signs".

Take your code:

bool sameSign(int num1, int num2)
{
    if (num1 > 0 && num2 < 0)
        return false;
    if (num1 < 0 && num2 > 0)
        return false;
    return true;
}

Fix the 0-handling, and you have:

bool sameSign(int num1, int num2)
{
    return num1 >= 0 && num2 >= 0 || num1 < 0 && num2 < 0
}

Now, that's pretty good, and I would happily "pass" that in a code review, but, can you do some tricks?

The simplest (code wise) is to use XOR:

return (num1 ^ num2) >= 0

That compares the bits, and if they are the same, it sets the resulting bit to 0. If the sign bits are the same, the resulting sign-bit is 0, and thus a positive (or 0) value.


Hackerrank: Pilling Up! challenge I've came up with solution to the Piling Up! problem on HackerRank. It passes all tests on HackerRank. How could I improve this code? Are there any cases outside those provided on HR that I've missed?

for _ in (range(int(input()))):
    no_of_cubes = int(input())
    side_lengths = list(map(int, input().strip().split()))
    result = "Yes"
    if max(side_lengths) not in (side_lengths[0], side_lengths[-1]):
        result = "No"
    print(result)

That was a fun little challenge to code against, although my solution was very different from yours!

With those kinds of challenges, it can be tempting to just write throw-away code. I would suggest though, if you are serious about coding, to just try to write the most professional code you can, even if it's just to solve this one challenge.

In particular, I find your code is not very expressive. There's no functions/methods/classes, there's really not anything telling me (or future you) what this code is for at all, so I'm having to actually read the code from beginning to end to even get an idea what it's supposed to do (let alone if it's doing it correctly). This also makes it much less reusable.

We can start by organizing input handling separately from program logic. In fact, I think __main__ would be a perfect place to handle getting input. You'll notice my code is somewhat more verbose, I personally prefer to make it obvious when doing "breaky" things like reading raw text input.

if __name__ == "__main__":
    num_cases = int(input())
    for case in range(num_cases):
        no_of_cubes = int(input())
        side_lengths = list(map(int, input().strip().split()))

I don't think it would be unreasonable to create a function to handle text input, but that may be a bit much for this. So, we have our input, now we just need to handle it.

One data structure to consider, and for which it seems like this challenge was written, is the deque...

  Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

However, you found a shorter, less literal way to pass the test cases, which, in the end, is the goal. So if you wanted to keep it at that, I'd just move the logic into a function and return a bool, and call it a day.

def can_be_piled(no_of_cubes: int, side_lengths: List) -> bool:
    if max(side_lengths) not in (side_lengths[0], side_lengths[-1]):
        return False
    return True

I also made a few other utility functions, one to split up the side lengths, the other to display the output. Note that I used Python 3 type hints in each function signature, in case that looks unfamiliar.

from typing import List

def can_be_piled(no_of_cubes: int, side_lengths: List) -> bool:
    if max(side_lengths) not in (side_lengths[0], side_lengths[-1]):
        return False
    return True

def get_side_lengths(raw_input: str) -> List:
    return list(map(int, raw_input.strip().split()))

def display_output(truthy: bool) -> None:
    if truthy:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    num_cases = int(input())
    for case in range(num_cases):
        no_of_cubes = int(input())
        side_lengths = get_side_lengths(input())
        display_output(can_be_piled(no_of_cubes, side_lengths))


Python implementation of multidimensional power spectral density with Welch method I have done my best to write Welch method implementation for python for multidimensional time series and still in the case of one dimensional time series I am getting inconsistent response compared to original Welch method. I have added comments and tried to be clear. Can anybody guide me about the mistake that I might have in implementation?

from scipy.fftpack import fft,fftfreq
import numpy as np
from math import ceil,floor
import sys
from scipy.signal import welch,get_window
from matplotlib import pyplot as plt
import warnings
from scipy.lib.six import string_types

def win_sig(x,nperseg):
    """A function just to cut a multidimensional time series into pieces of specific length (nperseg) """

    #checking whether the size of time series are smaller than the window lenght
    if nperseg >= x.shape[-1]:
        N = nperseg
        win_num = 1
    elif nperseg/2 == nperseg/2.:
        N = nperseg/2+1
        win_num = ceil(x.shape[-1]/float(N-1))
    else:
        N = nperseg/2
        win_num = ceil(x.shape[-1]/float(N))

    #index set manipulation for generating the splitted version of the signals faster
    idx_temp=np.indices((win_num,nperseg))
    idx_temp=np.tile((idx_temp[0]*N+idx_temp[1]).T,x.shape[0]).T.reshape((x.shape[0],win_num,-1))

    #padding zeros for the last window when the last window is longer than the remaining of signal
    pad_len=(win_num-1)*N+nperseg-x.shape[-1]
    idx_mat=np.arange(0,x.shape[0])[...,None,None]*(idx_temp.flatten()[-1]+1)+idx_temp
    pad_mat=np.zeros((x.shape[0],pad_len))
    x=np.concatenate((x,pad_mat),axis=-1)

    return x.flatten()[idx_mat].reshape((x.shape[0],win_num,-1))

def ndim_welch(x,nperseg,window = 'hanning',scaling = 'density',fs = 1.0,axis = -1):
    if x.shape[-1] < nperseg:
        warnings.warn('nperseg = %d, is greater than x.shape[%d] = %d, using '
                    'nperseg = x.shape[%d]'
                    % (nperseg, axis, x.shape[axis], axis))
        nperseg = x.shape[-1]

    #setting the window as is done in original scipy.signal
    if isinstance(window, string_types) or type(window) is tuple:
            win = get_window(window, nperseg)
    else:
        win = np.asarray(window)
        if len(win.shape) != 1:
            raise ValueError('window must be 1-D')
        if win.shape[0] > x.shape[-1]:
            raise ValueError('window is longer than x.')
        nperseg = win.shape[0]

    #setting the scale as is done in original scipy.signal
    if scaling == 'density':
        scale = 1.0 / (fs * (win*win).sum())
    elif scaling == 'spectrum':
        scale = 1.0 / win.sum()**2
    else:
        raise ValueError('Unknown scaling: %r' % scaling)

    #turning the multidimensional time series into multiple time series of windowed sections using the function 'win_seg'
    windowed_sig = win_sig(x,nperseg)
    windowed_sig = np.multiply(win,windowed_sig)

    #calculating the fourier transform
    windowed_seg_fft = fft(windowed_sig)
    windowed_fft = np.mean(windowed_seg_fft,axis=1).T

    #returning the spectral density with calcualting outerproducts to get the crossspectrum matrix and also returning the frequenct set
    spec_density = np.einsum('...i,...j->...ij',windowed_fft,windowed_fft.conjugate())
    spec_density *= scale
    spec_freq = fftfreq(nperseg)
    return spec_freq,np.squeeze(spec_density)
b=np.random.randn(5)
segment = 5
a = (b)[None,...]
print ndim_welch(a,nperseg=segment)[1].real,welch(b,nperseg=segment)[1]

For later reference here is the correct code:

from __future__ import division, print_function, absolute_import
from scipy.fftpack import fft,fftfreq
import numpy as np
from math import ceil,floor
import sys
from scipy.signal import get_window,welch,signaltools
from matplotlib import pyplot as plt
import warnings
from scipy.lib.six import string_types

def win_sig(x,nperseg,padded='False'):
    """A function just to cut a multidimensional time series into pieces of specific length (nperseg) """

    #checking whether the size of time series are smaller than the window lenght
    if nperseg>=x.shape[-1]:
        N=nperseg
        win_num=1
    elif int(nperseg/2.)==nperseg/2.:
        N=int(nperseg/2.)
    else:
        N=int(nperseg/2.)+1
    if padded:
        win_num=ceil(x.shape[-1]/float(N))
    elif nperseg<x.shape[-1]:
        win_num=int(x.shape[-1]/float(N))-1

    #index set manipulation for generating the splitted version of the signals faster
    idx_temp=np.indices((win_num,nperseg))
    idx_temp=idx_temp[0]*N+idx_temp[1]

    #padding zeros for the last window when the last window is longer than the remaining of signal
    pad_len=(win_num-1)*N+nperseg-x.shape[-1]
    if padded:
        pad_mat=np.zeros((x.shape[0],pad_len))
        x=np.concatenate((x,pad_mat),axis=-1)

    return x.reshape(-1,x.shape[-1])[:,[idx_temp]].reshape((x.shape[0],win_num,-1))

def ndim_welch(x,nperseg=256,window='hanning',scaling = 'density',detrend='constant',fs=1.0,axis=-1,padded=False):
    """Multidimensional Welch method: Calculating Power Spectral Density for time series of multiple [and one] dimension."""

    ##################################################################
    # checking whether the time series lengths are longer than window
    # length for welch method. If negative the size has been set to time series
    # length. (Taken from original scipy.signal.welch)

    if (not padded) and x.shape[-1] < nperseg:
        warnings.warn('nperseg = %d, is greater than x.shape[%d] = %d, using '
                    'nperseg = x.shape[%d]'
                    % (nperseg, axis, x.shape[axis], axis))
        nperseg = x.shape[-1]

    #########################################################
    # setting the window as is done in original scipy.signal

    if isinstance(window, string_types) or type(window) is tuple:
            win = get_window(window, nperseg)
    else:
        win = np.asarray(window)
        if len(win.shape) != 1:
            raise ValueError('window must be 1-D')
        if win.shape[0] > x.shape[-1]:
            raise ValueError('window is longer than x.')
        nperseg = win.shape[0]

    ######################################################
    #setting the scale as is done in original scipy.signal

    if scaling == 'density':
        scale = 1.0 / (fs * (win*win).sum())
    elif scaling == 'spectrum':
        scale = 1.0 / win.sum()**2
    else:
        raise ValueError('Unknown scaling: %r' % scaling)

    #########################################################
    #  windowing the signal
    # (turning the multidimensional time series into multiple t
    # time series of windowed sections using the function 'win_seg')

    windowed_sig=win_sig(x,nperseg,padded)

    ##################################
    # detrending step

    if not detrend:
        detrend_func = lambda seg: seg
    elif not hasattr(detrend, '__call__'):
        detrend_func = lambda seg: signaltools.detrend(seg, type=detrend)
    elif axis != -1:
        # Wrap this function so that it receives a shape that it could
        # reasonably expect to receive.
        def detrend_func(seg):
            seg = np.rollaxis(seg, -1, axis)
            seg = detrend(seg)
            return np.rollaxis(seg, axis, len(seg.shape))
    else:
        detrend_func = detrend

    windowed_sig=detrend_func(windowed_sig)

    #######################################
    # spectral density estimation

    # multiplying by window
    windowed_sig=np.multiply(win,windowed_sig)

    # calculating the fourier transform
    windowed_seg_fft=fft(windowed_sig)
    windowed_fft=windowed_seg_fft.T

    # returning the spectral density with calcualting outerproducts to get the
    # crossspectrum matrix and also returning the frequency set

    spec_density=np.mean(np.einsum('...i,...j->...ij',windowed_fft,windowed_fft.conjugate())*scale,axis=1)
    spec_freq=fftfreq(nperseg)
    return spec_freq,np.squeeze(spec_density).real


PHP mcrypt AES encryption wrapper There are two keys: the main is aes128 and the second is XTEA, used just for randomization of data inside the AES. Randomization is done with secret random key that is not know even if someone knows exactly what is encrypted. Also the key is produced by doing hash many number of times and this hash is salted with the iv so it is not possible to make a dictionary attack with precomputed hashes.

function aes128ctr_en($data,$key,$hash_rounds = 0) {
    //iv is created
    $iv = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
    //internal secret random string is created so no one knows what
    //is exactly encoded by main cipher
    $xtea = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
    //password is hashed in many rounds to prevent dictionary attack,
    //hashing is done with individual iv for hmac so it make no sense to use
    //precalculated hashes
    for($i=0;$i<=$hash_rounds;++$i) $key = hash_hmac('sha256',$key,$iv,true);
    //string is randomized for use in aes, so no one knows what actually will be encoded
    //this is not actual encoding so password is stored inside with xtea encoded string,
    //second half of this password is used as IV for xtea
    //again: THIS IS NOT ACTUAL ENCODING
    $data = $xtea.mcrypt_encrypt('xtea',$xtea,$data,'ofb',substr($xtea,8));
    //hash is added to check if return string is really what we looked for,
    //must match with string on decoding
    $data = hash('md5',$data,true).$data;
    //actual encoding, IV is prepended to encrypted string
    return $iv.mcrypt_encrypt('rijndael-128',$key,$data,'ctr',$iv);
}

function aes128ctr_de($data,$key,$hash_rounds = 0) {
    $iv = substr($data,0,16);
    $data = substr($data,16);
    for($i=0;$i<=$hash_rounds;++$i) $key = hash_hmac('sha256',$key,$iv,true);
    $data = mcrypt_decrypt('rijndael-128',$key,$data,'ctr',$iv);
    $md5 = substr($data,0,16);
    $data = substr($data,16);
    if (hash('md5',$data,true)!==$md5) return false;
    $xtea = substr($data,0,16);
    $data = substr($data,16);
    return mcrypt_decrypt('xtea',$xtea,$data,'ofb',substr($xtea,8));
}

$key = 'suPer_secret aAnd L10ng ppswrd$%';
$encrypted = aes128ctr_en('the bomb will blow up at 1 pm',$key,12345);
echo aes128ctr_de($encrypted,$key,12345);

I really don't have knowledge to make it better. I'm not that educated in all this to read RFCs and make algorithms out of it. I'm also constrained to methods that are precompiled in core PHP binary as I want these methods to be able to run on remote servers.

You should use a key strengthening function like PKBDF2, scrypt or bcrypt to generate a key from the password.
The part with XTEA is useless: you're relying on security through obscurity.
You shouldn't hash before encrypting if you want to ensure the data has not been tampered with. Use HMAC SHA-256 on the encrypted data.

And finally: don't write your own crypto algorithm. Use well known and audited solutions.


Find the intersect area of two overlapping rectangles This is my solution to find the coordinates of 2 overlapped rectangles implemented in JavaScript. Each rectangle is represented by 2 points, each with 2 (x,y) coordinates.

Can this code be improved?

const maxOfX = (rec) => (Math.max(rec.x1, rec.x2));
const maxOfY = (rec) => (Math.max(rec.y1, rec.y2));
const minOfX = (rec) => (Math.min(rec.x1, rec.x2));
const minOfY = (rec) => (Math.min(rec.y1, rec.y2));
const comBinedRectangle = (rec1, rec2) => {
  let overlappedRec = {};
  const NolappingFromX = maxOfX(rec1) <= minOfX(rec2) || minOfX(rec1) >= maxOfX(rec2);
  const NolappingFromY = maxOfY(rec1) <= minOfY(rec2) || minOfY(rec1) >= maxOfY(rec2);
  if (!(NolappingFromX || NolappingFromY)) {
    overlappedRec.x1 = Math.max(minOfX(rec1), minOfX(rec2));
    overlappedRec.y1 = Math.max(minOfY(rec1), minOfY(rec2));
    overlappedRec.x2 = Math.min(maxOfX(rec1), maxOfX(rec2));
    overlappedRec.y2 = Math.min(maxOfY(rec1), maxOfY(rec2));
  }

  return overlappedRec;
}
const rectangle1 = { x1: 2, y1: 2, x2: 4, y2: 4 };
const rectangle2 = { x1: 3, y1: 3, x2: 6, y2: 2 };
console.log(comBinedRectangle(rectangle1, rectangle2));
// { x1: 3, y1: 2, x2: 4, y2: 3 }

/**
 * Returns intersecting part of two rectangles
 * @param  {object}  r1 4 coordinates in form of {x1, y1, x2, y2} object
 * @param  {object}  r2 4 coordinates in form of {x1, y1, x2, y2} object
 * @return {boolean}    False if there's no intersecting part
 * @return {object}     4 coordinates in form of {x1, y1, x2, y2} object
 */
const getIntersectingRectangle = (r1, r2) => {
  [r1, r2] = [r1, r2].map(r => {
    return {
      x: [r.x1, r.x2].sort((a,b) => a - b),
      y: [r.y1, r.y2].sort((a,b) => a - b)
    };
  });

  const noIntersect = r2.x[0] > r1.x[1] || r2.x[1] < r1.x[0] ||
                      r2.y[0] > r1.y[1] || r2.y[1] < r1.y[0];

  return noIntersect ? false : {
    x1: Math.max(r1.x[0], r2.x[0]), // _[0] is the lesser,
    y1: Math.max(r1.y[0], r2.y[0]), // _[1] is the greater
    x2: Math.min(r1.x[1], r2.x[1]),
    y2: Math.min(r1.y[1], r2.y[1])
  };
};

/*  ↓  DEMO  ↓  */

const rectangle1 = { x1: 2, y1: 2, x2: 4, y2: 4 };
const rectangle2 = { x1: 3, y1: 3, x2: 6, y2: 2 };

console.log(getIntersectingRectangle(rectangle1, rectangle2));
// { x1: 3, y1: 2, x2: 4, y2: 3 }

First, both rectangles get transformed into object with keys x and y and sorted arrays of two of corresponding them coordinates as values.
r1 = {
  x: [2, 4], // x1, x2
  y: [2, 4]  // y1, y2
}
r2 = {
  x: [3, 6], // x1, x2
  y: [2, 3]  // Y2, Y1 !
}

That's because for this job it is important to know which of xs and ys is lesser and which is greater. Rather than Math.max() and Math.min() a single .sort() can be used.
Alternative would be to declare that (x1, y1) is assumed to always be top-left corner, but as I see in rectangle2 in your question, that is apparently not always the case.
Now, noIntersect is negated
!(a.left > b.right || b.left > a.right || a.top > b.bottom || b.top > a.bottom);

which tests if in both axes sides from one end of one figure exceed opposite-direction end side of the other figure, e.g. if left side of figure a is more to the right than the right side of figure b.
At the end we return false if there is no intersection of our rectangles, or an object with coordinates if there is. Intersecting part will always span from:
the greater of the 2 lesser xs of both rectangles
to
the lesser of the 2 greater xs of both rectangles.


Determine if a string only contains repetitions of a substring This is my first Python program in years, it's just a simple string manipulation program. Given a string, determine if it contains repetitions of any substring. For example, testtest contains two substring test and nothing else.

def onlySubstrings(stringOrig):
    stringCopy = (stringOrig+'.')[:-1] # copy string contents
    for i in range(1, len(stringCopy)): # for each character
        stringCopy = stringCopy[1:]+stringCopy[0] # shift first char to end
        if stringCopy == stringOrig: # if equivalent to original input
            return True # it consists of substrings only
    else: # otherwise the only substring is the string itself
        return False

if __name__ == '__main__':
    wordList = ['testtest','testteste','test','tetestst'] # some test words
    print('The below words only contain substring repetitions:')
    for word in wordList: # for each word
print(onlySubstrings(word), '\t', word)

If you imagine the string as circular unto itself, the string can only contain equal substring(s) if you can move the characters to the left or right and get the same original string in less than len shifts:

testtest - 0 shifts, original string
esttestt - 1 shift, not original
sttestte - 2 shifts, not original
ttesttes - 3 shifts, not original
testtest - 4 shifts, original again

Since 4 < len, it contains only substring repetitions.

testteste - 0 shifts, original string
esttestet - 1 shift, not original
...
etesttest - (len-1) shifts, not original
testteste - len shifts, original again

Since we couldn't find the original string again in under len shifts, it does not only contain repetitions of a substring.

The code is relatively concise and easy to read. Here are some points that could be improved:

A general thing is the amount of commenting, you should generally resort to comments only when it's hard to make the code self-explanatory. You don't really need to comment each line of the code.
stringCopy = (stringOrig+'.')[:-1] # copy string contents
You can make a copy this way instead stringCopy = stringOrig[:].
To make the code more readable, you can create a function that shifts a string n characters. This will really help make the code more readable.
The else keyword after the for loop is not needed since you return anyway if you didn't finish the loop. else is usually used with break in the for loop.
The name of the function could be slightly improved, maybe consists_of_repeated_substrings. This is longer but is very easy to understand.
A note on performance: your algorithm creates a copy of the original string in each iteration. This works fine for shorter strings, but if you wanna make it more efficient you can consider matching the string without making a shifted copy of it.

Incorporating these comments you could rewrite the code as follows:

def shifted_string(str, n):
  return str[n:] + str[:n]

def consists_of_repeated_substrings(str):
    '''
    Checks whether a string consists of a substring repeated multiple times.
    Ex. 'testtesttest' is the string 'test' repeated 3 times.
    '''

    # The string can only contain equal substrings if you can shift it n
    # times (0 < n < len) and get the same original string.
    for i in range(1, len(str)):
        if shifted_string(str, i) == str:
            return True
    return False

A clever algorithm for doing the same thing is as follows:

double_str = (str + str)[1:-1]
return double_str.find(str) != -1

The idea is similar to yours, so I will leave understanding it as an exercise.


Java/Swing GUI code/layout, am I doing this wrong? I've never done Java GUI's before. After much trouble I've gotten my GUI to look how I want, however it feels as if my code is very inefficient, as if I'm going about this the wrong way?

     //main panels
private JPanel westPanel = new JPanel(new BorderLayout());
private JPanel eastPanel = new JPanel(new BorderLayout());

//door panels
private JPanel doorsPanel = new JPanel(new BorderLayout());
private JPanel doorsGrid = new JPanel(new GridBagLayout());
private JPanel doorButtons = new JPanel(new FlowLayout());

//light panels
private JPanel lightsPanel = new JPanel(new BorderLayout());
private JPanel lightsGrid = new JPanel(new GridBagLayout());
private JPanel lightTimerGrid = new JPanel(new GridBagLayout());
private JPanel lightButtons = new JPanel(new FlowLayout());

//list panels
private JPanel listPanel = new JPanel(new BorderLayout());
private JPanel listButtons = new JPanel(new GridBagLayout());
private JLabel itemDesc = new JLabel("Item Name - Item Price");
private JLabel totalPrice = new JLabel("Total Price: ");

doorsPanel.setBorder(BorderFactory.createTitledBorder("Manage Doors: "));
doorsPanel.add(doorsGrid, BorderLayout.NORTH);
doorsPanel.add(doorButtons, BorderLayout.SOUTH);

lightsPanel.setBorder(BorderFactory.createTitledBorder("Manage Lights: "));
lightsPanel.add(lightsGrid, BorderLayout.NORTH);
lightsPanel.add(lightButtons, BorderLayout.SOUTH);
lightsPanel.add(lightTimerGrid, BorderLayout.CENTER);

listPanel.setBorder(BorderFactory.createTitledBorder("Manage Shopping List: "));
listPanel.add(listButtons, BorderLayout.EAST);

westPanel.add(doorsPanel, BorderLayout.NORTH);
westPanel.add(lightsPanel, BorderLayout.CENTER);

eastPanel.add(listPanel, BorderLayout.SOUTH);

add(westPanel, BorderLayout.WEST);
add(eastPanel, BorderLayout.EAST);

Your code seems perfectly fine!

However...

If all of this code is in the same block (e.g., a constructor or a layout builder method), I would recommend that you break up the layout code into smaller functions. That will improve readability and code structure a bit.

Also, you should definately familiarize yourself with some GUI builders for Java (in my case it was WindowBuilder for Eclipse). Writing layout code by hand can be a pain and a source of bugs that you won't be able to resolve easily.


Parse data into an array of structs I'd had a hard time getting this to work. I’d like to parse a file containing data and copy this data into a struct.

The data file (test.dat) looks like this:

1,"Tom","Smith"
2,"Peter","Perth Junior"
3,"Cathy","Johnson"

I use the following function.

func parseDataFile() {

    struct person {
        var id: Int
        var first: String
        var last: String
    }

    var friends: [person] = []
    let filePath = Bundle.main.path(forResource: "test", ofType: "dat")
    guard filePath != nil else { return }
    let fileURL = URL(fileURLWithPath: filePath!)
    do {
        let file = try String(contentsOf: fileURL, encoding: .utf8)
        let arrayOfLines = file.split { $0.isNewline }
        for line in arrayOfLines {
            let arrayOfItems = line.components(separatedBy: ",")
            let tempPerson = person(id: Int(arrayOfItems[0])!,
                                    first: arrayOfItems[1].replacingOccurrences(of: "\"", with: ""),
                                    last: arrayOfItems[2].replacingOccurrences(of: "\"", with: "")
            )
            friends.append(tempPerson)
        }
    } catch {
        print(error)
    }
}

I read the data into a string, split it up into an array (every line is a record). The records are copied into the struct person. This works fine, but I'm sure this is far from optimum.

I was testing a lot with PropertyListDecoder().decode(), but this seems to accept only dictionary formatted data (not sure though ?!).

Next, is it necessary to use an array record, as intermediate step, prior putting the line into a struct?

Last, is there no method to copy all comma separated strings to an array, without filling every property of the struct individually (like I did)?

Besides that, I believe that there is also a much more efficient way to get rid of the string delimiting quotes than using replacingOccurrences(of:with:)?

Any comments would be appreciated.

This

let filePath = Bundle.main.path(forResource: "test", ofType: "dat")
guard filePath != nil else { return }
let fileURL = URL(fileURLWithPath: filePath!)

is an anti-pattern in Swift, see also When should I compare an optional value to nil? on Stack Overflow. Instead of testing a value against nil and then force-unwrapping it, you should use optional binding:

guard let filePath = Bundle.main.path(forResource: "test", ofType: "dat") else { return }
let fileURL = URL(fileURLWithPath: filePath)

This can be further simplified by retrieving an URL in the first place, instead of getting a file path and converting that to an URL:

guard let fileURL = Bundle.main.url(forResource: "test", withExtension: "dat")
    else { return }

But actually this is a situation where I would prefer force-unwrapping: A missing resource file in the application bundle is a programming error and there is no way of recovering from that situation in a sensible way. It should be detected early during development:

let fileURL = Bundle.main.url(forResource: "test", withExtension: "dat")!

The same reasoning applies to reading and decoding the file:

let file = try! String(contentsOf: fileURL, encoding: .utf8)

Using split() here

let arrayOfLines = file.split { $0.isNewline }

is good: It creates an array, but the array elements are substrings, i.e. they contain references into the character storage of the original file string. The same method can be applied to split each line to avoid data duplication:

for line in arrayOfLines {
    let arrayOfItems = line.split(separator: ",")
    // ...
}

This

let tempPerson = Person(id: Int(arrayOfItems[0])!,
                        first: arrayOfItems[1].replacingOccurrences(of: "\"", with: ""),
                        last: arrayOfItems[2].replacingOccurrences(of: "\"", with: "")

would crash if a line has less than 3 comma-separated items, or if the first item is not an integer. However, as mentioned above, this is acceptable if the data is read from your own resource file (and not from some external resource): We can rely on the data to be well-formed.

It is a bit difficult to read though, and I would split the single statement into parts:

let id = Int(arrayOfItems[0])!
let firstName = arrayOfItems[1].replacingOccurrences(of: "\"", with: "")
let lastName = arrayOfItems[2].replacingOccurrences(of: "\"", with: "")
let tempPerson = Person(id: id, first: firstName, last: lastName)

With respect to removing the delimiters: What you do is fine if the data file has exactly the format from your example, and there are no embedded quotation marks or commas in the fields. An alternative is

let firstName = String(arrayOfItems[1].dropFirst().dropLast())
let lastName = String(arrayOfItems[2].dropFirst().dropLast())

which might be slightly more efficient because it does not need bridging to NSString. (But I did not measure it.)

Finally note that your code does not parse all valid CSV files. Problems are for example

embedded commas: 4,"Sammy","Davis, Jr."
embedded quotation  marks: 5,"John","Foo""Bar"
or embedded newlines.

Before you try to implement all those features yourself I would suggest to have a look at some existing Swift CSV parsing libraries.


Filling a memory segment with a bit pattern I want to fill a memory segment with a certain byte pattern using powerpc assembly:

# Task: Fill the area from 0x8000 to (inclusive) 0x8FFF with 0x55 (per byte read/write)

# Write start address - 1 into a register
addis r2, r0, 0x0000
ori r2, r2, 0x7FFF

# Bit pattern is 0x55
addi r3, r0, 0x55

# Size of memory segment + 1
addis r4, r0, 0x0000
ori r4, r4, 0x1000
# Move that length to CTR register
mtctr r4

loop:
#Write pattern from r3 into the address (1 + r2), and write the result of 1 + r2 back into r2
stbu r3, 1(r2)
# decrement CTR and see if we have reached the end of the segment
bdnz

You have some unnecessary comments. For example, this comment:

# Move that length to CTR register
mtctr r4

Anyone who knows this instruction set should be easily able to know what that line is doing.

Comments are supposed to explain why, not how because "how" is very easy to find out on one's own.

You did not specify what assembler you were using, but if your assembler allows for creating macros, I recommend that you make macros for those "random" numbers that are in your code.

These "random" numbers are called magic numbers; they've just appeared out of no-where.

In the NASM assembler, you can do something like this:

%define BIT_PATTERN 0x55

Then, in the line where you are working with the bit pattern, you write:

addi r3, r0, BIT_PATTERN

And now there is no confusion about where that number came from and you can remove that comment from above this line.

You should see if you can create macros for this bit pattern like I showed you, and for the memory segment addresses.

Note: I could not find a PowerPC assembler any where on the internet so my recommendations from here on may be slightly flawed in some places.

These lines can be simplified:

addis r2, r0, 0x0000
ori r2, r2, 0x7FFF

All you seem to be trying to do here is stick the value 0x7FFF into the register r2. However, you are taking two instructions to do this:

Move 0 into r2
Make r2 become 0x7FFF with ori

This seems a little unnecessary; why can't you just put 0x7FFF into r2 to begin with, like you did when you put the bit pattern into r3? A much simpler way of writing this would be:

li r2, 0x7FFF

which is directly equivalent to

addi r2, 0, 0x7FFF

Note: This assumes that r0 was 0 to being with, which I think it was.

The above will put the value 0x7FFF into r2. You can do this same thing for when you are putting the size of the memory segment into r4, and when you are putting the bit pattern into r3.

It didn't look like you specifically needed to actually use the addis instruction, which seems unnecessarily complicated for simply putting a value into a register.

However, if you did, just change the instruction to:

lis r2, 0x7FFF

You are using the registers incorrectly.

According to this page, the registers r2, r3, and r4 are for the table of contents pointer, the return of a function/subroutine, and (commonly) a function/subroutine argument, respectively.

I think you should be using the register r4 through r10 because, since you are not using a subroutine, these registers can now be used for general purpose. You might be okay with using r3, but you definitely should not be using r2.

Putting it all together:

li r4, 0x7FFF
li r5, 0x55
li r6, 0x1000

mtctr r6

loop:
    stbu r5, 1(r4)
    bdnz

If you notice any bugs, notify me.


Parsing objects from complex String in Java I want to convert string arrays with following structure:

static String[] lines = {
                          "@1      var_decl         name: testStr  parent: @7",
                          "                         srcp: Auto.cpp:6         "
                        };

into Java objects with following structure:

class Token {
   String type;
   String name;
   String source;
   Token parent;
}

So far I'm parsing this in this way:

Token parseLines(String[] lines) {

    String[] firstElements = lines[0].split(" ");
    String[] secondElements = lines[1].split(" ");

    Token newToken = new Token();

    newToken.type = firstElements[6];
    newToken.name = firstElements[16];
    String parentName = firstElements[19];
    newToken.parent = getParent(parent); // find parent by name
    newToken.source = secondElements[26];
    return newToken;
}

As you can see, this is far from elegant. How can I improve this?

My approach would start by looking something like the code below. Obviously whatever you wind up with should be in its own class/method to do the mapping from String[] to Token.

public final class Test {

    private static final int TYPE_COLUMN = 1;
    private static final int NAME_COLUMN = 3;
    private static final int PARENT_COLUMN = 5;
    private static final int SOURCE_COLUMN = 7;

    public static void main(final String[] args) {
        final String[] lines = {
                "@1      var_decl         name: testStr  parent: @7",
                "                         srcp: Auto.cpp:6         "
              };

        final String[] values = (lines[0] + lines [1]).split("\\s+");
        System.out.println(All Values:" + java.util.Arrays.toString(values));
        System.out.println("Type: " + values[TYPE_COLUMN]);
        System.out.println("Name: " + values[NAME_COLUMN]);
        System.out.println("Parent: " + getParent(values[PARENT_COLUMN]));
        System.out.println("Source: " + values[SOURCE_COLUMN]);

    }

    private static String getParent(final String parentId) {
        return "Parent";
    }
}


A C function for returning the address of the calling function Suppose you are given two functions, foo and bar, and neither of them are inlined. Now, if foo calls for bar and bar calls for called_from, bar receives the address of the caller, that is, the address of foo. I know that there is no real need for such computation as it is always possible to simply pass an enumeration that indicates the caller, yet I was in the mood for hacking the stack.

My code compiles on Visual Studio.

main.cpp:

#include <stdio.h>

/************************************************************************
* Suppose that foo() calls for bar() and bar() calls for called_from(). *
* Now if neither bar() and foo() are inlined functions, bar() receives  *
* the address of foo() from the function called_from().                 *
************************************************************************/
void* called_from() {
    __asm {
        mov eax, [ebp]
        mov eax, [eax]     // foo's ebp
        mov eax, [eax + 4] // foo's return address
        mov edx, eax;      // we might need a copy of
                           // the foo's return address

        sub eax, 5;        // the adress of the instruction 'call foo'
        mov bl, [eax]      // the opcode of the call instruction
        inc eax            // [eax] points to the address of foo

        mov eax, [eax];    // load the caller's address

        cmp bl, 0xE8
        je RelationalAddress // the address is relational

        cmp bl, 0xFF
        je Exit              // the adress is absolute
        jmp Abort

        RelationalAddress:
        add eax, edx         // convert relational address
                             // to an abolute one
        jmp Exit

        Abort:
        mov eax, 0           // failure, return null pointer
        Exit:
    }
}

// We need the macro as otherwise it will obscure the actual caller.
#define is_called_from(n) (called_from() == (void*) n)

Here are a few tests:

void foo();
void bar();
void baz();

int main() {
  printf(
      "main:\t0x%p\n"
      "foo: \t0x%p\n"
      "bar: \t0x%p\n"
      "baz: \t0x%p\n"
      "\n",
      main,
      foo,
      bar,
      baz);

  foo();
  bar();
  baz();

  getchar();
  return 0;
}

void foo() {
  printf("This is foo:\n"
         "called from %p\n"
         "that is, from ",
         called_from());

  if (is_called_from(main))
  {
      puts("main.\n");
  }
  else if (is_called_from(bar))
  {
      puts("bar.\n");
  }
  else
  {
      puts("somewhere else.\n");
  }
}

void bar() {
  printf("This is bar:\n"
         "called from 0x%p\n"
         "\n",
         called_from());

  foo();
}

void baz() {
  printf("This is baz:\n"
         "called from 0x%p\n"
         "\n",
         called_from());

  foo();
}

Didn't totally work
After porting the code to gnu C style, it only "sort of" worked for me.  I was able to have foo() print that it was called from bar() or baz().  However, if foo() was called directly from main(), then it crashed when trying to find its caller.  That's probably because on my system (Cygwin 32-bit, using Gnu C compiler), main() doesn't have a caller on the stack.
Clobbered register
It's not safe to write to ebx without pushing it on the stack and popping it off later.  ebx is considered non-volatile, which means that a function must preserve its value.  If you don't, then the calling function will be affected because its local variable may be stored in ebx, for example.  You can safely use eax, ecx, and edx though, because they are all considered volatile registers (i.e. you are allowed to clobber them).  So you should change your ebx accesses to ecx instead.
Not portable
Your asm statement assumes that the compiler will insert these lines at the top of the function:
    pushl   %ebp
    movl    %esp, %ebp

That may be what your compiler does, but it's not a certainty.  For example, with my GNU C compiler, it normally outputs the above code.  But with the -O2 option, it does this instead:
    subl    $28, %esp

If you want to make sure that you get the function prologue you need, you should write the whole thing in assembly and include the prologue/epilogue you require.


Scaling and cropping an image adaptively based on the window dimensions I've tried my best (I'm new to JS) to write a script that make an image fit to its parent div with respect of the ratio and overflowing when needed.

For example, if the height of the image is smaller than the window's height, I set the height equal to the window's height and the width overflow the window's width. I then horizontally center the image.

If the width is smaller than the window's width, I do the way around.

An example can be seen here: JSFiddle

Note that the example doesn't work as I'm seeing it on my browser (Chrome). Refresh simulation might not work properly.

The fact is that everything is working as expected when I refresh the page. If I try to resize the page, the ratio is not respected at all. But then again, If I refresh the page (after it's been resized), the image fits perfectly.

function imageFitToScreen() {
  var windowWidth = $(window).width();
  var windowHeight = $(window).height();
  var postThumbnailWidth = $('#postThumbnail').width();
  var postThumbnailHeight = $('#postThumbnail').height();
  var imageWidth = $('#postThumbnail').find('img').width();
  var imageHeight = $('#postThumbnail').find('img').height();
  if ((windowHeight < windowWidth) && (imageHeight < imageWidth)) {
    $('#postThumbnail').find('img').css('width', 'auto');
    $('#postThumbnail').find('img').css('height', '100%');
  }
  var imageWidth = $('#postThumbnail').find('img').width(); /* imageWidth value has changed with the if before */
  if ((windowHeight < windowWidth) && (imageWidth < postThumbnailWidth)) {
    $('#postThumbnail').find('img').css('min-width', '100%');
    $('#postThumbnail').find('img').css('height', 'auto');
  }
  if ((windowWidth < windowHeight) && (imageWidth < imageHeight)) {
    $('#postThumbnail').find('img').css('width', '100%');
    $('#postThumbnail').find('img').css('height', 'auto');
  }
  var imageHeight = $('#postThumbnail').find('img').height(); /* imageHeight value has changed with the if before */
  if ((windowWidth < windowHeight) && (imageHeight < postThumbnailHeight)) {
    $('#postThumbnail').find('img').css('width', 'auto%');
    $('#postThumbnail').find('img').css('min-height', '100%');
  }
}

$(window).on("load", imageFitToScreen);
$(window).on("resize", imageFitToScreen);

I double the var imageHeight and var imageWidth before they are called again because they change within the first and third IF.

I don't know if it's important for you to know that I'm changing the #postThumbnail width/height before I run this script.

function refreshDynamicSize() {
  $('#content').find('#postThumbnail').css('min-height', $(window).height() - $('header').height());
  $('#content').find('#postThumbnail').height($(window).height() - $('header').height());
  $('#content').find('#postThumbnailTitle').css('line-height', $(window).height() + 'px');
  $('#content').find('#extend').css('min-height', $('#postThumbnail').height());
}

$(window).on("load", refreshDynamicSize);
$(window).on("resize", refreshDynamicSize);

What I'm looking for is an optimisation of the code as it works on refresh but not on resize.

It might surely be really simple (like change in execution order, or an "on.load" something...).

This seems like the kind of thing that should be done purely in CSS using media queries, specifically orientation.  When the window is taller than it is wide, the rules inside

@media all and (orientation: portrait) { … }

… would apply.  When the window is wider than it is tall, it would be

@media all and (orientation: landscape) { ... }

Furthermore, I would consider that image to be background-image styling for
The post title
 rather than an  element in its own right.  The scaling should be handled by a background-size rule.


Ansible playbook to generate webserver folder structure with users and projects I try to generate with ansible a folder structure for a webserver with users and linked projects.

The playbook works. But with more users and projects it gets quite complex to handle.
How can I simplify my code or vars sections?

I read a hint about using blocks so that all tasks inside it could use the same loop.
Is that the way to go?

The docs on blocks don't have a lot of examples. Any hint or link to examples is most appreciated.
Of course if you have any other pointers, please let me know.

---
- hosts: localhost
  become: yes
  become_method: sudo

#  check_mode: yes
  vars:
    project_base_path: /usr/src/project
    www_base_path: "/var/www/{{ansible_hostname}}"

    projects:
      mars: "{{ project_base_path }}/mars"
      venusnew: "{{ project_base_path }}/venus/new"
      venusold: "{{ project_base_path }}/venus/old"

    users:
      goku:
        present: true
        pw: #vault
      luffy:
        present: true
        pw: #vault

    user_projects:
      - uname: goku
        uproject:
          - lname: mars
            spath: "{{ projects.mars }}"
      - uname: luffy
        uproject:
          - lname: venusnew
            spath: "{{ projects.venusnew }}"
          - lname: project
            spath: "{{ projects.venusold }}"
  tasks:
    - name: check www path | Check if the path is available or create it
      file:
        path: "{{ www_base_path }}"
        owner: www-data
        group: www-data
        state: directory

    - name: check user www directory | Check if the directory of the user is available or create it
      file:
        owner: www-data
        group: www-data
        state: directory
        path: "{{ www_base_path }}/{{ item.key}}"
      with_dict: "{{ users }}"

    - name: check projects in usr src | Check if the directory of the user is available or create it
      file:
        owner: www-data
        group: www-data
        state: directory
        path: "{{ item.value}}"
      with_dict: "{{ projects }}"

    - name: link projects to users | Create links for the users
      file:
        state: link
#        force: yes
        owner: www-data
        group: www-data
        src:  "{{ item.1.spath }}"
        dest: "{{ www_base_path }}/{{ item.0.uname }}/{{ item.1.lname }}"
      with_subelements:
        - "{{ user_projects }}"
        - uproject

I can think of 3 options.

Using a role

As you work in Ansible progresses you'll find the number of tasks and variables harder to manage as a single file.  You'll likely want to create an ansible role.

ansible-galaxy init <your role name>

This will create a structure of folders with defaults, vars, files, handlers, tasks, meta and templates.

You can then separate out your variables into separate files while keeping them originally defined in defaults/main.yml in order to easily override them while controlling how there initialized.
Force 'manual' loading of vars conditionally within the role by overriding defaults/main.yml with custom logic in tasks.

This can apply to stand alone task files also, but I prefer using roles.
Here are two examples:

# including vars that are outside your role on inventory dir path level.
- include_vars:
   file: "{{inventory_dir | dirname}}/group_vars/rdu.yml"
  when: env == 'rdu'

# including vars that are within your role to a var called dataset.
- include_vars:
   file: "{{role_path}}/defaults/datasets/{{dataset_name}}.yml"
  when: dataset_name is defined

You can also use the vars folder within the role but I prefer to use defaults/main.yml to set defaults and then write over the defaults later.
If the values are static and should not be changed then you can consider using vars/main.yml this assumes you are using a role.
Put variables which are associated with a specific group under your group_vars and then make the association in your inventory file.

See http://docs.ansible.com/ansible/latest/intro_inventory.html#group-variables

My suggestion is to create a role, and then organize your variables into similar groups where possible and keep defaults in the role/role-name/defaults.main.yml and then override them based on the logic of your variables.

So looking at your code it seems that each project (mars, venusnew, and venusold) could like get there own yml file.  Using conditional logic you can decide which vars to load.


Removing comments from a C source file I wrote this program to remove comments from a C source file, accepting a file name from the command prompt. Let me know if I missed anything or if there are any improvements that can be made in the program.

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

void m_cmnt( FILE *fp )
{
    int prev=0 , ch ;

    while ((ch=getc(fp))!=EOF)
    {
        if ( prev== '*' && ch == '/')
            return ;
        else
        prev=ch ;
    }
}

void s_cmnt( FILE *fp )
{
    int ch ;
    while ( (ch=getc(fp))!='\n' && ch!=EOF )
        ;
}

int main ( int c , char **arr )
{
        FILE *fp , *np ;
        int ch , prev=0 ;
        bool String=0 ;

        fp = fopen(arr[1] , "r") ;
        np = fopen("temp.txt" , "w") ;

        if (fp==NULL )
        {
            printf ("Invalid/No Filename given as Argument ! \n") ;
            return 1 ;
        }
        while ((ch=getc(fp))!=EOF )
        {
            /* file pointer currently not inside a string */
            if ( !String )
            {
                if ( ch=='/' )
                {
                    prev=ch ;
                    ch= getc(fp) ;
                    switch(ch)
                    {
                        case '*'  : m_cmnt( fp) ;
                                     break ;
                        case '/'  : s_cmnt( fp) ;
                                     break ;
                        default   :  putc(prev , np) ;
                                     putc(ch , np) ;
                                     break ;
                    }
                }
                else putc( ch ,np ) ;
            }
            else  putc(ch , np) ;

            if ( ch=='\"')
                String = !String ;
            prev = ch ;
        }

    fclose(fp) ;
    fclose(np) ;
    remove(arr[1]) ;
    rename( "temp.txt" , arr[1] ) ;
    return 0 ;
}

Bug: String escaping

In C, "foo \" bar" is a legal string, but it will confuse the state of your program (so " bar" will be seen as not in a string, while everything after the end of the string will be seen as inside a string). You need to handle at least the escape sequence \" within strings.

Bug: Comments as token separators

If you have the (admittedly weird) C:

int/**/bar;

That will parse as int, bar, ; (declaration of an integer called bar). With comments removed as by this program, it will come out as:

intbar;

Which is probably a parse error.

C syntax should always allow arbitrary whitespace around comments, so this could be fixed by always emitting some whitespace after removing a comment. That could make the output rather ugly, so if you wanted to be 'clever' you could try to only insert extra whitespace when necessary.

Bug: potentially out-of-bounds access through arr[1]

c should be checked to make sure it's greater than 1 before accessing through arr[1].

Suggestion: State machine

The above-mentioned bug is part of a larger issue: there's a lot of "hidden" state to do with things like "what was the previous character" etc.

The nice thing about most programming languages (including C) is that they are designed so that lexical analysis (which is what you need to do to remove comments) is very simple, and can be done with a finite-state automaton (often just called a state machine).

In some sense your program is already a finite-state machine, with the state being the combination of the String flag, the prev variable, and which function you're in---but it's a little hard to keep track of. Introducing an explicit state machine will make the code clearer, and make it easier to handle cases like escaped quotes in strings.

There are various implementation patterns for state machines; a common one for small/simple state machines, such as this one, is to use an enum to name some states:

enum { START, COMMENT_START, COMMENT, COMMENT_END, LINE_COMMENT, STRING, STRING_ESCAPE, };

and then use a switch statement to behave differently depending on the state:

int state = START;

...

switch (state) {
case START:
    if (c == '/') state = COMMENT_START;
    /* other branches */
    break;
case COMMENT_START:
    if (c == '*') state = COMMENT;
    else if (c == '/') state = LINE_COMMENT;
    /* other branches */
    break;
    .
    .  /* etc */
    .
}

Convention: standard names for arguments to main

The almost universal convention is for the signature of main to be

int main(int argc, char *argv[])

There isn't anything inherently wrong with using different names for those variables, but using argc/argv makes it slightly easier for other people to read.

Pedantry: whitespace

The use of whitespace around punctuation seems a little...haphazard. (For example, some parentheses have spaces around them, while others have none; some commas have spaces both before and after, some have one, some have none). Regardless of which style you prefer (which is an opinion thing), the inconsistency makes it more difficult to read.

Feature: not-in-place modification

A useful behaviour (and the behaviour I'd expect) would be to be able to call

commentremover foo.c

and have it print the comment-removed version of the program to STDOUT, without clobbering foo.c.


Find index of the nearest larger number of a number The task:

  Given an array of numbers and an index i, return the index of the
  nearest larger number of the number at index i, where distance is
  measured in array indices.

  For example, given [4, 1, 3, 5, 6] and index 0, you should return 3.

  If two distances to larger numbers are the equal, then return any one
  of them. If the array at i doesn't have a nearest larger integer, then
  return null.

  Follow-up: If you can preprocess the array, can you do this in
  constant time?

My solution:

const nearestLargestNumber = (arr, idx1) => {
  const num = arr[idx1];
  let nearestLargest;
  const findIdxOfNearestLargest = (idxOfNearestLargest, item, idx2) => {
    if (item > num &&
       (idxOfNearestLargest === null || nearestLargest > item )) {
      nearestLargest = item;
      idxOfNearestLargest = idx2;
    }
    return idxOfNearestLargest;
  };

  return arr.reduce(findIdxOfNearestLargest, null);
};

console.log(nearestLargestNumber([4, 1, 3, 5, 6], 0));

EDIT: I mistook "nearest" to mean "numerically closest" but the problem asks for minimum distance from the index.  As the other answer points out, there are faster methods than visiting every element.

The answer to the followup question is "yes."

"Larger" is ambiguous: if you ask someone for a "large negative number" they probably don't answer "negative one."   Attribute this to sloppiness on the author's part, unless you've reason to suspect trickery.

I'm not a fan of these variable names: idx1 should be idx0, or i0 or initialIndex.  nearestLargest isn't the largest anything and nearestLarger would be more accurate.  num is a number, but so is everything else—maybe minimum or baseline or mustBeGreaterThan. nearestLargestNumber contains an index, not a number, while the number is held in nearestLargest.

I suggest one common prefix for your index variables and another prefix for value variables (though you don't really need more than one).

const nearestGreater = (arr, i0) => arr.reduce(
        (iNearestGreater, val, i) =>
            ( val > arr[i0] && ( iNearestGreater===null || val < arr[ iNearestGreater ] ) ) ?
                i : iNearestGreater,
        null
    );


Tic Tac Toe in Swing This is a Tic Tac Toe game I wrote in Java (Swing). It fully works when detecting the winner or a tie. I'm wondering if there's any way I can improve it or clean it up.

I'm trying to achieve a 3 by 3 simple Tic Tac Toe game. The first player is X and the second player is O.

My X and O buttons are images. When a button is pressed, the value goes up. If it's odd, it's X. If it's even, it's O.

Because I didn't know how to compare images, I stored a parallel String array to compare the values. Should I be using a 2-D array?

/* Tic Tac Toe */

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class TicTacToe implements ActionListener {
    JFrame window = new JFrame("Tic Tac Toe");
    JButton b[] = new JButton[9];

    String letter = "";
    ImageIcon X;
    ImageIcon O;
    ImageIcon ltr;
    int value = 0;
    boolean win = false;
    String[] letters = new String[9];

    public TicTacToe() {
        // Initialize Array
        for (int i = 0; i < 9; i++) {
            letters[i] = "";
        }

        // Assign images
        X = new ImageIcon(getClass().getResource("X.png"));
        O = new ImageIcon(getClass().getResource("O.png"));
        // Create the Window
        window.setSize(500,500);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new GridLayout(3,3));

        // Add Buttons
        for (int i = 0; i < 9; i++) {
            b[i] = new JButton();
            window.add(b[i]);
        }

        // Add ActionListener
        for (int i = 0; i < 9; i++) {
            b[i].addActionListener(this);
        }

        window.setVisible(true);
    }

    public void actionPerformed(ActionEvent a) {
        value++;
        // Who's Turn
        if (value % 2 == 1) {
            ltr = X;
            letter = "X";
        }
        if (value % 2 == 0) {
            ltr = O;
            letter = "O";
        }

        // Display Letters
        for (int i = 0; i < 9; i++) {
            if (a.getSource() == b[i]) {
                b[i].setIcon(ltr);
                b[i].setDisabledIcon(ltr);
                b[i].setEnabled(false);
                letters[i] = letter;
            }
        }

        // Who Won

        // Horizontal
        if (letters[0].equals(letters[1]) && letters[1].equals(letters[2]) && !letters[0].equals("")) {
            win = true;
        } else if (letters[3].equals(letters[4]) && letters[4].equals(letters[5]) && !letters[3].equals("")) {
            win = true;
        } else if (letters[6].equals(letters[7]) && letters[7].equals(letters[8]) && !letters[6].equals("")) {
            win = true;
        }

        // Vertical
        if (letters[0].equals(letters[3]) && letters[3].equals(letters[6]) && !letters[0].equals("")) {
            win = true;
        } else if (letters[1].equals(letters[4]) && letters[4].equals(letters[7]) && !letters[1].equals("")) {
            win = true;
        } else if (letters[2].equals(letters[5]) && letters[5].equals(letters[8]) && !letters[2].equals("")) {
            win = true;
        }

        // Diagonal
        if (letters[0].equals(letters[4]) && letters[4].equals(letters[8]) && !letters[0].equals("")) {
            win = true;
        } else if (letters[2].equals(letters[4]) && letters[4].equals(letters[6]) && !letters[2].equals("")) {
            win = true;
        }

        if (win) {
            JOptionPane.showMessageDialog(null, "Player " + letter + " wins!");
            for (JButton i : b) {
                i.setEnabled(false);
            }
        } else if (!win && value == 9) {
            JOptionPane.showMessageDialog(null, "The game ended in a tie.");
        }
    }

    public static void main(String[] args) {
        new TicTacToe();
    }
}

Change your fields' visibility to private as others object shouldn't know (nor care) about the inner working of your TicTacToe, this is known as Encapsulation
Turn the buttons into a 2D array and make the name clearer (b isn't really informative ^^)
Avoid magic numbers (talking about 3, 9, 500 which can be replaced by GRID_LENGTH, GRID_SIZE...) : this way, not only it's clearer for a newcomer but if you ever change one value it'll be updated everywhere
I don't think there is any point in making win a field, it's only used like a local variable
Turn the // WHO WON part into a method that'll do all the checks for you and return you a boolean : in general, calling multiple short methods makes for a clearer code as the code is more declarative this way (and it removes useless comments)
For same reasons as above, turn the victory message printing into its own method
Use a for loop to check every lines and every columns without caring for their size, that'll make for a clearer code and it'll also be easier to modify the current behaviour (if you ever want to allow for differents grid size)
You may want to not compute diagonals unless someone has checked one of the diagonal value, it'll probably slighty increase cyclomatic complexity though so it's up to you ;)
You forgot to disable the buttons if the game ends in a tie... in the same way as points 5 and 6, creating a disableTicTacToe or disableFrame method may be neat
Maybe you should consider offering the players a new game when one has ended


WordPress: multiple loops I have two loops on my page - each with their own category. It works, but I don't know if this is the best practice as I'm pretty new to this stuff.

<?php $my_query = new WP_Query( 'category_name=news&posts_per_page=3' );
        while ( $my_query->have_posts() ) : $my_query->the_post();
                $do_not_duplicate[] = $post->ID; ?>
                <!-- Do stuff... -->
<?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

<?php $second_query = new WP_Query( 'category_name=reviews&posts_per_page=4' );
        while ( $second_query->have_posts() ) : $second_query->the_post();
                $do_not_duplicate[] = $post->ID; ?>
                <!-- Do stuff... -->
<?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

The only thing that changes between the first and second half is the query parameters.

<?php

foreach (array('news' => 3, 'reviews' => 4) as $category => $posts_per_page) {
    $wp_query = new WP_Query(
        "category_name=$category&posts_per_page=$posts_per_page"
    );
    while ( $wp_query->have_posts() ) {
        # etc.
    }
}

?>


Python merge sort for a list containing distinct values This code below is what I think should be the implementation of merge sort in Python and it works as expected. It sorts the given list, where we can safely assume that all values are distinct. But after considering some online implementations I am doubtful about mine. So the base question is "Is this even Merge sort?".

def merge(arr):
    # base case
    length = len(arr)
    half = length//2
    if length == 1 or length == 0:
        return arr
    # recursive case
    firstHalf = merge(arr[:half])  # sort first half
    secondHalf = merge(arr[half:])  # sort second half
    length_firstHalf = len(firstHalf)
    length_secondHalf = len(secondHalf)
    sortedList = []

    i, j = 0, 0  # variables for iteration
    while i != length_firstHalf and j != length_secondHalf:  # add elements into the new array until either of then two sub arrays is completely traversed
        if firstHalf[i] > secondHalf[j]:
            sortedList.append(secondHalf[j])
            j += 1
            continue
        if firstHalf[i] < secondHalf[j]:
            sortedList.append(firstHalf[i])
            i += 1
    return(sortedList + firstHalf[i:] + secondHalf[j:])  # return the array after adding whats left of sub array which wasnt completely traversed

To address your immediate concern, yes it is a merge sort.

The naming is quite unusual. The procedure you call merge does the merge sort, and should be called so. The merge phase of the merge sort is done by the

    while i != length_firstHalf and j != length_secondHalf:

loop and the subsequent return. It is advisable to factor it out into a standalone merge procedure. OTOH I don't endorse a complicated return expressions.
It is unclear why do you limit yourself to the distinct values. The second if clause may be safely made into an else, and there is no more worries. Notice that your first comparison firstHalf[i] > secondHalf[j] is the way to handle duplicates.
Computing half doesn't belong to the base case.
As a nitpick, length == 1 or length == 0 is a long way to say length < 2.


Performance of Median routine using min performs abysmally I am writing a routine to calculate median using the minimum of the numbers and then changing the value of the minimum to a large value outside the range of numbers (assuming you know the nature of the numbers).  I know I could use many other proven techniques, but have chosen to play around with this one.

I don't see why the performance is poor. There are 3 loops, however, only two are nested at any one time.  There is no sorting involved, only finding the first occurrence of a minimum and making the new value outside the range.  If it finds the same number a second time, it ignores the number until the next iteration.  It iterates for half of the total series before the median is found.  It works dandy except for the speed.

How do I improve the efficiency of this code?

float trashMin(float array[], unsigned int length, float median){
    //what we want to do in this routine is find the lowest in the array
    //we then make the lowest number, the same as the highest possible number and
    //after iteratively going through the array 1/2 of the full length we will find the median

    unsigned int halflength = (length / 2) + 1;
    unsigned int i = 0;
    unsigned int j = 0;
    unsigned int k = 0;
    float highNumber = 999.0;//this is an arbitrary number, well outside of range of the number series
    float median = 0;

    for (i = 0; i < halflength; ++i)
    {
        float lowestInArray = array[0];
        bool firstTime = true;// is it the first time we see this number

        for (j = 0; j < length; ++j)
        {// find the lowest and highest number in the array
            float comparitor = array[j];
            lowestInArray = (lowestInArray < comparitor) ? lowestInArray : comparitor;
        }//end j

        // now that we know which is the smallest number, eliminate only 1st occurance of it
        for (k = 0; k < length; ++k)
        {
            float comparitor = array[k];
            if (comparitor == lowestInArray && firstTime == true)
            {
                array[k] = highNumber;
                firstTime = false;
            }
        }//end k
        median = lowestInArray;
    }//end i
    return median;
}

The structure of your function is

for (i = 0; i < halflength; ++i)    // N/2 iterations
{
    ...

    for (j = 0; j < length; ++j)    // N iterations
    {
        ...
    }

    for (k = 0; k < length; ++k)    // N iterations
    {
        ...
    }
}

this makes \$ N/2 (N+N) = N^2\$ iterations, where \$ N \$ is the length
of the array.

There are small improvements possible: In the k-loop, if a
matching element has been found, you can break-out early:

    // now that we know which is the smallest number, eliminate only 1st occurance of it
    for (k = 0; k < length; ++k)
    {
        float comparitor = array[k];
        if (comparitor == lowestInArray)
        {
            array[k] = highNumber;
            break;
        }
    }

But actually this loop is not needed at all: In the j-loop,
remember the index where the lowest element has been found,
and then set to a "large" number directly:

    float lowestInArray = array[0];
    unsigned int indexOfLowest = 0;

    for (unsigned int j = 1; j < length; ++j) {
        float comparitor = array[j];
        if (comparitor < lowestInArray) {
            lowestInArray = comparitor;
            indexOfLowest = j;
        }
    }
    array[indexOfLowest] = FLT_MAX;

Also FLT_MAX is a better choice than 999.0 for a "large number".
This reduces the number of iterations by a factor of 2.

  If it finds the same number a second time, it ignores the number until
  the next iteration.

Yes, but the j-loop still traverses over the entire array. Instead of
replacing the found minimal element by FLT_MAX, you could replace it
by the last array element, and then reduce the upper bound
for the j-loop accordingly:

for (unsigned int i = 0; i < halflength; ++i)
{
    float lowestInArray = array[0];
    unsigned int indexOfLowest = 0;

    for (unsigned int j = 0; j < length - i; ++j) {
        float comparitor = array[j];
        if (comparitor < lowestInArray) {
            indexOfLowest = comparitor;
            indexOfLowest = j;
        }
    }
    array[indexOfLowest] = array[length - i - 1];
    median = lowestInArray;
}

This reduces the number of iterations again. But it is still
\$  O(N^2) \$, and I doubt that much more is possible with this
algorithm.

As you already noticed, sorting the array first and then taking
the middle element is faster. This is no surprise since sorting can
typically be done in \$  O(N \log N) \$ operations.