Number to words in left to right direction I have faced this question in an interview:

If we enter a number it will convert into individual strings and display in same order.
Ex: If I enter 564 then the output should be FIVE SIX FOUR.

I have written the following working code (of course it has some limitations).  Suggest any possible ways of optimizing this code.
public class NoToWord {

    public static void main(String[] a)
    {
        int no = 0;
        String[] words= new String[]{"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
        String[] word=new String[10];

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            no = Integer.parseInt(br.readLine());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int i,j;
        j=0;
        while(no>0){
            i = no%10;
            no /= 10;
            word[j] = words[i];
            j++;
        }
        for(int k= word.length;k>0;k--)
        {
            System.out.println(word[k-1]+" ");
        }
    }
}

This code:

int i,j;
j=0;
while(no>0){
    i = no%10;
    no /= 10;
    word[j] = words[i];
    j++;
}
for(int k= word.length;k>0;k--)
{
    System.out.println(word[k-1]+" ");
}

can be drastically simplified to:

String numbers = String.valueOf(no);
for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}

Or you may save save the user input as String (but make sure it only contains digits). You will have something like this:

 String numbers = br.readLine();
 for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}


JPEG metadata processor I am looking to make the below code a bit more efficient / OOP based. As can be seen by the X, Y & Z variables, there is a bit of duplication here. Any suggestions on how to make this code more pythonic?

The code functions as I wish and the end result is to import the dictionary values into a MySQL database with the keys being the column headers.

import fnmatch
import os
import pyexiv2

matches = []
dict1 = {}

# The aim of this script is to recursively search across a directory for all
# JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2
# module to extract all EXIF, IPTC and XMP data from the image. Once extracted
# the key (ie. "camera make" is generated and it's respective value
# (ie. Canon) is then added as the value in a dictionary.
for root, dirnames, filenames in os.walk('C:\Users\Amy\Desktop'):
  for filename in fnmatch.filter(filenames, '*.jpg'):
      matches.append(os.path.join(root, filename))
      for entry in matches:
          metadata = pyexiv2.ImageMetadata(entry)
          metadata.read()
          x = metadata.exif_keys
          y = metadata.iptc_keys
          z = metadata.xmp_keys
          for key in x:
              value = metadata[key]
              dict1[key] = value.raw_value
          for key in y:
              value = metadata[key]
              dict1[key] = value.raw_value
          for key in z:
              value = metadata[key]
              dict1[key] = value.raw_value
              print dict1

import fnmatch
import os
import pyexiv2

matches = []
dict1 = {}

dict1 isn't a great name because its hard to guess what it might be for.

# The aim of this script is to recursively search across a directory for all
# JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2
# module to extract all EXIF, IPTC and XMP data from the image. Once extracted
# the key (ie. "camera make" is generated and it's respective value
# (ie. Canon) is then added as the value in a dictionary.
for root, dirnames, filenames in os.walk('C:\Users\Amy\Desktop'):

Your code will be a bit faster if you put stuff into a function rather than at the module level.

  for filename in fnmatch.filter(filenames, '*.jpg'):
      matches.append(os.path.join(root, filename))
      for entry in matches:

ok, you add each file you find to the matches. But then each time you go over all the matches. I doubt you meant to do that. As its stand, you are going to look at the same file over and over again

          metadata = pyexiv2.ImageMetadata(entry)
          metadata.read()
          x = metadata.exif_keys
          y = metadata.iptc_keys
          z = metadata.xmp_keys

x y and z aren't great variable names. But its seems you aren't really interested in them seperately, just in all the keys. In that case do

keys = metadata.exif_keys + metadata.iptc_keys + metadata.xmp_keys

to combine them all into one list. (I'm guessing as to what exactly these keys are but, I think I it'll work.)

          for key in x:
              value = metadata[key]
              dict1[key] = value.raw_value

I'd combine the two lines

dict1[key] = metadata[key].raw_value

          for key in y:
              value = metadata[key]
              dict1[key] = value.raw_value
          for key in z:
              value = metadata[key]
              dict1[key] = value.raw_value
              print dict1

If you put combine x,y,z as above, you'll only need the one loop


What takes precedence: readability or elimination of side effects? I have a method:

  def removeExpiredCookies(jar: CookieJar): CookieJar = {
    val currentDate = System.currentTimeMillis / 1000L
    jar.filter(_._2._2 > currentDate)
  }

You use said method like so.

var cookieJar = new CookieJar
cookieJar = removeExpiredCookies(cookieJar)

That method has no side effects. But it's used inside a class:

class CookieManager {
      type ExpiryDate = Long
      type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]

      var cookieJar = new CookieJar

      private def removeExpiredCookies(jar: CookieJar): CookieJar = {
        val currentDate = System.currentTimeMillis / 1000L
        jar.filter(_._2._2 > currentDate)
      }

      def getCookie(domain: String): Set[Cookie] = {
        cookieJar = removeExpiredCookies(cookieJar)
        cookieJar.find(_._1 endsWith (domain))
      }
}

Is it better to write the method such as above or to have a more succinct and readable code but with side-effecting methods? I'm guessing as this is encapsulated inside a class, this is actually "better" for maintainability but it is not as pure functional programming. It's an imperative style. However, the strongest argument against this is that it's more difficult to test as the tests are not as isolated.

class CookieManager {
      type ExpiryDate = Long
      type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]

      var cookieJar = new CookieJar

      private def removeExpiredCookies {
        val currentDate = System.currentTimeMillis / 1000L
        cookieJar = cookieJar.filter(_._2._2 > currentDate)
      }

      def getCookie(domain: String): Set[Cookie] = {
        removeExpiredCookies() //bracket to indicate side effect
        cookieJar.find(_._1 endsWith (domain))
      }
}

(I'm making my comment into an answer.) You can separate everything that is static (not using the state of instances of CookieManager) into a companion object (and import the object at the beginning of the class for convenience). This way, it is clear what functions use this directly or indirectly (by accessing class variables). This often helps me make my code clearer, and prevents stupid mistakes such as confuse class variables with function arguments etc.

class CookieManager {
  import CookieManager._

  var cookieJar = new CookieJar

  def getCookie(domain: String): Set[Cookie] = {
    cookieJar = removeExpiredCookies(cookieJar)
    cookieJar.find(_._1 endsWith (domain))
  }
}

object CookieManager {
  type ExpiryDate = Long
  type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]

  private def removeExpiredCookies(jar: CookieJar): CookieJar = {
    val currentDate = System.currentTimeMillis / 1000L
    jar.filter(_._2._2 > currentDate)
  }
}


C++ thread-safe averaging Although having very little C++ experience, I was tasked to implement several statistics objects that are safe to be asynchronous accessed by different threads, that collect data in relatively small memory caches and do the math when asked. Many of those I need to write are based on averaging, so help me by inspecting  basic averaging class. I just hope to avoid any strategic errors in design of my cargo-cult code-gluing efforts.

#include <mutex>

template <typename T, int N> class Average {
    T data[N];
    int head;
    double avg;
    int itr;
    int counter;
    std::mutex _mutex;

public:

Average() : head(0), avg(0.), itr(0), counter(0) {
};

void empty() {
    std::unique_lock<std::mutex> lock(this->_mutex);

    head = 0;
    avg = 0.;
    itr = 0;
    counter = 0;
}

int count() {
    std::unique_lock<std::mutex> lock(this->_mutex);

    return counter;
}

void push(T value) {
    std::unique_lock<std::mutex> lock(this->_mutex);

    counter++;
    data [head] = value;
    double tmp = 0.;

    if (++head == N) {
        head = 0;

        for (int i = 0; i < N; i++) {
            tmp = tmp + data[i];
        }

        tmp = tmp / N;
        avg = (avg * itr) + tmp;
        itr += 1;
        avg = avg / itr;
    }
}

double average() {
    std::unique_lock<std::mutex> lock(this->_mutex);

    double tmp = 0.;

    if (head == 0){
        if (itr == 0) return 0.0;
        return avg;
    }

    for (int i = 0; i < head; i++) {
        tmp = tmp + data[i];
    }

    if (itr == 0) return tmp / head;

    tmp = tmp/N;
    return ((avg * itr) + tmp) / ((double)itr + (double)head/(double)N);

    }
};

As an usage example, by extending the Average class, I implemented a RunningAverage class which averages only let say last N pushed values. I got a worker pool that perform Monte Carlo simulation where it is preferred to maintain step acceptance rate 0.5+/-0.1 and when rate falls outside, I adjust model parameters. So I got something like:

#define ACCEPT_STEP 1
#define DECLINE_STEP 0

RunningAverage <float, ACC_BUFFER_LEN> global_acceptance_rate;

and thread do something like:

global_acceptance_rate.push(ACCEPT_STEP); // or
global_acceptance_rate.push(DECLINE_STEP);

So this allows me to dynamically control simulation.

Code

Prefer std::array over plain C-style arrays. It has more normal copy / assignment semantics (which admittedly isn't relevant here), but also allows you to access the size directly from the array.
Naming:

head is usually used for the first populated element (of a list, for example). In this case it refers to the first empty space instead, so next might be a more appropriate name.
avg, itr: prefer full names over abbreviations.
_mutex: the underscore prefix is usually used to denote a member, but this is the only member that has one?
sum would be a better name than tmp. It's also better to declare variables as close as possible to the point of use.

double sum = 0.;
for (auto i : data) // range-based for loop for brevity
    sum += i;

Sum loops like this may also be written using the std::accumulate algorithm:

    #include <numeric>
    ...
    using std::begin;
    using std::end;
    auto sum = std::accumulate(begin(data), end(data), 0.0);

When referring to _mutex in member functions, the code uses this->_mutex. Which rather defeats the point of using the underscore prefix. No other members are referred to with this->.
The itr and head variables are unnecessary, as they can both be trivially calculated: itr = counter / N; head = counter % N;
Getter functions, e.g.count(), average() should be const. Note that for this to compile, the mutex member must then be made mutable (one of the few instances where mutable is to be recommended).

Design

This appears to be a Cumulative Moving Average. Data storage is actually unnecessary for such an average! (Which can be seen in the existing code since  the data is periodically overwritten. There is no advantage in creating an Average<double, 1297> over an Average<double, 1>. The average() function will return the same result for the same data regardless.)

Since the data is private and cannot be accessed externally, it becomes irrelevant... As such, most of the code can be deleted! :)

class CumulativeMovingAverage
{
    std::size_t n;
    double average;

public:

    CumulativeMovingAverage(): n(0u), average(0.0) { }

    std::size_t get_count() const
    {
        return n;
    }

    double get_average() const
    {
        return average;
    }

    void update(double x)
    {
        // formula straight from wikipedia:
        //average = (x + n * average) / (n + 1u);
        //++n;

        // improved formula from Toby Speight (see comments):
        ++n;
        average += (x - average) / n;
    }
};

Thread safety / templateyness is left as an exercise to the reader (the original code looks correct to me).


Determine whether a word appears in a sentence Given an array of words representing a sentence and a word to search for, the method must determine whether the word appears in the sentence.

Specifications

Case insensitive.
The arguments are never null.
The sentence is in the English language.

/**
 * A case-insensitive search on a sentence to find whether a given word can be found in it. It
 * keeps certain punctuation in mind.
 *
 * @param  aSentence An array of words forming a sentence. Cannot be {@code null}.
 * @param  aWord     The word to search for. Cannot be {@code null}.
 *
 * @return {@code true} if the word appeared at least once in the sentence, {@code false}
 *         otherwise.
 */
public boolean sentenceContainsWord(final String[] aSentence, String aWord)
{
  // The search is case-insensitive
  aWord = aWord.toLowerCase();

  // Loop through the words in the sentence
  for (int i = 0; i < aSentence.length; i++)
  {
    String sentenceWord = aSentence[i];

    // If the word in the sentence matches, return immediately
    if (sentenceWord.toLowerCase().equals(aWord))
    {
      return true;
    }

    // The word could end with punctuation like a comma or a dot
    int lastSentenceWordIndex = sentenceWord.length() - 1;
    String lastCharacter = Character.toString(sentenceWord.charAt(lastSentenceWordIndex));
    if (lastCharacter.matches("[.,:;]") && sentenceWord.substring(0, lastSentenceWordIndex).equals(aWord))
    {
      return true;
    }
  }

  return false;
}

The String class provides the method .equalsIgnoreCase(). It seems to me, calling .toLowerCase() and then .equals() has to process the string twice, but could be done in a single run.

It is unclear how well the sentence is processed before it enters the method as array. I will be a little optimistic in my assumptions.

You can give it a cleaner structure using streams [if you are using Java 1.8 at least]. It provides a method .noneMatch(predicate) which is short-circuiting just as your loop is now. Using streams makes it easy to add a cascade of string preprocessing steps before the final comparison. Removing punctuation as you have it now, it could be written as follows:

import java.util.Arrays;

public static boolean sentenceContainsWord(final String[] aSentence, final String aWord)
{
    return !Arrays.stream(aSentence)
                  .map((w) -> w.replaceAll("\\.|,|:|;", ""))
                  .noneMatch((w) -> w.equalsIgnoreCase(aWord));
}

My optimistic assumption here is that there is no punctuation in between a word which might result from a too simplistic tokenisation (e.g. .split(" ")). Using .replaceAll() removes a lot of the clutter around finding trailing punctuation and extracting substrings.

Resources:

Java Doc:
Stream::noneMatch
Java Doc:
String::equalsIgnoreCase
Java Doc:
String::replaceAll


Replace keys in values with key->values from same dictionary I have a dictionary whose values may contain keys that are already in the dictionary. What we are actually talking about are parameters. Sometimes a parameter is defined by a number plus another parameter, etc.

It looks something like this:

paramDict = {'ad': '2*dmcg/factor*(xw/factor)',
'dmcg': 2.05e-07,
'dxwn_3vna': 10.0,
'factor': 1,
'xw': '0+dxwn_3vna'}

If there is another parameter in the value it is of type string, otherwise it is an int or a float. After the replacing I want the value to be a float.

The code I wrote to solve this problem is this:

    for _ in range(10):
        for key, value in paramDict.items():
            if type(value) is str:
                matchList = re.findall('[a-z]\w*', value)
                matchList = [match for match in matchList if match != 'e']
                for match in matchList:
                    param = paramDict[match]
                    paramDict[key] = value.replace(match, str(param))
                try:
                    paramDict[key] = eval(paramDict[key])
                except:
                    pass

It works as far as I can tell, but it just doesn't feel right to just repeat the whole process a finite number of times and hope that all the strings have been replaced. Is there a safer way?

Well what you want there is evaluating expressions while keeping track
of dependencies, so you should definitely not implement it via regular
expressions and hoping that running it ten times is enough.

The best way in Python would probably be using the
ast module to parse and
figure out the referenced variables, then calculate dependencies and
evaluate the parsed expressions via
compile
and eval
while passing in the referenced variables in the local parameter.

That way you make sure that the expressions are actually valid, you can
use Python expressions and you can (and should) also detect cycles in
the specification.

Below is a sketch how to do that, not saying that is the best code,
please edit or comment with improvements, I couldn't find a good example
while searching.

import ast, _ast

params = {
    'ad': '2*dmcg/factor*(xw/factor)',
    'dmcg': 2.05e-07,
    'dxwn_3vna': 10.0,
    'factor': 1,
    'xw': '0+dxwn_3vna',
    'foo': 'bar',
    'bar': 'foo'
}

parsed = {}

for key, value in params.iteritems():
    parsed[key] = value

    if type(value) in (str, unicode):
        parsed[key] = ast.parse(value, mode="eval")

evaluated = {key: value for key, value in parsed.iteritems()}

So at this point the evaluated dictionary is mostly a copy of the
params, except that expressions have been parsed.

def referenced(code):
    return [node.id for node in ast.walk(code) if "id" in node._fields]

referenced returns a list with the names of referenced variables in
the expression.

evaluating = []

def resolve(key, value):
    if key in evaluating:
        raise Exception("Loop while evaluating {}".format(key))

    if type(value) is not _ast.Expression:
        evaluated[key] = value
        return value

    evaluating.append(key)

    locals = {name: resolve(name, evaluated[name]) for name in referenced(value)}

    result = eval(compile(value, "<unknown>", "eval"), globals(), locals)

    evaluated[key] = result

    evaluating.pop()

    return result

resolve evaluates the expression recursively but also keeps track of
the stack (in evaluating), so it can detect cycles by looking up the
current variable.  It also assigns the results immediately, so in
further invocations it will return early (the not _ast.Expression
case).

for key, value in parsed.iteritems():
    try:
        resolve(key, value)
    except Exception as exception:
        print ("Error while evaluating {}: {}".format(key, exception))

print(evaluated)

Lastly, iterate over all entries and try to evaluate them.


Calculating and displaying number statistics I'm writing a program which takes individual int inputs from the user and then outputs some details on the numbers (average, min, max and how many).
Input.readInt() is a method I made which simply reads an integer from the command line and returns it.

There are a few things I'd like to improve - for the average the float does not seem to work, it only holds prints out value to nearest integer. I'd also like to format this to always display 2 decimal places.
Is there any way to dynamically assign the size of the array? So I could enter more than 10 values?

I'm looking for advice on more efficient methods (both speed and code length), and any other general advice which could help me learn.

public class NumberStats {

    public static void main(String[] args) {
        int[] input = new int[10];
        int i;
        int total = 0;
        int min = 0;
        int max = 0;
        double average = 0;
        int count = 0;

        while (true) { // READ INPUTS
            System.out.print("Please enter a number: ");
            input[count] = Input.readInt();

            if (input[count] == 0) {
                break;
            } else if (input[count] < 0) {
                System.err.println("Error: " + input[count]
                        + " is not valid, exiting.\n");
                break;
            } else if (input[count] > 100) {
                System.out
                        .println("Warning: "
                                + input[count]
                                + " is not valid and will be excluded from final statistics.");
            }

            if (input[count] <= 100) { // IF INPUT VALID
                if (count == 0) {
                    min = input[count];
                    max = input[count];
                } else if (input[count] < min) {
                    min = input[count];
                } else if (input[count] > max) {
                    max = input[count];
                }
                count++;
                System.out.println("#" + count + ": " + input[count - 1]);
            }

        }
        if (count != 0) {
            for (i = 0; i < input.length; i++) { // CALCULATE SUM
                total += input[i];
            }
            average = total / count; // CALCULATE AVERAGE

            System.out.println("Total: " + total);
            System.out.println("Count: " + count);
            System.out.println("Min: " + min);
            System.out.println("Max: " + max);
            System.out.println("Average: " + average);
        } else {
            System.out.println("No valid input");
        }
    }
}

Please tell me this is for your personal benefit and that you aren't asking me to do your homework!

average = total / count;

total and count are both integers, so / performs integer division.  The result is then converted to a double.  This should fix your problem:

average = ((double) total) / ((double) count);

  Is there any way to dynamically assign the size of the array? so i
  could if i wish enter more than 10 values?

Use a java.util.ArrayList:

// old:
// int[] input = new int[10];
// new:
List<Integer> input = new ArrayList<Integer>();

  I'd also like to format this to always display 2 decimal places

Look at java.text.DecimalFormat.

General Advice

You do an awful lot of typing and a lot of dereferencing (and typing!).  Declare a local inVal parameter:

int inVal = 0;
...

inVal = Input.readInt();
if (inVal < 0) {
    ...
}
// Finally, after all your checks and calculations, add inVal to your array (or List):
input[count] = inVal;

The point of most loop syntax is to make the exit conditions for the loop obvious.  Instead of while (true) I'd like to see something like:

do {
    ...
} while (inVal >= 0)

I like that you calculate your max and min in the input loop.  You could count your total in that loop as well  instead of taking a second loop through your data.  Hmm...  If you do that, you don't need to use an array or a List, just inVal.

You have "magic numbers" 0 and 100.  Years from now when three other programmers have worked on this code, they may add a percentage calculation as x / 100 so that when you decide to increase your number of inputs to 200, you search-and-replace 100 with 200 you have broken your percentage calculation.  You should factor these out of your code:

public final int MAX_NUM_INPUTS = 100;
public final int INPUT_TOO_LOW_VALUE = 0;

This clarifies what you are comparing in a way that Magic Numbers could not:

if (count > MAX_NUM_INPUTS) ...

if (inVal <= INPUT_TOO_LOW_VALUE) ...

Hopefully no-one would ever calculate percent as x / MAX_NUM_INPUTS.  Now you can change these limits in one place without doing any search-and-replace.

UPDATE:

System.out.println...

Yeah, Java is funny about string concatenation.  If you have a non-final variable as part of a String, it can cause a bunch of nasty overhead.  For a little program like yours, it really doesn't matter what you do.  If it were going to print out a String in a loop, then I'd suggest the following change.  Note that System.err.println() uses an OS-specific line separator - not necessarily \n.

// This is fine for your program..
System.err.println("Error: " + input[count]
                        + " is not valid, exiting.\n");

// Option 1: Use multiple print stmts to avoid String concatenation:
System.err.print("Error: ");
System.err.print(inVal);
System.err.println(" is not valid; exiting.");
System.err.println();

// Option 2: Use a StringBuilder (also uses "method chaining" idiom):
System.err.println(new StringBuilder().append("Error: ")
                                      .append(inVal)
                                      .append(" is not valid; exiting.")
                                      .toString());
System.err.println();

This really isn't important in your specific example because it's so small.  In a bigger program or a production situation String concatenation can be a real performance problem.  People often make mistakes in logging code that really slows a system down.  I think later versions of Java have tamed this issue.  I know IntelliJ IDEA reports various times when it's better to use the + signs vs. a StringBuilder.  I've checked the compiled code a few times when I thought it was wrong, and it turned out to be right, so now I just trust it to tell me.


Robustly dealing with malformed Unicode files I'm writing a script that deals reads UTF-8-encoded XML files and writes parts of those files into a tempfile for further processing.

Sometimes, the input files will have a few malformed characters. If it's just "a few" occurrences, I want those glossed over, but if the file is majorly corrupted, I want to see an error message. I have a solution for this working right now, but I have this nagging feeling that this isn't a clean way to do  this.

This creates an example file with malformed data:

f = open("test.xml","w+b")
f.write("\x3c\x61\x3e\x31\x3c\x2f\x61\x3e\x0a\x3c\x62\x3e\x32\xc3\x0a\xbc\x3c\x2f\x62\x3e\x0a")
f.close()

Yes, I know it's probably a stray linebreak that's causing my "malformed utf-8" problem, but let's not make that the issue here.

Now, the following is a simplified version I have in place to deal with malformed utf-8 data up to a certain limit:

import codecs

sourcefile = open("test.xml", "r")

# First line always XML declaration, no special treatment
line = sourcefile.readline()

i = 1
unicodeerror = 0

while line:
    try:
        pos = sourcefile.tell()
        line = sourcefile.readline().decode("utf-8")
    except UnicodeDecodeError as e:
        print "WARNING: Encoding error in line " + str(i+1)
        sourcefile.seek(pos, 0)
        line = sourcefile.readline().decode("utf-8","ignore")
        unicodeerror += 1
    i += 1

if unicodeerror > 5:
    raise StandardError('ERROR: Too many Unicode errors')

As you can see, I read the input file as a byte string, and then read each line individually, doing the UTF-8-Decode within the try-except-clause. That way, I can catch the UnicodeDecodeError and count it. Only after counting it, reread the line, this time ignoring possible mistakes.

However, it "feels wrong" to simply read the file like this instead of doing a codecs.open(FILE, MODE, "utf-8"). With the codecs method, however, I see no way to reread the line with a different error handling directive after I hit the UnicodeDecodeException.

Am I being too cautious? Is this maybe the best / only reliable way to do this? OR is there a much easier solution (which can be achieved within the standard library!)?

The answer to your question depends on the version of python being used, and exactly what behavior you want. In Python 3.1 and up, the surrogateescape error handler can adeptly handle corrupted files that are otherwise encoded with UTF-8, and even write them back out again. Just use codecs.open(FILE, MODE, "utf-8", "surrogateescape"). If you want to know when invalid bytes were encountered, you can either scan for the relevant surrogate characters (those in the range U+DC80..U+DCFF), or compare to values you get from the replace error handler.

Through Python 2.7, it appears that the surrogateescape error handler is unavailable. You could contrast the results between the ignore and replace error handlers, but there is no convenient way to process the file in Unicode and write it out byte for byte.

In either version, you can theoretically write your own error handler that performs similarly to surrogateescape, ignore or replace, and counts the number of problems it sees. I'm uncertain whether this count can be scoped to a single file, however, as it appears an error handler only receives knowledge of the substring in question when an error is encountered.

On to a code review. Your code feels almost clunky to me. There's a stray import codecs, a lot of repetition (I can't fathom why re-reads the line with an error) and it doesn't try to leverage iterators. Perhaps you're on a particularly old version of Python (no, you use as in the except line), or perhaps you just haven't worked with iterators much. Probably most of this was from trying to extract the core issue, but I can only review it as is. I apologize for any errors in my code that follows; I haven't tested it, but I am willing to update it.

I would be strongly tempted to replace most of your code with something like this, and that's before trying to leverage anything I talked about above:

unicodeerror = 0
for i, line in enumerate(open("test.xml", "r")):
    try:
        line.decode("utf-8")
    except UnicodeDecodeError:
        print "WARNING: Encoding error in line", i+1
        unicodeerror += 1

if unicodeerror > 5:
    raise StandardError("ERROR: Too many Unicode errors")

If you need to do more, such as actually process the line, then it's reasonable to save the results of the decode, and to try again with an error handler in the except clause:

    try:
        text = line.decode("utf-8")
    except UnicodeDecodeError:
        # error tracking omitted
        text = line.decode("utf-8", "ignore")
    process(text)

If you wanted to integrate a comparison between two error handlers, it would replace the exception, so you could do something like this:

import codecs
unicodeerror = 0
for i, (ignored, replaced) in enumerate(zip(
    codecs.open("test.xml", "r", "utf-8", "ignore"),
    codecs.open("test.xml", "r", "utf-8", "replace"))):
    if ignored != replaced:
        print "WARNING: Encoding error in line", i+1
        unicodeerror += 1
if unicodeeror > 5:
    raise StandardError("ERROR: Too many Unicode errors")

And I'll leave a custom error handler totally up to you. If it works, it would probably be a lot more efficient than this approach, but there's something to be said for the simplicity of the visible code.

As a side comment, while I found this question interesting enough to delve into, the more I did so, the more it felt like a question about the right way to do this than a request to review your code. Keep in mind that it's much more on topic here to review code and make suggestions on how to improve it. So this particular approach isn't necessarily a great fit for codereview.SE.


Extract integers from a string that is split at given positions I am writing a program which runs quite slow and on profiling I found that the bottleneck is to split a given string at given positions.

The first and short version I wrote was (80% of 67 sec, i.e. 53 sec spent):

split list pos = uncurry (:) $ mapAccumR (flip splitAt) list pos

A faster version I wrote is (76% of 21 sec, i.e. 15 sec spent):

split :: String -> [Int] -> [Int]
split = go [] 0 0
    where
        -- no more string to split
        go nums num _ [] _ = num : nums
        -- no more position to split
        go nums num _ list [] = read (intToDigit num : list) : nums
        go nums num i (l:ls) pos@(p:ps)
            | i == p = go (num:nums) (digitToInt l) (i+1) ls ps
            | otherwise = go nums (10 * num + digitToInt l) (i+1) ls pos

How can I improve this?

Walking across the list of positions from the right cuts off suffixes, requiring you to keep traversing and copying the corresponding prefixes over. If you cut off prefixes instead, you only need to traverse once.

import Data.List
import Data.Tuple

splitAts :: [Int] -> [a] -> ([[a]], [a])
splitAts is xs = swap $ mapAccumL go xs (zipWith (-) is (0:is)) where
  go :: [a] -> Int -> ([a], [a])
  go xs i = swap $ splitAt i xs

This piece of code is, incidentally, the epitome of order confusion and what wouldn't happen if there was a way to bundle API updates with automatic patchers to old code.


Encrypting data on client side and passing it to server side I'm passing the data to PHP server side which will use the information later as this:

    <script> function encrypt() {
        var salt = CryptoJS.lib.WordArray.random(128/8);
        var key256Bits500Iterations = CryptoJS.PBKDF2("'.$token.'", salt, { keySize: 256/32, iterations: 500 });
        var iv  = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
        var encrypted = CryptoJS.AES.encrypt(document.loginForm.password1.value, key256Bits500Iterations, { iv: iv });
        var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
        var key_base64  = encrypted.key.toString(CryptoJS.enc.Base64);
        var iv_base64   = encrypted.iv.toString(CryptoJS.enc.Base64);
        var data = {encrypted: data_base64, iv: iv_base64, key: key_base64};
        document.loginForm.encrypted.value = JSON.stringify(data);
        return true;
    } </script>

My question is, since I am passing this through the form as POST, that still can be sniffed with shark-like tools and then decrypted with all information being passed through anyways.

What information should be private and how should I make them private? How could they be private if the IV, data, and the key are being send through the POST that are needed when decrypting the string?

How is the logic here flawed and how should it be used to protect data communication between client and server side computing?

What information should be private?

The key should be private, everything else can be public (the iv, the source, etc).

  How is the logic here flawed

You are using a symmetric key algorithm, which means that the same key decrypts and encrypts data, which in turn means that you would have to exchange the key between the parties (which would need to happen over a different channel, for example paper mail).

What you actually need is an asymmetric algorithm, which has a public key for encryption and a private key for decryption.

If you need to encrypt more data than showing here, you can use an asymmetric algorithm to exchange the key of a symmetric algorithm (as asymmetric encryption is unpractically slow). This is how HTTPS works, for example.

  how should it be used to protect data communication between client and server side computing?

Use HTTPS. At the time, there really isn't an alternative for this. (well, you could use third party services such as OpenID). You definitely need asymmetric encryption, and you should definitely not write your own.

Misc

either always use camelCase or always snake_case, don't mix them without reason.
key256Bits500Iterations is quite descriptive, but I think key would be just fine as well, and easier to read (and what if you change it to 600 iterations? Either your name would be wrong, or you would need to change it).
encrypt doesn't just encrypt, it also changes the form. I would to this in a different function and just let encrypt do the encrypting.
wherever you do the form manipulation, you should also set document.loginForm.password1.value to something else right there.


Project Euler # 74 Digit factorial chains in Python The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:

1! + 4! + 5! = 1 + 24 + 120 = 145

  Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169;
  it turns out that there are only three such loops that exist:

169 → 363601 → 1454 → 169
871 → 45361 → 871
872 → 45362 → 872

  It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,

69 → 363600 → 1454 → 169 → 363601 (→ 1454)
78 → 45360 → 871 → 45361 (→ 871)
540 → 145 (→ 145)

  Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.

  How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?

Here's my implementation in Python.

from math import factorial
from time import time

def get_factorial_sequence_length(number, factorials, lengths):
    """Return length of factorial sequence of number."""
    if number in lengths:
        return lengths[number]
    chain = [number]
    while len(chain) == len(set(chain)):
        if chain[-1] in lengths:
            index = chain.index(chain[-1])
            return lengths[chain[-1]] + len(chain[:index])
        chain_next = sum(factorials[digit] for digit in str(chain[-1]))
        chain.append(chain_next)
    duplicate_index = chain.index(chain[-1])
    for num in chain:
        index = chain.index(num)
        if index <= duplicate_index:
            lengths[num] = len(chain[index:-1])
        if index > duplicate_index:
            lengths[num] = len(chain[duplicate_index:index]) + len(chain[index:-1])
    return lengths[number]

def get_sequence_counts(upper_bound, target_chain_size, lengths={}):
    """Return count of factorial sequences which have length target_chain_size within range upper_bound exclusive."""
    factorials = {str(n): factorial(n) for n in range(10)}
    for number in range(1, upper_bound):
        chain_length = get_factorial_sequence_length(number, factorials, lengths)
        lengths[number] = chain_length
        if chain_length == target_chain_size:
            yield number

if __name__ == '__main__':
    start_time = time()
    print(len(set(get_sequence_counts(1000000, 60))))
    print(f'Time: {time() - start_time} seconds.')

A few comments.

First, your algorithm for computing the length of a chain is quadratic, because you convert your list to a set at each iteration. Second, there's a lot going on in get_factorial_sequence_length. I'd break the function up. You essentially have three parts: 1. Generate the elements of the sequence; 2: determine when to stop generating the sequence; 3. Determine the length of the non-repeating section (and memoize the length for all the seen numbers). The first part should be its own generator.

def generate_sequence(factorials, num):
    while True:
        yield num
        num = sum(factorials[digit] for digit in str(num)

Now get_factorial_sequence_length can look like:

def get_factorial_sequence_length(number, factorials, lengths):
    chain = []
    seen = set()
    for num in generate_sequence(factorials, number):
        if num in lengths:
            memoize_lengths_found(chain, num, lengths)
            return lengths[num] + len(chain)
        if num in seen:
            memoize_lengths_new(chain, num, lengths)
            return lengths[num]
        chain.append(num)
        seen.add(num)

memoize_lengths_found and memoize_lengths_new could use some work on the names, and I leave the implementations as an exercise to the reader.


Function to add a node with a unique ID and x,y coordinates This here is a function that adds a graph node, with a unique id to an x,y matrix.

The rules are that :

The node id must be unique
Only one node can exist at a given coordinate.

Here's my function that attempts to add a node with given id, at given x y coordinates .

def addNode(self, node_id, x, y):
    if self.node_list[node_id] != None:
        raise exception("This node ID already exists.")
    else:
        if self.spacialMatrix[x][y] != None:
            raise exception("This node position is already populated.")
        else:
            self.spacialMatrix[x][y] = node_id
            self.node_list[node_id] = [x,y]

How else would I do this?

I generally prefer keeping an if/else structure (so that you know that you are capturing all branches of your logic flow, rather than leaving unhandled else conditions).

def addNode(self, node_id, x, y):
    if self.node_list[node_id] != None:

Since None is a guaranteed singleton, you could use is not None rather than != None.

        raise exception("This node ID already exists.")

If this exception is quite common, assuming this code is part of a tree structure of some sort, you could write a custom exception such as NodeError to handle all such error - that'd be neat.

else:

Is it necessary to have the else here? If the if clause above raises an exception, this block won't be executed anyway; so I'd suggest you should remove this and unindent the code below.

    if self.spacialMatrix[x][y] != None:
        raise exception("This node position is already populated.")

Same thing I mentioned above - is not None and NodeError exception. Also, wouldn't the wrong x and y arguments raise an IndexError? Have you done anything else in the code to ensure that this won't happen?

    else:
        self.spacialMatrix[x][y] = node_id
        self.node_list[node_id] = [x,y]

This part looks good.

My suggestions:

class NodeError(exception):
    """
    For node related errors.
    """
    pass

def addNode(self, node_id, x, y):
    if self.node_list[node_id] is not None:
        raise NodeError("This node ID already exists.")
    if self.spacialMatrix[x][y] is not None:
        raise NodeError("This node position is already populated.")
    self.spacialMatrix[x][y] = node_id
    self.node_list[node_id] = [x,y]

Note: Adding doc strings would be a very good idea!


Calculate hat, waist, and jacket size when given age, height, and weight Intro to Computer Science project here. Calculates the hat, waist, and jacket size of the user when given age, height, and weight. Seems to output correctly.

Here are the guidelines for the assignment.

  Write a program that asks for the user’s height, weight, and age, and
  then computes clothing sizes according to the formulas:

  Hat size = weight in pounds divided by height in inches and all multiplied by 2.9
  Jacket size (chest in inches) = height times weight divided by 288 and then adjusted by adding 1/8 of an inch for each 10 years over the age of 30.  (Note
  that the adjustment only takes place after a full 10 years.  Thus, there is no adjustment for ages 30 through 39, but 1/8 of an inch is added for age 40.)
  Waist in inches=weight divided by 5.7 and then adjusted by adding 1/10 of an inch for each 2 years over age 28.  (Note that the adjustment only takes place after a full 2 years. Thus, there is no adjustment for age 29, but 1/10 of an inch is added for age 30.)

  Use functions for each calculation. (Thus, write 3 functions.)

I did this a tad hastily so pardon any messiness.

I am required to use namespace stdas it makes it easier for the teacher to read.

#include <iostream>

using namespace std;

double hat(double,double);

double jacket(double,double,int);

double waist(double,double,int);

int main ()
{
    double height, weight;
    int age;
    char answer;

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    do
    {
        cout<< "Enter the user's height in inches: ";
        cin>>height;
        cout<< "Enter the user's' weight in pounds: ";
        cin>>weight;
        cout<< "Enter the user's' age: ";
        cin>>age;
        cout<< "\tThe user's Hat size: " << hat(weight ,height) << "\tThe user's Jacket size: "<< jacket( height, weight, age) << "\tThe user's Waist size: "<< waist( height, weight, age)<< "\n \nWould you like to continue (y/n)? ";
        cin>>answer;
    }
        while(toupper(answer) == 'Y');
        return 0;
    }

    double hat(double weight ,double height)

    {
        return ((weight/height) * 2.9);
    }

    double jacket(double height,double weight,int age)
    {
        double size;
        int j;
        if (age>=30)
        {
        if((age % 10) !=0)
        age = age-(age%10);
        j= (age-30)/10;
        size =((height * weight) / 288)+((1.0/8)*j);
        }
        else
        size =((height * weight) / 288);
        return size;
    }

    double waist(double height,double weight,int age)
    {
        double size2;
        int k;

        if(age >= 28)
        {
            if((age % 2) !=0)
            age = age-(age%2);
            k = (age-28)/2;
            size2 = (weight/(5.7))+( (1.0/10)*k);
        }
        else
        size2 = weight / (5.7);
        return size2;
    }

I see some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  An alternative that may still meet your needs may be to put it within main rather in the global context.

Eliminate parentheses to enhance readability

Adding parentheses where they are not needed makes the code harder to read and comprehend than it needs to be.  For example, in the hat function, we have this:

return ((weight/height) * 2.9);

With no change in the effective calculation, we can simply write this:

return weight / height * 2.9;

I think that's a little easier to read.

Fix the formatting

It seems you may already know this, but your indentation and use of whitespace is not consistent.  It's less important which particular conventions you use than choosing one and applying it consistently.

Specify parameter names in function prototypes

With a function prototype like this:

double hat(double,double);

I can't tell which parameter is the height and which is the weight without looking at the implementation code.  Since function prototypes tend to become the documentation for your code's public interface, make it easier on the user of these functions by writing the prototype like this:

double hat(double weight, double height);

Or even like this to make the units unambiguous:

double hat(double weightInPounds, double heightInInches);

Don't pass parameters that are not needed

The waist routine does not need or use the height, so that parameter can and should be eliminated.

Use all required #includes

The code uses toupper() but doesn't include the corresponding header.  The code should have

#include <cctype>

Simplify expressions

The jacket and waist calculations are more complex than they need to be.  For example, for the waist routine, one could write this:

double waist(double weight, int age)
{
    double waist = weight / 5.7;
    if (age > 28) {
        waist += (age - 28) / 2 * 0.1;
    }
    return waist;
}

Note that the calculation (age - 28) / 2 is done using integer math, so that subexpression will yield 0 for ages of 28 or 29 as per the specification.  Understanding implicit conversions and particularly numeric conversions will be very helpful to you as you write future programs.


Adding a checkbox to a JavaScript class object I'm working on adding checkbox functionality that controls adding new checkboxes to a div element as well a tracking checkbox behavior.  My goal is to make this dirt simple.  I've noticed that there is some JavaScript function prototypes for creating objects such as checkboxes and also controlling basic behavior such as visibility, whether its checked or disabled and maybe even adding a label or image next to the checkbox.  My plan is to add this to an array or list and how can this be done?

I just need basic class object in JavaScript to be created to track just whether its checked, visible, or disabled.   In my case when its disabled it will not be checked, but may change in a later release.  I've looked at GWT and ZWT JavaScripting libraries and they seem too complicated.  Is there a simple solution I can do myself?

Looking for some constructive criticism, a good link or two for reference, and perhaps an estimate on whether this is feasible and how would I add a checkbox to the class below, and do I also have to worry about adding events to this?  And what would be the best way to track multiple famous people in this example: a list, an array, or another class?  I'm thinking a dynamic array of some kind.

    // Constructor for dynamic checkbox classes
var FamousPerson = function (id, checkStatus, visibleStatus, enabledStatus) {
    this.id = id;  // primary key for a person for a specific row
    this.checkStatus = checkStatus;
    this.visibleStatus = visibleStatus;
    this.enabledStatus = enabledStatus;
}

FamousPerson.prototype.getId() = function () {
    return this.id;  // id is reference stored in xml or database row
};

FamousPerson.prototype.update = function (checkStatus, visibleStatus, enabledStatus) {
    // note: don't update id
    this.checkStatus = checkStatus;  // boolean 0 is not checked, 1 is checked
    this.visibleStatus = visibleStatus; // boolean 0 is not visible, 1 is visible
    this.enabledStatus = enabledStatus; // boolean 0 is not enalbed, 1 is enabled
};

FamousPerson.prototype.getCheckStatus = function () {
    return this.checkStatus;
};

FamousPerson.prototype.getVisibleStatus = function () {
    return this.visibleStatus;
};

In my opinion, it seems like this should be it's own class. You should have another object to control the FamousPerson objects and add them when they are instantiated. I would also decouple the checkbox from the FamousPerson class itself and tie the behavior in elsewhere.

As for the solution part, if you still want to add it in here, check out this. There's an example of creating a checkbox with a label and adding it to the DOM. Shouldn't be too hard to patch some of it in to your existing class.


what is Null Test in java? and how to rewrite the code to do the same by avoiding null test I would like to know what is null test in java? How to rewrite the below code by  avoiding null test. I was asked this question in an online test. I'll be grateful for any help offered.

String mystere() throws IOException {
      InputStream input = null;
      try {
        input = new InputStream(new File("foo.txt"));
        return new Scanner(input).nextLine();
      } finally {
        if (input != null)
          input.close();
      }
    }

The null test is the input != null condition here.

In your code if the constructor of the stream throws an exception the reference remains null so there is no way to call close on it, therefore the constructor call could be before the try-catch block. The generic pattern is the following:

    final InputStream input = new FileInputStream(new File("foo.txt"));
    try {
        // do something with the stream
    } finally {
        input.close();
    }

Please note that I've changed new InputStream(...) to new FileInputStream(...). InputStream an interface, you cannot instantiate it.

In Java 7 it's a little bit simpler:

try (final InputStream input = new FileInputStream(new File("foo.txt"))) {
    // do something with the stream
}

References: Guideline 1-2: Release resources in all cases in the Secure Coding Guidelines for the Java Programming Language, Version 4.0 documentation.


RxJs - Flat nested swithMaps and pass variables on Http interceptor How can the following method be flattened? I tried to pipe all the operators to the first pipe (from(this.fireAuth.currentUser)) but I lost access to the previous variables. It's an  Angular HTTP interceptor that adds a Bearer Token when the user has logged in, the chain should continue as usual when the user has not logged in yet.
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken()).pipe(
          switchMap(token => {
            if (isApiUrl) request = this.addToken(request, token);
            return next.handle(request).pipe(
              catchError(error => {
                if ( isApiUrl && token && error instanceof HttpErrorResponse && error.status === 403) {
                  return this.handle403Error(request, next);
                }
                else{
                  return throwError(error);
                }
              })
            );
          })
        )
      })
    );
  }

Piping to the first observable... I have no access to the token var in the catchError block
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken());
      }),
      filter<string>(x => typeof(x) === "string"), //x can be string to HttpEvent<any>
      switchMap(token => {
        if (isApiUrl) request = this.addToken(request, token);
        return next.handle(request)
      }),
      catchError(error => {
        if ( isApiUrl && error instanceof HttpErrorResponse && error.status === 403) {
          return this.handle403Error(request, next);
        }
        else{
          return throwError(error);
        }
      })
    );
  }

I'm also wondering what's happening in the scenario where user is falsy, does it mean the request will be canceled because it does not pass the filter?
Thanks.

Your specific example can be simplified by treating the non-observables as simple variables, eg:
intercept(
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {

  const user = this.fireAuth.currentUser;
  if (!user) return next.handle(request);

  const isApiUrl = request.url.startsWith(apiCloudURL);
  const token = user.getIdToken();

  if (isApiUrl) request = this.addToken(request, token);

  return next.handle(request).pipe(
    catchError(error => {
      if ( isApiUrl &&
            token &&
            error instanceof HttpErrorResponse &&
            error.status === 403) {
        return this.handle403Error(request, next);
      } else {
        return throwError(error);
      }
    })
  )
}

However, in the general case your question uncovers a couple of interesting RxJS "patterns".
First let's ignore the path where there is no user.  What you end up with is a sequence of requests (ie your switchMaps), but where the result of any earlier request is any later request.  There is no completely clean solution to this in standard RxJS - a number of options are discussed in this article Aggregating RxJS Requests.  Nesting is the most common solution, which was your starting point.
I have been involved in the implementation of a utility to address this scenario.
With your example the resultant code would be:
intercept(
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {

  const isApiUrl = request.url.startsWith(apiCloudURL);

  return concatJoin(
    from(this.fireAuth.currentUser),
    ([user]) => from(user.getIdToken),
    ([user, token]) => {
      if (isApiUrl) request = this.addToken(request, token);
      return next.handle(request).pipe(...),
    },
  ).pipe(
    // resultant value is [user, token, result] - we just want the result
    map([,,result]) => result
  );
}

Now returning to handle the case where there is no user, in your implementation you are right, the filter would cause it to never emit a value.  There has to be a level of nesting:
intercept(
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {

  const isApiUrl = request.url.startsWith(apiCloudURL);

  return from(this.fireAuth.currentUser).pipe(
    switchMap(user => {  // or use the iif operator
      if (!user) return next.handle(request);

      return concatJoin(
        (from(user.getIdToken),
        ([token]) => {
          if (isApiUrl) request = this.addToken(request, token);
          return next.handle(request).pipe(...),
        },
      ).pipe(
        // resultant value is [token, result] - we just want the result
        map([,result]) => result
      );

    )
  )
}


Why below recursive DP solution is so slow? (Leetcode Q# 123 - Best Time to Buy and Sell Stock III) This is regarding leetcode Question# 123. I have solved the question (code below) but the solution is showing "Your runtime beats 5.89 % of cpp submissions."? Is there any additional optimization I can do to make it run faster?
class Solution {
    int maxProfitUtility(vector<int>& prices, int i, int buyOrSell, int k, vector<vector<vector<int>>>& dp){
        if(i == prices.size() || k == 0){
            return 0;
        }
        if(dp[i][buyOrSell][k] != INT_MIN){
            return dp[i][buyOrSell][k];
        }
        int x, y;
        if(buyOrSell == 0){
            x = maxProfitUtility(prices, i + 1, 1, k - 1, dp) - prices[i];
            y = maxProfitUtility(prices, i + 1, 0, k, dp);
        }else{
            x = maxProfitUtility(prices, i + 1, 0, k - 1, dp) + prices[i];
            y = maxProfitUtility(prices, i + 1, 1, k, dp);
        }
        dp[i][buyOrSell][k] = max(x,y);
        return max(x,y);
    }
public:
    int maxProfit(vector<int>& prices) {
        int k = 4;
        vector<vector<vector<int>>> dp(prices.size(), vector<vector<int>>(2, vector<int>(k + 1, INT_MIN)));
        return maxProfitUtility(prices, 0, 0, k, dp);
    }
};

Recursion comes with overheads. You need to push to the call stack and create a new context for your code to execute in.
I would convert this to an iterative solution.
You also don't need to allocate so much memory. Think closely about what information you actually need. HINT: If you could only go long on the stock, you would only need to store 2 ints as you iterate over the list to get your maximum profit.
Furthermore leetcode has the option of viewing code from the fastest solutions. Check that out and if you don't understand why their solution is so much faster, post on stack overflow.


Change size of elements until parent reaches certain height I wrote this method and I would like to refactor it so it is easier to understand and looks cleaner. However, I don't know how or where to start. If you could give it your best shot and explain your approach to how you did it, it would be very helpful to me. The function reduces the size of elements until the parent container reaches a certain height (in this case 25 or less).

function _AdjustHeightOwlDots() {
    let dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height();
    if (!dotRowHeight || dotRowHeight === 25 || dotRowHeight === 0) {
      return;
    }
    this._waitFor(`#${get(this, 'elementId')} div.owl-dots > button > span`).then(() => {
      if (dotRowHeight && dotRowHeight > 25) {
        for (let index = 0; index < 10; index += 1) { // default size of dot is 10x10px
          // first the margin because it looks better
          document.querySelectorAll(`#${get(this, 'elementId')} div.owl-dots > button > span`).forEach((el) => {
            const elCopy = el;
            const elStyle = elCopy.currentStyle || window.getComputedStyle(elCopy);
            if (parseFloat(elStyle.margin, 10) > 1) {
              elCopy.style.margin = `${parseFloat(elStyle.margin, 10) - 1}px`;
            }
          });
          dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height();
          if (dotRowHeight > 25) {
            document.querySelectorAll(`#${get(this, 'elementId')} div.owl-dots > button > span`).forEach((el) => {
              const elCopy = el;

              if (el.offsetHeight > 1) {
                elCopy.style.height = `${el.offsetHeight - 1}px`;
                elCopy.style.width = `${el.offsetHeight}px`;
              }
            });
          }
          const el = document.querySelector(`#${get(this, 'elementId')} div.owl-dots > button > span`);
          const elStyle = el.currentStyle || window.getComputedStyle(el);

          if (el.offsetHeight === 1 && parseFloat(elStyle.margin, 10) <= 1) { // cant get smaller
            break;
          }
          dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height();

          if (dotRowHeight <= 25) { break; }
        }
      }
    })
      .catch((/* e */) => {
      //
      });
  },

Edit: Follow up: Find size for elements to fit in certain width

It looks difficult to decypher indeed. Let's try it though. Some little bits which came to my mind at first glance:

I'd recommend using 4 spaces of indentation
maybe it's personnal taste but I would try not mixing jquery and vanilla js
as I understood, this keyword always refers to the same object, doesn't it? in that case maybe you could declare the selectors at the top of the function?

const thisElementId = get(this, 'elementId');
const selectorOwlDots = `#${thisElementId} .owl-carousel .owl-dots`;
const selectorButtonSpans = `#${thisElementId} div.owl-dots > button > span`;

declarations of const elCopy = el; are useless, just refer to el and rename it to something more meaningful
the handler of _waitFor should be declared as a function:

this._waitFor( selectorButtonSpans ).then( changeSizes ).catch( handleError );

function changeSizes() {
    ...
}

function handleError( err ) {
    ...
}

you can also simplify the initial exit condition a bit

let dotRowHeight = $(selectorOwlDots).height() || 25;
if ( dotRowHeight <= 25 ) {
    return;
}

you have two initial checks on dotRowHeight - I think you could reduce them to just one ( one is the one I simplified, the other is inside the _waitFor handler )

That should make the code a bit more readable BUT I think this code is doing the wrong thing altogether. The problem is - you are changing the size of elements in a loop until some condition is met. This is a bad practice - I've seen people ending up with infinite loops when doing such things. What I think you should do instead is:

read all the sizes you need
calculate sizes to apply to elements
apply sizes
if anything breaks - you do not have an infinite loop of elements jumping up and down on your page

Always try to minimize the number of interactions between your script and the UI.


jQuery grid-system - handing different row widths I made a function in jQuery for my home-made grid system. When a row has too many columns in it, it removes the HTML code from that row.

Normally in my grid system it fits 12 columns in 1 row, but with the function this can easily be changed.

One column with the size of 1 (declared as: column size-1) has a width of 1/12 (or 8.3333%).

function validateRowWidth() {
    var _row = $('.row');
    _row.each(function (index, element) {
        var totalWidth = 0,
            _columnSize = $(element).find('[class*="size-"]');
        _columnSize.each(function (index, element) {
            var width = $(element).outerWidth(true),
                inProcent = Math.round((width / $(element).parent().width()) * 100);
            totalWidth += inProcent;
        });
        if (totalWidth > 100) {
            console.log('You have to many columns into your '+(index + 1)+'th row');
            $(element).remove();
        }
    });
}

Is there any way I can improve this?

Things I pondered:

What's with the underscores everywhere?
Why not use regular jQuery convention and use this instead of element in your each iterator?
What's the use-case for this? A regular user will never see the console, so logging to it doesn't help anyone.
Even if someone is watching the console, what's the point of warning them when the row is just summarily removed? At least give the user a chance to fix the problem. It's worse if you're not looking at the console - then stuff is just gone with no explanation.
And the warning, "You have too many columns", isn't really truthful. The problem is that the columns - even if it's just 1 - are too wide. You code isn't checking how many there are.
But mostly: Why use percentages? Just compare widths directly. Saves you a whole lot of trouble (and code)

This seems clearer to me:

function validateRowWidth() {
  $('.row').each(function (index) {
    var row = $(this), // use `this`
        widthSum = 0;

    // sum up the (direct descendant) column widths
    row.children('[class*="size-"]').each(function () {
      widthSum += $(this).outerWidth(true); // 1 line is all you need here
    });

    // compare and warn if need be
    if(widthSum > row.width()) {
      // alert is not a great choice, but it's better than console.log,
      // if this is user-facing. Explain the problem, and propose solutions.
      alert("Row " + index + " is too wide. Remove one or more columns or make them narrower.");
    }
  });
}


Calculate the number of primes in a range I wrote some code to return how many prime numbers are in a specific range and what they are. It also tells you whether the number of primes is also a prime!

I feel like this seems like a fairly long winded approach for something that's probably very simple, can someone please tell me how I can improve this?

def prime_number():
    primes = []
    primes_2 = []
    low = int(input("What number would you like to start at? "))
    high = int(input("What number would you like to go up to? "))
    if int(low) == 1 and int(high) == 1:
        print("1 isn't a prime number dumb dumb")
    elif high < 2:
        print("Don't be annoying")
    else:
        for x in range(int(low), int(high)):
            for i in range(2, x):
                if (x % i) == 0 and x != i:
                    break
                elif (x % i) == 1 and i <= (x - 2):
                    continue
                elif (x % i) == 1 and i == (x - 1):
                primes.append(x)
            x = x + 1
        print("The number of prime numbers is: ", len(primes))
        for y in range(2, int(low)):
            for z in range(2, y):
                if (y % z) == 0 and y != z:
                    break
                elif (y % z) == 1 and z <= (y - 2):
                    continue
                elif (y % z) == 1 and z == (y - 1):
                    primes_2.append(y)
            y = y + 1
        if int(len(primes)) in primes or int(len(primes)) in primes_2:
            print("Huh, fancy that!", len(primes), "is also also a prime number!")
        print("The prime numbers are: ",primes)

Welcome to Code Review! Here are some suggestions.

Naming

Choose a better name than primes_2. I'm not clear on what this variable does.

Write some documentation

...in triple quotes at the top of your function. Describe its inputs and outputs.

Separate user input from processing

Put your calculation code in a separate function from your user input and output code.

Validation

If the user enters invalid input, consider looping until the input they provide is valid. Or, at least - return out of the function if it's invalid, instead of having a large else covering the rest of your code.

Increment-and-assign

Use x += 1 instead of x = x + 1.

Formatted output

Consider using this form instead:

print(f'Huh, fancy that! {len(primes)} is also a prime number!')


Communicating with other fragments or to activity Android documentation says:

  Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

My question is: Why should Fragments never communicate directly? Because it can cause problems or simply because of "good" code (clean code, maintenance...)?

Fragments communicate directly in my apps and I have not encountered any problem yet. Here an example of how I pass data from an "Event" fragment to a "Event Details" fragment:

public class UpcomingEventsFragment extends Fragment {

    private UpcomingEventsAdapter mAdapter;
    private ListView listview;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_upcomingevents, container, false);
        listview = (ListView) rootView.findViewById(R.id.upcomingevents);
        mAdapter = new UpcomingEventsAdapter(getActivity());
        listview.setAdapter(mAdapter);

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Event event = mAdapter.getItem(position);
                Bundle args = new Bundle();
                args.putString("id", event.getId());

                EventDetailsFragment fragment = new EventDetailsFragment();
                fragment.setArguments(args);
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        return rootView;
    }
}

Android application design best practices suggest that fragments should be modular and independent from each other, so that you may able to arrange them differently - not just on screen, but also changing relationships among them - when you are targeting devices with widely different screen sizes, e.g. smartphones and tablets. Those very same best practices suggest that you don't see nor use the whole activity interface in a fragment, but only a subset that you have defined through a proper custom interface, which typically contains callback methods that are invoked in cases such as yours, when an action taken in a fragment must trigger the creation and display of another fragment.

However, note that there is an interesting API that has been thought exactly for the purpose of starting a fragment from another fragment, and possibly returning a result to the caller fragment, much like startActivity and onActivityResult do for activities. I do believe that, while modularity and independence are indeed best design practices, there may be cases when two fragments are strictly intertwined, so much that that dependency is preserved even on different devices; and the cited API is there to help.


Using boost::mpi to take the Euclidean norm of a vector I am learning MPI (via boost::mpi) and wrote this program that takes the euclidean norm of a 1-D vector (represented as an array here.) I want to make sure that I am using boost::mpi properly, in terms of both functions used and the way the code is parallelized.

The sample below is the program with just the norm functionality; it takes no input from the user and always uses the same seed for consistency reasons. Another limitation is that the vector size must be evenly divisible into the MPI world size.

I appreciate any comments and am thankful for your time.

#include <boost/mpi.hpp>
#include <chrono>
#include <cmath>
#include <iostream>
#include <numeric>
#include <random>
#include <utility>
#include <vector>

int main() {
  boost::mpi::environment env;
  boost::mpi::communicator world;
  //unsigned long TWIST_SEED = std::chrono::system_clock::now().time_since_epoch().count();
  unsigned long TWIST_SEED = 2;
  unsigned long VECT_SIZE = 10;
  double *main_vector = new double[VECT_SIZE];
  if (world.rank() == 0) {
    std::mt19937 generator(TWIST_SEED);
    std::uniform_real_distribution<double> dis(-222222.22, 222222.22);
    for (int i = 0; i < VECT_SIZE; i++) {
      main_vector[i] = dis(generator);
    }
  }
  int n_bar = VECT_SIZE / world.size();
  if (world.rank() == 0) {
    if (VECT_SIZE <= 10) {
      std::cout << "Your vector is small enough to output. It is: \n{";
      for (int i = 0; i < VECT_SIZE; i++) {
        if (i == VECT_SIZE - 1) {
          std::cout << main_vector[i];
        } else {
          std::cout << main_vector[i] << ", ";
        }
      }
      std::cout << "}" << std::endl;
    }
  }
  double *local_vector = new double[n_bar];
  boost::mpi::scatter(world, main_vector, local_vector, n_bar, 0);
  std::vector<double> dot;
  double local_dot = 0.0;
  for (int i = 0; i < n_bar; i++) {
    local_dot += local_vector[i] * local_vector[i];
  }
  boost::mpi::gather(world, local_dot, dot, 0);
  if (world.rank() == 0) {
    std::cout << "The norm is " << sqrt(std::accumulate(dot.begin(), dot.end(), 0.0)) << std::endl;
  }
  delete[] main_vector;
  return 0;
}

You've misspelt std::sqrt.

Calculation of 2D and 3D Euclidean norm is more accurate and efficient via std::hypot() - would it be reasonable to use that as a basis for the N-dimensional form?

As always, prefer standard containers such as std::vector over raw pointers created with new[].


Convert binary tree to doubly linked list The code works and I get the results I want. Please comment about complexity, a shorter way of implementing the solution, and advice for better unit tests.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class BinaryTreeToList
    {
        public BinaryTreeToList()
        {

        }

        public DoubleLinkedListNode ConvertTreeToDoubleLinkedListNode(TreeNode root)
        {
            if (root == null)
            {
                return null;
            }
            DoubleLinkedListNode res = new DoubleLinkedListNode();
            res.Index = root.Index;
            if (root.Left != null)
            {
                var newNode = ConvertTreeToDoubleLinkedListNode(root.Left);
                newNode.Previous = res;
                res.Next = newNode;
            }
            if (root.Right != null)
            {
                if (res.Next == null)
                {
                    var newNode = ConvertTreeToDoubleLinkedListNode(root.Right);
                    newNode.Previous = res;
                    res.Next = newNode;
                }
                else if (res.Next.Next == null)
                {

                    var newNode = ConvertTreeToDoubleLinkedListNode(root.Right);
                    newNode.Previous = res.Next;
                    res.Next.Next = newNode;

                }
                else
                {
                    DoubleLinkedListNode temp = res;
                    while (temp.Next != null)
                    {
                        temp = temp.Next;
                    }
                    var newNode =  ConvertTreeToDoubleLinkedListNode(root.Right);
                    newNode.Previous = temp;
                    temp.Next = newNode;

                }
            }
            return res;
        }
    }

    public class DoubleLinkedListNode
    {
        public int Index { get; set; }
        public DoubleLinkedListNode Next { get; set; }
        public DoubleLinkedListNode Previous { get; set; }
    }
}

Unit Test

using System;
using System.Collections.Generic;
using ConsoleApplication2;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests
{
    [TestClass]
    public class BinaryTreeConvertToList
    {
        [TestMethod]
        public void TestMethod1()
        {
            BinaryTreeToList binaryTreeToList = new BinaryTreeToList();
            //            0
            //        2         4
            //     6    8          10
            TreeNode root = new TreeNode(0);
            root.Left = new TreeNode(2);
            root.Right = new TreeNode(4);
            root.Left.Left = new TreeNode(6);
            root.Left.Right = new TreeNode(8);
            root.Right.Right = new TreeNode(10);

            var res1 = binaryTreeToList.ConvertTreeToDoubleLinkedListNode(root);
            Assert.AreEqual(0, res1);
            Assert.AreEqual(2, res1.Next);
        }
    }
}

Naming

I personally prefer a class named Convert for such a task. This would also be more natural because the NET provided converting methods live in a Convert class too.
to be consistent with the NET naming I also would prefer the method be named ToDoubleLinkedListNode()
instead of shortening the name of the node to be returned to res, name it convertedNode
you should name the node which is returned by the recursive calls leftNode or rightNode.

General

by extracting the search for the last Next node which is not null to a separate method, the if..else if..else can be removed.
if you use a guard claus for root.Right == null you save horizontal spacing.
the method should be static, because it doesn't depend on any internal state of the class itself. This makes the constructor obsolete.

Refactoring

After all for above is applied the refactored code looks like

public class Convert
{
    public DoubleLinkedListNode ToDoubleLinkedListNode(TreeNode root)
    {
        if (root == null) { return null; }

        DoubleLinkedListNode convertedNode = new DoubleLinkedListNode { Index = root.Index };

        if (root.Left != null)
        {
            var leftNode = ToDoubleLinkedListNode(root.Left);
            leftNode.Previous = convertedNode;
            convertedNode.Next = leftNode;
        }

        if (root.Right == null) { return convertedNode; }

        var rightNode = ToDoubleLinkedListNode(root.Right);

        DoubleLinkedListNode lastNextNode = FindLastNextNode(convertedNode);
        rightNode.Previous = lastNextNode;
        lastNextNode.Next = rightNode;

        return convertedNode;
    }
    private static DoubleLinkedListNode FindLastNextNode(DoubleLinkedListNode node)
    {
        while (node.Next != null)
        {
            node = node.Next;
        }
        return node;
    }
}


POSIX shell compatible and POSIX conforming dirname implementation The discussion in the comments of this answer made me wonder how hard it would be to write a built-in only version of dirname.

This is what I ended up with but I'm reasonably confident it should be able to be improved (I haven't spent much time thinking about it yet).

Any improvements/suggestions are welcome.

#!/bin/sh

p=$1
alt=$2
skip78=

stripslashes() {
    i=$1
    while [ "$i" != "$o" ]; do
        o=$i
        i=${i%/}
    done
    eval "$2=\$i"
}

[ "$p" = '//' ] || {
    case "$p" in
        *[!/]*|'')
            stripslashes "$p" p
            case "$p" in
                */*)
                    p=${p%/*}
                    ;;
                *)
                    p=.
                    skip78=skip78
                    ;;
            esac
            ;;
        *)
            p=/
            skip78=skip78
            ;;
    esac
}
[ -n "$skip78" ] || {
    { [ "$p" != '//' ] || [ -z "$alt" ]; } && {
        stripslashes "$p" p
        [ -z "$p" ] && p=/
    }
}

printf -- %s\\n "$p"

The POSIX spec for dirname is:

  If string is //, skip steps 2 to 5.
  If string consists entirely of <slash> characters, string shall be set to a single <slash> character. In this case, skip
  steps 3 to 8.
  If there are any trailing <slash> characters in string, they shall be removed.
  If there are no <slash> characters remaining in string, string shall be set to a single <period> character. In this case, skip steps 5 to 8.
  If there are any trailing non- <slash> characters in string, they shall be removed.
  If the remaining string is //, it is implementation-defined whether steps 7 and 8 are skipped or processed.
  If there are any trailing <slash> characters in string, they shall be removed.
  If the remaining string is empty, string shall be set to a single <slash> character.

Update: Made a gist.

I don't think there's a really compelling reason for this eval in stripslashes:

eval "$2=\$i"

It's a dirty hack to update the parameter variable in-place.
But this is not a common practice, I don't know other commands or built-ins that work that way, and I would find such usage unexpected.
I would find it more usable if stripslashes behaved more like other commands do:

print the result on stdout
set the result in a designated variable (like REPLY)

That would be more in-line with common UNIX practices, and unsurprising, familiar.

As a minor nitpick, I avoid quoting when it's unnecessary.
For example instead of [ "$p" != '//' ], I would write [ "$p" != // ]

Instead of this:

        [ -z "$p" ] && p=/

This form is shorter:

        [ "$p" ] || p=/

This might be subjective, but I would rewrite this part using regular if-else:

[ -n "$skip78" ] || {
    { [ "$p" != '//' ] || [ -z "$alt" ]; } && {
        stripslashes "$p" p
        [ -z "$p" ] && p=/
    }
}


Rearrange an array in place such that the first and last halves are interleaved Given an array of n elements in the following format { a1, a2, a3, a4,
  ….., an/2, b1, b2, b3, b4, …., bn/2 }. The task is shuffle the array
  to {a1, b1, a2, b2, a3, b3, ……, an/2, bn/2 } without using extra
  space.

  Input:

  The first line of input contains an integer T denoting the
  number of test cases. Then T test cases follow, Each test case
  contains an integer n denoting the size of the array. The next line
  contains n space separated integers forming the array.

  Output:

  Print the shuffled array without using extra space.

  Constraints:

  1<=T<=10^5

  1<=n<=10^5

  1<=a[i]<=10^5

  Example:

  Input:

  2

  4

  1 2 9 15

  6

  1 2 3 4 5 6

  Output:

  1 9 2 15

  1 4 2 5 3 6

My approach:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

class ShuffleArray {

    private static int [] getShuffledArray (int[] arr) {
        //List <Integer> arrList = new ArrayList<>();

        return shuffleArray(arr,1,arr.length/2);
    }

    private static int [] shuffleArray (int[] arr, int swapInd1, int swapInd2) {
        if (swapInd2 == arr.length- 1) {
            return arr;
        }
        int temp = arr[swapInd2];

        for (int i = swapInd2 ; i > swapInd1; i--) {
            arr[i] = arr[i - 1];
        }

        arr[swapInd1] = temp;
        return shuffleArray(arr, swapInd1 + 2, swapInd2 + 1);
    }

    public static void main (String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            int numTests = sc.nextInt();

            while (numTests-- > 0) {
                int size = sc.nextInt();
                int[] arr = new int[size];
                for (int i = 0; i < size; i++) {
                    arr[i] = sc.nextInt();
                }
                int[] soln = getShuffledArray(arr);
                for (int i = 0; i < soln.length; i++) {
                    System.out.print(soln[i] + " ");
                }
                System.out.println();
            }
        }
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference

The recursion results in \$O(n)\$ space complexity (each recursive invocation consumes some stack), so technically you did not fulfill the requirement of _not using extra space. Since it is a tail recursion, it can easy to eliminate. Unfortunately, Java doesn't do it, so you have to eliminate it manually. Fortunately, it is just a mechanical rewrite.
The time complexity is \$O(n^2)\$. There is not much to do with the current approach. There is however a linear solution: an element at index k goes to either 2k, if k < n/2, or 2k - n + 1 otherwise. Convince yourself that this permutation has no loops, and just follow a chain of indices.
The loop

for (int i = swapInd2 ; i > swapInd1; i--) {
    arr[i] = arr[i - 1];
}

shifts a range, and deserves to be a function on its own (shift_rangeperhaps).


Covariance in generic collections I have a some classes and interface

public interface IGeoObject
    {
        GeoCoordinate GetGeocoordinate();
    }

public class User : IGeoObject
    {
        public GeoCoordinate GetGeocoordinate()
        {
            //...
            return GeoCoordinate;
        }
    }

public class Venue : IGeoObject
    {
        public GeoCoordinate GetGeocoordinate()
        {
            //...
            return GeoCoordinate;
        }
    }

public class Place : IGeoObject
    {
        public GeoCoordinate GetGeocoordinate()
        {
            //...
            return GeoCoordinate;
        }
    }

I have, example variable users with type List<User>

And I have method with signature

double GetMinDistance(List<IGeoObject> objects, GeoCoordinate position)

I can't pass users to GetMinDistance, because covariance of generic types not work.

I can create additional list and use method .ConvertAll (or .CasT<T>):

List<IGeoObject> list = new List<User>(listUser).ConvertAll(x => (IGeoObject)x);
var dist = GeoTest.GetMinDistance(list, position);

I'm not sure that this is the most elegant solution. Most embarrassing that the caller must do this conversion.

This is similar to my problems in the architecture? There are more elegant solutions?

P.S. Long story, but I really can not give the coordinates of the same species in all classes.

You can make GetMinDistance generic:

double GetMinDistance<T>(IList<T> objects, GeoCoordinate position)
  where T: IGeoObject
{
    // ...
}

You can use it like this:

List<User> user = ....;

GetMinDistance(user, position);


Generating a vigenere square in LaTeX3 I'm trying to generate a vigenere square using expl3. My aim is to provide an easy interface for different alphabets and different scaling. Therefore I chose a tabular-based approach which seemed very easy to customize.

Points I would especially appreciate feedback to:

Is using tabular a good idea or might it be very bad (e.g. when the user customizes array stretches)?
Am I abusing expl3 at any point (local vs. global)?
the user interface in general (key-value approach)

Code:

\documentclass{article}
\usepackage[landscape]{geometry}
\usepackage{xparse}

\ExplSyntaxOn
\keys_define:nn { vigenere }
    {
        font        .code:n    = { \cs_set_eq:NN \__vigenere_font: #1 },
        font   .default:n = { \small },
        font   .initial:n = { \small },
        tabcolsep .dim_set:N = \l__vigenere_tabcolsep_dim,
        tabcolsep .initial:n = { 3pt },
        alphabet  .tl_set:N  = \l__vigenere_alphabet_tl,
        alphabet  .initial:n = { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z }
    }
\NewDocumentCommand { \printvigeneretabular } { O{} }
    {
        \group_begin:
        \keys_set:nn { vigenere } { #1 }
        \clist_set:NV  \l_tmpa_clist \l__vigenere_alphabet_tl
        \clist_clear:N \l_tmpb_clist
        \tl_clear:N    \l_tmpa_tl
        \int_step_inline:nnnn { 1 } { 1 } { \clist_count:N \l_tmpa_clist }
            {
                \tl_put_right:Nx \l_tmpa_tl { c| }
            }
        \__vigenere_font:
        \dim_set_eq:NN \tabcolsep \l__vigenere_tabcolsep_dim
        \expandafter\tabular\expandafter{\expandafter|\l_tmpa_tl}
            \hline
            \bool_while_do:nn { \int_compare_p:n { \clist_count:N \l_tmpa_clist > 0 } }
                {
                    \clist_use:Nnnn \l_tmpa_clist { & } { & } { & }
                    \clist_if_empty:NF \l_tmpb_clist
                        { & \clist_use:Nnnn \l_tmpb_clist { & } { & } { & } }
                    \clist_gpop:NN \l_tmpa_clist \l_tmpa_tl
                    \clist_gput_right:NV \l_tmpb_clist \l_tmpa_tl
                    \\\hline
                }
        \endtabular
        \group_end:
    }
\ExplSyntaxOff

\begin{document}
 \printvigeneretabular\par
 \printvigeneretabular[font=\tiny,alphabet={1,2,3,4,5,6,7,8,9,10},tabcolsep=1pt]
\end{document}

About your points:

The interface seems pretty clear.
If you fear about the \arraystretch parameter being abused, you're right: on a double spaced document all tables come out horribly and local remedies are often necessary. Maybe adding a stretch key could help for these cases.
Yes, you're abusing local and global assignments.

Some comments about the code:

There is no point in the key alphabet to set a tl variable, which is then converted to a clist
There's no need to set a .default:n for the font key: the value specified with .default:n would be used if the key is called without assigning a value
\int_step_inline:nnnn can be done more simply using the * feature of tabular
Never use \expandafter in expl3 code
You should not use global assignments on local variables
\clist_gpop:NN should be \clist_gpop_left:NN (but I changed it into \seq_pop_left:NN)
One can do with a simpler loop, using \prg_replicate:nn

I'd also prefer to prepare the table body outside the table, with sequences instead of clists, which are less efficient.

\documentclass{article}
\usepackage[landscape]{geometry}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand { \printvigeneretabular } { O{} }
 {
  \vigenere_tabular:n { #1 }
 }

% keys
\keys_define:nn { vigenere }
 {
  font      .code:n       = { \cs_set_eq:NN \__vigenere_font: #1 },
  font      .initial:n    = { \small },
  tabcolsep .dim_set:N    = \l__vigenere_tabcolsep_dim,
  tabcolsep .initial:n    = { 3pt },
  alphabet  .clist_set:N  = \l__vigenere_alphabet_clist,
  alphabet  .initial:n    = { A, B, C, D, E, F, G, H, I, J, K, L, M,
                              N, O, P, Q, R, S, T, U, V, W, X, Y, Z }
 }

% variables
\tl_new:N \l__vigenere_tablebody_tl
\seq_new:N \l__vigenere_alphabet_seq

% internal function
\cs_new_protected:Nn \vigenere_tabular:n
 {
  \group_begin:
  % set the keys
  \keys_set:nn { vigenere } { #1 }
  % make a sequence from the alphabet
  \seq_set_from_clist:NN \l__vigenere_alphabet_seq \l__vigenere_alphabet_clist
  % set the font and the tabcolsep
  \__vigenere_font:
  \dim_set_eq:NN \tabcolsep \l__vigenere_tabcolsep_dim
  % prepare the table body
  \tl_clear:N \l__vigenere_tablebody_tl
  \prg_replicate:nn { \seq_count:N \l__vigenere_alphabet_seq }
   {
    \tl_put_right:Nx \l__vigenere_tablebody_tl
     {
      \seq_use:Nn \l__vigenere_alphabet_seq { & }
      \exp_not:n { \\ \hline }
     }
    \seq_pop_left:NN \l__vigenere_alphabet_seq \l_tmpa_tl
    \seq_put_right:NV \l__vigenere_alphabet_seq \l_tmpa_tl
   }
  % make the table
  \tabular { | *{\clist_count:N \l__vigenere_alphabet_clist }{ c| } }
  \hline
  \tl_use:N \l__vigenere_tablebody_tl
  \endtabular
  \group_end:
 }
\ExplSyntaxOff

\begin{document}

\printvigeneretabular

\printvigeneretabular[font=\tiny,alphabet={1,2,3,4,5,6,7,8,9,10},tabcolsep=1pt]

\end{document}


String formatting for uint64_t that represents a fixed-point decimal My goal is to take a uint64_t that represents a fixed-point decimal, and output a string representation of the decimal. The fixed-point representation always has eight decimal places, so for example 1.12345678 is represented as 112345678.

How can I make the following code cleaner and/or faster? Obviously all the character insertions/deletions are very slow, but what's the best way to get rid of those?

std::string uint64_to_string(uint64_t n) {
  auto retval = std::to_string(n);  // Initial conversion to string

  if(retval.size() <= 8) {
    // Add leading zeros if necessary, so for example n=1 becomes 000000001
    size_t num_leading_zeros = 9 - retval.size();
    retval.insert(0, num_leading_zeros, '0');
  }

  // Insert decimal, so 000000001 becomes 0.00000001
  retval.insert(retval.size() - 8, 1, '.');

  // Trim trailing zeros, and trim '.' if it is the last character
  boost::trim_right_if(retval, [](char c) { return (c == '0' || c == '.'); });
  return retval;
}

std::string uint64_to_string(uint64_t n) {

Make interfaces easy to use correctly and hard to use incorrectly.

The function name is confusing as it would lead me to believe that if I called uint64_to_string(1ull), I would expect a returned value of "1".

From your problem statement:

  My goal is to take a uint64_t that represents a fixed-point decimal

Instead of using a built-in integer type, leverage the type system by using a fixed-point decimal class.

Ensure you are using <cstdint> and prefix the namespace on the integral type std::uint64_t.

Avoid magic numbers. If 8 is supposed to represent a fixed radix point, you should document that by assigning it to a descriptive variable name.  If you use a fixed-point decimal class, you could just refer to its radix point instead.

  How can I make the following code cleaner and/or faster? Obviously all the character insertions/deletions are very slow, but what's the best way to get rid of those?

If you've measured and multiple allocations are slowing you down, calculate the string length of your result first, then fill it with the characters.  I highly recommend you watch Andrei Alexandrescu's Fastware talk he's been giving for the past few years.  He covers this exact topic of converting integers to strings using specific optimization techniques.


Finding the Longest Word in a String Challenge:

  Return the length of the longest word in the provided sentence.

I've made a solution that works but it is kinda bad since the time complexity is \$O(n \log n)\$ and it involves mutation.

function findLongestWordLength(str) {
  let strSplit = str.split(" ");
  let wordLengthArray = [];
  for(let i = 0; i < strSplit.length; i++)
  {
    wordLengthArray.push(strSplit[i].length);
  }
  wordLengthArray.sort(function(a , b){return a - b});
  return wordLengthArray[wordLengthArray.length - 1];
}

I basically split the string, pushed all the word lengths in an empty array, then used the ascending sort function. After that I returned the last index of the new array which is the longest length.

Test Cases:

findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.
findLongestWordLength("May the force be with you") should return 5.
findLongestWordLength("Google do a barrel roll") should return 6.
findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.

I would appreciate some hints/tips on a better algorithm.

You are creating an array of strings (using str.split(" ")) as well as an array of numbers (wordLengthArray), then sorting wordLengthArray.  All three of those operations are wasteful, if you are aiming for performance.

function findLongestWordLength(str) {
  let maxLen = -1;
  for (var i = 0, j; (j = str.indexOf(" ", i)) != -1; i = j + 1) {
    maxLen = Math.max(maxLen, j - i);
  }
  return Math.max(maxLen, str.length - i);
}

console.log(6 == findLongestWordLength("The quick brown fox jumped over the lazy dog"));
console.log(5 == findLongestWordLength("May the force be with you"));
console.log(6 == findLongestWordLength("Google do a barrel roll"));
console.log(8 == findLongestWordLength("What is the average airspeed velocity of an unladen swallow"));
console.log(19 == findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"));

Depending on the browser/interpreter, your function is 33% to 86% slower than mine.