texts:
Please review my answer for this interview question:
Merge k sorted arrays, using min heap.

import java.util.*;
public class MinHeap{
 public static class HeapItem implements Comparable<HeapItem>{
      int[] array;
      int index;        // the index of current element
      public HeapItem(int[] arr, int index) {
           array = arr;
           index = 0;
      }
      @Override
      public int compareTo(HeapItem h){
          if(array[index] > h.array[h.index]){
              return 1;
          }else if(array[index] < h.array[h.index]){
              return -1;
          }else{
              return 0;
          }
      }
 }
 public static List<Integer> mergeArrays(int[][] arrays) {
      if (arrays == null || arrays.length == 0) {
          throw new IllegalArgumentException("Invalid input!");
      }
      // priority queue is heap in Java
      PriorityQueue<HeapItem> pq = new PriorityQueue<HeapItem>();
      // add arrays to the heap
      for (int i = 0; i < arrays.length; i++) {
          pq.add(new HeapItem(arrays[i], 0));
      }
      List<Integer> result = new ArrayList<Integer> ();
      while (!pq.isEmpty()) {
          HeapItem current = pq.remove();
          result.add(current.array[current.index]);
          if (current.index < current.array.length-1) {
             pq.add(new HeapItem(current.array, current.index+1));
          }
     }
     return result;
 }
 public static void main(String[] args){
     int[] arr1 = {1, 3, 5, 7};
     int[] arr2 = {2, 4, 6, 8};
     int[] arr3 = {0, 9, 10, 11};
     System.out.println(mergeArrays(new int[][] {arr1, arr2, arr3}));
 }
}


texts: Nested for each loop (parallell) API call to work around API response 5000 row limitation

texts:
How can I optimize my code to retrieve the data faster? I'm currently using nested foreach loops to ping API on 2 levels (for each KPI -> for each municipality).

API holds KPI data for each municipality in Sweden. Because the API is built with limitation of 5000 response limit per request i have to use iteration to ping the api. The API holds KPIs for municipalities in Sweden. There are some 2000-3000 KPIs and for each KPI there are 290 municipalities and each municipality holds data for 1 or several years for that KPI.

Link to API documentation: https://github.com/Hypergene/kolada

Packages I need to use:

httr \$\rightarrow\$ get the data from the API
jsonlite \$\rightarrow\$ converting JSON to dataframes
foreach \$\rightarrow\$ foreach loops
snow \$\rightarrow\$ running foreach loops as parallel

Some set up:

url \$\leftarrow\$ "http://api.kolada.se"
path \$\leftarrow\$ ("/v2/municipality?title") # path metadata municipality look up table.
path2 \$\leftarrow\$ ("/v2/kpi") #path metadata KPI lookup table

Function to ping the API with input KPI id and municipality id:

API_get <- function(kpi,municipality){
as.data.frame(fromJSON(
  content(
    GET(url = url,
        path = str_c("/v2/data/kpi/",kpi,"/municipality/",municipality)),"text"))) %>%
  unnest() %>%
  select(kpi_id = values.kpi,
         municipality_id = values.municipality,
         period = values.period,
         gender,
         status,
         value) %>%
  type_convert()}

Alternative function that tries to simplify the function to speed up the process:

API_get2 <- function(kpi,municipality){
as.data.frame(fromJSON(
  content(
    GET(url = url,
        path = str_c("/v2/data/kpi/",kpi,"/municipality/",municipality)),"text"))) %>%
  unnest()}

The speed difference between API_get2 runs 1-1, 5 secs faster than API_get on 1 KPI and all of the 290 municipalities.

Here is the nested foreach loop that I run:

system.time(
foreach(k = SKL_kpi_has_no_gender$kpi_id[1:1],
        .combine = rbind,
        .packages = c("tidyverse","jsonlite","httr","stringr")) %:%
        foreach(m = as.character(SKL_municipality$municipality_id[1:290]),
        .combine = rbind,
        .packages = c("tidyverse","jsonlite","httr")) %dopar% API_get2(k,m) )

   user  system elapsed
   0.20    0.03    3.17

I have tried running the mapply function as the function i created has two inputs but it seem to be slower. It runs on one of my CPU cores so maybe that is why the foreach has a speed advantage. I am more wondering if there is a way to make the speed non-linear with the increase in KPIs that is iterated over.


texts:
In my application I need some resources to be loaded and I have services to load each of them and then I need some point to know that all requests finished. First thought was to use $q.all with array of promises from that services. But it would be resolved only if all promises resolved which is now always the right case because some of them may be rejected. Finally I ended up with this code:

.service 'dataRepository', ($q, Categories, Items, Settings, Session) ->
    data: {}
    fetch: ->
        res = $q.defer()
        foo =
            categories: Categories.fetch()
            items: Items.fetch()
            settings: Settings.fetch()
            user: Session.fetch()

        cEnded = 0
        for k, p of foo
            p.then do (k) =>
                (result) =>
                    @data[k] = result

            p.finally do (k) =>
                =>
                    cEnded++
                    if cEnded is _.size foo
                        res.resolve @data
        res.promise

I can put result of dataRepository.fetch() in resolve of $urlRouterProvider of ui-router and in my controllers I can be sure that data loading finished.

But this is not looking like a good solution. So the question is, are there better ways to wait for the requests pool?


texts: Calculating how much $ goes into each defaulting bucket

texts:
I have the following code which I use to determine how much of each repayment goes into each late payments bucket (i.e. 0-7 days past due, 7-15 days past due... etc)

For example, the repayment amount is 100. 20 gets repid early, and then the customer misses the repayment date. Therefore, 80 goes into the 0-7dpd bucket and so on. Similarly, if the customer does not repay for 7 days, the 80 goes into the 7-15dpd bracket.

The code works, but takes a long time. I was wondering if there is a method to make the code run faster.

repayments['principal_0_7_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 2.0), repayments.amount_principal - (repayments.child_principal_repaid_early), 0)
repayments['principal_7_15_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 7.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days), 0)
repayments['principal_15_30_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 15.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days), 0)
repayments['principal_30_45_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 30.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days), 0)
repayments['principal_45_60_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 45.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days), 0)
repayments['principal_60_90_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 60.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days + repayments.child_principal_repaid_45_60_days), 0)
repayments['principal_90_120_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 90.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days + repayments.child_principal_repaid_45_60_days + repayments.child_principal_repaid_60_90_days), 0)
repayments['principal_120_plus_dpd'] = np.where((repayments.paid_y_n == 'no') & (repayments.days_since_due >= 120.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days + repayments.child_principal_repaid_45_60_days + repayments.child_principal_repaid_60_90_days + repayments.child_principal_repaid_90_120_days), 0)

You can use the following test data. The expected output is also included below:

df = pd.DataFrame({
'amount_principal':[456.6459958, 456.6459958],
'days_since_due':[1068, 1061],
'paid_y_n':['yes, 'no'],
'child_principal_repaid_early':[0, 0],
'child_principal_repaid_1_7_days':[0, 0],
'child_principal_repaid_7_15_days':[0, 0],
'child_principal_repaid_15_30_days':[0, 180.2126753],
'child_principal_repaid_30_45_days':[0, 0],
'child_principal_repaid_45_60_days':[0, 0],
'child_principal_repaid_60_90_days':[0, 0],
'child_principal_repaid_90_120_days':[0, 0],
'child_principal_repaid_120_plus_days':[0, 0]}, index = [0,1])


texts:
Problem statement: Given an integer list from 0 to 100 find the missing Element.

I saw this problem on reddit on a compilation of interview questions, tried it out for fun. Mainly tried to generalize the code for any boundry(not just 100) and multiple missing arguments. Focused on readability and writing docstrings based on Google's recommendations. Did I hit my targets? How can and should my code be improved. Thanks!

"""
    Problem: Given a list from 0 to 100, find the missing element
"""

def makeIntArray(excludedValues, boundry):
    return [i for i in range(boundry + 1) if i not in excludedValues]

def compareToComplete(partial):
    """ Compares a possibly partial list to its complete version

        Args:
            partial: List containing integer type, all duplicates will be ignored

        Returns:
            Set of unique  missing elements or empty set if partial is complete

        example:
             partial = [1,2,3,4,6,8,10], complete = [0,1,2,3,4,5,6,7,8,9,10]
             returns: {0,5,7,9}
    """
    partial.sort()
    return {i for i in range(partial[-1] + 1)}.difference(set(partial))


texts: Reverse Polish Notation shell interpreter with one variable in C

texts:
I wrote an RPN shell stack-based interpreter. It supports following operators: +, -, *, /, %, ^. Right now it only works with positive numbers. It features also printing out the top stack element by entering new line character and popping out the result with = operator. I decided to also add one variable available to the user, it is the x variable, which can be used in two states. X (capital X) is used for reading the value of the variable and x (lowercase x) is used for writing the value to the variable.

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

#define CRESET   "\033[0m"
#define CYELLOW  "\033[33m"
#define CRED     "\033[31m"

#define MAXOP 100
#define NUMBER '0'
#define MAXSTACK 100
#define BUFSIZE 100

int getop(char []);
void push(double);
double top(void);
double pop(void);
int getch(void);
void ungetch(int);

int sp = 0;
double stack[MAXSTACK];
char buf[BUFSIZE];
int bufp = 0;
double x = 0;

main () {
    int type;
    double _op;
    char s[MAXOP];

    while ((type = getop(s)) != EOF) {
        switch (type) {
            case NUMBER:
                push(atof(s));
                break;
            case '+':
                push(pop() + pop());
                break;
            case '*':
                push(pop() * pop());
                break;
            case '-':
                _op = pop();
                push(pop() - _op);
                break;
            case '^':
                _op = pop();
                push(pow(pop(), _op));
                break;
            case '/':
                _op = pop();
                if (_op != 0.0)
                    push(pop() / _op);
                else
                    printf(CRED "ERROR: Cannot divide by 0\n" CRESET);
                break;
            case '%':
                _op = pop();
                if (_op != 0.0)
                    push(fmod(pop(), _op));
                else
                    printf(CRED "ERROR: Cannot divide by 0\n" CRESET);
                break;
            case 'x':
                x = pop();
                break;
            case 'X':
                push(x);
                break;
            case '\n':
                printf(CYELLOW "Top: %.8g\n" CRESET, top());
                break;
            case '=':
                printf(CYELLOW "Result: %.8g\n" CRESET, pop());
                break;
            default:
                printf(CRED "ERROR: Unknown command %s\n" CRESET, s);
                break;
        }

    }

}

void push(double f) {
    if (sp < MAXSTACK)
        stack[sp++] = f;
    else
        printf(CRED "ERROR: Stack is full, cannot push %g\n" CRESET, f);
}

double top(void) {
    if (sp > 0)
        return stack[sp - 1];
    else {
        return 0.0;
    }

}

double pop(void) {
    if (sp > 0)
        return stack[--sp];
    else {
        printf(CRED "ERROR: Stack is empty\n" CRESET);
        return 0.0;
    }

}

int getop(char s[]) {
    int i, c;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;

    s[1] = '\0';

    if (!isdigit(c) && c != '.')
        return c;
    i = 0;
    if (isdigit(c))
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.')
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';
    if (c != EOF)
        ungetch(c);
    return NUMBER;

}

int getch(void) {
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) {
    if (bufp >= BUFSIZE)
        printf(CRED "UNGETCH: Too many characters\n" CRESET);

  else
        buf[bufp++] = c;

}

Samples

Input:

> 2 2 + =

Output:

Result: 4
Top: 0

Input:

> 3 x
> X 5 +

Output:

Top: 8

Input (x = 3):

> X 3 ^ 2 +

Output:

Top: 29

Could you review my code? Are there any issues I missed regarding the user input?


texts: Object wrapper/parameter injection module

texts:
I made an object wrapper/parameter injector and I hope it will be useful. I made it for a project I am working on but then decided to try polishing it a bit.

The use case is for wrapping objects such that you can inject parameters into their methods by calling the wrapper as a function. I was heavily inspired by AngularJS and their use of parameter injection to almost create a DSL with their framework.

Questions:

Is this a well-designed module?
Is my code legible?
Am I over looking something that might lead to bugs later?
Is something like this safe to use?

Repo

negotiator.js

# A small tool for proxying objects behind a wrapper that can inject
# parameters into their methods.

# Extract parameter names from a function,
# position is given by position this array.
if module
  _ = require('underscore');
else
  _ = window._

utils = {};

utils.parameterNames = (func) ->

  funcArgs = func.toString().split('(')[1].split(')')[0].split(',')

  return (k.trim() for k in funcArgs)

# Inject parameters from a context object into a function.
# Passed parameters are supplied by the 'params' argument.
utils.injectAndApply =(func, parameters, context, target) ->

  signature = utils.parameterNames func
  parameters = [] if _.isEmpty(parameters)

  for position, name of signature
    parameters[position] = context[name] if context[name]?

  parameters.length = signature.length;
  return func.apply target ? {}, parameters

# Constructor for proxy object.
utils.Proxy = (real) ->

  @$real = real
  self = this

  for key, method of real when typeof method is 'function'
    do (method, key) ->
      self[key] = ->
        utils.injectAndApply method, arguments, @$context ? {}, @$real

  return this

# Build a context object from an arguments list.
utils.buildContextFromParams = (func, parameters) ->
  signature = utils.parameterNames func
  context = {}
  for key, value of parameters
    context[signature[key]] = value

  return context

# This is the circular wrapper that returns a version of itself with
# a set context.
utils.innerWrapper = (proxy, templateFunction, parameters) ->
  wrapper = ->
    utils.innerWrapper(proxy,templateFunction,arguments);

  context = utils.buildContextFromParams templateFunction, parameters
  context.$real = proxy.$real
  context.$wrapper = wrapper
  context.$proxy =  proxy
  context.$context = context;
  utils.injectAndApply templateFunction, parameters, context, proxy
  wrapper.$context = context;

  wrapper.__proto__ = proxy;

  return wrapper

# Returns a function that wraps object.
# not intended to be called as a constructor
utils.makeWrapper = (real, templateFunction) ->
  proxy = new utils.Proxy real

  return utils.innerWrapper proxy, templateFunction, []

negotiator = utils.makeWrapper
negotiator.utils = utils;

if module
  module.exports = negotiator
else
  window.negotiator = negotiator

return


texts: Program looks for correct balance of ( [ and { in expression

texts:
I'm still new to programming. (First exposure was school about a year ago), and for some reason this problem really gave me a lot of problems trying to solve it. Can you help me understand what I could have done different/better here?

import java.util.*;
public class Lab10 {
    public static void main(String[] args) throws Exception {
        Stack<String> stack = new Stack<>();

        Scanner input = new Scanner(System.in);
        System.out.print("Enter string: ");
        String s = input.nextLine();
        input.close();
        StringTokenizer tokens = new StringTokenizer(s, "[] () {}", true);

        while (tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            //Push opening delimeter to stack
            if (token.compareTo("(") == 0 || token.compareTo("{") == 0 ||
                    token.compareTo("[") == 0) {
                stack.push(token);
            }

            //when closing delimiter is encountered pop the stack
            else if (token.compareTo(")") == 0 || token.compareTo("}") == 0  ||
                    token.compareTo("]") == 0) {
                String popped = stack.pop();
                //make sure that there is a corresponding closing delimiter   for every opening
                if (!stack.isEmpty());
                if (token.compareTo(")") == 0 && popped.compareTo("(") != 0 ||
                    token.compareTo("}") == 0 && popped.compareTo("{") != 0 ||
                    token.compareTo("]") == 0 && popped.compareTo("[") != 0)   {
                    System.out.println("Incorrect grouping pairs.");
                    break;
                }
                //if stack is empty that means every thing was correct
                else if (stack.isEmpty()){
                    System.out.println("Correct grouping pairs.");
                }

            }
        }
    }
}


texts: Searching a nested data structure for 2 attributes

texts:
So I have the following data structures

export class BudgetGroupInfo {
    name: string;
    bcInfo: BudgetCatInfo[] = [];
}

export class BudgetCatInfo {
    name: string;
    description: string;
    bcAccounts: BCAccountInfo[] = [];
}

export class BCAccountInfo {
  name: string;
  description: string;
}

What I need to be able to do is find which BudgetGroupInfo contains both BudgetCatInfo.name and BCAccountInfo.name

This is what I have so far and it works, but I feel like this isn't the most efficient want to do this.

getGroupInfo(budCat: string, account: string, budgetGroupInfo: BudgetGroupInfo[]): BudgetGroupInfo {
    let groupInfo = null;

    budgetGroupInfo.forEach(infoGroup => {
      infoGroup.bcInfo.filter(bcInfo => bcInfo.name == budCat)
      .map(bcInfo => bcInfo.bcAccounts)
        .forEach(accounts => {
            const acctInfo: BCAccountInfo = accounts.find(acct => acct.name == account);
            if(acctInfo) {
              groupInfo = infoGroup;
            }
          });
      })

    return groupInfo;
  }

First I go through the groups and find which ones have the specific budCat
I take the valid BudgetCatInfo and map the bcAccount array
I search that array and look for the specified account
If I find it then I set it for return.

Just a note that there won't always be a result and there will never be multiple matches.


texts: Argument parser for a word count and/or line count program

texts:
How to make code dry in this example? My program is working, but I want to improve it by shorting my code.
.

parser = argparse.ArgumentParser()
parser.add_argument('--words', '-w', action='store_true')
parser.add_argument('--lines', '-l', action='store_true')
parser.add_argument('filename')
args = parser.parse_args()

if args.words:
    print "Words in a file: {}" .format(print_words(args.filename))

elif args.lines:
    print "Lines in a file: {}" .format(print_lines(args.filename))

else:
    print "Words in a file: {}" .format(print_words(args.filename))
    print "Lines in a file: {}" .format(print_lines(args.filename))

I guess by adding a new function and putting the function call in the else statement.

I tried with the print_all function, I added the function call in the else statement.

def print_all(filename, args):
    for a in read_file(filename):
        if a in args:
            print "All word counts :", a

When I run the program using the print_all function I get:

Namaspace(words=False, filename='someFile.txt', lines=False)


texts:
As an exercise (scroll to the first set of exercises) for learning Haskell, I have to implement foldl1.

I believe I have implemented it successfully and while there is an answer available, it would be great to have the eye of an expert and more importantly, the thought process of why certain decisions were made.

Below is my code.

foldl1' :: (a -> a -> a) -> [a] -> a
foldl1' f [a] = a
foldl1' f xs =
  foldl1' f ((f (xs !! 0) (xs !! 1)):(drop 2 xs))


texts: Probabilistic Matrix Inspection - Suggested by a paper, implemented by me

texts:
I have read this paper and I actually found it interesting.

This is an attempt to implement the proposed algorithm. I would like to know:

Is my algorithm correct by what is discribed in the paper?
Is my algorithm easy to understand?

Here is my little program

// Based on http://www.ijcai.org/Proceedings/16/Papers/053.pdf
//
// The paper uses two matrices, but I decided to "join" them into 1 matrix of
// tuples. Things are easier this way (isn't it a valid reason?).
//
// A matrix is a list of lists, but...
//
// It is not like you would expect.
//
// Each inner list represents a column, not a row!
//
// A "standard" visualization of a matrix is:
//        column1  column2  column3
//  row1 (1,  90) (1,  10) (0,  90)
//  row2 (0,   0) (1, 100) (1,  40)
//  row3 (0,  10) (1,  80) (1, 100)
//
// In my program it is seen as:
//           row1        row2        row3
//  colum1 (1,  90)    (0,   0)    (0,  10)
//  colum2 (1,  10)    (1, 100)    (1,  80)
//  colum3 (0,  90)    (1,  40)    (1, 100)
//
// It is made this way because, in this specific case, it is easier to go
// recursively in a list of columns.

let exampleMatrix = [
    [1,  90;    0,   0;    0,  10]

    [1,  10;    1, 100;    1,  80]

    [0,  90;    1,  40;    1, 100]
]

let optimalColumnOrderOf matrix =
    let sumProbabilities column =
        column
        |> List.map (fun (_, q) -> q)
        |> List.reduce (+)

    let comparator column1 column2 =
        let sum1 = sumProbabilities column1
        let sum2 = sumProbabilities column2

        sum2 - sum1

    matrix
    |> List.sortWith comparator

let thereIsZeroProbabilityIn column =
    List.exists (fun (_, q) -> q = 0) column

let optimalRowOrderOf column =
    let comparator (_, q1) (_, q2) =
        q2 - q1

    column
    |> List.sortWith comparator

let isColumnFeaseble column =
    let thereIsZeroIn c =
        c
        |> optimalRowOrderOf
        |> List.exists (fun (n, _) -> n = 0)

    if thereIsZeroProbabilityIn column then false
    else
        column
        |> List.filter (fun (_, q) -> q < 100)
        |> thereIsZeroIn
        |> not

let isMatrixFeaseble matrix =
    matrix
    |> optimalColumnOrderOf
    |> List.exists isColumnFeaseble

[<EntryPoint>]
let main argv =
    printf "%O" (isMatrixFeaseble exampleMatrix)

    System.Console.ReadKey() |> ignore

    0


texts: C# consecutive and redundant null checks

texts:
I am working on a C# application and I want to support multiple themes, so I wrote a ThemeManager class that can check, load and apply a specific theme. A theme is considered valid, when all of it's member variables are set (not null). If a theme is invalid I want to throw an IncompleteThemeException. However the following code feels a bit stupid...
public static void Load(Theme theme)
{
    AccentBrush = theme.AccentBrush ?? throw new IncompleteThemeException();
    AccentBrushLight = theme.AccentBrushLight ?? throw new IncompleteThemeException();
    WarningBrush = theme.WarningBrush ?? throw new IncompleteThemeException();
    WarningBrushLight = theme.WarningBrushLight ?? throw new IncompleteThemeException();
    ErrorBrush = theme.ErrorBrush ?? throw new IncompleteThemeException();
    ErrorBrushLight = theme.ErrorBrushLight ?? throw new IncompleteThemeException();
    MainBackgroundBrush = theme.MainBackgroundBrush ?? throw new IncompleteThemeException();
    InactiveDecoratorBrush = theme.InactiveDecoratorBrush ?? throw new IncompleteThemeException();
    SecondaryBackgroundBrush = theme.SecondaryBackgroundBrush ?? throw new IncompleteThemeException();
    MainTextBrush = theme.MainTextBrush ?? throw new IncompleteThemeException();
    SecondaryTextBrush = theme.SecondaryTextBrush ?? throw new IncompleteThemeException();
    DefaultPasswordIndicatorBrush = theme.DefaultPasswordIndicatorBrush ?? throw new IncompleteThemeException();

    AccentColor = theme.AccentColor ?? throw new IncompleteThemeException();
    MainBackgroundColor = theme.MainBackgroundColor ?? throw new IncompleteThemeException();
    AccentColorLight = theme.AccentColorLight ?? throw new IncompleteThemeException();
}

I thought about maybe using reflection to somehow iterate over all members of the theme instance to check if one of them is null, but I'm unsure what the best solution to this would be in terms of readability, performance and extensibility in the future.
How can this be improved?


texts:
Project Euler Problem 27

  Euler discovered the remarkable quadratic formula:

  \$n^2 + n + 41\$

  It turns out that the formula will produce \$40\$ primes for the
  consecutive values \$n = 0\$ to \$39\$. However, when \$n = 40, 40^2 + 40 + 41 =
> 40(40 + 1) + 41\$ is divisible by \$41\$, and certainly when \$n = 41, 41^2 +
 41 + 41\$ is clearly divisible by \$41\$.

  The incredible formula \$n^2 − 79n + 1601\$ was discovered, which produces
  \$80\$ primes for the consecutive values \$n = 0\$ to \$79\$. The product of the
  coefficients, \$−79\$ and \$1601\$, is \$−126479\$.

  Considering quadratics of the form:

  \$n^2 + an + b\$, where \$|a| < 1000\$ and \$|b| < 1000\$

  where \$|n|\$ is the modulus/absolute value of \$n\$ e.g. \$|11| = 11\$ and \$|−4| = 4\$
  Find the product of the coefficients, \$a\$ and \$b\$, for the quadratic
  expression that produces the maximum number of primes for consecutive
  values of \$n\$, starting with \$n = 0\$.

My Implementation:

I used Sieve of Eratosthenes for finding primes. I also used a HashSet for fast searching.

static void Main()
{
    HashSet<int> primes = Primes(10000000);

    Func<int,int,int,int> f = (a,b,n) => n * n + a * n + b;

    int maxCount = int.MinValue;
    int x = 0;
    int y = 0;
    for(int a = -999;a < 1000;a++)
    {
        for(int b = -999;b < 1000;b++)
        {
            int count = 0;
            int n = 0;
            while(primes.Contains(f(a,b,n++))) count++;
            if(count > maxCount)
            {
                maxCount = count;
                x = a;
                y = b;
            }
        }
    }

    Console.WriteLine("x * y = {0}",x * y);
}

static HashSet<int> Primes(int n)
{
    HashSet<int> primes = new HashSet<int>();
    BitArray a = new BitArray(n+1,true);

    for(int i = 2;i <= Math.Sqrt(n);i++)
    {
        if(a[i])
        {
            for(int j = i * i;j <= n;j += i)
            {
                a[j] = false;
            }
        }
    }

    for(int i = 2;i < a.Length;i++)
    {
        if(a[i]) primes.Add(i);
    }
    return primes;
}

How can I improve this? Can you offer a more efficient implementation?


texts: Decrypt multiple 10Mb files with defined password

texts:
One operation of my Android project is to decrypt one file (chosen in a set of ~30 files for pagination1) of ~10 Mb each and I do this with the following:

fun InputStream.cipherDecryptWithSessionPwd(password: String): String {
    var payloadArray: List<Byte>? = this.readBytes().toList()
    var salt = payloadArray?.subList(0,32)
    var spec: Rfc2898DeriveBytes? = Rfc2898DeriveBytes(password, salt?.toByteArray(), 50000)
    var realData = payloadArray?.subList(32, payloadArray.size)

    val keyBytes = spec?.getBytes(256 / 8)
    val ivBytes = spec?.getBytes(128 / 8)

    var cipher: Cipher? = Cipher.getInstance("AES/CFB/PKCS7Padding")
    var secretKey: SecretKeySpec? = SecretKeySpec(keyBytes, "AES")
    var ivSpec: IvParameterSpec? = IvParameterSpec(ivBytes)
    cipher?.init(Cipher.DECRYPT_MODE, secretKey, ivSpec)
    var byteArrayInputStream: ByteArrayInputStream? = ByteArrayInputStream(realData?.toByteArray())
    var decipherStream: CipherInputStream? = CipherInputStream(byteArrayInputStream, cipher)

    val d = BufferedReader(InputStreamReader(decipherStream, Charsets.UTF_8), 0xFFFF)
    return d.readLine()
}

The problem with this is that at around the 72nd time2 I repeat the operation Android kills my application because it runs out of memory3.

This is the second version of the decryption function, the first one caused the OOM error around the 25th time the operation was made. The problem here clearly is the number of conversions done (InputStream -> ByteArray -> List<Byte> and others).

I don't know how to optimize more, the first version of the method was not mine and I never did encryption (and optimization) before.

Scenario (and what have been tried):
 1 - Files are stored encrypted on the device, can't have them decrypted but at runtime
 2 - With the decrypted result (JSON) I fill a model using [Gson] (https://github.com/google/gson), but the OOME seem to be thrown when my function is running (the exception points at the first line of the function)
 3 - Calculations are done and the model is disposed of when the next page is shown, then the whole operation has to be repeated
 # - We tried reducing the number of JSON "records" inside each file from 5000 per file to 1000 per file reducing the file size to 2 Mb but the problem persists

Notes:
 1 - We event tried reducing the pagination reaching files size to 2 Mb but the problem persists
 2 - This has to be done at least 130 times per session
 3 - With, Knox my application is the only one allowed to run on the device


texts: Reverse int within the 32-bit signed integer range

texts:
Problem

  Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0. Optimized code here.

Feedback

I'm looking for any ways I can optimize this with modern C++ features overall. I hope my use of const-correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?

Based on the submission feedback from LeetCode, is it safe to say that the time complexity is \$O(n)\$ and space complexity is \$O(n)\$? If I can reduce the complexity in anyway would love to know!

#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>

class Solution
{
    public:
        int reverse(int i) {
            bool is_signed = false;
            if(i < 0) { is_signed = true; }

            auto i_string = std::to_string(i);

            std::string reversed = "";
            while(!i_string.empty()) {
                reversed.push_back(i_string.back());
                i_string.pop_back();
            }

            try {
                i = std::stoi(reversed);
            } catch (const std::out_of_range& e) {
                return 0;
            }

            if(is_signed) { i *= -1; }

            return i;
        }
};

int main()
{
    Solution s;
    assert(s.reverse(1) == 1);
    assert(s.reverse(0) == 0);
    assert(s.reverse(123) == 321);
    assert(s.reverse(120) == 21);
    assert(s.reverse(-123) == -321);
    assert(s.reverse(1207) == 7021);
    assert(s.reverse(INT_MAX) == 0);
    assert(s.reverse(INT_MIN) == 0);
}


texts: Project Euler #7 in C: find 10001st prime using something like Sieve of Eratosthenes

texts:
I've gotten a solution for Project Euler #7 in C (find the 10,001st prime). I came up with the very simple algorithm myself (from what I can tell it's similar, if not identical, to the Sieve of Eratosthenes).

#include <stdio.h>

#include <stdlib.h>

long prime_finder(int amount_of_primes);

int main(void)
{
int amount_of_primes = 0;

printf("How many primes would you like?\n");
scanf("%d", &amount_of_primes);

printf("%d: %ld\n", amount_of_primes, prime_finder(amount_of_primes));

return 0;
}

long prime_finder(int amount_of_primes)
{
int total_primes_found = 0;

long * primes = malloc(sizeof(long) * amount_of_primes);

for(int i = 0;i < amount_of_primes; i++) //set everything to 0
{
    primes[i] = 0;
}

for(long i = 1; total_primes_found < amount_of_primes;i++) //find the primes
{
    if(i<14) //cheat a little for the first primes
    {
        switch (i)
        {
            case 1:
                break;

            case 2:
                primes[total_primes_found++] = 2;
                break;

            case 3:
                primes[total_primes_found++] = 3;
                break;

            case 5:
                primes[total_primes_found++] = 5;
                break;

            case 7:
                primes[total_primes_found++] = 7;
                break;

            case 11:
                primes[total_primes_found++] = 11;
                break;

            case 13:
                primes[total_primes_found++] = 13;
                break;

            default:
                break;
        }
    }

    else //if it is a larger number
    {
        if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0
|| i % 7 == 0 || i % 11 == 0 || i % 13 == 0) /*makes the program a little quicker if the
*current number divides by a low number like 2 or 3*/
        {
            goto End;
        }

        else
        {
            for(int j = 0; j < total_primes_found; j++) //the brute force part of the program
            {
                if(i % primes[j] == 0)
                {
                    goto End;
                }
            }

            primes[total_primes_found++] = i;
        }

        End:;

    }
}

for(int i = 0 ; i < amount_of_primes - 1 ; i++)
    printf("%d: %ld\n", i+1, primes[i]);

return primes[amount_of_primes - 1];
}


texts: Levenshtein Distance with Haskell Vectors and Memoization

texts:
Is the following an effective way to implement the Levenshtein Distance with Haskell vectors?

  import qualified Data.Vector as V

  levenshtein s1 s2 = levenshteinV (V.fromList s1) (V.fromList s2)

  levenshteinV p1 p2 = lev V.! l1 V.! l2
    where
      lev    = V.map levi      (V.enumFromN 0 (l1 + 1))
      levi i = V.map (levij i) (V.enumFromN 0 (l2 + 1))
      levij i j
        | i == 0    = j
        | j == 0    = i
        | otherwise =
          ((lev V.! (i - 1) V.!  j)      + 1) `min`
          ((lev V.!  i      V.! (j - 1)) + 1) `min`
          ((lev V.! (i - 1) V.! (j - 1)) + ind (i - 1) (j - 1))

      ind i j = if p1 V.! i == p2 V.! j then 0 else 1
      l1      = V.length p1
      l2      = V.length p2

In particular, should I be using V.map to construct the vectors or is there a better approach? Perhaps V.generate? Or does it not make a difference because of lazy evaluation?


texts: Calling a copy constructor in Presenter to prepare a list of Models

texts:
I'm new to MVP. In a presenter I have following code. Here what am I trying is to create a list of Model objects (in this case IAttendance objects) and to show them on a DataGridView in the View.

Every time an attendance is entered on the View, AddAttendanceObjectToGrid() method on the presenter will be called to add the new attendance to the list. So to add a new Attendance model to the list I'm using a copy constructor in my Model.

Now this code runs giving the desired output but I feel this could be further improved to get the best of MVP.

class AttendancePresenter : BasePresenter
{
    private IAttendance _Model;
    private readonly IAttendanceView _View;

    BindingSource BS = new BindingSource();
    List<IAttendance> AttendanceList = new List<IAttendance>();

    public AttendancePresenter( IAttendance model, IAttendanceView view )
    {
        _Model = model;
        _View = view;
    }

    private void AddAttendanceObjectToGrid()
    {
        SetModelPropertiesFromView(_Model, _View); // Call base class method to update the Model with data
        IAttendance attendanceModel = new Attendance(_Model); // Use copy constructor to get a new copy of model
        AttendanceList.Add(attendanceModel); // Add new model to list
        BS.DataSource = AttendanceList; // Show list on the grid
        _View.AttendanceInGrid = BS;
    }
}

MY MODEL

class Attendance : IAttendance
    {
        public string PointID { get; set; }
        public string PointName { get; set; }
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public DateTime InTime { get; set; }
        public DateTime OutTime { get; set; }
        public string ShiftType { get; set; }

        public Attendance() // Default constructor
        {
        }

        public Attendance(IAttendance attendance) //Copy constructor
        {
            PointID = attendance.PointID;
            PointName = attendance.PointName;
            EmployeeID = attendance.EmployeeID;
            EmployeeName = attendance.EmployeeName;
            InTime = attendance.InTime;
            OutTime = attendance.OutTime;
            ShiftType = attendance.ShiftType;

        }
    }


texts:
I need to create matrices that follow a specific format: the matrix is a square NxN matrix and the off-diagonals all have the same value (param) and the diagonals have values such that the rows sum to zero (in other words, they are equal to 0 - param * (N-1). The output is a numpy array

Here is my code. Is there any way I can make this more readable/elegant? Speed is also important.

import numpy as np

def makeMatrix(param, N):
    ar = []
    for i in range(N):
        ar.append([ param for st in range(N) ])
        ar[i][i] = 0-(param*(N-1))

    return np.array(ar, dtype=np.double)


texts: Retrieving access token from SharedPreference

texts:
Here is code that retrieves an access token from SharedPreference.

  public static AuthToken getFromPreference(SharedPreferences p) {
    try {
      String at = p.getString(ACCESS_TOKEN_KEY, "");
      String uid = p.getString(USER_ID_KEY, "");
      long t = p.getLong(EXPIRES_AT_KEY, -1);

      if (at.isEmpty() || uid.isEmpty() || t == -1)
        return null;

      return new AuthToken(at, uid, t);
    } catch (ClassCastException e) {
      Log.wtf(TAG, "Incorrect field type in shared preference.");
      return null;
    }
  }

Can I omit exception handling if I don't expect it to happen in normal workcycle? Or should I handle even this terrible situation to not let app crash?


texts:
I my firm a few people have following problem:

A Content Management System is hosted externally. The treaty doesn't include database-access.

In September the treaty will expire. So they have to get the content copied.

I have tried to figure out something. So this programming is a first-try. A prototype in the best-case.

It works only with the HTML source-code of the articles from these news-site: heise.de

I could have used another site as well. It was just for having something to experiment with.

Here's the code I have written so far:

document.getElementById('exportText').addEventListener('click', function() {
  'use strict';
  var exportText = '';
  var re = /(data\-article\-type="meldung">)(.*)(<\/article)/m;
  var reString  = '(
)(.*?)(<\/h2>)|';
      reString += '(
)(.*?)(<\/p>)|';
      reString += '(
)(.*?)(<\/h3>)|';
      reString += '(
)(.*?)(<\/p>)';
  var matches  = [];
  var mainText = document.getElementById('source')
                         .value                            // Get the content from the first text-box.
                         .replace(/\r?\n|\r|\s{2,}/g, '')  // Remove line breaks; Multiple blanks to ONE blank.
                         .match(re)[0];                    // Restrict the area which is searched.

  re = new RegExp(reString, 'gm');

  // Search in the "meldung-wrapper"-container for h2-, h3-headlines and paragraphs.
  while ((matches = re.exec(mainText)) !== null) {
    exportText += ( matches[2] || matches[5] ||
                    matches[8] || matches[11] || '' ) + '\n\n';
  }

  document.getElementById('target').value = exportText;
});

document.getElementById('reset').addEventListener('click', function() {
  document.getElementById('source').value = '';
  document.getElementById('target').value = '';
});
* {
  background-color: #cdcdcd;
}

.wrap {
  width: 800px;
  margin: 10px auto;
}

label {
  font-weight: 900;
  margin: 10px 0;
  display: block;
}

textarea {
  background-color: #efefef;
  border-radius: 4px;
}

label,
button {
  font-family: verdana;
  sans-serif;
}

.control {
  display: inline-block;
  text-decoration: none;
  color: #fff;
  padding: 6px 8px;
  border: 1px solid;
  text-align: center;
  text-transform: uppercase;
  margin: 12px 5px;
  border-radius: 4px;
  background-color: #9a9a9a;
  font-size: .9rem;
}

.control:hover {
  background-color: #232323;
  color: #efefef;
}

.control:active {
  opacity: 0.6;
}

#target {
  padding: 4px 5px;
}
<!doctype html>

  <title>Exporter Script</title>
  <link rel="stylesheet" href="css/style.css" />

      HTML Source-Code
      <textarea id="source" rows="10" cols="100"></textarea>

      Exportierte Inhalte
      <textarea id="target" rows="20" cols="100"></textarea>

      Export starten
      Reset Textboxes

You've got to paste the source-code of an article into the textbox "HTML Source Code". Then click the button. Then the second textbox contains the textual content of the article including inline-tags (hyperlinks, bold, italic etc. are desired to be exported too).

What do you think about the approach?

- Is this a good approach? Or is there a better way to accomplish this task?

Please keep in mind that I don't have database-access.

- Are there points which can or must be improved in my programming?

- Any ideas how to accomplish a better structure?

Looking forward to reading your hints, comments and recommendations.


texts:
I cobbled together a function from various sources that takes an integer and returns it as its respective English word formatted as a string. The function is as follows:

def int2word(num, separator="-"):
    """Transforms integers =< 999 into English words

    Parameters
    ----------
    num : int
    separator : str

    Returns
    -------
    words : str
    """
    ones_and_teens = {0: "Zero", 1: 'One', 2: 'Two', 3: 'Three',
                      4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven',
                      8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven',
                      12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen',
                      15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen',
                      18: 'Eighteen', 19: 'Nineteen'}
    twenty2ninety = {2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty',
                     6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety', 0: ""}

    if 0 <= num < 19:
        return ones_and_teens[num]
    elif 20 <= num <= 99:
        tens, below_ten = divmod(num, 10)
        if below_ten > 0:
            words = twenty2ninety[tens] + separator + \
                ones_and_teens[below_ten].lower()
        else:
            words = twenty2ninety[tens]
        return words

    elif 100 <= num <= 999:
        hundreds, below_hundred = divmod(num, 100)
        tens, below_ten = divmod(below_hundred, 10)
        if below_hundred == 0:
            words = ones_and_teens[hundreds] + separator + "hundred"
        elif below_ten == 0:
            words = ones_and_teens[hundreds] + separator + \
                "hundred" + separator + twenty2ninety[tens].lower()
        else:
            if tens > 0:
                words = ones_and_teens[hundreds] + separator + "hundred" + separator + twenty2ninety[
                    tens].lower() + separator + ones_and_teens[below_ten].lower()
            else:
                words = ones_and_teens[
                    hundreds] + separator + "hundred" + separator + ones_and_teens[below_ten].lower()
        return words

    else:
        print("num out of range")


texts: Rust, compute gcd: modularity, references

texts:
This is my first time trying Rust. I wrote this code to compute the greater common divisor of 2 integers. Any advice to improve it? Am I using modularity/reference/borrow/dereference the correct way?

File src/gcd.rs:

// calculate the gcd of two integers
// https://en.wikipedia.org/wiki/Greatest_common_divisor

pub fn gcd(a: &i64, b: &i64) -> i64 {
    let mut _a = *a;
    let mut _b = *b;
    while _b != 0 {
        let tmp = _a;
        _a = _b;
        _b = tmp % _b;
    }
    _a
}

#[cfg(test)]
mod tests {
    use ::gcd;

    #[test]
    fn test_gcd() {
        assert_eq!(gcd::gcd(&60, &168), 12);
        assert_eq!(gcd::gcd(&1071, &1029), 21);
    }
}

File src/main.rs:

mod gcd;

fn main() {
    println!("gcd({}, {}) = {}", 60, 168, gcd::gcd(&60, &168));
}

Directory structure:

$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── gcd.rs
│   └── main.rs
└── target
    ├── ...


texts:
I have following code to use timer (System.Timers.Timer) in windows service. The goal is that new time handler should not occur if previous one didn't finish its job. Here is how I achieve this:

protected override void OnStart(string[] args)
{

            try
            {
                //
                // Create and start a timer.
                //
                m_mainTimer = new System.Timers.Timer();
                m_mainTimer.Interval = 60000;   // every one min
                m_mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
                m_mainTimer.AutoReset = false;  // makes it fire only once
                m_mainTimer.Enabled = true;
            }
            catch (Exception ex)
            {
              // omitted
            }

}

And:

protected override void OnStop()
    {
        try
        {
            // Service stopped. Also stop the timer.
            m_mainTimer.Enabled = false;
            m_mainTimer = null;

        }
        catch (Exception ex)
        {

        }

    }

Also in handler:

private void timer1_Tick(object sender, ElapsedEventArgs e)
        {

            try
            {
            }catch(Exceptione x)
            {
            }
            finally
            {

            if (null != m_mainTimer)
            {
                m_mainTimer.Start(); // re - enable the timer
            }
            }
}

It works but my question is is this approach safe? Maybe I should make m_mainTimer volatile? Because of the null check inside finally?


texts:
I've wrote a little program to play Tic-Tac-Toe:

public class Control {
    public static void main(String args[]) {
        Gui gui = new Gui();

    }
}

The following classed is used for applying the rules of tic-tac-toe:

import javax.swing.*;

public class TicTacToe {
    public static int count = 0;
    public static String[][] board = new String[3][3];
    public boolean test = true;

    public void buttonClicked(JButton button) {
        if(test) {
            if(button.getText().equals("")) {
                count++;
                if(count % 2 == 1) {
                    button.setText("X");
                }
                if(count % 2 == 0) {
                    button.setText("O");
                }
            }
        }

    }

    public void gameRules(JButton button) {
        if(test) {

            //"X" or "O"?
            String string = button.getText();

            //Gives coordinates of the button
            int x = Character.getNumericValue(button.getName().charAt(0));
            int y = Character.getNumericValue(button.getName().charAt(1));
            board[x][y] = string;

            if(board[0][0] != null && board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {
                JOptionPane.showMessageDialog(null,string + " won.");
                test = false;
            }

            else if(board[0][2] != null && board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0])) {
                JOptionPane.showMessageDialog(null,string + " won.");
                test = false;
            }
            else if(count == 9) {
                JOptionPane.showMessageDialog(null, "draw.");
                test = false;
            }
            else {
                for (int i = 0; i < 3; i++) {
                    if (board[i][0] != null && board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2])) {
                        JOptionPane.showMessageDialog(null, string + " won.");
                        test = false;
                        break;
                    }
                    if (board[0][i] != null && board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i])) {
                        JOptionPane.showMessageDialog(null, string + " won.");
                        test = false;
                        break;
                    }
                }
            }
        }
    }
}

And finally the class for the GUI:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Gui {
    public Gui() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        TicTacToe ticTacToe = new TicTacToe();
        panel.setLayout(new java.awt.GridLayout(3, 3));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        for (int i = 0; i < 3; i++){
            for(int j = 0; j < 3; j++) {
                final JButton button = new JButton();
                String string = i +  "" + j;
                button.setText("");
                button.setName(string);
                button.addActionListener(
                        new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                ticTacToe.buttonClicked(button);
                                ticTacToe.gameRules(button);
                            }
                        });
                button.setFont(new Font("Arial", Font.PLAIN, 40));
                button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                panel.add(button);
            }

        }

        frame.add(panel);
        frame.setSize(400,400);
        frame.setVisible(true);

    }
}

I would appreciate any suggestions to improve the code.


texts: Updating a list of a few dozen document resources in MongoEngine

texts:
This is my model:

class Subject(Document):
    uri = StringField(required=True,unique=True)
    resources = EmbeddedDocumentListField('Resource')
    date_modified = DateTimeField(default=datetime.datetime.now)

    meta = {
        'indexes': [
            {'fields': ['uri'], 'unique': True},
        ],
    }

class Resource(EmbeddedDocument):
    uri = StringField(required=True)
    title = StringField()
    snippet = StringField()
    image = StringField()
    source = StringField()
    adapter = StringField()

I am not sure if I am following the 'ideal' process when updating the embedded document. Based on Subject modified date, I need to re-set the resources. Old resources need to be deleted, as we only want current ones.

Approach 1: Add all resources to list, then save

resources = []
for p in programmes:
    #create or update the resource of this document with provided programme
    resources.append(Resource(uri=p['uri'], title=p['title'],snippet = p['snippet'],image = p['image'],adapter = p['adapter'],source = p['source']))
subject.resources = resources
subject.date_modified = datetime.datetime.now()
subject.save()

Approach 2: Using update, set each one separately.

    subject.update(unset__resources=None)
    for p in programmes:
        #create or update the resource of this document with provided programme
        resource = Resource(uri=p['uri'], title=p['title'],snippet = p['snippet'],image = p['image'],adapter = p['adapter'],source = p['source'])
        subject.update(add_to_set__resources = resource )
        subject.update(set__date_modified=datetime.datetime.now())

Which approach is better/more efficient? I expect to get up to 50 resources, no more than that.


texts:
I have built a Rails app where users can login using Facebook. They have an account on the Rails app but do any authentication in it other than creating a session if they have logged into Facebook successfully.

The first part is using the SDK to get the access_token if they have logged in:

FB.getLoginStatus(function (response) {
    if(response.authResponse) {
        $.post('/auth', {access_token: response.authResponse.access_token}, function(response) {
            window.location.href = '/';
        });
    }
});

And then I pass this to my create method in my controller:

def create
    user = User.from_facebook(params[:access_token])
    session[:user_id] = user.id
end

And the model has the following methods:

def self.from_facebook(access_token)
    # get the user from the FB API
    fb_user = get_user(access_token)
    # either return or create a user from the ID
    where(id: fb_user.id).first_or_create do |user|
        user.id = fb_user.id
        user.name = fb_user.name
    end
end

private

def get_user(access_token)
    response = RestClient get "https://graph.facebook.com/me?access_token=#{access_token}"
end

So I basically either return an existing user or create a new user with the user id that comes from using the access token. This should prevent any unauthorized access and only log in the correct user as it means that the user is logged in using the access token to get the user from Facebook.

Are there any flaws in this method? I know I don't handle if the access_token is invalid, etc. I'm more interested in the security aspect of logging the user in by getting there ID from the token, but as this is all done server side, it seems pretty secure. I also don't want to use anything like Omniauth or other gems.


texts: Insert a page definition in the right order

texts:
I have a table SlideList that defines all available slides that can be put into a PowerPoint presentation. I have a table ReportList that defines which slides go into a presentation for a company and the order they're to be inserted.

I've been maintaining ReportList by hand (yes, that's a nightmare and needs to be fixed, but it's not the point of this post), so upon initial creation of a report, I've left gaps of 10 in the SlideOrder so it's easy to insert additional slides without having to renumber everything by hand.

I've written the following T-SQL to identify the SlideOrder value to use when inserting a new slide immediately after an existing slide for every report that has that slide in it.

For example: I have existing slide Foo, and I've created a new slide Bar. I need to insert Bar as the next slide after Foo in every report that contains Foo. Some reports may have Foo as slide #50, others as slide #302 - this code will figure that out, split the gap to the next slide, and return that value as the SlideOrder for Bar. If there is no gap (Foo is SlideOrder #50, and Baz exists at SlideOrder #51) it will simply print a message and I'll have to adjust that one by hand.

Here is my T-SQL code. While it's functional, I'm looking for improvements to this code and to learn more T-SQL. If you're feeling really generous and want to rewrite it to update all the SlideOrder values > Foo so that Baz can be inserted and there are no gaps in SlideOrder, go for it! I'll be very grateful, but that's not what I'm after at the moment. (Note that this code simply prints out the SlideOrder of Foo, the SlideOrder that Bar will go in, and the SlideOrder of what follows - it doesn't do the actual insert.)

USE DevDB
GO

DECLARE @SlideToFollow as nvarchar(300)
SELECT @SlideToFollow = 'Foo'

DECLARE @SlideToFollowID as int
SELECT @SlideToFollowID = SlideID
  FROM ReportList RL inner join SlideList SL on RL.SlideID = SL.ID
 WHERE SlideName = @SlideToFollow

DECLARE @CurrentClinicID as int
SELECT @CurrentClinicID = min(ClinicID)
  FROM ReportList
 WHERE SlideID = @SlideToFollowID

WHILE @CurrentClinicID is not null
BEGIN
  DECLARE @Slide1QOrder as int
  SELECT @Slide1QOrder = SlideOrder
    FROM ReportList
   WHERE SlideID = @SlideToFollowID
     and ClinicID = @CurrentClinicID

  DECLARE @NextSlideOrder as int
  SELECT @NextSlideOrder = min(SlideOrder)
    FROM ReportList
   WHERE ClinicID = @CurrentClinicID
     AND SlideOrder > @Slide1QOrder

  IF @NextSlideOrder = @Slide1QOrder + 1
    PRINT N'ClinicID: ' + Cast(@currentClinicID as nvarchar) + ' does not have room to insert a new slide after order: ' + cast(@Slide1QOrder as nvarchar);
  ELSE
  BEGIN
    DECLARE @NewSlideOrder as int
    SELECT @NewSlideOrder = @Slide1QOrder + (@NextSlideOrder - @Slide1QOrder)/2
    PRINT N'ClinicID: ' + Cast(@CurrentClinicID as nvarchar) + '  ' + @SlideToFollow + ' slide order: ' + Cast(@Slide1QOrder as nvarchar) + ' New Slide Order: ' + Cast(@NewSlideOrder as nvarchar) + '  Next Slide Order: ' + Cast(@NextSlideOrder as nvarchar);
  END

  SELECT @CurrentClinicID = min(ClinicID)
    FROM ReportList
   WHERE SlideID = @SlideToFollowID
     AND ClinicID > @CurrentClinicID
END

SlideList:

CREATE TABLE [dbo].[SlideList](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [SlideName] [nvarchar](50) NULL,
    [SlideDesc] [nvarchar](255) NULL,
    [ExcelWksht] [nvarchar](255) NULL
GO

ReportList:

CREATE TABLE [dbo].[ReportList](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ClinicID] [int] NULL,
    [SlideID] [int] NULL,
    [SlideOrder] [int] NULL
GO


texts:
I would like the following code reviewed:

  I am trying to create a local server which listens indefinitely and
  provides the latest information. The server runs another while loop
  which fetches the latest info every one hour.

  I have tried
  multi-threading approach, in which one thread is a socket server (runs
  indefinitely) and another thread (runs indefinitely with sleep)
  updates the latest info to a global variable.The global variable is
  then accesses by the server and is sent to it's clients.

from socket import *
import threading
import pandas as pd
import json
import time
import datetime
import thread

#Global Info variable
info = pd.DataFrame()

def getInfo():
    global info
    while 1:
        print "Information retrieval running"
        try:
            #This will bring the required info as pandas df
            info = retriveInfoFromDB()
        except:
            pass
        time.sleep(3600)

def runServer():
    global info
    address = ('localhost', 6005)
    server_socket = socket(AF_INET, SOCK_DGRAM)
    server_socket.bind(address)
    while(1):
        print "Listening"
        recv_data, addr = server_socket.recvfrom(2048)
        server_socket.sendto(info.to_json(path_or_buf = None, orient = 'records', date_format = 'epoch', double_precision = 10, force_ascii = True, date_unit = 'ms', default_handler = None), addr)

th1 = threading.Thread(target=runServer)
th2 = threading.Thread(target=getInfo)

th1.start()
th2.start()


texts:
Recently I created a small app using JavaScript, and I would love for some JavaScript developers if they have the time of day, to tell me their opinions so I can grow and improve.

I'm mostly working on back-end tasks with PHP and Go, but I thought making something small in JS would be fun attempt.

Basically it's an app that sorts an image based on users choice of sorting algorithm. You first say how many rows and columns want, and past an image URL. The app then shuffles it and asks you what sort do you want.

It is then visual when sorting it back to original.

I know this is not a typical question, but I would love to get some opinions on code, and look of app. So, what do you think? Any recommendation ?

GitHub of project:

https://github.com/fvukojevic/Image-Sorting-Visualizer (if someone wants to star  ) Application: https://image-sorting-visualizer.herokuapp.com/

Example of one sorting algorithm where I'm saving every swap into an array of "animations":

function bubbleSort(arrayCopy, animations) {
    let sorted = false;
    let counter = 0;
    while(!sorted){
        sorted = true;
        for(let i=0;i<arrayCopy.length -1 - counter; i++) {
            if(arrayCopy[i].val > arrayCopy[i+1].val){
                swap(i, i+1, arrayCopy);
                sorted = false;
                animations.push([i, i+1]);
            }
        }
        counter++
    }
}


texts: Coordinating camera stage movement and data readout

texts:
The purpose of this code is important, so here's a quick rundown.

This code runs controls a physical machine which utilizes a camera and a moving stage holding an object to be imaged.  Imaging can be broken down into two parts; exposing (collecting photons) and readout (reading the formatted image from the camera over USB).

Stage moves are performed asynchronously.  The object being imaged is broken up into many (700+) "tiles" which must be imaged separately, so one move + expose + readout for each tile.

An optimization which saves ~3 minutes per imaging operation is to begin moving to tile N+1 after exposing tile N but before readout has completed.  We then wait for readout to complete, expose the current tile, and repeat the process again.

This leads to a loop structure that, while correct, is a bit confusing.  It's not a horrible piece of code, but it's been bugging me and I'd like to spend some time today refactoring it.  Problem is, I haven't come up with any great ideas.

Here's the loop structure:

void ScanLoopExample()
{
    var tiles = GetAllTiles();
    var firstTile = tiles.First();

    // get into position for the first tile
    MoveStageAsync(firstTile.X, firstTile.Y, firstTile.Z);

    foreach(var nextTile in tiles.Skip(1))
    {
        // wait for the move to complete
        WaitForMotionEnd();

        // expose over the first tile
        ExposeTile();

        // get into position for the next tile
        // we *must* make this move right here in
        // order to save time moving while the camera is busy
        MoveStageAsync(nextTile.X, nextTile.Y, nextTile.Z);

        // wait for the image to arrive from the camera,
        // we cannot expose again until this completes
        WaitForReadout();
    }

    // because we only moved to the last tile
    // without capturing, capture it here
    WaitForMotionEnd();
    ExposeTile();
    WaitForReadout();
}

Like I said, not the worst code ever, but there are a couple of things I don't like:

I don't like that part of the logic is separated from the loop itself (the move to the first tile).
I don't like that the foreach variable is the tile to move to, not the tile being captured.  It has slightly confused two coworkers I showed it to (though they got it quick enough after I explained the process).
I don't like that the capture code (wait + expose + readout) must be repeated after the loop is finished.

I've tried a couple of variants, but nothing I have come up with can get all of the capture logic in the body of the loop.  This is a bit of an obsessive need to make the code as pretty as possible, but hey, it's the weekend and I'm not on the clock.

The tricky bit is that we must begin the asynchronous move of the stage after exposure but before readout.  That places a strict rule on the ordering of operations in the loop.


texts: Efficiently squaring each element in a sorted array, keeping it sorted

texts:
The other day I was asked the following question during an interview:

  Given a sorted array, how would you square each element of this array, while keeping it sorted?

I froze up and wrote a horribly inefficient solution I've included below. Basically, I iterate through the original array, squaring each element, and then sort that array via bubble sort. (I know, I could do better, but it's what came to mind at first).

Is there a way to do this more efficiently, perhaps an \$\mathcal{O}(N)\$ solution?

void bubbleSort(int *arr, int length);

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

    int arr[] = {-3,-2,0,4,5,8};

    for(int i = 0; i < 6; i++) {
        arr[i] *= arr[i];
    }

    bubbleSort(arr, 6);

    for(int j = 0; j < 6; j++)
        cout << arr[j] << endl;
}

void bubbleSort(int *arr, int length) {
    int temp;

    for(int i = 0; i < length; i++) {
        for(int j = 0; j < length; j++) {
            if(arr[j] < arr[j+1]) {
                temp = arr[j+1];
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

Elements can be negative or positive.


texts: HTML template for win-loss data in Javascript with Mustache

texts:
Can anyone suggest a better way to implement my template code?

var $teams = $('#info');

var template = "{{#data}}
{{teamName}} 	{{playedGames}}	{{wins}}	{{draws}}	{{losses}}	{{goalDifference}}	{{points}}
{{/data}}";

$.ajax({
  headers: {
    'X-Auth-Token': '0fc841d392274cb5a26804330ac11e98'
  },
  type: 'GET',
  dataType: 'json',
  url: 'http://api.football-data.org/v1/soccerseasons/401/leagueTable',
  success: function(standings) {
    $teams.append(Mustache.render(template, {data:standings.standing}));
  }
});

This template is pulling in information from an API to display the latest league statistics.


texts:
I am currently using this code (and more) to deal with 2D matrices. I am not very proficient in C, so I am not quite sure, if this is a good way of doing it.
I've seen other people in similar situations using pointers to a struct, but I didn't want to complicate things...

typedef struct CMatrix {
    double *m;
    uint32_t width;
    uint32_t height;
} CMatrix;

-

CMatrix newCMatrix(uint32_t width, uint32_t height) {
    CMatrix rtn;
    rtn.m = malloc(width * height * sizeof(double));
    bzero(rtn.m, width * height * sizeof(double));

    rtn.width = width;
    rtn.height = height;

    return rtn;
}

-

CMatrix ma = newCMatrix(2, 2);

All ideas are welcome!


texts: Asynchronous method and collection binding

texts:
I have a WPF application, in which I'd like to bind a collection to a combobox using an asynchronous method :

<ComboBox  Margin="2,0,5,0" Width="178" ItemsSource="{Binding Animateur}" DisplayMemberPath="nom"   SelectedIndex="0"  />

the viewmodel class

_service.GetAnimateur((item, error) =>
                      {
                          if (error != null)
                          {
                              // TODO : traitement d'erreur
                          }
                          else
                          {
                              _Animateur.Clear();
                              item.ForEach(Elem =>
                              {
                                  _Animateur.Add(Elem);
                              });

                          }
                      });

the Asynchrounous method :

public async void GetAnimateur(Action<List<fiche>, Exception> callback)
        {
            try
            {
                Task<List<fiche>> data = (Task<List<fiche>>)Task.Run(
                    () =>
                    {
                        DataEntities _db = new DataEntities();
                        var dpcs = _db.fiche;
                        return new List<fiche>(dpcs);
                    });
                var result = await data;
                callback(result, null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        }

I have 20128 items in the table fiche, the problem is that GetAnimateur takes a lot of time to fill the combobox.

What are the errors that I commited in this code?
How can I improve it?


texts:
I have a more massive sp, in which I use some temporary tables, below is a part of the sp where I am updating a field in a temporary table two times.

Update #BalSheet
set OBCr = OBDr + isnull(trialDeb.amount,0)
from (
    Select v.AccountId,
        v.CompanyId,
        Sum(isnull(v.Amount,0)) Amount
    From #vwJournalDetails v , #TempJournalHeader h
    where v.JournalCredit = 1 and // 1
        h.JournalId = v.JournalId and
        h.CompanyId = v.CompanyId and
        h.JournalDate >= @dtPrevFinUnclosedSDate and
        h.JournalDate <= @dtLastFinUnclosedEDate
    group by v.CompanyId, v.AccountId
) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
    trialDeb.CompanyId = #BalSheet.CompanyID and
    trialDeb.CompanyId = @intCompanyId and
    #BalSheet.AcType ='L'

Update #BalSheet
set OBCr = OBDr - isnull(trialDeb.amount,0)
from (
    Select v.AccountId,
        v.CompanyId,
        Sum(isnull(v.Amount,0)) Amount
    From #vwJournalDetails v , #TempJournalHeader h
    where v.JournalCredit = 0 and // 2
        h.JournalId = v.JournalId and
        h.CompanyId = v.CompanyId and
        h.JournalDate >= @dtPrevFinUnclosedSDate and
        h.JournalDate <= @dtLastFinUnclosedEDate
    group by v.CompanyId, v.AccountId
) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
    trialDeb.CompanyId = #BalSheet.CompanyID and
    trialDeb.CompanyId = @intCompanyId and
    #BalSheet.AcType ='L'

As you can see, the two update query looks similar, and the only difference is in the where condition checking v.JournalCredit value.

If the v.JournalCredit = 1 I add the amount to the current value in the table, and when the v.JournalCredit = 0 I subtract the amount from the current value.

it is working correctly, but there are other update queries similar to this in the sp, So I was wondering if there is any way to mix these update query into one?


texts: Insert into array in reverse while iterating forward

texts:
So currently I have this function:
function loadPath(chunkSize, dataSize, depth, index) {
  let path = []
  let i = 0
  while (i < depth) {
    path.unshift(index % chunkSize)
    index = Math.floor(index / chunkSize)
    i++
  }
  return path
}

I would now like to pass in path as a variable from an object pool of short path arrays. So for example:
function loadPath(path, chunkSize, dataSize, depth, index) {

}

let path = new Array(3)
loadPath(path, 5, 100, 3, 41)
console.log(path) // 1, 3, 1
loadPath(path, 5, 100, 3, 50)
console.log(path) // ...

The question is, how can I do that without using push/unshift or reverse operations on the array? Basically just treating the array as a static block of memory, while at the same time not adding any unnecessary operations.
function loadPath(path, chunkSize, dataSize, depth, index) {
  let i = 0
  let x = depth - 1
  while (i < depth) {
    path[x] = index % chunkSize
    index = Math.floor(index / chunkSize)
    i++
    x--
  }
}

My question is, can this be done with any fewer temp variables? Some magic along the lines of this?
function loadPath(path, chunkSize, dataSize, depth, index) {
  let i = 0
  while (i < depth) {
    // something tricky perhaps here?
    // since x and i have a reciprocal relationship...
    // somehow fill it in backwards...
    path[depth - i] = index % chunkSize
    index = Math.floor(index / chunkSize)
    i++
  }
}

Or perhaps there is another way entirely to write this algorithm to be in as few steps and operations and temp variables as possible.
Could also use this floor implementation integrated somehow if it helps :)
function floor(n) {
  return ~~n - (~~n > n)
}


texts: Updating number of article views - potential concurrent access issue?

texts:
I have articles on my website (built in PHP) and when an article is viewed the number of views is recorded back in the database. The SQL code snippet of my load method is:

SELECT *
FROM article
WHERE id = :id;
UPDATE article
SET views = views + 1
WHERE id = :id;

This works fine, but I've only tested it locally with one user - me.

What happens if hundreds of people tried accessing the same article at once? I.e. would the update slow things down considerably? If so, is there a better way of doing this?


texts: Python optimized base64 writer for streamed files

texts:
I needed to make a base64 file encoder where you can control the read buffer size. This is what I came up with and it's quite fast. It might be able to be simpler but still maintain its performance characteristics. Any suggestions?

def chunked_base64_encode(input, input_size, output, read_size=1024):
    """
    Read a file in configurable sized chunks and write to it base64
    encoded to an output file.

    This is an optimization over ``base64.encode`` which only reads 57
    bytes at a time from the input file. Normally this is OK if the
    file in question is opened with ``open`` because Python will
    actually read the data into a larger buffer and only feed out
    57 bytes at a time. But if the input file is something like a
    file stream that's read over the network, only 57 bytes will be
    read at a time. This is very slow if the file stream is not
    buffered some other way.

    This is the case for MongoDB GridFS. The GridOut file returned by
    GridFS is not a normal file on disk. Instead it's a file read in
    256 KB chunks from MongoDB. If you read from it 57 bytes at a time,
    GridFS will read 256 KB then make lots of copies of that chunk
    to return only 57 bytes at a time. By reading in chunks equal
    to the GridFS chunk size, performance is 300 times better.

    Performance comparison:

        File size 10 MB
        Save to MongoDB took 0.271495819092 seconds
        Fast Base 64 encode (chunk size 261120) took 0.250380992889 seconds
        Base 64 encode (chunk size 57) took 62.9280769825 seconds

        File size 100 MB
        Save to MongoDB took 0.994009971619 seconds
        Fast Base 64 encode (chunk size 261120) took 2.78231501579 seconds
        Base 64 encode (chunk size 57) took 645.734956026 seconds

    For regular files on disk, there is no noticeable performance gain
    for this function over ``base64.encode`` because of Python's built
    in buffering for disk files.

    Args:
        input (file): File like object (implements ``read()``).
        input_size (int): Size of file in bytes
        output (file): File like object (implements ``write()``).
        read_size (int): How many bytes to read from ``input`` at
            a time
    """
    # 57 bytes of input will be 76 bytes of base64
    chunk_size = base64.MAXBINSIZE
    base64_line_size = base64.MAXLINESIZE
    # Read size needs to be in increments of chunk size for base64
    # output to be RFC 3548 compliant.
    read_size = read_size - (read_size % chunk_size)
    num_reads = int(ceil(input_size / float(read_size)))
    # RFC 3548 says lines should be 76 chars
    base64_lines_per_read = read_size / chunk_size

    input.seek(0)
    for r in xrange(num_reads):
        is_last_read = r == num_reads - 1
        s = input.read(read_size)
        if not s:
            # If this were to happen, then ``input_size`` is wrong or
            # the file is corrupt.
            raise ValueError(
                u'Expected to need to read %d times but got no data back on read %d' % (
                    num_reads, r + 1))

        data = b2a_base64(s)

        if is_last_read:
            # The last chunk will be smaller than the others so the
            # line count needs to be calculated. b2a_base64 adds a line
            # break so we don't count that char
            base64_lines_per_read = int(ceil((len(data) - 1) / float(base64_line_size)))

        # Split the data chunks into base64_lines_per_read number of
        # lines, each 76 chars long.
        for l in xrange(base64_lines_per_read):
            is_last_line = l == base64_lines_per_read - 1
            pos = l * base64_line_size
            line = data[pos:pos + base64_line_size]
            output.write(line)

            if not (is_last_line and is_last_read):
                # The very last line will already have a \n because of
                # b2a_base64. The other lines will not so we add it
                output.write('\n')


texts:
I'd like to improve this selection sort code

package com.arun.sort;

import java.util.Arrays;

public class SelectionSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 131, 13, 11, 1 };

        SelectionSort sort = new SelectionSort();

        sort.selectionSort(arr);

        System.out.println(Arrays.toString(arr));

    }

    public int[] selectionSort(int[] a) {

        int min;
        for (int out = 0; out < a.length - 1; out++) {
            min = out;
            for (int in = out + 1; in < a.length; in++) {
                if (a[in] < a[min]) {
                    min = in;

                }
            }
            int tempValue = a[out];
            a[out] = a[min];
            a[min] = tempValue;

        }

        return a;

    }

}


texts: Solving the problem of using directives in a header file with a macro. Is this stupid?

texts:
I am writing some library code that is mostly templates and so is all contained in header files. I know that placing a using declaration in a header will pollute all the files that include it, but I'm also starting to be really annoyed by having to spell out all the namespaces..
After a bit of tinkering I came up with these macros:

#define MACRO_CONCAT_IMPL( x, y ) x##y
#define MACRO_CONCAT( x, y ) MACRO_CONCAT_IMPL( x, y )

#define PRIVATE_NAMESPACE_IMPL( name ) namespace name { namespace exports{} } using namespace name::exports; namespace name {

#define PRIVATE_NAMESPACE PRIVATE_NAMESPACE_IMPL(MACRO_CONCAT(private_namespace_,__COUNTER__))
#define END_PRIVATE_NAMESPACE }

#define PUBLIC_SECTION namespace exports{
#define END_PUBLIC_SECTION }

To be used like this:

namespace MyNamespace{

PRIVATE_NAMESPACE

    using namespace std;
    using namespace ThirdParty::Library;
    using namespace MyCompany::OtherProduct;

PUBLIC_SECTION

    class Class{
        wstring GetString();
    };
END_PUBLIC_SECTION

END_PRIVATE_NAMESPACE

}

This will create a private namespace with the using declarations and a nested one with the publicly available code that is then imported into the topmost namespace (MyNamespace).

This is different from a plain nested namespace as it expands into this:

namespace MyNamespace{
    namespace private_namespace_0{

      using namespace std;
      using namespace ThirdParty::Library;
      using namespace MyCompany::OtherProduct;

      namespace exports{
            class Class{
                wstring GetString();
            };
        }
    }
    using namespace private_namespace_0::exports;
}

This way the "public" section has access to the "private" one and only the public one is accessible with MyNamespace::.
The weird thing with the counter is to ensure each header has its own private namespace so that declarations are not shared between separate header files. Giving an ID to the namespaces is also the only reason that i'm using macros.

Using a "private" namespace seems to be accepted practice as boost does it too. I also know that __COUNTER__ isn't really portable but vc++ and gcc both support it..

Is there anything really wrong with this idea or a better/standard way to do it?


texts:
I was trying one of the problems found on HP Codewars 2007: (2)

  Task Description:
  The CodeWars judges and scorekeepers need help printing the team names above each column on our score sheet. But we want them to look nice, so they need to be printed vertically. All we have to use is a list of team names. Please write
  us a program that will take a list of team names, and print them vertically.

  Program Input Your program will prompt for a team name. Continue prompting for names until you receive “END”. Unlike the real CodeWars,
  this one will be limited to 16 teams maximum.

  Program Output Your program will output to the screen each team’s name, in the order it was entered, arranged vertically such that it is
  read from top to bottom. There should be two spaces between each name
  as printed.

I attempted the problem and created the Java solution below:

import java.util.Scanner;
import java.util.ArrayList;

public class Prob02 {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);

        ArrayList<String> teams = new ArrayList<>();
        ArrayList<Integer> log = new ArrayList<>();

        do{
            System.out.print("Enter team name: ");
            teams.add(stdin.nextLine());
            //System.out.println(); Optional for clearer display. But not required.
        } while (!"END".equals(teams.get((teams.size()-1))));
                    //while END is not equal to last element of teams

        teams.remove(teams.get((teams.size()-1)));

        //Find largest String length
        //set defaults - index is 0 and elementLength is first length
        int index = 0;
        int elementLength = teams.get(0).length();

        //If the first one was indeed the longest one and the only one...
        log.add(index);

        for(int i = 0; i < teams.size(); i++) {
            if ((teams.get(i)).length() > elementLength) {
                //overwrite index and elementLength if the new one is larger than the default
                index = i;
                elementLength = (teams.get(i)).length();

                log.add(index); //now, we only need index (or team).
            }

            //repeat.
        }

        String longest = teams.get( log.get(log.size()-1) );

        int longestLengthOfTeam = longest.length();

        int letterYouArePrinting = 0;

        for(int i = 0; i < (longestLengthOfTeam); i++){

            for(int x = 0; x < teams.size(); x++) {
                String team = teams.get(x);
                String[] teamSplit = team.split("");
                //CONVERT !! !!! !!!!!
                ArrayList<String> teamTheNewOne = new ArrayList<>();
                for(int ttno=0; ttno < teamSplit.length; ttno++) {
                    teamTheNewOne.add(teamSplit[ttno]);
                }

                boolean inBoundChecker = (letterYouArePrinting >= teamTheNewOne.size());
                if (inBoundChecker == true) {
                    System.out.print("   "); //not a whole line! 3 Spaces, [1] + 2 req.
                    continue;
                }

                    //Print first letter of all teams
                    System.out.print(teamTheNewOne.get(letterYouArePrinting) + "  " /*Two spaces rule*/);

            }

            System.out.println();
            letterYouArePrinting++;
        //Now, print next letter
        }

    }
}

Is there a more efficient way to solve this problem?

P.S.: Problem can be found at http://www.hpcodewars.org/past/cw10/problems/Prob02%20--%20Vertical%20Printing.pdf .


texts:
Overview:

I'm using the following page template and scripts for navigation. I use a single page that loads menus and context content, and then use ajax or GET variable to load main-div's content, by passing $p variable to a php switch. Browser history is handled whith pushState function.

Main page:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="main-div">
<?php

if (isset($_GET['p'])) {
    $p = $_GET['p'];

} else {
    $p = "main";
}

require_once("assets/switch.php");

?>
    </div>

    <script>
    // Define state on first load
    function defineState() {
            "use strict";
            window.history.replaceState("<?php echo $p ?>", "", "");
        }
    window.onload = defineState;

    function navegacion(dashboard, history) {

       "use strict";
       var urlPath = dashboard;
       var xmlhttp;
       var ActiveXObject;

       if (window.XMLHttpRequest) {
           // code for IE7+, Firefox, Chrome, Opera, Safari
           xmlhttp = new XMLHttpRequest();
       } else {
           // code for IE6, IE5
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function() {
           if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {

                window.scrollTo(0, 0);

                //document.title = "TITLE";

                document.getElementById("main-div").innerHTML = xmlhttp.responseText;

                if(history !== 1) {
                    window.history.pushState(dashboard, "", "index.php?p="+urlPath);
                }

           }
       };
       xmlhttp.open("POST","assets/ajaxapi.php", true);
       xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
       xmlhttp.send("dashboard="+dashboard);

    }

    // Allows for back and forward browswe buttons

    window.onpopstate = function(e){
    "use strict";
    if(e.state){
        navegacion(e.state, 1);
    }
    };

    </script>

  </body>
</html>

ajaxapi.php:

<?php
if (isset($_POST['dashboard'])) {
    $p = $_POST['dashboard'];

} else {
    $p = NULL;
}

require_once("./switch.php");

Could there be any performance or error issues with this code, or how could this script be enhanced?

Thanks.


texts:
I've made a program that outputs you the most common word in txt file. Does anybody know how to optimize it so that it would work for bigger files and run faster?

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <math.h>

using namespace std;

int main()
{
    ifstream in("file.txt");

    if(!in){
        cerr << "Could not open file.txt.";
        return EXIT_FAILURE;
    }

    string str, str2, strn, tab[10000], tab2[10000];
    int i, k, j, n, l, tabl;
    char c = 179;
    vector<int> tabs;
    vector<string> stringi;

    while(getline(in, str2)){
        str += str2;
        str += ' ';
    }
    k = 0;
    for(i = 0; i < str.length(); i++){
        if(str[i] != ' ' && str[i] != '.' && str[i] != '\t' && str[i] != ','
           && str[i] != ';' && str[i] != ':' && str[i] != '}' && str[i] != '{'){
            tab[k] += tolower(str[i]);
        }else{
            k++;
        }
        if(str[i] == '.' || str[i] == '\t' || str[i] == ',' || str[i] == ';'
        || str[i] == ':' || str[i] == '}' || str[i] == '{') {
            k--;
        }
    }
    tabl = k;

    k = 0;
    for(i = 0; i < tabl; i++){
        for(j = 0; j < tabl; j++){
            if(tab[i] == tab[j]){
                k++;
            }
        }
        tabs.push_back(k);
        k = 0;
    }
    for(i = 0; i < tabl; i++){
        for(j = 0; j < tabl-1; j++){
            if(tab[j] < tab[j+1]){
                n = tabs.at(j);
                tabs.at(j) = tabs.at(j+1);
                tabs.at(j+1) = n;
                strn = tab[j];
                tab[j] = tab[j+1];
                tab[j+1] = strn;
            }
        }
    }
    for(i = 0; i < tabl; i++){
        for(j = 0; j < tabl-1; j++){
            if(tabs.at(j) < tabs.at(j+1)){
                n = tabs.at(j);
                tabs.at(j) = tabs.at(j+1);
                tabs.at(j+1) = n;
                strn = tab[j];
                tab[j] = tab[j+1];
                tab[j+1] = strn;
            }
        }
    }
    tab2[0] = tab[0];
    for(i = 0; i < tabl; i++){
        if(tab[i] != tab[i+1]){
            tab2[i] = tab[i+1];
        }
    }
    k = 1;
    l++;
    for(i = 0; i < tabl; i++){
        if(!tab2[i].empty()){
            l++;
        }
    }
    cout << "------------------------------------" << endl;
    cout << "|--->TABLE OF MOST COMMON WORDS<---|" << endl;
    cout << "------------------------------------" << endl;
    for(i = 0; i < tabl; i++){
        if(!tab2[i].empty() && k <= 20 ){
            cout << c << k++ << "." << '\t' << c << tab2[i] << '\t' << c << "*" <<
            tabs.at(i+1)
            << '\t'  << c << roundf(((float)tabs.at(i+1)*100/l)*100)/100 << "%" <<
            endl;
        }
    }
    cout << "------------------------------------" << endl ;
    cout << "|----->Dif. strings: " << '\t' << l << "<-------|" << endl ;
    cout << "------------------------------------" << endl;

    return 0;
}

Output image:


texts:
The following code was written to be a submission to this challenge on PPCG.

It uses this algorithm, the Meissal-Lehmer method. I follow the Wikipedia entry pretty naively, except I tried to memoize the phi function.

Please see @Shepmaster's answer for cleaned up, more idiomatic Rust.

I am looking for ways to improve speed. Most improvements I believe will come from optimizing the phi function, which is used recursively. Answers about making my code more idiomatic Rust are also welcome.

I've been compiling with cargo build --release. The code runs in ~3 sec for input 1,000,000 and a lot longer for 10,000,000.

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let x: usize = (args[1]).trim().parse()
        .expect("expected a number");

    let root: usize = (x as f64).sqrt() as usize;
    let y: usize = (x as f64).powf(0.3333333333333) as usize + 1;

    let sieve_size: usize = x/y+2;//y+1;
    let mut sieve: Vec<bool> = vec![true; sieve_size ];
    let mut primes: Vec<usize> = vec![0; sieve_size ];
    sieve[0] = false; sieve[1] = false;

    let mut a: usize = 0;
    let mut num_primes = 1;

    let mut num_primes_smaller_root: usize = 0;

    // find all primes up to x/y ~ x^2/3 aka sieve_size
    for i in 2..sieve_size {
        if sieve[i] {
            if i<= root {
                if i<=y {
                    a+=1;
                }
                num_primes_smaller_root+=1;
            }

            primes[num_primes] = i;
            num_primes +=1;
            let mut multiples: usize = i;
            while multiples < sieve_size {
                sieve[multiples] = false;
                multiples += i;
            }
        }
    }

    let mut phi_results: Vec<Vec<usize>> = vec![ vec![0; a+1 ];x+1 ];

    let mut p_2: usize = 0;
    for i in a+1..num_primes_smaller_root+1 {
        let mut first_term: usize = 0;
        while primes[first_term]< x/primes[i] {
            //println!("checking {} vs {}...",primes[first_term],x/primes[i]);
            first_term+=1;
        }
        if primes[first_term]==x/primes[i] {
            first_term +=1;
        }
        p_2 += (first_term -1) - i + 1;
    }

    /*println!("y={}; a={}",y,a);
    println!("P2 = {}",p_2);
    println!("phi({},{}) = {}",x, a, phi(x,a,&primes));
    */
    println!("pi({}) = {}", x, phi(x,a,&primes,&mut phi_results)+a-1-p_2);
}

fn phi(x:usize, b:usize, primes:&Vec<usize>, phi_results:&mut Vec<Vec<usize>>)->usize {
    if b==0 {
        return x;
    }
    if phi_results[x][b] != 0 {
        return phi_results[x][b];
    }
    let value: usize = phi(x,b-1,primes,phi_results) - phi(x/primes[b],b-1,primes,phi_results);
    phi_results[x][b] = value;
    return value;
}

I'm kind of new to the site, so please let me know how to improve this post as a whole too, if necessary


texts: Parsing a u8 separated vector of FromStr from a BufRead

texts:
I need to read a vector of e.g. integers from a stream, usually from stdin but sometimes also from a file. The input is always less than a megabyte, and is sometimes separated by commas and sometimes by newlines.
I'm calling the code directly from my main function, so I'm more concerned with returning a human readable error rather than something that can be caught and recovered from programmatically, hence I'm using String as the error type.
pub fn parse_vector<T: BufRead, S: FromStr>(buf: T, sep: u8) -> Result<Vec<S>, String> {
    buf.split(sep)
        .enumerate()
        .filter_map(|(i, entry)| {
            let entry_nr = i + 1;

            let entry = match entry.map(String::from_utf8) {
                Err(e) => return Err(format!("Cannot read entry {}, {}.", entry_nr, e)).into(),
                Ok(Err(e)) => return Err(format!("Cannot read entry {}, {}.", entry_nr, e)).into(),
                Ok(Ok(v)) => v,
            };

            let trimmed = entry.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(
                    trimmed
                        .parse::<S>()
                        .map_err(|_| format!("Cannot parse entry {}: '{}'", entry_nr, entry)),
                )
            }
        })
        .collect()
}

The above code works as far as I can tell, but I'm wondering if there's a nicer way to deal with the mess in the match expression. The functions from_utf8 and split return different error types, but both implement Display so maybe there's some elegant way to eliminate some code duplication there that I don't know about (I'm new to rust, coming from c++).

What are my options to make this code more readable?
Is it considered bad practice to return String as an error type?


texts: (codefights) check for almost increasing subsequence

texts:
(This problem is from CodeFights, so I'm not entirely sure that I should be posting a solution here, but given that some people posted a solution to this problem in the comments I think I should be OK.)

The input to the code is an array of integers, and an almost increasing sequence is such an array that can be turned into a strictly increasing sequence of integers by removing 0 or 1 elements.  The output should be true if the array is an almost increasing sequence, and false otherwise.

boolean almostIncreasingSequence(int[] sequence) {
    boolean noFailuresYet = true;
    for(int i = 0; i < sequence.length-1; i++) {
        if(sequence[i] >= sequence[i+1]) {
            if(noFailuresYet) {
                if(i != 0 && i != sequence.length-2) {
                    if(sequence[i+1] <= sequence[i-1]) {
                        //Here we run the next iteration of the loop manually
                        //Alternatively we could set sequence[i] = sequence[i-1]
                        //but I don't want to modify the input array
                        //in case this function were to get used to check something elsewhere
                        if(sequence[i+2] <= sequence[i]) {
                            return false;
                        }
                        i++;
                    }
                }
                noFailuresYet = false;
            } else {
                return false;
            }
        }
    }
    return true;
    }

What I don't like about this code is that it has a bunch of nested if statements.

After looking at a solution code, I saw that the condition in the 2 innermost if statements could be replaced by a local check that returns false immediately if there is a certain local pattern, but I would like to know if I can reduce the nested if statements without using that (unless there is a natural way to come up with that idea by thinking about improving the code).


texts:
This question is related to this one, since it's about the same Codility exercise (Tape Equilibrium instructions): Time complexity of tape equilibirum

Basically, given an integer array, the objective is to split it at a given index into 2 smaller arrays, sum each arrays and find the smallest absolute difference possible between the 2 arrays.

Example:

I have an array A[] = {3, 1, 2, 4, 3}.

If I split at index 1, left array is {3} and right array is {1, 2, 4, 3}. The absolute difference is |(3) - (1 + 2 + 4 + 3)| = 7.

The smallest possible split is with index 3, where left array is {3, 1, 2} and right array is {4, 3} and the absolute difference is |(3 + 1 + 2) - (4 + 3)| = 1.

I have written the following code:

class Solution {

    private Map<Integer, Integer> lowerSplitSumValue;
    private Map<Integer, Integer> upperSplitSumValue;

    public void loadSplitSumValue(int[] A) {
        if (lowerSplitSumValue == null) {
            lowerSplitSumValue = new HashMap<Integer, Integer>();
            upperSplitSumValue = new HashMap<Integer, Integer>();
        }

        for (int i = 1 ; i < A.length ; ++i) {
            if (i != 1) {
                lowerSplitSumValue.put(i, lowerSplitSumValue.get(i - 1) + A[i - 1]);
                upperSplitSumValue.put(A.length - i, upperSplitSumValue.get(A.length - i + 1) + A[A.length - i]);
            } else {
                lowerSplitSumValue.put(i, A[0]);
                upperSplitSumValue.put(A.length - i, A[A.length - 1]);
            }
        }
    }

    public int solution(int[] A) {
        if (A == null || A.length < 1) {
            return 0;
        }

        loadSplitSumValue(A);

        int smallestValue = Math.abs(lowerSplitSumValue.get(1) - upperSplitSumValue.get(1));

        for (int i = 2 ; i < A.length - 1 ; ++i) {
            int newValue = Math.abs(lowerSplitSumValue.get(i) - upperSplitSumValue.get(i));

            if (newValue < smallestValue) {
                smallestValue = newValue;
            }
        }

        return smallestValue;
    }
}

From my understanding, this should be at most \$O(N*log(N))\$:

I'm using several for loops, but none of them are nested, so their complexity is \$O(N)\$.
Each for loops are accessing a Map, which to my understanding have a general complexity of \$O(log(N))\$.

However, when I submit this code on Codility, the compiler says only 33% of the performance tests passed, and the complexity is \$O(N*N)\$, which is way higher than what I expected...

Why does Codility consider my algorithm to be \$O(N*N)\$? Java Maps aren't supposed to be that slow...