texts:
Is there anything I can improve in my UserManager class which saves and loads info about users connected to my server?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.ArrayList;
import server.engine.CustomLog;

public class UserManager {

public static synchronized User loadUser(String id, Socket s) {
    User user = null;
    if (id == null) {
        return user;
    }
    File f = new File("users.dat");
    if (f.isFile() && f.canRead()) {
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.equals("[" + id + "]")) {
                    user = new User(s);
                    user.id = id;
                    user.password = br.readLine().split("=")[1];
                    user.username = br.readLine().split("=")[1];
                    break;
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }
    }
    return user;
}

public static synchronized ArrayList<User> loadAllUsers()
{
    File f = new File("users.dat");
    ArrayList<User> users = new ArrayList();
    if (f.isFile() && f.canRead()) {
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.matches("^(\\[[0-9]*\\])$")) {
                    User user = new User(null);
                    user.id = line.replace("[", "").replace("]", "");
                    user.password = br.readLine().split("=")[1];
                    user.username = br.readLine().split("=")[1];
                    users.add(user);
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }
    }
    return users;
}

public static synchronized void saveUser(User user) {
    File f = new File("users.dat");
    String content = "";
    String newLine = System.getProperty("line.separator");
    boolean found = false;
    if (f.isFile() && f.canRead()) {
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.equals("[" + user.id + "]") && br.readLine().equals(user.password)) {
                    found = true;
                    content += "[" + user.id + "]" + newLine;
                    content += "password=" + user.password + newLine;
                    content += "username=" + user.username + newLine;
                    br.readLine();
                } else {
                    content += line + newLine;
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }
    }
    if (!found) {
        content += "[" + user.id + "]" + newLine;
        content += "password=" + user.password + newLine;
        content += "username=" + user.username + newLine;
    }
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {
        writer.write(content);
        writer.close();
    } catch (FileNotFoundException | UnsupportedEncodingException ex) {
        CustomLog.error(ex.getMessage());
    } catch (IOException ex) {
        CustomLog.error(ex.getMessage());
    }
}
}

EDIT: I forgot to mention that my client and server uses auto-register. Basically id and the password are randomly generated when the client requests registration and server saves them as a new user and client saves them too and keeps using them to log in. So user is only prompted to enter his username. Thats why I was not bothered about privacy of the passwords because they are just random numbers and letters.


texts:
Just for learning and practicing I've created a completely recursive version of the merge sort algorithm.

I've tested it a little bit and it seems working, but I'm quite sure that it can be largely improved. In particular, I'm hating the long if-else conditional inside the sort function. I think it's really bad written but I can't figure out a way to "beautify" the code without using a loop.

function merge(left, right, array){
    if (left.length == 0 && right.length == 0) {
        return array;
    } else if (left.length == 0) {
        return array.concat(right);
    } else if (right.length == 0) {
        return array.concat(left);
    } else if (left[0] < right[0]) {
        array.push(left.shift());
    } else if (left[0] > right[0]) {
        array.push(right.shift());
    } else {
        array.push(left.shift());
        right.shift();
    }
    return merge(left, right, array);
}

function mergeSort(array){
    if (array.length > 1) {
        return merge(mergeSort(array.slice(0, Math.ceil(array.length/2))),
            mergeSort(array.slice(Math.ceil(array.length/2))), []);
    } else {
        return array;
    }
}


texts: Finding palindromic strings of even length

texts:
Given a string of digits. Find the length of longest substring of even length i.e. 0,2,... which is a palindrome or which can be rearranged to form a palindrome (see example below).

Here is my code:

def is_palindrome(string):
    length=len(string)
    new_d=[' ']*length
    #For rearranging the substring
    for i in range(length/2):
        new_d[i]=string[i]
        if string[i] in string[i+1:]:
            sindx=length-1-(string[::-1].index(string[i]))
            new_d[-(i+1)]=string[sindx]
    string1=('').join(new_d)
    return string1==string1[::-1]

def substring(number):
    subs=[]
    length=len(number)
    for i in range(length):
        for j in range(i+2,length+1,2):
            #print(number[i:j])
            yield number[i:j]

def count_palindromes(number):
    palindromes=[]
    palindromes.extend(filter(is_palindrome,substring(number)))
    #print(palindromes)
    if len(palindromes):
        lengths=[]
        for i in palindromes:
            lengths.append(len(i))
        lengths.sort(reverse=True)
        return lengths[0]
    else:
        return 0

number=raw_input()
length=count_palindromes(number)
print(length)

Input: String of numbers(0-9)
Ouput:Length of longest palindromic substring of even length

Example
Input:12345354987
Longest palindromic even length substring: 345354
On rearranging: 345543
Output:6


texts:
Can you review below code for performance and stability considerations? It is supposed to take a filename or NULL. If it is a filename, read given file into memory. If it is NULL, read from stdin into memory.

struct file_data {
    char *data;
    size_t numChars;
};

/* Read whole file into memory */
struct file_data read_file(char *filename) {
    FILE *f;
    char buffer[BUFFER_SIZE];
    char *data = NULL;
    size_t current_size = 0;
    size_t totalChars = 0;
    size_t nchars;

    if(filename) {
        f = fopen(filename, "r");
    } else {
        f = stdin;
    }

    do {
        data = (char *)realloc(data, current_size + BUFFER_SIZE);
        assert(data);
        current_size+=BUFFER_SIZE;
        nchars = fread(buffer, 1, BUFFER_SIZE, f);
        memcpy(&data[totalChars], buffer, nchars);
        totalChars+=nchars;
    } while(nchars == BUFFER_SIZE);

    struct file_data fd = {data, totalChars};
    return fd;
}


texts: HashMap Implementation (dictionary) in Python

texts:
I attempted making a hashmap in python, and it was harder, due to some limitations but this is my version of dictionaries in python. Are there any way to simplify or do the same thing in less code along with tips and tricks?

class HashMap:
    def __init__(self, memory): # refers to the length of the bucket
            self.data = [None] * memory
            self.memory = memory

    def _hash(self, key):
        hashed_value = 0
        bucket_length = self.memory
        string_length = len(key)
        i = 0
        while i < string_length:
            hashed_value += (ord(key[i]) * i) % bucket_length
            if hashed_value > bucket_length-1:
                hashed_value %= bucket_length-1

            i += 1
        return hashed_value

    def set(self, key, value):
        address = self._hash(key)
        bucket = self.data[address]
        if not bucket:
            self.data[address] = [key, value, None] # None refers to next pointer
        else:
            while bucket[2] != None:
                bucket = bucket[2]
            bucket[2] = [key, value, None]

    def get(self, key):
        address = self._hash(key)
        bucket = self.data[address]
        if bucket:
            while bucket[2] != None or key != bucket[0]:
                bucket = bucket[2]
            if bucket:
                return bucket[1]
        raise KeyError

    def keys(self):
        keys_list = []
        bucket_list = self.data
        for bucket in bucket_list:
            current_bucket = bucket
            if bucket:
                while current_bucket != None:
                    keys_list.append(current_bucket[0])
                    current_bucket = current_bucket[2]
        return keys_list


texts: Get the indices of a range elements by relative order of the values

texts:
I've just asked

What's the idiomatic way to get the sort order of data, without actually applying it?

(or see the original it was found to be a dupe on). So, I want to implement properly what seems to be the only suggested option - generating an array of indices and sorting it by the original data's relative order. Here's my code (ignoring includes):

template<typename RAIterator, typename Comparator, typename Size = size_t>
inline std::vector<Size>
sorted_indices(RAIterator first, RAIterator last, Comparator comparator)
{
    std::vector<Size> result(last - first);
    std::iota(result.begin(), result.end(), 0);
    auto adapted_comparator = [&first, comparator](Size lhs, Size rhs) {
        return comparator(first[lhs], first[rhs]);
    };
    std::sort(result.begin(), result.end(), adapted_comparator);
    return result;
}

template<typename RAIterator, typename Size = size_t>
inline std::vector<Size>
sorted_indices(RAIterator first, RAIterator last)
{
    using value_type = typename std::iterator_traits<RAIterator>::value_type;
    auto comparator = [](const value_type& lhs, const value_type& rhs) { return lhs < rhs; };
    return sorted_indices<RAIterator, decltype(comparator), Size>(first, last, comparator);
}

template<typename Container, typename Comparator, typename Size = typename Container::size_type>
inline std::vector<Size> sorted_indices(Container& container, Comparator comparator)
{
    return sorted_indices<typename Container::const_iterator, Size>(
        std::begin(container), std::end(container), comparator);
}

template<typename Container, typename Size = typename Container::size_type>
inline std::vector<Size> sorted_indices(Container& container)
{
    return sorted_indices<typename Container::const_iterator, Size>(
        std::begin(container), std::end(container));
}

Have I covered all my bases or is there something I might be missing? Also, how legitimate is it to return the vector of indices?


texts:
I wrote a function to find all the possible permutations of a list in Haskell. I know it can definitely be optimized, but I'm not sure how. I'm pretty sure foldl or foldl' can be used, but I'm not sure how. It gets kinda slow when the size of the argument for perms is more than 6 items, but I don't know if this is avoidable.

What could I do to improve this function, mainly to simply it, improve it stylistically, and boost performance?

perms :: [a] -> [[a]]
perms = perms' 0
  where
    perms' _ [x, y] = [[x, y], [y, x]]
    perms' c xs
      | c == length xs = []
      | otherwise = (sub_perm xs) ++ (perms' (c + 1) (shift xs))
    sub_perm (x:xs) = fmap (\a -> x:a) $ perms xs
    shift xs = (last xs):(init xs)


texts: Breadth-first search in Java: Competitive style - follow-up

texts:
I have improved my BFS in Java according to vnp's suggestions. Again, we wish to find shortest paths in directed unweighted graphs using BFS, competitive style (no Maps, Set's or Lists):

import java.util.Arrays;

class BFS {

    static int[] bfs(int[][] graph, int sourceNode, int targetNode) {
        int[] queue = new int[graph.length];
        int[] parents = new int[graph.length];

        for (int i = 0; i < parents.length; i++) {
            parents[i] = -1; // -1 denotes 'not used'
        }

        int queueStartIndex = 0;
        int queueEndIndex = 1;

        queue[0] = sourceNode;
        parents[sourceNode] = -2;

        while (queueStartIndex < queueEndIndex) {
            int currentNode = queue[queueStartIndex++];

            if (currentNode == targetNode) {
                return buildPath(targetNode, parents);
            }

            for (int childNode : graph[currentNode]) {
                if (parents[childNode] == -1) {
                    parents[childNode] = currentNode;
                    queue[queueEndIndex++] = childNode;
                }
            }
        }

        return null;
    }

    private static int[] buildPath(int targetNode, int[] parents) {
        int pathLength = 0;
        int node = targetNode;

        while (node >= 0) {
            pathLength++;
            node = parents[node];
        }

        int[] path = new int[pathLength];
        int pathIndex = path.length - 1;
        int currentNode = targetNode;

        while (currentNode >= 0) {
            path[pathIndex--] = currentNode;
            currentNode = parents[currentNode];
        }

        return path;
    }

    /*    B ----+
         /      |
        A       E
         \      /
          C - D
    */

    public static void main(String[] args) {
        int a = 0;
        int b = 1;
        int c = 2;
        int d = 3;
        int e = 4;

        int[][] graph = new int[5][];
        graph[a] = new int[]{ c, b };
        graph[b] = new int[]{ e };
        graph[c] = new int[]{ d };
        graph[d] = new int[]{ c, e };
        graph[e] = new int[]{ b, d };

        // A -> B -> E
        int[] path = bfs(graph, a, e);
        System.out.println(Arrays.toString(path));

        // A <- B <- E does not exist:
        System.out.println(Arrays.toString(bfs(graph, e, a)));

        graph = new int[4][];
        graph[a] = new int[]{ b, c };
        graph[b] = new int[]{ d };
        graph[c] = new int[]{ a, d };
        graph[d] = new int[]{ b, c };

        /*     B
              / \
             A   D
              \ /
               C
        */

        // A -> B -> D
        path = bfs(graph, a, d);
        System.out.println(Arrays.toString(path));

        path = bfs(graph, d, a);
        // D -> C -> A:
        System.out.println(Arrays.toString(path));
    }
}

Please tell me anything that comes to mind.


texts:
The goal of this code is to save a list of 250000 words with a number that indicates its frequency. The 250000 are sorted alphabetically but the frequency is unsorted. The idea is that a user must insert capitalized words, spaces or numbers after each word to lookup in the saved 250000-word list.

The max number of inputs are 1000 word+space+frequency pair per line.

The frequency domain is \$1 <= frequency <= 1000000\$. Every input must result in an output containing a list of the most relevant words \$>=\$ word-frequency entered and also ordered alphabetically in descending order.

How can I finish this code in a more efficient way?

public static void Main()
{
   {
      var dic = new Dictionary<string, int>();

      int counter = 0;

      StreamReader sr = new StreamReader("C:\\dicti.txt");

      while (true)
      {
          string line = sr.ReadLine();   // To read lines
          string[] ln;
          if (line == null) break;            // There is no more lines
          try
          {
              ln = line.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
              string a = ln[0];
              int b = Convert.ToInt32(ln[1]);

              dic.Add(a, b);
          }
          catch (IndexOutOfRangeException) { break; }
      }

      string[] ln2;
      string am, word;
      int bm;

      do
      {
                //counter++;
                do
                {
                    word = Console.ReadLine();

                    ln2 = word.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

                    am = ln2[0];

                    bm = Convert.ToInt32(ln2[1]);

                } while (!(am.Length >= 2 && bm >= 1 && bm <= 1000000));

                if (true)
                {
                    var aj = (dic.Where(x => x.Value >= bm)
                        .Where(x => x.Key.StartsWith(am))
                        .OrderByDescending(d => d.Value).Take(2));

                    foreach (var p in aj)
                    {
                        Console.WriteLine("{0} ", p.Key);
                    }
                }
            } while (counter < 1001);
   }
}


texts: Simulated annealing for magic square-of-squares puzzle

texts:
I'm working on a function that takes in a NumPy array containing only mutually distinct positive square numbers. I want the function to pick an element at random, find if there is a lower positive square number than the number selected: (1) if there is, return the array with the lower positive square number in place of the original element (2) if there isn't, return a copy of the original array.

The reason I'm developing this function is to create a simulated annealing solution to the Magic Square of Squares Puzzle, and this function would serve as one of the mutations to the candidate solution.

I've had a go at the implementation:

def last_square(x):
    xcopy = x.copy()
    index_1 = np.random.randint(0, x.shape[0]), np.random.randint(0, x.shape[1])
    c = x[index_1]-1
    while np.sqrt(c) != int(np.sqrt(c)) or c in set(x.flatten()):
        if c < 2:
            return xcopy
        else:
            c -= 1
    x[index_1] = c
    return x

Will my function always have the behaviour I've specified?

Edit 1

I've been asked some clarifying questions that I'll address here. There were very helpful in getting me to see what else I still had to explain.

Why are you iterating through all possible numbers less than the chosen one, instead of just iterating through the array itself?

I am looking for the next smallest positive square number below the one that was randomly selected from the array that is not in the array.

Why do you care about sqrt in last_square at all? Taking the square root of the elements will not change their ordering.

I agree that removing the square too that not change the ordering of the the square numbers currently within the array, nor does it change the position of a candidate square number c among all positive square numbers.

I care about checking if np.sqrt(c) != int(np.sqrt(c)) because a number whose square root is an integer is a square number.

Do you care whether the lower number is chosen non-deterministically? What should happen if there is more than one lower number? Currently it looks like you've implemented a lookup for the next lowest number closest to the chosen number, which is not what you described in the question.

The randomized selection of an element in the array is of course random, but taking that element being chosen, I'm aiming for the rest of the behaviour of the function to be deterministic. That is to say, given the array and the randomly selected element, then the function will always give the same return.

I want to preserve the mutual distinctness of the positive square numbers within the array, so my goal is to find the next lowest positive square number that is not in the array. I was trying to acheive this by inclusively disjoining c in set(x.flatten()) to the header of the loop, thereby keeping the loop going when c is still a number within the array.

As written, if you find a lower number and copy it to the chosen location, your claim that the array's elements are mutually distinct will be violated.

Using the following

if c < 2:
            return xcopy
        else:
            c -= 1

I am checking if c has gone too low, in which case I return a copy of the original array. If I break from the loop, the following lines will change the original array and return the array with the substitution completed.

x[index_1] = c
    return x

I think what I am having trouble with in part may be when calling np.sqrt on c without checking if c is non-negative. I'll work on correcting that and editing the code when I've resolved that issue.

Let me know if there are further questions. I'm happy to clarify.


texts:
How can I improve the speed of this LINQ query?

using (var txn = new TransactionScope(TransactionScopeOption.Required,
        new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
{
     var myAlertsList = (from alerts in _db.Alerts.AsNoTracking()
                         where alerts.AlertID >= Id.AlertID && alerts.DataWystapienia >Id.DataWystapienia
                         select new MyAlerts { AlertID = alerts.AlertID, DataWystapienia = alerts.DataWystapienia, Message = alerts.Message })
                        .OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows).Concat((
                         from subAlerts in _db.SubAlerts.AsNoTracking()
                         where subAlerts.AlertID >= Id.AlertID && subAlerts.DataWystapienia > Id.DataWystapienia
                         select new MyAlerts { AlertID = subAlerts.AlertID, DataWystapienia = subAlerts.DataWystapienia, Message = subAlerts.Message })
                        .OrderByDescending(c => c.AlertID).Take(Id.NumberOfRows)).OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows);

     return myAlertsList;
}

It seems like the order by date is the longest process in this query. Is this correct?
The database has about a million records. NumberOfRows is max 200. Time of this query is 45ms (after using only one orderby). Is there something more that I can do to improve that LINQ query?


texts: Stack based esoteric language interpreter in Ruby

texts:
For a while now, I've wanted to write a stack-based "Turing-tarpit". This is the perfect excuse to learn Ruby, which I have never used before, so I wrote Brain-flak.

The language only uses these characters, ()[]{}<> in various contexts. Here is the interpreter:

class Stack
  def initialize(name)
    @name = name
    @data = []
  end

  def pop
    if @data.length != 0 then
      return @data.pop
    else
      return 0
    end
  end

  def push(current_value)
    @data.push(current_value)
  end

  def peek
    return @data.last || 0
  end

  def print
    while @data.length > 0 do
        puts pop
    end
  end

  def talk
    puts @name
  end
end

def is_opening_bracket?(b)
  return '([{<'.include? b
end

def is_closing_bracket?(b)
  return ')]}>'.include? b
end

def brackets_match?(b1, b2)
  s = [b1, b2].join('')
  return ['()', '[]', '{}', '<>'].include? s
end

def read_until_stack_end(s, start)
  stack_height = 0
  s[start + 1..s.length].each_char.with_index(1) do |c, i|
    case c
    when '{' then stack_height += 1
    when '}' then
      stack_height -= 1
      if stack_height == -1 then
        return i
      end
    end
  end
  return nil
end

left = Stack.new('Left')
right = Stack.new('Right')
main_stack = Stack.new('Main')
active = left

source_index = 0
current_value = 0
error = false

if ARGV.length < 1 then
  puts "Welcome to Brain-Flak!"\
       "\nUsage:"\
       "brain_flak source_file"\
       "brain_flak source_file args\n"
  exit
end

source_path = ARGV[0]
source_file = File.open(source_path, 'r')
source = source_file.read
source_length = source.length

ARGV[1..-1].each do|a|
  active.push(a.to_i)
end

while true do
  current_symbol = source[source_index..source_index+1] or source[source_index]
  if source_index >= source.length then
    break
  end

  if ['()', '[]', '{}', '<>'].include? current_symbol
    case current_symbol
      when '()' then current_value += 1
      when '[]' then current_value -= 1
      when '{}' then current_value += active.pop
      when '<>' then active = active == left ? right : left
      else
        error = true
        break
    end
    source_index += 2

  else
    current_symbol = current_symbol[0]
    if is_opening_bracket?(current_symbol) then
      if current_symbol == '{' and active.peek == 0 then
        new_index = read_until_stack_end(source, source_index)
        if new_index == nil then
          error = true
          break
        else
          source_index = new_index
        end
      else
        main_stack.push([current_symbol, current_value, source_index])
      end
      current_value = 0

    elsif is_closing_bracket?(current_symbol) then
      data = main_stack.pop
      if not brackets_match?(data[0], current_symbol) then
        error = true
        break
      end

      case current_symbol
        when ')' then active.push(current_value)
        when ']' then puts current_value
        when '>' then current_value = 0
        when '}' then source_index = data[2] - 1 if active.peek != 0
        end
    end
    source_index += 1
  end

  if source_index >= source_length then
    break
  end

end

if error then
  puts 'Invalid character in source file!'
  exit
end

active.print

Does this follow the best practices of Ruby? Is it easy to understand? Like I said, this is the first thing I've written in Ruby, so there are probably lots of things that I'm doing in the roundabout/less convenient way. For example, there are so many then keywords! I don't know if or where these are necessary.


texts:
I am trying to solve a set of differential equations in x,y,z, I have made simple kutta 2 code in python before but not with 3 variables. I am not sure if what i have done is an acceptable way to adjust for 3.
Here is what i have so far: (i have not entered the exact solution as i do not know it)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Define function to compute velocity field

A = 0.2
B = 1.0
C = 0.20

def velfun(x,y,z,t):

    xvelocity =  (A*np.sin(z) +  C*np.cos(x))
    yvelocity =  (B*np.sin(x) + A*np.cos(z))
    zvelocity =  (C*np.sin(y) + B*np.cos(x))
    return xvelocity, yvelocity, zvelocity

# Set stopping time
# and the step length

Nstep = 10000
h     = 0.01

# Create arrays to store x and t values

x     = np.zeros(Nstep);
y     = np.zeros(Nstep);
z     = np.zeros(Nstep);

# Set the initial condition

x[0] = 1
y[0] = 0
z[0] = 0

# Carry out steps in a loop

for k in range(1,Nstep):

    # Provisional Euler step

    xx    = x[k-1]
    yy    = y[k-1]
    zz    = z[k-1]
    ux,uy,uz = velfun(xx,yy,zz)
    xp    = x[k-1] + h*ux
    yp    = y[k-1] + h*uy
    zp    = z[k-1] + h*uz
    # Compute velocity at provisional point

    uxp,uyp,uzp = velfun(xp,yp,zp)

    # Compute average velocity

    uxa = 0.5*(ux + uxp)
    uya = 0.5*(uy + uyp)
    uza = 0.5*(uz + uzp)

    # Make final Euler step
    # using average velocity

    x[k] = x[k-1] + h*uxa
    y[k] = y[k-1] + h*uya
    z[k] = z[k-1] + h*uza

# Exact solution

# Plot results
fig = plt.figure()
ax = plt.axes(projection='3d')
ax = plt.axes(projection='3d')
ax.scatter3D(x,y,z,'b',label='x (with RK2)')

plt.show()


texts:
I am new to Go and the web token / JTW concept. In order to learn Go and learn about web tokens, I am making my own implementation in Go (never to be used, of course).

If a user gets authenticated (assume that part is secure), I generate a web token, [header].[payload].[signature]. The header contains a timestamp of when the token was created. The payload has the user id and maybe role in there too, and the signature is there to show that the payload hasn't been altered.

Are there any security concerns with this?
Is there a way to improve the performance / speed of this?

package gwt

import (
    "crypto/hmac"
    "crypto/sha512"
    "crypto/subtle"
    "encoding/base64"
    "encoding/json"
    "errors"
    "fmt"
    "os"
    "strings"
    "time"
)

var Expired error = errors.New("Token expired")
var Invalid error = errors.New("Invalid token")

var expireAfter int = 60 * 60 * 24 * 7
var refreshAfter int = 60 * 60 * 24 * 3
var secret []byte

func init() {
    gwtSecret := os.Getenv("GWT_SECRET")
    if gwtSecret == "" {
        fmt.Println("You must set GWT_SECRET environment variable: export GWT_SECRET=change_this")
        os.Exit(0)
    } else if len(gwtSecret) < 16 {
        fmt.Println("GWT_SECRET must be longer than 16 characters")
        os.Exit(0)
    }

    secret = []byte(gwtSecret)
}

func Expire(e int, r int) {
    expireAfter = e
    refreshAfter = r
}

func Make(object map[string]interface{}) (string, error) {
    exp := time.Now().Format(time.UnixDate)
    header := base64.StdEncoding.EncodeToString([]byte(exp))

    payloadBytes, err := json.Marshal(object)
    if err != nil {
        return "", err
    }

    payload := base64.StdEncoding.EncodeToString(payloadBytes)

    return header + "." + payload + "." + sign(header+payload), nil
}

func GetPayload(token string) (map[string]interface{}, string, error) {
    parts := strings.Split(token, ".")
    if len(parts) != 3 || subtle.ConstantTimeCompare([]byte(sign(parts[0]+parts[1])), []byte(parts[2])) != 1 {
        return nil, "", Invalid
    }

    headerBytes, err := base64.StdEncoding.DecodeString(parts[0])
    if err != nil {
        return nil, "", Invalid
    }

    header := string(headerBytes)

    created, err := time.Parse(time.UnixDate, header)
    if err != nil {
        return nil, "", Invalid
    }

    expired := created.Add(time.Second * time.Duration(expireAfter)).Before(time.Now())
    if expired {
        return nil, "", Expired
    }

    payloadBytes, err := base64.StdEncoding.DecodeString(parts[1])
    if err != nil {
        return nil, "", Invalid
    }

    var payload map[string]interface{}
    if err := json.Unmarshal(payloadBytes, &payload); err != nil {
        return nil, "", Invalid
    }

    var newToken string
    stale := created.Add(time.Second * time.Duration(refreshAfter)).Before(time.Now())
    if stale {
        newToken, err = Make(payload)
        if err != nil {
            return nil, "", Invalid
        }
    } else {
        newToken = ""
    }

    return payload, newToken, nil
}

func sign(s string) string {
    h := hmac.New(sha512.New, secret)
    h.Write([]byte(s))

    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

The token will be stored locally on the client, sent via http headers on the necessary requests, and everything is https.

An updated version can be found here.


texts: Thread spawning child threads and waiting for children to finish

texts:
Scenario: I have a main thread which spawns few child threads to do some independent tasks. After each child thread finishes their tasks, the main thread proceeds. The code I have written is working in most of the time. However, in case one of child thread gets blocked, the main thread has to wait for ever. As it is not happening frequently, I am kind of OK as of now. But I am looking for a better solution

I am not trying to interrupt the child threads by waiting in main thread and then interrupting the child threads, because I don't know upfront how much time I need to wait for all the children to finish their tasks.However, it should not take more than 10 mins(worst case) for the children to finish their tasks. But if I go with thread interrupt way, I will have to wait for 10 mins always even if all children finishes their tasks in 2 mins itself. Lots of time (8 min here) will be wasted for nothing.

So, is it possible to review my code and suggest if any enhancement is possible?

Thread Class

public class MyThread implements Runnable{

@Override
public void run() {
    /*
     * Actual method do the following:
     * 1. Say we have 10 person. So, do the following for each person
     *   1.1 Fetch social network(FB,LN,TW etc )profiles
     *   1.2 Process the profiles and store in database
     * 2. Finished
     */
    System.out.println("hello world by thread "+ Thread.currentThread().getName());
  }
}

Invoker Class

public class ThreadInvoker {

public static void main(String[] args){

    List<Thread> threadList = getMyThreadList();

    for (Thread thread : threadList) {
        thread.start();
    }

    System.out.println("Waiting for Child Threads to die");

    for (Thread thread : threadList) {
        try {
            thread.join();
            System.out.println(thread.getName() + " Finished its job");
        } catch (InterruptedException e) {
            System.out.println("Interrupted Exception thrown by : "
                    + thread.getName());
        }
    }

    System.out.println("All Child Threads Finished their Job");
}

/**
 * Dummy method to get a list of Threads. Content of this method may not be reviewed.
 * Actual method do some other way to return a list of threads
 * @return
 */
private static List<Thread> getMyThreadList() {
    List<Thread> threadList = new ArrayList<>();
    MyThread myThread;
    Thread thread;
    for(int i=0; i<10; i++){
        myThread = new MyThread();
        thread = new Thread(myThread);
        thread.setName("Thread "+i);
        threadList.add(thread);
    }
    return threadList;
 }
}


texts:
I made my own version of merge sort:

    (defn rsort[a]
      (cond
        (<= (count a) 1) a
        :else
          (let [half    (/ (count a) 2)
                [lh rh] (split-at half a)]
            (loop [res () slh (rsort lh) srh (rsort rh)]
              (cond
                (empty? slh) (into srh res)
                (empty? srh) (into slh res)
                :else
                  (if (< (first slh) (first srh))
                    (recur (cons (first slh) res) (rest slh) srh)
                    (recur (cons (first srh) res) slh (rest srh))))))))

Any suggestion how improve this code?


texts: Getting the length of a file in characters

texts:
Here's my function for getting the length of a file, in characters:

unsigned int GetFileLength(std::string FileName)
{
std::ifstream InFile(FileName.c_str());
unsigned int FileLength = 0;
while (InFile.get() != EOF) FileLength++;
InFile.close();
return FileLength;
}

How can this be improved?


texts: Generating a PANDAS DataFrame of simulated coin tosses

texts:
It's taking my machine quite a long time to execute 1 billion (1st loop x 10, 2nd loop x 1000, 3rd loop x 100,000) instructions. Suggestions for performance enhancements? Sources of potential concern:

global variables slower than local variables?
using for loops instead of something like map?
overhead for class instantiation?
overhead of storing results in a dictionary before making a pandas frame?

from numpy import random
from pandas import DataFrame, concat

class coin(object):

    HEADS = 1
    TAILS = 0
    FLIP_TIMES = 10

    def __init__(self):
        self.frequency = self.flip10()

    def flip10(self):
        choices = [coin.HEADS, coin.TAILS]
        record = []
        for i in xrange(coin.FLIP_TIMES):
            record.append(random.choice(choices))
        return sum(record) / float(coin.FLIP_TIMES)

class trial(object):

    NUM_COINS = 1000
    DEFAULT_VAL = 11.0 / 10.0
    C_RAND_IDX = random.randint(0, NUM_COINS)

    def __init__(self):
        self.results = self.flip1000()

    def flip1000(self):
        v_rand = trial.DEFAULT_VAL
        v_first = trial.DEFAULT_VAL
        v_min = trial.DEFAULT_VAL
        for i in xrange(trial.NUM_COINS):

            # grab frequency
            v_i = coin().frequency

            # hold on to pocket minimum frequency
            if v_i < v_min:
                v_min = v_i

            # get random frequency
            if i == trial.C_RAND_IDX:
                v_rand = v_i

            # get first
            if i == 0:
                v_first = v_i

        # some error checking to make sure they don't
        # still have their default values at this point
        # would be great
        return {'rand': v_rand, 'first': v_first, 'min': v_min}

data = DataFrame([trial().results for i in xrange(100000)])


texts: Finding matching PDF files in different folders and merging the two files into one

texts:
I have code which currently loops through one folder, finds two matching pdf-filenames and merges them into 1 pdf-file always in the same order. File 1 then File 2. My code is slow, maybe because merging PDF files takes a long time, but also because it has to search one folder and match filenames. Before I searched through two folders, but that took too long. I do not want to write the filenames to an Excel-file and then match, but I want to merge the PDF files immediately when VBA finds a match. I found some code and adjusted it to my needs and put some new things into it.

I have seen a lot of code using Acrobat or Pdftk, but I do not have Acrobat and Pdftk does not work with me even though I do exactly what is written on several sites. For some reason Pdftk does not merge my files.

My code matches filenames based on the first part of the filename, before the AnotherWord 2014.pdf or before SomeWord.pdf.

Example document name1: John Doe SomeWord.pdf
Example document name2: John Doe AnotherWord 2014.pdf

Please look at this code and please post code which will do the same thing, only much faster. My code isn't the best, but it works. I use PDF reDirect Pro v2.5.2 (freeware) and a reference to the program.

    Sub MergePDF_Files()
'Only works with PDF reDirect Pro v2.5.2
'And needs to have a reference to PDF_reDirect_v2500 and PDF reDirect Pro Remote Control
Dim fs As Object
Dim fld As Object
Dim fld2 As Object
Dim objFile As Object
Dim objFile2 As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim oPDF As New PDF_reDirect_v25002.Batch_RC_AXD
Dim TempBool As Boolean
Dim Files_to_Merge(1) As String
Dim ObjFileName() As String
Dim CellNameValue() As String
Dim ofn As String
Dim cnv As String
Dim i As Integer

Set fld = fs.GetFolder("C:\MyFolder\PDF Merge\Merging Area")
Set fld2 = fs.GetFolder("C:\MyFolder\PDF Merge\Merging Area\Merged")
i = 1

For Each objFile In fld.files
For Each objFile2 In fld.files
    CellNameValue() = Split(objFile.Name, " SomeWord.pdf")
    cnv = CellNameValue(0)
    ObjFileName() = Split(objFile2.Name, " AnotherWord 2014.pdf")
    ofn = ObjFileName(0)
    Files_to_Merge(1) = fld & "\" & ofn & " AnotherWord 2014.pdf"
    Files_to_Merge(0) = fld & "\" & cnv & " SomeWord.pdf"
    If StrComp(ofn, cnv) = 0 Then
    With oPDF

        TempBool = .Utility_Merge_PDF_Files(fld2 & "\" & ofn & " AnotherWord 2014.pdf", Files_to_Merge) 'The file merges here unless it generates an error and goes to If Not TempBool Then...

        If Not TempBool Then
            'MsgBox "An Error Occured: etc.
        Else
            'Optional
        End If
    End With
    End If
    i = i + 1
    Next objFile2
     i = i + 1
    Next objFile
    Set oPDF = Nothing
End Sub


texts: Using the same RecyclerView.Adapter with a different ViewHolder

texts:
I would use the same RecyclerView.Adapter with two or more different fragments. Every fragment uses a different view items layout so I must use a different RecyclerView.ViewHolder for binding the data.

For the implementation I have created one RecycleView.ViewHolder that binds the two different view layout with a switch but I think might be something better for this kind of situation.

public class TFViewHolder extends RecyclerView.ViewHolder  {

    public final static int LAYOUT_ONE = 1;
    public final static int LAYOUT_TWO = 2;

    public Integer mId;

    public ImageView mThumb;
    public TextView mName;

    public TextView mTitle;
    public TextView mDescription;

    public final View mView;

    public TFViewHolder(View itemView, int layoutType) {
        super(itemView);

        mView = itemView;

        switch (layoutType) {

            case LAYOUT_ONE:
                mThumb = (ImageView) itemView.findViewById(R.id.thumb);
                mName = (TextView) itemView.findViewById(R.id.name);
                break;
            case LAYOUT_TWO:
                mTitle = (TextView) itemView.findViewById(R.id.title);
                mDescription = (TextView) itemView.findViewById(R.id.description);
                break;
        }

        itemView.setTag(itemView);
    }
}

The RecyclerView.Adapter:

public class TFRecyclerViewAdapter extends RecyclerView.Adapter<TFViewHolder> {

    protected Context context;
    protected List items;
    private int layout;
    private int layoutType;

    public TFRecyclerViewAdapter(Context context) {
        this.context = context;
    }

    public TFRecyclerViewAdapter(Context context, int layout, int layoutType) {
        this(context);

        this.layout = layout;
        this.layoutType = layoutType;
    }

    public void setItems(List items){
        this.items = items;
    }

    @Override
    public void onBindViewHolder(final TFViewHolder holder, final int position) {
        holder.mId = position;
    }

    @Override
    public TFViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(layout, parent, false);

        return new TFViewHolder(itemView, layoutType);
    }

    @Override
    public int getItemCount() {
        int l = 0;

        if (items != null) {
            l = items.size();
        }

        return l;
    }
}

Two different adapters that extend the TFRecyclerViewAdapter of above:

public class TFNewsRecyclerViewAdapter extends TFRecyclerViewAdapter {

    public TFNewsRecyclerViewAdapter(Context context, int layout) {
        super(context, layout, TFViewHolder.LAYOUT_NEWS);
    }

    @Override
    public void onBindViewHolder(TFViewHolder holder, int position) {

        final News item = (News) items.get(position);

        holder.mTitle.setText(item.getTitle());
        holder.mDescription.setText(item.getDescription());

        super.onBindViewHolder(holder, position);
    }
}

and

public class TFTeamsRecyclerViewAdapter extends TFRecyclerViewAdapter {

    public TFTeamsRecyclerViewAdapter(Context context, int layout) {
        super(context, layout, TFViewHolder.LAYOUT_TEAMS);
    }

    @Override
    public void onBindViewHolder(TFViewHolder holder, int position) {

        final Team team = (Team) items.get(position);

        Glide.with(holder.mThumb.getContext())
                .load(team.getThumb())
                .fitCenter()
                .crossFade()
                .into(holder.mThumb);

        holder.mName.setText(team.getName());

        super.onBindViewHolder(holder, position);
    }
}


texts: Inherit from Dictionary or create my own class with a dictionary

texts:
I'm working C# on an exercise that is it very strange.

I have these three classes.

public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>

On the exercise there is this strange declaration:

var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

public class Dictionary : Dictionary<object, object>

But I'm not sure if it is a good idea to inherit from Dictionary into a production environment (where I'm going to apply what I have learned).

So, I have decided to change the declaration on my custom dictionary class with this:

public class Dictionary
{
    Dictionary<object, object> dictionary = new Dictionary<object, object>();

    public object this[object index]
    {
        get
        {
            return dictionary[index];
        }

        set
        {
            dictionary[index] = value;
        }
    }

    public bool ContainsKey(object key)
    {
        return dictionary.ContainsKey(key);
    }
}

Which one is better?

By the way, I have to use ContainsKey in the exercise.

I can't modify the exercise. I have to create the classes that make it compiles and works (do whatever it does).


texts: Alternatives for checking if something is not None in Python

texts:
I recently bumped into dry-python/returns, which seems like a very useful project. In the project description, the authors describe a snippet which can be written with their Maybe container in a better way (according to the authors):
The original code is:
if user is not None:
     balance = user.get_balance()
     if balance is not None:
         credit = balance.credit_amount()
         if credit is not None and credit > 0:
             discount_program = choose_discount(credit)

And the improved version is:
discount_program: Maybe['DiscountProgram'] = Maybe.from_optional(
    user,
).bind_optional(
    lambda real_user: real_user.get_balance(),
).bind_optional(
    lambda balance: balance.credit_amount(),
).bind_optional(
    lambda credit: choose_discount(credit) if credit > 0 else None,
)

This is a legitimate solution. However, I would write the first code as:
if user:
   balance = user.get_balance()
   if balance:
      credit = balance.credit_amount()
      if credit > 0:
          discount_program = choose_discount(credit)

Being a long time pylint user that the style that is recommended.
Honestly, I've never given it much thought, and now that I saw the first
code, I started asking myself if I should give it some thought.
The most dangerous place IMHO, in my version is:
if credit > 0:

Since None will raise here a TypeError. However, the original line can be written as:
if credit and credit > 0:
   discount_program = choose_discount(credit)

My favorite style for re-writing this block would be very LISPy. I use getattr with a default value which is callable (a lambda which returns None). This very similar to what the example in return does, but without a 3rd party library:
choose_discount(
   getattr(
      getattr(user, 'get_balance', lambda: None)(),
      'credit_amount', lambda: 0)())

Which I think would not be like by many because it's very unusual. Also, for this to work properly, I would write choose_discount as:
def  choose_discount(credit):
    if credit:
        return "Your discount choosing ..."
    else:
        return "No discount"

If allowed to use a newer version of Python, I would probably use the walrus operator here:
if (credit := getattr(getattr(user, 'get_balance', lambda: None)(), 'credit_amount', lambda: 0)()) > 0:
    discount_program = choose_discount(credit)

This style strongly assume that credit_amount always returns a type which can be numerically compared ... Hence, the caveat I mentioned earlier, with credit being a None is implicitly handled.
I have a few questions regarding this.

Can you point out possible caveats in my style?
Could I be missing out something terrible, and I should look for is not None
explicitly?
Is the functional style legitimate here or should I absolutely avoid it?


texts: Progressively split and map a large, line-based string

texts:
Goal

I have a large string (~10MB in ~400k lines). I want to "efficiently" split it on a delimiter and map the resulting sets of lines. Efficiently is defined as something that is fast (wall time), even when RAM may be limited.

The delimiter is always a fixed string comprising a full line of the input. The delimiter always appears as the last line of the string. When multiple delimiters occur in sequence, I want to skip the interceding values. Each set of lines between the delimiters is also is processed one line at a time, though they are often further split into sets.

For example, given this string:

a: 1
b: blah
c: cats
a: 2
b: burgers
c: canoodling
done
d: 3
done
d: 4
done
d: 5
done
done
done
q: 6
x: xiph
z: 42
q: 7
x: xena
q: 8
z: 17
done

…I want to process the lines between each done independently, and (based on logic outside the scope of this question) produce something like:

[
  [
    { a:1, b:'blah', c:'cats' },
    { a:2, b:'burgers', c:'canoodling' }
  ],
  { d:3 },
  { d:4 },
  { d:5 },
  [
    { q:6, x:'xiph', z:42 },
    { q:7, x:'xena' },
    { q:8, z:17 }
  ]
]

Possible Approaches

The simplest approach is something like:

# skipping empty lines in the map
large_string.split("done\n").map{ ... }.compact

# pre-rejecting empty lines
large_string.split("done\n").reject(&:empty?).map{ ... }

...but that creates all the sub-string results and possibly will not work well in a limited RAM situation.

As an alternative, I have currently coded up:

[].tap do |result|
  large_string.scan(/(.*?)(?:^done\n)/) do |(match)|
    result << match unless match.empty?
  end
end

This feels gross to me, creating unnecessary wrapper arrays.

Further, benchmarking it (when plenty of RAM is available) shows it to be about 8–10× slower than just split/map/compact.

I've considered using strscan to walk through the string, but this seems unnecessary.

This code performs only about 5× slower than split (and requires me to rewrite my chunk processor to handle lines instead of strings):

delim = "done\n"
[].tap do |result|
  accum = []
  str.each_line do |line|
    if line==delim
      result << process(accum) unless accum.empty?
      accum=[]
    else
      accum << line
    end
  end
end

Is there a better, more elegant way to do this that is performant when RAM is available, but that degrades gracefully when the data set is large


texts: Is given pattern a subString of given input string? KMP implementation

texts:
My implementation of Knuth Morris Pratt algorithm. Looking forward for code review comments. Let me know of there is a better way to implement this algorithm.

import static org.junit.Assert.*;

import org.junit.Test;

public class IsPatternASubString {

    public static boolean isSubString(String s, String p){

        int sIndex = 0;
        int pIndex = 0;
        boolean matchStarted = false;

        while(sIndex < s.length()-1){

            if(s.charAt(sIndex) == p.charAt(pIndex)){
                //Are in the middle of matching process and just getting started
                matchStarted = (pIndex == 0) ? true : matchStarted;

                //Increment both index pointers
                sIndex++;
                //If last char of pattern match exit returning true
                if(pIndex == p.length()-1)
                    return true;
                pIndex++;
            }else{
                //Check if you are broken in the mid way while a matching started
                //If not in stop mid way then just incr sIndex and continue
                if(!matchStarted)
                    sIndex++;
                else{
                    String suffixPrefix = isSuffixIsAlsoAPrefix(p.substring(0, pIndex));
                    if(suffixPrefix != null){
                        pIndex = suffixPrefix.length();
                    }else{
                        //Reset match found flag and pIndex - start from O index of pattern
                        pIndex = 0;
                        matchStarted = false;
                    }
                }
            }
        }
        return false;
    }

public static String isSuffixIsAlsoAPrefix(String input){

        if(input == null || input.length() == 1)
            return null;

        int mid = input.length()/2;
        int left = mid-1;
        int right = input.length()-1;
        int matchCharCount = -1;

        while(left >= 0){
            if(input.charAt(left) == input.charAt(right)){
                matchCharCount = (matchCharCount == -1) ? left+1 : matchCharCount;
                left--;
                right--;
            }else{
                matchCharCount = -1;
                left--;
            }
        }
        return (matchCharCount != -1) ? input.substring(0, matchCharCount) : null;
    }

    @Test
    public void testValidInput_1(){
        String s = "ABCBABCBABDO";
        String p = "BABD";
        assertTrue(isSubString(s, p));
    }

    @Test
    public void testValidInput_2(){
        String s = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        String p = "AAAAA";
        assertTrue(isSubString(s, p));
    }

    @Test
    public void testFailure(){
        String s = "BBBBBBBBBBBBBBBB";
        String p = "AAAA";
        assertFalse(isSubString(s, p));
    }

    @Test
    public void testValidInput_3(){
        String s = "BBBBBBBBBBBBBBBBCDEFBBBBBCDEFGHBBB";
        String p = "BBBCDEFG";
        assertTrue(isSubString(s, p));
    }

}


texts:
I need to upload images to a remote HTTP server from a local script. The image name format is {32-char MD5}.jpg. Server directory format is 6c/d3/6cd3556deb0da54bca060b4c39479839.jpg. So, for example, if I upload the image called 6cd3556deb0da54bca060b4c39479839.jpg, it should be available at https://example.com/6c/d3/6cd3556deb0da54bca060b4c39479839.jpg.

The local script basically does a HTTPS multipart/form-data POST request with the "file" and "password" fields to a remote server (https://example.com/up.php).

Remote server has a PHP script (up.php) which checks if the "password" is correct and then either allows file uploading or disallows it.

Is this script secure? What can go wrong?

This is the code I use on the server. It checks password against SHA-512 hash and then checks if the filename extension is ".jpg".

<?php
// Upload Script
//
// You need to post "file" and "password", which is checked
// against using SHA-512

// Check if the password is correct
$password_hash = "128-characters long SHA-512 string here";
if (hash("sha512", $_POST["password"]) != $password_hash) {
    http_response_code(403);
    echo "403 Access Denied";
    exit(1);
}

if(!empty($_FILES["file"])) {
    // Check if the filename extension is ".jpg",
    // otherwise deny uploading
    $file_parts = pathinfo($_FILES["file"]["name"]);
    if ($file_parts["extension"] != "jpg") {
        http_response_code(500);
        echo "Incorrect File Extension";
        exit(1);
    }

    // Filename of the file being uploaded
    $filename = $_FILES["file"]["name"];

    // Build a directory path
    $tmp_a = mb_substr($filename, 0, 2); // First 2 chars of a filename
    $tmp_b = mb_substr($filename, 2, 2); // 3 to 4 chars of a filename
    $tmp_c = $filename;
    $directory = "$tmp_a/$tmp_b";
    // Full path to the file including the directory
    $full_path = "$directory/$filename";

    // If the directory doesn't exist, then create it
    if (!file_exists($directory)) {
        mkdir($directory, 0755, true);
    }

    // Upload the file
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $full_path)) {
        echo "Success";
    } else {
        http_response_code(500);
        echo "Something went wrong";
        exit(1);
    }
}


texts: Python 2.7 text adventure map and movement

texts:
I have been writing a python text adventure and the map module i wrote is very clunky. It is a list with compass dirs as the navigation. The problem with this is, i refer to each room by index number, and this is SUPER confusing. If anyone has any helpful advice it would be greatly appreciated.

map module (the sub-lists are just things that are in the room.):

map=[]
map.append({"name":"The Courtyard of the Castle Darkspur.",
"info":"You are in a courtyard with stone walls and moss covering the              ground.\nThere is a puddle of odd looking liquid south of you. \nTo the north is a large wooden door with a rusty iron handle.\n",
"connects":[{"north":1}],
"items":[Weapon("knife","Rusty Knife(lv 0)","It's pretty rusty...",2,4)],
"npcs":[NPC("davkas","Davkas",0,"Greetings, traveller.\nRead the scroll on the ground. It will cost you nothing.","The only advice I can give you is to read the scroll I have left in the room.")],
"npcitems":[],
"enemies":[Enemy(["onyx","spider"],"Onyx, Corrupted Spider","Fang","YOU INTRUDE UPON MY DOMAIN, HUMAN.",random.randint(0,5),5)],
"enemyitems":[Weapon("fang"," Corrupted Fang","It looks poisonous, but deadly.(lv 1)",5,5)],
"riddle":[],
"reward":[],
"scrolls":[Scroll("scroll","Scroll of Learning","scrollx","Hello, Traveller. It is I, the Prince Darkspur. I am the only one who made it out of this cursed fortress before the curse struck. I am leaving this scroll here in the hope that some valiant hero will attempt to restore the glory of my home. I tried many a time and the challenge proved too great for me.")]})
room=map[0]
map.append({"name":"The Castle Entry.",
"info": "\nA wrought iron Gargoyle looms above your head. On top of the gate is the crest of the family darkspur, who many years ago fell victim to a curse placed on the castle by a wizard.\n",
"connects":[{"south":0},{"north":2}],
"items":[Item("potion","Lesser Health Potion","It heals you, a little.",5,5),],
"npcs":[],
"npcitems":[],
"enemies":[],
"enemyitems":[],
"riddle":[Riddle("I weaken all men for hours each day.\nI show you strange visions while you are away.\nI take you by night, by day take you back,\nNone suffer to have me, but do from my lack.\n","sleep")],
"reward":[Item("key","Foyer Key","It opens the door to the castle.",0,0)],
"scrolls":[Scroll("scroll","Scroll of wisdom","scrolly","The story of the Family Darkspur.\nMany years ago, a family of valiant knights and warrior-women reigned over this land.\nThey were kind and generous to all that did them no harm.\nTo those that challenged their authority, a quick and painless death was their punishment.\nThe only thing more important to the Family Darkspur than power was wealth.\nThe family always ran into battle dressed in the finest dragon-scale mail with diamonds around their necks.\nLittle did they know that this would be their downfall.\nBEWARE OF MYSTERIOUS TREASURE.")]})


texts: Project Euler #1 Sum of multiples of 3 and 5 python implementation

texts:
Given:

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
  Find the sum of all the multiples of 3 or 5 below 1000.

My Solution:

def sum_multiples(num, limit):
    """ Calculates the sum of multiples of a given number.
    Args:
        num: The multiple.
        limit: The upper limit.
    Returns:
        The sum of the terms of a given multiple.
    """
    sum = 0
    for i in xrange(num, limit, num):
        sum += i
    return sum

def sum(limit):
    return (sum_multiples(3, limit) +
            sum_multiples(5, limit) -
            sum_multiples(15, limit))

print sum(1000)

Is there any better or more pythonic way? I have used generators for a very large calculation. Also, how can I get the running time for a given N?


texts: Adding a new class to HTML tag and writing it back with Beautiful Soup

texts:
I am working on an HTML document to which I need to add certain classes to some elements. In the following code, I am adding class img-responsive.

def add_img_class1(img_tag):
    try:
        img_tag['class'] = img_tag['class']+' img-responsive'
    except KeyError:
        img_tag['class'] = 'img-responsive'
    return img_tag

def add_img_class2(img_tag):
    if img_tag.has_attr('class'):
        img_tag['class'] = img_tag['class']+' img-responsive'
    else:
        img_tag['class'] = 'img-responsive'
    return img_tag

soup = BeautifulSoup(myhtml)
for img_tag in soup.find_all('img'):
    img_tag = add_img_class1(img_tag) #or img_tag = add_img_class2(img_tag)

html = soup.prettify(soup.original_encoding)
with open("edited.html","wb") as file:
    file.write(html)

Both functions do same, however one uses exceptions and another has_attr from BS4. Which is better and why?
Am I doing the right way of writing back to HTML? Or shall convert entire soup to UTF-8 (by string.encode('UTF-8')) and write it?


texts: Queuing e-mail notifications in a background thread

texts:
I'm new to parallel programming concepts. I'm trying to implement fire-and-forgot kind of method in my project. Somebody please evaluate the below code & let me whether this is thread safe or not.

    //Controller
    public ActionResult AddMail(Guid userId)
    {
        EmailNotification.QueueMailAync(userId);
    }

    //BL
    public static class EmailNotification
    {
    public static void QueueMailAync(Guid userId)
    {
        HostingEnvironment.QueueBackgroundWorkItem
        (
            cancellationToken =>
            {
                try
                {
                    QueueMail(userId);
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }
        );
    }

    static void QueueMail(Guid userId)
    {
        using (var context = new DBEntities())
        {
            var user = context.Users.FirstOrDefault(u => u.Id == userId);

            string body = context.EmailContents.FirstOrDefault().BodyText;
            body = body.Replace("{USER_NAME}",user.UserName);

            var mail = new ArchOver.Model.Email();
            mail.BodyText = body;
            mail.UserId = userId;
            mail.Subject = "Aync";
            mail.EmailTo = user.Person.Email;

            context.Users.Add(mail);
            context.SaveChanges();
        }
    }
}


texts: Checking if all possible combinations of any two array elements in an array contains 0-9 atleast once

texts:
I am coding for an online platform. The code is working on some test cases but is getting a Time limit exceeded. What are the ways to make my code more efficient?

  Input

5
129300455
5559948277
012334556
56789
123456879

  Output

5

  Explanation

  Winning Pairs:

  129300455 56789 -->contains all from 0-9 atleast once

  129300455 123456879-->contains all from 0-9 at least once etc

   import java.io.*;
   import java.util.*;
   import java.text.*;
   import java.math.*;
   import java.util.regex.*;

   public class Main {

static int winningLotteryTicket(String[] tickets,int n)
 // tickets = array of all strings

 {
    int count=0;
    boolean b=false;
    // the i and j loop are to create all possible combinations
    for(int i=0;i<n;i++)
{

    for(int j=i+1;j<n;j++)
    {

     if(i!=j)
     { String check=tickets[i]+tickets[j];

     // running loop to check from 0-9 atleast once
     for(int u=0;u<=9;u++)
     {
         String r=u+"";
         b=check.contains(r);
         if(!b)
         {
         break;
         }

     }
     if(b){count++;}
     }
    }
}
    return count;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    String[] tickets = new String[n];
    for(int tickets_i = 0; tickets_i < n; tickets_i++){
        tickets[tickets_i] = in.next();
    }
    int result = winningLotteryTicket(tickets,n);
    System.out.println(result);
    in.close();
}
}


texts: Code Chef's Cleaning Tables: find the minimum number of tables to clean

texts:
Description:

  Haku has been newly hired by Chef to clean tables at his restaurant.
  So whenever a customer wants a table, Haku must clean it.

  But Haku happens to be a lazy boy. So in the morning, when the
  restaurant is opened, all the tables are dirty from night before.

  The customer don't leave the table unless they are politely requested
  to do so. And customers can order meal later again. So if they were
  already having a table, they can be served on the same table [Haku
  doesn't have to clean :)]. But if they don't have a table then they
  must be given some table [Haku must clean :(]

  The restaurant has N tables. When a customer requires a table, he/she
  can occupy any unoccupied table. However if all tables are occupied,
  then Haku is free to ask politely any customer to leave his/her table.
  And the freed table can be given to the waiting customer.

  Now Chef has the psychic ability to tell the order of customer meal
  requests for the entire day. Given this list, help Haku find the
  minimum number of times he has to clean the tables.

Link

Input:

First line contains integer T, number of test cases. First line of each test case contains 2 integers N, number of tables and M, number of customer orders. Followed by M integers on next line, which is the order in which customers ask for meal. Customers are referenced by integer C.

Output:

For each test case output the minimum number of times Haku must clean the table(s).

Code:

class Main {
  public static int solve(int N, int[] orders) {
    Map<Integer, LinkedList> positions = new HashMap<>();
    for (int i = 0; i < orders.length; i++) {
      int order = orders[i];
      positions.computeIfAbsent(order, x -> new LinkedList<Integer>()).add(i);
    }
    Set<Integer> table = new HashSet<>();
    //System.out.println(positions);
    int count = 0;
    for (int i = 0; i < orders.length; i++) {
      int order = orders[i];
      if (table.contains(order)) {
        positions.get(order).removeFirst(); // remove the first entry
        continue;
      }
      count++;
      if (table.size() < N) {
        positions.get(order).removeFirst(); // remove the first entry
        table.add(order);
        continue;
      } else {
        int farthestOrder = findIndex(table, orders, i, positions);
        table.remove(farthestOrder);
        table.add(order);
      }
    }
    System.out.println("Count: " + count);
    return count;
  }

  private static int findIndex(
      Set<Integer> table, int[] orders, int i, Map<Integer, LinkedList> positions) {
    // case 1: There is at least one order which is not seen in future
    for (int order : orders) {
      if (positions.get(order).size() == 0) {
        return order;
      }
    }
    // case 2: All the orders can be seen, find farthest
    int max = -1;
    for (; i < orders.length; i++) {
      int order = orders[i];
      int position = (int) positions.get(order).getLast();
      max = Math.max(position, max);
    }
    return orders[max];
  }

  public static void main(String[] args) {
    solve(2, new int[]{1, 2, 3, 4});
    solve(2, new int[]{4, 1});
    solve(3, new int[]{1, 2, 1, 3, 4, 1});
    solve(3, new int[]{1, 2, 1, 3, 4});
  }
}

Question(s):

I assume that the solution is \$O(N^2)\$ where \$N\$ is the number of orders.
Is there any linear time algorithm possible?


texts:
I have a class MassiveDTO that contains lists. At some point in the project, I need to generate an object of this class, that will contain some hardcoded data.
I would like to know if there is a better way (or a design pattern) to populate those lists with known data.

With the method generateLists I populate them and I use them later on.
Keep in mind, I need this class not to be static because I reuse it on the project.

MassiveDTO class

public class MassiveDTO {

  private List<String> company = new ArrayList<>();
  private List<String> partners = new ArrayList<>();
  private List<String> biodata = new ArrayList<>();

  public MassiveDTO(){}

  public MassiveDTO(List<String> company, List<String> partners, List<String> biodata) {
    super();
    this.company = company ;
    this.partners = partners ;
    this.biodata = biodata;
  }

  /** Getters and Setters **/
  public List<String> getCompany() {
    return company;
  }

  public void setCompany(List<String> company) {
    this.company = company;
  }

  public List<String> getPartners() {
    return partners;
  }

  public void setPartners(List<String> partners) {
    this.partners = partners;
  }

  public List<String> getBiodata() {
    return biodata;
  }

  public void setBiodata(List<String> biodata) {
    this.biodata = biodata;
  }

  public void generateLists(){
    /** Company**/
    company.add("X0788");
    company.add("X0192");

    /** Partners **/
    partners.add("X0081");

    /** Biodata**/
    biodata.add("X0913");

  }

}

My first idea is to create another static class that will extend MassiveDTO in order to reuse those lists, and that class will be static because I will only need it to contain those specific lists with their data.


texts:
I have written this code for UVa Challenge 100:

#include<iostream>
using namespace std;
int main(){
int i,j,a,b,k,tot,gtot;
while(cin>>i>>j){
gtot=0;
a=i<j?i:j;
b=i<j?j:i;
for(int l=a;l<=b;l++){
tot=1;k=l;
while(k!=1){
tot++;
if((k%2)==0)k=k/2;
else k=(3*k)+1;
}

if(tot>gtot) gtot=tot;
}
cout<<i<<" "<<j<<" "<<gtot<<endl;
}
return 0;
}

The challenge is about finding the length of the longest Collatz sequence in a given range. Each input row contains two numbers, the minimum and maximum sequence start number to check. After calculating the maximum length of all sequences starting with a number in this range, this lentgh must be printed together with the given inputs.

My code produces the correct output for the given examples so I think it is correct but the online judge disagrees.


texts:
I wrote this program which generates anagrams for a given word.
The init function will create a dictionary of words. it can be read from a text file or array. Here I'm reading words from an array to create my dictionary.
I would like some advice on how to optimize this code or any changes or suggestions needed to improve efficiency of this code is appreciated.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {

    static Map<String, ArrayList<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

    private void addToMap(String key, String word) {
        ArrayList<String> anagramList = dictionaryMap.get(key);

        if (anagramList == null) {
            anagramList = new ArrayList<String>();
            anagramList.add(word);
            dictionaryMap.put(key, anagramList);

        }
        if (!anagramList.contains(word)) {
            anagramList.add(word);
            dictionaryMap.put(key, anagramList);
        }
    }

    private String createMap(String word) {
        Map<Character, Integer> characterCountMap = new HashMap<Character, Integer>();
        StringBuffer buff = new StringBuffer();
        char arr[] = word.toLowerCase().toCharArray();
        Arrays.sort(arr);
        String sortString = Arrays.toString(arr);
        for (int i = 0; i < sortString.length(); i++) {
            char c = sortString.charAt(i);
            if (characterCountMap.containsKey(c))
                characterCountMap.put(c, characterCountMap.get(c) + 1);
            else
                characterCountMap.put(c, 1);
        }

        for (Map.Entry<Character, Integer> entry : characterCountMap.entrySet())
            buff.append(entry.getKey() + entry.getValue());

        return buff.toString();
    }

    private Map<String, ArrayList<String>> init(String[] words) {
        for (String word : words) {
            addToMap(createMap(word), word);

        }
        return dictionaryMap;
    }

    private String[] getAnagrams(String word) {

        String key = createMap(word);
        List<String> al = dictionaryMap.get(key);
        String[] arr = al.toArray(new String[al.size()]);
        return arr;
    }

    public static void main(String[] args) {
        Solution obj = new Solution();
        System.out.println("This is a debug message");
        String arr[] = { "ate", "eat", "THIS", "EAT" };
        obj.init(arr);
        for (String anagram : obj.getAnagrams("tea"))
            System.out.println(anagram);

    }
}


texts: A Simple C++ Client That Sends Data Over TLS Using OpenSSL

texts:
I am learning C++ and socket programming and OpenSSL. As such, I decided to make a simple client that opens a TLS connection and writes some data as practice. It also serves as a base for more complex applications.

I'm very new to C++, so I don't know if I'm using good naming conventions or other basic practices. The program is using OpenSSL 1.1.0.

#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

//Not sure what headers are needed or not
//This code (theoretically) writes "Hello World, 123" to a socket over a secure TLS connection
//compiled with g++ -Wall -o client.out client.cpp -L/usr/lib -lssl -lcrypto
//Based off of: https://www.cs.utah.edu/~swalton/listings/articles/ssl_client.c
//The OpenConnection method was heavily based on the answer to this post: https://stackoverflow.com/questions/52727565/client-in-c-use-gethostbyname-or-getaddrinfo

const int ERROR_STATUS = -1;

SSL_CTX *InitSSL_CTX(void)
{
    const SSL_METHOD *method = TLS_client_method(); /* Create new client-method instance */
    SSL_CTX *ctx = SSL_CTX_new(method);

    if (ctx == nullptr)
    {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
    return ctx;
}

int OpenConnection(const char *hostname, const char *port)
{
    struct hostent *host;
    if ((host = gethostbyname(hostname)) == nullptr)
    {
        perror(hostname);
        exit(EXIT_FAILURE);
    }

    struct addrinfo hints = {0}, *addrs;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    const int status = getaddrinfo(hostname, port, &hints, &addrs);
    if (status != 0)
    {
        fprintf(stderr, "%s: %s\n", hostname, gai_strerror(status));
        exit(EXIT_FAILURE);
    }

    int sfd, err;
    for (struct addrinfo *addr = addrs; addr != nullptr; addr = addr->ai_next)
    {
        sfd = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
        if (sfd == ERROR_STATUS)
        {
            err = errno;
            continue;
        }

        if (connect(sfd, addr->ai_addr, addr->ai_addrlen) == 0)
        {
            break;
        }

        err = errno;
        sfd = ERROR_STATUS;
        close(sfd);
    }

    freeaddrinfo(addrs);

    if (sfd == ERROR_STATUS)
    {
        fprintf(stderr, "%s: %s\n", hostname, strerror(err));
        exit(EXIT_FAILURE);
    }
    return sfd;
}

void DisplayCerts(SSL *ssl)
{
    X509 *cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
    if (cert != nullptr)
    {
        printf("Server certificates:\n");
        char *line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        printf("Subject: %s\n", line);
        delete line;
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        printf("Issuer: %s\n", line);
        delete line;
        X509_free(cert);
    }
    else
    {
        printf("Info: No client certificates configured.\n");
    }
}

int main(int argc, char const *argv[])
{
    SSL_CTX *ctx = InitSSL_CTX();
    SSL *ssl = SSL_new(ctx);
    if (ssl == nullptr)
    {
        fprintf(stderr, "SSL_new() failed\n");
        exit(EXIT_FAILURE);
    }

    //Host is hardcoded to localhost for testing purposes
    const int sfd = OpenConnection("127.0.0.1", argv[1]);
    SSL_set_fd(ssl, sfd);

    const int status = SSL_connect(ssl);
    if (status != 1)
    {
        SSL_get_error(ssl, status);
        ERR_print_errors_fp(stderr); //High probability this doesn't do anything
        fprintf(stderr, "SSL_connect failed with SSL_get_error code %d\n", status);
        exit(EXIT_FAILURE);
    }

    printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    const char *chars = "Hello World, 123!";
    SSL_write(ssl, chars, strlen(chars));
    SSL_free(ssl);
    close(sfd);
    SSL_CTX_free(ctx);
    return 0;
}

Here's the same code in a Gist!


texts:
I'm learning Ruby 2.3 and I've tried to implement a function which performs the Luhn credit card verification algorithm on an input string, returning true if it matches and false if it doesn't.

def luhn(card_no)
    card_no.split("")  # Break into individual digits
           .reverse  # Start from the end
           .each_with_index
           .map {|x, i| i.odd? and x.to_i * 2 or x.to_i}  # Double every other digit
           .map {|x| if x.to_s.length > 1; x.to_s.split("").map(&:to_i).inject(:+); else x end}  # If any numbers are now 2-digit, add their digits
           .inject(:+) % 10 == 0  # Check if multiple of 10
end

p luhn("4070590981311") # => true
p luhn("3103138183910") # => false

Is there any way to make this code shorter or more "Ruby-like"? I'm sure there  must be a better way to perform the second map operation.


texts:
I am developing a high level OpenCL binding in Haskell, and I need peer-review and testing. It currently only gets platform and device info from OpenCL.

I have lots of functions that only change the returned type and the size of the type passed to the C library, but I don't know how to fix it.

GitHub

getDeviceInfoUlong :: CLDeviceInfo_ -> CLDeviceID -> IO (Either CLError CLulong)
getDeviceInfoUlong infoid device = alloca $ \(dat :: Ptr CLulong) -> do
  whenSuccess (raw_clGetDeviceInfo device infoid size (castPtr dat) nullPtr)
    $ peek dat
    where
      size = fromIntegral $ sizeOf (0::CLulong)

getDeviceInfoSizet :: CLDeviceInfo_ -> CLDeviceID -> IO (Either CLError CSize)
getDeviceInfoSizet infoid device = alloca $ \(dat :: Ptr CSize) -> do
  whenSuccess (raw_clGetDeviceInfo device infoid size (castPtr dat) nullPtr)
    $ peek dat
    where
      size = fromIntegral $ sizeOf (0::CSize)


texts: Liveupdate phone number forms and test for international numbers

texts:
I took a base from here and built on it. You call the function with onkeypress (hence live changing).

The function gives output like this for domestic numbers:

  (123) 456–7890

When the numbers pass the above character limit (13), the function outputs international numbers like this:

  +12 (345) 678-9012

It doesn't handle backspacing elegantly (reformatting), which is on my to-do list.  I'm looking for feedback on how to improve.

 var mask = function(content) {
      var val = content.value.split('');
      if (val.length > 13) {
        tel = '+'
      }
      else {tel = '('}
      for(var i=0; i< val.length; i++) {
        if(val[i] == '+'){
          val[i]='';
        }
        if(val[i] =='('){
          val[i]='';
        }
        if(val[i]==')'){
          val[i]='';
        }
        if(val[i]==' '){
          val[i]='';
        }
        if(val[i]=='-'){
          val[i]='';
        }
      }
      for(var i=0; i<val.length; i++){
          if (i==3){
            if (val.length>13) {
            val[i]= ' (' + val[i];
            }
            else {
            val[i]=val[i]+') ';
            }
          }
          if (i==7){
            if (val.length>13) {
            val[i]= val[i] + ') ';
              if (val[i+2] == '–') {
                val[i+2]='';
                val[i+5]='–'
              }
            }
          }
          if(i==8 && val[i+1] != '–'){
            if (val.length <= 13) {
            val[i]=val[i]+'–';
            }
          }
          tel=tel+val[i];
      }
      content.value=tel;
    };


texts:
I wrote a crawler that for every page visited collects the status code.
Below my solution. Is this code optimizable?

import urllib

def getfromurl(url):
    start = urllib.urlopen(url)
    raw = ''
    for lines in start.readlines():
        raw += lines
    start.close()
    return raw

def dumbwork(start_link, start_url, text, pattern, counter):
    if counter < 2:
        counter = counter +1
        while start_link != -1:
            try:
                start_url = text.find('/', start_link)
                end_url = text.find('"', start_url + 1)
                url = 'http:/' + text[start_url + 1 : end_url]
                page_status = str(urllib.urlopen(url).getcode())
                row = url + ', ' + page_status
                t.write(row + '\n')
                temp = str(getfromurl(url))
                print row
                dumbwork(temp.find(pattern), 0, temp, pattern, counter)
                start_link = text.find(pattern, end_url + 1)
            except Exception, e:
                break
    else:
        pass

t = open('inout.txt', 'w')
text = str(getfromurl('http://www.site.it'))
pattern = '<a href="http:/'
start_link = text.find(pattern)
dumbwork(start_link, 0, text, pattern, 0)
t.close()


texts:
I'm fairly new to Java and was trying to make a program that's generates the primes from 2 - 100. I originally had a design of my own making but it was fairly inefficient so I did some research and come across the Sieve of Eratosthenes, which is supposedly the the efficient way to find primes from 2 - n.

public class SieveofEratosthenes {
    public static int[] primes(int num) {
        int primeCounter = 0;
        int[] numPrimes;
        // Boolean array made 1 element longer because SOE starts at 2
        // i.e. index 2 will correspond to 2, instead of index 0 corresponding to 2 (0, 1 will be unused)
        boolean[] primes = new boolean[num + 1];
        // Fill primes array with true
        for (int i = 2; i < primes.length; i++) {
            primes[i] = true;
        }

        /*
         * Calculate primes up to num using Sieve of Eratosthenes algorithm
         */
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (primes[i]) {
                for (int k = i * i; k <= num; k += i) {
                    if (primes[k]) {
                        primes[k] = false;
                        primeCounter++;
                    }
                }
            }
        }

        /*
         *  Return array
         */
        numPrimes = new int[(num - 1)- primeCounter];  // Set size equal to number of primes in primes
        primeCounter = 0; // Reuse variable
        for (int i = 2; i < primes.length; i++) {
            if (primes[i]) {
                numPrimes[primeCounter] = i;
                primeCounter++;
            }
        }
        return numPrimes;
    }// End primes()
}// End class

I don't think I have a complete grasp on the concept of the Sieve of Eratosthenes algorithm, but I'm pretty sure I've got most of the key points.

How efficient is my code? Are there any particularly popular ways of implementing the Sieve of Eratosthenes into Java?


texts:
Upon coming face to face with the mighty cross-origin request block, and needing to get a JSON file from an external source, I decided to use the Yahoo Query Language in order to achieve this.

I'm starting to wonder however whether this code is really the most efficient way of doing it, considering the source can be in JSON, XML and Steams own language.

function getID64(name) {
    var Site = 'https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=' + key + '&vanityurl=' + name;
    //console.debug("getID64 - " + Site);
    var yql = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from json where url="' + Site + '"') + '&format=json&callback=?';
    //console.debug("getID64 - " + yql);
    $.getJSON(yql, function(data) {
        app.id64 = data.query.results.response.steamid;
        //console.debug("getID64 - " + app.id64);
        //From here onwards it's just changing some elements on the webpage and starting the next function
        document.getElementById("Steam64ID2").innerHTML += " " + app.id64;
        document.getElementById("Steam64ID").value += "" + app.id64;
        document.getElementById("SteamID2").innerHTML += " " + document.getElementById("SteamID").value;
        getFriendList(document.getElementById('Steam64ID').value);
    });
}

Considering for the first half I am only trying to get and parse the file, is there an easier way of doing this?


texts:
I would like to know if this is a great stack implementation. I created my own exception. Was that a bad idea or unnecessary? Should I have just thrown a IndexOutOfBounds exception instead of my own.

import java.util.*;
public class Stack2{
    private int[] stack;
    private int size;

    public Stack2(){
        stack = new int[10];
        size = 0;
    }

    public Stack2(int height){
        if(height <= 0){
            throw new EmptyStackException();
        }
        stack = new int[height];
        size = 0;
    }

    public void add(int value){
        if (size == stack.length){
            throw new StackOverflowException();
        }
        stack[size] = value;
        size++;
    }

    public int pop(){
        if(size == 0){
            throw new EmptyStackException();
        }
        size--;
        return stack[size + 1];
    }

    public int peek(){
        if(size == 0){
            throw new EmptyStackException();
        }
        return stack[size - 1];
    }

    public boolean isEmpty(){
        if(size == 0){
            return true;
        }
        return false;
    }

    public int getSize(){
        return this.size;
    }

    class StackOverflowException extends RuntimeException{
        public StackOverflowException(){
            super("Nothing can be added to the stack. The stack was full and has overflowed");
        }

        public StackOverflowException(String message){
            super(message);
        }
    }
}


texts: Increment up the build number in AssemblyInfo.cs on every build

texts:
I just wrote this short little program to increment up the build number for my projects every time I build them.

After compiling this exe, I just call it in the pre-build command line.

I did take out the filename string because I used it thrice, and I figured I'd get some flack if I didn't.

static void Main()
{
    int num;
    string file = "AssemblyInfo.cs";
    if (File.Exists(file))
        File.WriteAllLines(file, File.ReadAllLines(file).Select(s => !s.Trim().StartsWith("[assembly: AssemblyFileVersion(") ? s : string.Join(".", s.Trim(']').Trim(')').Trim('"').Split('.').Select((n, i) => i != 3 ? n : !int.TryParse(n, out num) ? n : (num + 1).ToString())) + "\")]"));
}

I realize this is complex, and the average person wont be able to read it. I use magic numbers, and I do some things specifically to keep the glory on 1 line. Feel free to bask in the presence of psychedelic code (which just wants to be your friend).


texts: Find the correct path through a 5 x 5 grid (coderbyte 'Correct path')

texts:
I've completed the following coderbyte question and would like feedback as to whether it follows Python best practices, is efficient and so forth.

The coderbyte problem:

Have the function calcpath(str) read the str parameter being passed, which will represent the movements made in a 5x5 grid of cells starting from the top left position The characters in the input string will be entirely composed of: r, l, u, d, ?. Each of the characters stand for the direction to take within the grid, for example: r = right, l = left, u = up, d = down. Your goal is to determine what characters the question marks should be in order for a path to be created to go from the top left of the grid all the way to the bottom right without touching previously travelled on cells in the grid.

For example: if str is "r?d?drdd" then your program should output the final correct string that will allow a path to be formed from the top left of a 5x5 grid to the bottom right. For this input, your program should, therefore, return the string rrdrdrdd. There will only ever be one correct path and there will always be at least one question mark within the input string.

Examples

Input: "???rrurdr?",
Output: "dddrrurdrd"

Input: "drdr??rrddd?",
Output: "drdruurrdddd"

Code:

import itertools
import numpy as np

def calcpath(s):
    _map = {"d": 1, "u": -1, "l": -1, "r": 1}

    q_count = s.count("?")
    move_combinations = itertools.product(_map.keys(), repeat=q_count)

    while True:
        arry = np.array([[0]*5 for i in range(5)])
        arry[0][0] = 1  # start at 0, 0

        current_x = 0
        current_y = 0

        try:
            moves = next(move_combinations)
        except StopIteration:
            return None

        ss = s[::].replace("?", "{}").format(*moves)

        for move in ss:

            if move in "lr":
                current_x += _map.get(move)
            elif move in "du":
                current_y += _map.get(move)

            if current_x < 0 or current_x > 4:
                break
            elif current_y < 0 or current_y > 4:
                break
            elif arry[current_x][current_y]:
                break
            else:
                arry[current_x][current_y] = 1

        # check for completion
        if (current_x, current_y) == (4, 4):
            return ss

assert calcpath("???rrurdr?") == "dddrrurdrd"
assert calcpath("drdr??rrddd?") == "drdruurrdddd"
assert calcpath("??ddd??lrlddd?") == None


texts: A concurrent queue that supports exactly two threads and not more. One thread is allowed to push, the other to pop

texts:
My header file implementation:

#ifndef CIRCULARSPSC_H
#define CIRCULARSPSC_H

#include <atomic>
#include <cstddef>

template<typename Data, size_t Size>
class CircularSpsc
{
public:
    enum { queue_size = Size + 1 };

    CircularSpsc() : back(0), front(0){}
    virtual ~CircularSpsc() {}

    bool push_back(const Data& item)    ;
    bool pop_front(Data& item);

    bool isEmpty() const;
    bool isFull() const;

private:
    size_t increment(size_t idx) const;
    std::atomic<size_t> back;
    Data dataArray[queue_size];
    std::atomic<size_t> front;
};

#include "circularspsc.cpp"

#endif

My source file implementation:

#ifndef CIRCULARSPSC_CPP
#define CIRCULARSPSC_CPP

#include "circularspsc.hpp"

template<typename Data, size_t Size>
bool CircularSpsc<Data, Size>::push_back(const Data& item)
{
    const auto current_back = back.load(std::memory_order_relaxed);

    const auto next_back = increment(current_back);
    if(next_back != front.load(std::memory_order_acquire))
    {
        dataArray[current_back] = item;
        back.store(next_back, std::memory_order_release);
        return true;
    }
    return false;
}

template<typename Data, size_t Size>
bool CircularSpsc<Data, Size>::pop_front(Data& item)
{
    const auto currentfront = front.load(std::memory_order_relaxed);
    if(currentfront == back.load(std::memory_order_acquire))
        return false;

    item = dataArray[currentfront];
    front.store(increment(currentfront), std::memory_order_release);
    return true;
}

template<typename Data, size_t Size>
bool CircularSpsc<Data, Size>::isEmpty() const
{
    return (front.load() == back.load());
}

template<typename Data, size_t Size>
bool CircularSpsc<Data, Size>::isFull() const
{
    const auto nextback = increment(back.load());
    return (nextback == front.load());
}

template<typename Data, size_t Size>
size_t CircularSpsc<Data, Size>::increment(size_t idx) const
{
    return (idx + 1) % queue_size;
}

#endif

Client file implementation:

#include <iostream>
#include <thread>
#include <vector>
#include "circularspsc.hpp"
#include "dataobject.hpp"

#define QUEUESIZE 10000

void reader(CircularSpsc<int, QUEUESIZE>& cspsc_q)
{
    for(int i = 0; i < QUEUESIZE; i++)
    {
        int dataItem;
        cspsc_q.pop_front(dataItem);
        std::cout << "popped value: " << dataItem << std::endl;
    }
}

void writer(CircularSpsc<int, QUEUESIZE>& cspsc_q)
{
    for(int i = 0; i < QUEUESIZE; i++)
    {
        cspsc_q.push_back(i);
    }
}

int main()
{
    CircularSpsc<int, QUEUESIZE> cspsc_q;

    std::thread writer_thread(writer, std::ref(cspsc_q));
    std::thread reader_thread(reader, std::ref(cspsc_q));

    reader_thread.join();
    writer_thread.join();
}

This has the clear drawback that we can only create queues of very limited size (because with larger values of QUEUESIZE I am getting segfault (surely because the stack size is limited?)). In my next iteration I plan to implement a version with dynamic memory allocation inside the constructor of the queue for QUEUESIZE number of objects and then use placement new to move values inside the queue.


texts:
I've written a simple web service which allows a user to shutdown or reboot a system from the LAN. Although written to be used on an RPI which lacks a power or reset button, it can be used on any Linux system.

Aside from the missing secure login (I'm assuming everyone on the network can be trusted at this moment), I'd like to know if there are potential vulnerabilities in this script. Other comments are welcome too.

# This script serves a simple web page on port 8080 which allows the server to be shut down or restarted remotely.
# Both the shutdown and reboot executables must be executable by the owner of the process.
# If sudo access is required, ensure no password is required by using NOPASSWD.
# EXAMPLE: username myuser = NOPASSWD: /sbin/reboot

import cherrypy
from os import system

cherrypy.server.socket_host = '0.0.0.0'

class PyController(object):
    @cherrypy.expose
    def index(self):
        return """<html>
          <head></head>
          <body>
            <form method="post" action="shutdown">
            <button type="submit">Shut down</button>
            </form>
            <form method="post" action="restart">
            <button type="submit">Restart</button>
            </form>
          </body>
        </html>"""

    @cherrypy.expose
    def shutdown(self):
        system('sudo shutdown -h now')

    @cherrypy.expose
    def restart(self):
        system('sudo reboot')

cherrypy.quickstart(PyController())


texts: Error-handling / Self-Validating mechanism

texts:
The below idea seemed to look clean, to allow the object itself to validate its values for different scenarios.

For eg:

While creating the object, the value of Object1 and Object2 in SelfValidator object should be validated for not null.
At one scenario like inserting the SelfValidator object to Database, validation of value1 as non-zero has to be done, which is not necessary for an Update. A new validate function: validateForInsert(), which will validate and set the error data, can be included to SelfValidator class.

But I am sure, there might be some drawbacks, design flaws, which I would like to understand and improve.

ErrorInfo.java

public class ErrorInfo {
  String errorMessage = "";

  public void setErrorMessage(String errorMessage) {
    this.errorMessage = new StringBuffer(this.errorMessage).append("\n+").append(errorMessage).toString();
  }
}

SelfValidator.java

public class SelfValidator {

  String object1;
  String object2;
  int value1;
  ErrorInfo errorInfo;

  public ErrorInfo getErrorInfo() {
    return errorInfo;
  }

  public SelfValidator(String object1, String object2, int value1) {
    super();
    this.object1 = (object1 == "")?null: object1;
    validate(this.object1, "object1");
    this.object2 = (object2 == "")?null: object2;
    validate(this.object2, "object2");
    this.value1 = value1;
  }

  private void validate(String value, String dataMember) {
    if(value == null){
        if(errorInfo == null){
            errorInfo = new ErrorInfo();
        }
        errorInfo.setErrorMessage(dataMember +" value is invalid");
    }
  }
}

Demonstrator.java

public class Demostrator {
  public static void printValidOrNot(ErrorInfo errorInfo){
    if(errorInfo == null){
        System.out.println("Object valid");
        //Proceed with manipulating the object
    }else{
        System.out.println(errorInfo.errorMessage);
        // Break and handle the error.
    }
  }
  public static void main(String[] args) {
    SelfValidator selfValidatingObject1 = new SelfValidator("Test", "Test", 1);
    printValidOrNot(selfValidatingObject1.getErrorInfo());

    SelfValidator selfValidatingObject2 = new SelfValidator("", "", 1);
    printValidOrNot(selfValidatingObject2.getErrorInfo());
  }
}


texts: Get file name with extension and get only extension

texts:
I have again 2 functions but this time they return either the full file name with extension or just the extension with a dot.

Both actions are so similar that I just copy pasted the code from one and changed 1 character... but at the inside I am cringing because it looks terrible to just copy paste. In addition I am not sure if my way of doing it is good and efficient?

-- Return everything until first forward slash starting at the end. http://my.image.com/bla.jpg would return bla.jpg
function GetFileName(url)
  local str = url
  local temp = ""
  local result = ""

  -- Get file name + extension until first forward slash (/) and then break
  for i = str:len(), 1, -1 do
    if str:sub(i,i) ~= "/" then
      temp = temp..str:sub(i,i)
    else
      break
    end
  end

  -- Reverse order of full file name
  for j = temp:len(), 1, -1 do
    result = result..temp:sub(j,j)
  end

  return result
end

-- Get the extension of a string determined by a dot . at the end of the string.
function GetFileExtension(url)
    local str = url
  local temp = ""
  local result = "." -- ! Remove the dot here to ONLY get the extension, eg. jpg without a dot. The dot is added because Download() expects a file type with a dot.

  for i = str:len(), 1, -1 do
    if str:sub(i,i) ~= "." then
      temp = temp..str:sub(i,i)
    else
      break
    end
  end

  -- Reverse order of full file name
  for j = temp:len(), 1, -1 do
    result = result..temp:sub(j,j)
  end

  return result
end

Usage:

print(GetfileName("http://mypath.to.my.image/image.jpg"))
print(GetFileExtension("http://mypath.to.my.image/image.jpg"))

Result:

image.jpg
.jpg

What would be a better approach or is this as good as it goes? (I highly doubt that. :))


texts: More elegant Sass @mixin to create pseudo-element shapes

texts:
I picked up Sass last week, and I'm already diving into expressions. I have a @mixin that creates a CSS border triangle using the following call: .foo:after { ... @include triangle(bottom,8px,7px,8px,#4986c8); } producing something like:

Here's my @mixin:

@mixin triangle($dir,$tl,$size,$br,$clr) {
    $a: solid transparent;
    @if $dir == top {
        border-left: $tl $a; border-bottom: $size solid $clr; border-right: $br $a; border-top: 0;
    } @else if $dir == right {
        border-top: $tl $a; border-left: $size solid $clr; border-bottom: $br $a; border-right: 0;
    } @else if $dir == bottom {
        border-left: $tl $a; border-top: $size solid $clr; border-right: $br $a; border-bottom: 0;
    } @else if $dir == left {
        border-top: $tl $a; border-right: $size solid $clr; border-bottom: $br $a; border-left: 0;
    }
}

Works as expected; this just doesn't seem the most elegant way to write this particular mixin. How might you do this, or any improvement tips for my code?

In the same vein, I also created this (hopefully it is self-explanitory) to be used alongside:

@mixin pseudo-pos($dir) {
    content: ""; position: absolute;
    @if $dir == top { bottom: 100%; }
    @else if $dir == right { left: 100%; }
    @else if $dir == bottom { top: 100%; }
    @else if $dir == left { right: 100%; }
}