texts: Given a binary tree, \$T\$ whose nodes have positive values, find the value of the maximal path

texts:
Problem

Problem is Maximum sum path from https://firecode.io

Given a binary tree, \$T\$, whose nodes have positive values find the value of a maximal path. A path is a simple path from a node to another node. The value of a path \$P\$ is

$$val(P) = \sum\limits_{u \in P} val(u)$$

that is, the sum of the values of the nodes along \$P\$. A maximal path \$M\$ is one that satisfies:

$$\forall\ \ paths\ \ P,\ \ val(P) \le val(M)$$

Python solution

class BinaryTreeNode:
    def __init__(self, data, left = None, right = None):
        self.data = data
        self.left = left
        self.right = right

class BinaryTree:
    def __init__(self, root = None):
        self.root = root

    def max_sum_path(self, root):

        _, val_of_max_path = self._val_of_max_path(root)

        return val_of_max_path

    def _val_of_max_path(self, root):
        ''' Returns a tuple:
            ( val of the maximal path
              from a leaf up to root,

              val of the maximal path
              from a node to another
              node in this subtree )
        '''

        # base case
        if not root:
            return (0, 0)

        # recursive case

        ( val_of_max_path_from_a_leaf_up_to_left_child,
          val_of_max_path_in_left_subtree ) = (

              self._val_of_max_path(root.left) )

        ( val_of_max_path_from_a_leaf_up_to_right_child,
          val_of_max_path_in_right_subtree ) = (

              self._val_of_max_path(root.right) )

        val_of_max_path_from_a_leaf_up_to_root = root.data + max(

            val_of_max_path_from_a_leaf_up_to_left_child,
            val_of_max_path_from_a_leaf_up_to_right_child )

        val_of_max_path_that_has_a_turning_point_at_root = (

            val_of_max_path_from_a_leaf_up_to_left_child +
            root.data +
            val_of_max_path_from_a_leaf_up_to_right_child )

        val_of_max_path_in_this_subtree = max(

            val_of_max_path_in_left_subtree,
            val_of_max_path_in_right_subtree,
            val_of_max_path_that_has_a_turning_point_at_root )

        return ( val_of_max_path_from_a_leaf_up_to_root,
                 val_of_max_path_in_this_subtree )

Comments

I use very long descriptive variable names. I am not sure if I am overdoing it or not. Do you see a way to shorten them whilst maintaining meaning? I have an upcoming technical interview so I want to make sure I exhibit good style. Also, I will be coding in a shared Google Doc, so I won't have access to syntax highlighting. Any tips or suggestions are greatly appreciated.


texts: Split a character string based on change of character

texts:
I am contributing a solution to the following task on Rosetta Code:

  Task
  Split a string into comma (plus a blank) delimited strings based on a change of character (left to right).

  Show the output here (use the 1st example below).

  Blanks should be treated as any other character (except they are
  problematic to display clearly). The same applies to commas.

  For instance, the string:

    gHHH5YY++///\

  should be split and show:

    g, HHH, 5, YY, ++, ///, \

Here is the code:

// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
#include<string>
#include<iostream>
auto spliter(const std::string &input) {
   auto firstCommaPast = false;
   std::string res ="";
   auto prev = '\0';
   for(auto it = input.cbegin(); it != input.cend();++it) {
      if(*it!=prev) {
         if(!firstCommaPast) {
            firstCommaPast = true;
         } else {
            res+=", ";
         }
      }
      res+=*it;
      prev=*it;
   }
   return res;
}

int main() {
   auto input = R"(gHHH5  ))YY++,,,///\)";
   std::cout<<spliter(input);
}

I am fairly new to C++11/14 so any suggestions here will really help.


texts:
My colleagues often ask me, "Dude could you remind me what I have to type to build this target?". So I eventually implemented a nice workaround in my Makefiles.

I wanted my Makefiles to have a help target that give some usage clues to the users. This is achieved with an embedded Perl script and some markers.

Wherever I want a target to be documented, I simply add this trailing comment:

##@<category> <description>

Here is an example:

SCRIPT_VERSION=v1.0
SCRIPT_AUTHOR=John Doe

all:                ##@Build Build all the project
     echo "Hello World!" > all

clean:              ##@Cleaning Remove all intermediate objects
     rm all

mrproper: clean     ##@Cleaning Remove all output and interemediate objects

HELP_FUN = \
    %help; while(<>){push@{$$help{$$2//'options'}},[$$1,$$3] \
     if/^(\w+)\s*:.*\#\#(?:@(\w+))?\s(.*)$$/}; \
    print"$$_:\n", map"  $$_->[0]".(" "x(20-length($$_->[0])))."$$_->[1]\n",\
    @{$$help{$$_}},"\n" for keys %help; \

help: ##@Miscellaneous Show this help
    @echo -e "Usage: make [target] ...\n"
    @perl -e '$(HELP_FUN)' $(MAKEFILE_LIST)
    @echo -e "Written by $(SCRIPT_AUTHOR), version $(SCRIPT_VERSION)"
    @echo -e "Please report any bug or error to the author."

Here what I get if I type make help:

$ make help
Usage: make [target] ...

Miscellaneous:
  help                Show this help

Build:
  all                 Build all the project

Cleaning:
  clean               Remove all intermediate objects
  mrproper            Remove all output and interemediate objects

Written by John Doe, version v1.0
Please report any bug or error to the author.

In the case the Makefile takes time to parse the dependencies we can bypass the file for the help target:

ifeq (,$(filter help,$(MAKECMDGOALS)))
# Core of the makefile
endif

What do you think of this technique. Is it a good approach? Can I improve it?


texts: Bash script to encode images in base64 and generate a CSS file from them

texts:
These are the first lines of code I've ever written. I've been interested in the idea of learning to program for quite a while, but never really pulled the trigger, and now I've been playing around with some HTML & CSS and thought this might be a good starter project. So after a couple of days of furious googling, I managed to cobble this script together.

What I'm mostly curious about is the overall logic and structure of the code. The whole script grew organically from me looking up the Bash constructs and figuring out how to combine them to do what I want, so I don't know how sensible it is from the programming standpoint.

The idea is to keep the script in my project's folder and use relative paths, so I can just run it when I need to regenerate the CSS.

#!/bin/bash

# CSS ruleset template:
#
# .________::before { background-image: url(data:________;base64,__________); }
#  filename                                      mimetype        base64 str
#
# CSS class names and other identifiers can contain the characters
# A-Z, a-z, 0-9, hyphen, underscore and Unicode characters U+00A0 and higher.
# They cannot start with a digit, two hyphens or a hyphen followed by a digit.
# (https://www.w3.org/TR/CSS2/syndata.html#characters)
#
# url(), unquoted, requires escaping the characters ()'" and whitespace.
# url('') & url("") require escaping newlines and the quote used for quoting.
# (https://www.w3.org/TR/CSS2/syndata.html#uri)
#
# Base64 encoding uses characters A-Z, a-z, 0-9 and any two of these: +-.,:/_~
# Therefore, there's never need to escape anything, so no quotes are necessary.

css_path="icons.css" # relative to the script

cd "${BASH_SOURCE%/*}"

: > "$css_path"

for file in icons/*; do
    echo Processing "$file"

    filename="$(name_ext="${file##*/}"; echo "${name_ext%.*}")"
    ext="${file##*.}"

    shopt -s nocasematch
    case "$ext" in
        avif      ) mime="image/avif"   ;;
        bmp       ) mime="image/bmp"    ;;
        gif       ) mime="image/gif"    ;;
        jpg | jpeg) mime="image/jpeg"   ;;
        png       ) mime="image/png"    ;;
        svg       ) mime="image/svg+xml";;
        *         ) mime="unsupported"  ;;
    esac

    if [[ "$mime" = "unsupported" ]]; then
        unsupported+=("$file")
    elif [[ ! "$filename" =~ ^-?[A-Za-z_][A-Za-z0-9_-]*$ ]]; then
        invalid_class_name+=("$file")
    else
        base64str="$(base64 --wrap=0 "$file")"
        printf ".%s::before { background-image: url(data:%s;base64,%s); }\n" \
        "$filename" "$mime" "$base64str" \
        >> "$css_path"
    fi
done

if [[ -z "$unsupported" && -z "$invalid_class_name" ]]; then
    echo "All done!"
else
    if [[ -n "$unsupported" ]]; then
        printf "\n\n%s\n\n" "UNSUPPORTED FILES (SKIPPED)"
        printf "  %s\n"       "${unsupported[@]}"
    fi
    if [[ -n "$invalid_class_name" ]]; then
        printf "\n\n%s\n" "FILENAMES INVALID AS CSS CLASS NAMES (SKIPPED)"
        printf "  %s\n"   "Allowed characters: A-Z, a-z, 0-9, '-', '_'"
        printf "  %s\n\n" "Can't begin with: 0-9, '--', '-0' through '-9'"
        printf "  %s\n"   "${invalid_class_name[@]}"
    fi
fi
```


texts: Parser for tab-delimited data as a subclass of StringReader

texts:
I wanted to parse lines of text as tab-delimited items, and I had just been using a StringReader for something else and I came up with this:

class TabDelimitedFieldReader : StringReader
    {
        private string _nextLine;
        public TabDelimitedFieldReader(string s)
            : base(s)
        {
        }

        public IEnumerable<string> ReadFields()
        {
            if (_nextLine != null)
            {
                var fields = _nextLine.Split('\t');
                foreach (string field in fields)
                {
                    yield return field;
                }
            }
        }

        public bool HasMore
        {
            get
            {
                _nextLine = this.ReadLine();
                return (_nextLine != null);
            }
        }
    }

I can't think of another time I directly subclasses a .NET framework class like this.  I figure maybe I'm just strange and it's normal for others, or maybe there's a reason I wouldn't want to do it.


texts:
I want to use it when some function needs to return a list of something. Is it working as I think it should or is there undefined behavior somewhere? What I really tried to achieve is something like a templated <list> from C++ - for any type. I'm not sure if there is a standard solution/include/library for this.

list.h

#pragma once

#include <stddef.h>

struct list_handler
{
    struct list_node *head;
    struct list_node *tail;
    size_t count;
};

struct list_node
{
    void *data;
    struct list_node *next;
};

void list_init(struct list_handler *list);
void list_add(struct list_handler *list, void *data);
void list_free(struct list_handler *list);
void list_foreach(struct list_handler *list, void (*foreach_function)(void *));

list.c

#include "list.h"

#include <stdlib.h>

void list_init(struct list_handler *list)
{
    list->head = NULL;
    list->tail = NULL;
    list->count = 0;
}

void list_add(struct list_handler *list, void *data)
{
    struct list_node *new_node = malloc(sizeof(struct list_node));

    new_node->data = data;
    new_node->next = NULL;

    if (list->count > 0)
    {
        list->tail->next = new_node;
    }
    else
    {
        list->head = new_node;
    }

    list->tail = new_node;

    ++list->count;
}

void list_free(struct list_handler *list)
{
    struct list_node *current = list->head;
    struct list_node *previous;

    while (current != NULL)
    {
        previous = current;
        current = current->next;

        free(current);

        list->head = current;
        --list->count;
    }

    list->tail = NULL;
}

void list_foreach(struct list_handler *list, void (*foreach_function)(void *))
{
    struct list_node *current = list->head;

    while (current != NULL)
    {
        (*foreach_function)(current->data);
        current = current->next;
    }
}

Usage:

void list_print(void *data)
{
    int *temp = (int*) data;
    printf("%d\n", *temp);
}

void list_free_data(void *data)
{
    int *temp = (int*) data;
    free(temp);
    data = NULL;
}

int main(int argc, char *argv[])
{
    struct list_handler list;
    list_init(&list);

    for (size_t i = 0; i < 3; ++i)
    {
        int *data = malloc(sizeof(int));
        *data = i;
        list_add(&list, data);
    }

    list_foreach(&list, list_print);
    list_foreach(&list, list_free_data);

    list_free(&list);

    return 0;
}


texts: Optimizing a particle filter weighted selection step

texts:
I have a vector with 10000 particles that I use in a Particle Filter. The problem is that it's taking too long to compute the weighted selection of the particles.

I want to use a vector of weights (probabilities) to select elements from a vector (particles) to generate a new vector (new_particles) with the same size as the original, which has the most random items from the original set based on their weights.

Is there any way I can optimize this?

// util::NUMBER_OF_PARTICLES is a const int equal to 10000

// vector that holds particles weights
std::vector< double > probabilities;
probabilities.reserve(util::NUMBER_OF_PARTICLES);

// vector that will hold new particles
std::vector< GameParticle > new_particles;
new_particles.reserve(util::NUMBER_OF_PARTICLES);

// sum of all particle's weights
double sum_prob_all_particles = 0;

// calculate particle weights and save in vector
for(std::vector< GameParticle >::iterator it = game_particles_.begin(); it != game_particles_.end(); ++it)
{
    double probability = util::getProbOfMeasurementGivenParticle(*it, measurement);
    probabilities.push_back(probability);
    sum_prob_all_particles += probability;
}

ROS_ERROR_STREAM_COND(sum_prob_all_particles == 0, "Error, all particles have a zero probability of being correct");

// select new particle group
// counter used to count number of selected particles
int particlesCounter = util::NUMBER_OF_PARTICLES;
// random variable used to select particle value from 0 to sum_prob_all_particles
double random_variable = ( std::rand() / (double) RAND_MAX ) * sum_prob_all_particles;
double sum_probs = 0;

// counter of current particle to select
int counter = util::NUMBER_OF_PARTICLES - 1;

// while there are particles to select
while (particlesCounter > 0)
{
    // loops through all old particles and their weights
    int counter = util::NUMBER_OF_PARTICLES - 1;
    for(std::vector< double >::reverse_iterator it = probabilities.rbegin(); it != probabilities.rend(); ++it)
    {
        sum_probs += (double) *it;
        // if random variable selected this weight, get this particle
        while(sum_probs >= random_variable)
        {
            particlesCounter--;
            new_particles.push_back(game_particles_[counter]);
            random_variable += ( std::rand() / (double) RAND_MAX ) * sum_prob_all_particles;

            // get out of loops if no more particles
            if(particlesCounter == 0)
                goto AFTER_PARTICLES_SELECTED;
        }
        counter--;
    }
}

AFTER_PARTICLES_SELECTED:

ROS_INFO_STREAM("Observation step complete");

The part which is actually taking too long is after the // select new particle group comment. It takes an average of 0.984703 seconds for 5000 particles and 3.89787 seconds for 10000 particles, which is just too much.

The part before that comment only takes an average of 0.00142544 seconds for 10000 particles, so it's good enough.


texts:
I recently asked a question on StackOverflow, looking for a way to more easily turn a class attribute into a @property, but only if no other value has been provided to the class constructor. A simple way to do this is

class Demo(object):
    def __init__(self, value=None):
        self._value = value

    @property
    def value(self):
        if self._value is None:
            # some calculations to get value
            self._value = value
        return self._value

which I considered quite some overhead, so my question there asked for a decorator implementing this, and I came up with this solution

import functools

# https://stackoverflow.com/a/28961925/321973
def property_if_None_generator(f, cached=False):
    @functools.wraps(f)
    def wrapped(self):
        value = self.__getattribute__('_' + f.__name__)
        if value is not None:
            return value
        else:
            return f(self)
    if cached:
        wrapped = functools.lru_cache()(wrapped)
    return property(wrapped)

property_if_None = lambda f: property_if_None_generator(f, cached=False)
cached_property_if_None = lambda f: property_if_None_generator(f, cached=True)

then the question's example would turn into

class Demo(object):
    def __init__(self, value=None):
        self._value = value

    @chached_property_if_None
    def value(self):
        # some calculations to get value
        return value

Now I would appreciate any feedback on both the decorator itself and whether this is actually acceptable as opposed to the non-decorator version mentioned above. I'm especially concerned about the question whether it is a good idea to implicitly use the underscore-prepended attribute/property-name.

I have also considered making things even shorter by using another decorator (or even a metaclass) such that the __init__ wouldn't even have to do the self._value = value assignment, I'd also appreciate opinions on that.

edit Since the SO-answer merely received a downvote without comment so far, I'd really appreciate feedback on this...


texts:
In terms of readability, efficiency, and the best convention, which of the two is best?

Snippet A:

angular.module("main.loadbalancer").factory("AccountDataStorage", function() {
  var accountData;
  accountData = {};
  accountData.accountId = "No Account Loaded!";
  return {
    accountData: accountData
  };
});

Snippet B

angular.module("main.loadbalancer").factory("AccountDataStorage", function() {
  return { accountData: {} };
});

Regardless, accountId will be attached later on with:

angular.module('main.loadbalancer').controller('LoadBalancerCtrl', function($scope, LoadBalancerService, AccountDataStorage) {
  return (function(load) {
    $scope.$on('deviceNumberUpdated', load);
    return load();
  })(function() {
    return LoadBalancerService.getLoadBalancer().then(function(lb) {
      AccountDataStorage.accountData.accountId = lb.customer;
      return $scope.loadBalancer = lb;
    });
  });
});


texts: Function which takes a string as input and returns the most frequent character

texts:
I wrote a feature. And it works correctly. But in my opinion it is not optimal. But I have not found what standard features you can use to unleash it. Since I made it a simple sort of values. And it takes a long time to execute.

char getMaxOccuringChar(char* str)
{
    int count[ASCII_SIZE] = {0};

    int len = strlen(str);
    int max = 0;
    char result;

    for (int i = 0; i < len; i++) {
        count[str[i]]++;
        if (max < count[str[i]]) {
            max = count[str[i]];
            result = str[i];
        }
    }

    return result;
}


texts: Execute every Monday that is not the Monday following last Saturday in month

texts:
I think the following is good but wondering if it can be simplified or improved.

My condition for code execution is the following:

It is a Monday
AND
It is not the Monday following the last Saturday in the month.

This is the current sql:

DECLARE @now DATETIME = DATEADD(dd,DATEDIFF(dd,'19000101',SYSDATETIME()),'19000101');

IF (
        (--is it a monday?
            SELECT DATEPART(dw,@now)
        ) = 2

        AND

        (--is it not the monday following the last Saturday of the month?
            (
            SELECT DATEDIFF(
                            DAY,
                            @now-2,
                            DATEADD(MONTH,DATEDIFF(MONTH,0,@now-2)+1,0)-1
                        )
            ) > 6
        )
    )
BEGIN;

  ...
  ...

END;


texts: Spearman correlations between Numpy array and every Pandas DataFrame row

texts:
I want to efficiently calculate Spearman correlations between a Numpy array and every Pandas DataFrame row:

import pandas as pd
import numpy as np
from scipy.stats import spearmanr

n_rows = 2500
cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

df = pd.DataFrame(np.random.random(size=(n_rows, len(cols))), columns=cols)
v = np.random.random(size=len(cols))
corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
corr = pd.Series(corr)

For now, the calculation time of corr is:

%timeit corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
>> 1.26 s ± 5.19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

I found another good approach but it calculates only Pearson correlations:

%timeit df.corrwith(pd.Series(v, index=df.columns), axis=1)
>> 466 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Is there a way to calculate Spearman correlations faster?


texts: JavaScript constructor and namespace in object literal style

texts:
Is this a good way to create a class with a constructor and namespace in object literal style?

// root namespace
var myApp = myApp || {};

// sub namespace
myApp.model = {
    // Constructor
    Person: function (name) {
        this.name = name;
    }
};

myApp.model.Person.prototype = {
    sayName: function () {
        alert(this.name);
    },
    sayHi: function () {
        alert("Hi, " + this.name);
    }
};

var p1 = new myApp.model.Person("CK");
p1.sayName();
p1.sayHi();

JSHint shows no error and the full source code is here.


texts: Backbone subviews with non-uniform layout

texts:
I have a “featured projects” view that requires its subviews conform to a non-uniform grid: one narrow column with 3 items, then one wide column with 2 items, followed by another narrow column with 3 items. The width that is used for each subview is determined by the model’s display attribute. If there are any extra items in the collection, they are disregarded for the purposes of this view.

Here's the relevant portion of the code:

class App.Views.FeaturedProjects extends Backbone.View
  el: '#featured'
  template: '

'

  initialize: ->
    ...
    @collection.on 'reset', @addAll, this

  addOne: (item, el) =>
    view = new App.Views.Project model: item
    el.append view.render().el

  addAll: ->
    # … clear out existing subviews, then …

    # separate collection into wide & narrow
    narrow = @collection.where display: 'narrow'
    wide = @collection.where display: 'wide'

    # only display the grid if there are enough items to fill it
    if narrow.length >= 6 and wide.length >= 2
      column1 = $(@template).addClass('column-narrow')
      column2 = $(@template).addClass('column-wide')
      column3 = $(@template).addClass('column-narrow')

      # 3 narrow / 2 wide / 3 narrow
      @addOne(item, column1) for item in narrow[0..2]
      @addOne(item, column2) for item in wide[0..1]
      @addOne(item, column3) for item in narrow[3..5]

      @$el.append(column1).append(column2).append(column3)

My current approach works, but is there a better way of handling something like this?

EDIT

I took Marco's suggestions a bit further and ended up with the following:

class App.Views.FeaturedProjects extends Backbone.View
  columnTemplate: '

'

  defaults: ->
    columns: [
      { type: 'narrow', itemsPer: 3 }
      { type: 'wide', itemsPer: 2 }
      { type: 'narrow', itemsPer: 3 }
    ]

  initialize: (options) ->
    @options = _.extend({}, @defaults(), options)
    ...
    @collection.on 'reset', @addAll, this

  addAll: ->
    # … clear out existing subviews, then …
    items = {}
    valid = true
    # get unique column types
    uniqueColTypes = _.uniq _.pluck @options.columns, 'type'

    # separate collection by column type and verify there are enough items of each type
    for type in uniqueColTypes
      items[type] = @collection.where display: type
      valid = false if items[type].length < @minItems type

    # display the grid
    if valid
      for column in @options.columns
        columnHtml = $(@columnTemplate).addClass "column-#{column.type}"
        itemsPer = column.itemsPer
        @addOne items[column.type].shift(), columnHtml while itemsPer--
        @$el.append(columnHtml)

  # returns number of items with specified column type required to fill the grid
  minItems: (type) ->
    minItems = 0
    minItems += col.itemsPer for col in _.where @options.columns, {type: type}
    return minItems


texts:
I have built a timer program in JavaScript. It decrements one counter every second, and if that counter is at zero, it decrements another counter, and sets the first counter to 59. If the second counter now is below zero, then it stops the timer. Would it be more efficient to store the total seconds left, and calculate the minutes on the fly? Is there other stuff I can improve on?

var timerRun; // Variable for holding the interval
          var timeLeft; //Array; index 0 keeps track of the minutes, and index 1 keeps track of the seconds
          var timerRunning = false; //Boolean to keep track of whether the timer is running
          function tick() {
              // Subtract 1 second
              timeLeft[1] -= 1;
              if (timeLeft[1] < 0) { // Decrement the minute if neccessary
                  timeLeft[0] -= 1;
                  timeLeft[1] = 59;
              }
              if (timeLeft[0] < 0) { // Check if the timer is done
                  clearInterval(timerRun);
                  alert("Timer is done!");
                  timerRunning = false;
                  document.getElementById("timer").innerHTML = "Simple Timer";
              }
              if (timeLeft[1] < 10) { // Display the seconds as a two-digit number
                  timeLeft[1] = "0" + timeLeft[1];
              }
              document.getElementById("timer").innerHTML = timeLeft.join(":");
              if (timerRunning == false) {
                  document.getElementById("timer").innerHTML = "Simple Timer";
              }
          }
          function time() { // Restart timer
                clearInterval(timerRun)
                timerRun = setInterval(tick, 1000);
                // Create array
                timeLeft = document.getElementById("time").value.split(":");
                timerRunning = true;
          }
<!DOCTYPE html>

Simple Timer

      <input type="text" id="time" value="15:00">
      <button type="button"  onclick="time();" id="start">Start</button>


texts:
Task:
Create the Fizz Buzz game using Test Driven Developoment. Print the correct word for range 1-100.

The implementation:

public class Main {

    static final String FIZZ = "Fizz";
    static final String BUZZ = "Buzz";
    static final String FIZZ_BUZZ = "Fizz Buzz";

    public static void main(String[] args) {
        IntStream.range(1, 101).forEach((x) -> System.out.println(getWordForNumber(x)));
    }

    public static String getWordForNumber(int x) {
        if (isDivisibleWithoutRemainder(x, 15)) {
            return FIZZ_BUZZ;
        } else if(isDivisibleWithoutRemainder(x, 3)) {
            return FIZZ;
        } else if(isDivisibleWithoutRemainder(x, 5)) {
            return BUZZ;
        }
        return Integer.toString(x);
    }

    private static  boolean isDivisibleWithoutRemainder(int dividend, int divisor) {
        return (dividend%divisor == 0);
    }

}

The JUnit Test:

final class Number {
    private final int n;

    Number (int number) {
      n = number;
    }

    final boolean isMatchedToWord(final String word) {
      return Main.getWordForNumber(n).equals(word);
    }
}

class MainTest {
    @Test
    public void numbersAreMatchedToWords_Works() {
      assertTrue(new Number(1).isMatchedToWord("1"));
      assertTrue(new Number(2).isMatchedToWord("2"));
      assertTrue(new Number(3).isMatchedToWord("Fizz"));
      assertTrue(new Number(4).isMatchedToWord("4"));
      assertTrue(new Number(5).isMatchedToWord("Buzz"));
      assertTrue(new Number(6).isMatchedToWord("Fizz"));
      assertTrue(new Number(10).isMatchedToWord("Buzz"));
      assertTrue(new Number(15).isMatchedToWord("Fizz Buzz"));
      assertTrue(new Number(30).isMatchedToWord("Fizz Buzz"));
    }
}


texts:
I am debugging one legacy J2EE application I and think I found some dead code and some redundant condition checks. Please give me your thoughts on my observations i.e. if they are valid. Please note that I am not permitted to rewrite this block, only to fix something if wrong or redundant.

...
else if ((emailList != null) && (emailTest != null)
                  && (emailTest.compareTo(IParameterNames.EMAIL_GO) == 0))  // #1 One of the AND conditions to enter this "else if" block is: "emailList != null",
              {                                                             // #2 so if "emailList != null" is not "true" we wouldn't even be in this "else if" block.

                response.getOutputStream().print("...blah blah blah...");
                response.getOutputStream().print("...blah blah blah...");
                response.getOutputStream().print("...blah blah blah...");

                if (emailList != null)  //#3 Here we check again if primary condition is fulfilled: "emailList != null".
                                        //#4 If "emailList != null" is not "true" we wouldn't even be in this "else if" block.This should be removed IMHO
                {
                  response.getOutputStream().print(emailList.size());
                }
                else //#5 And as "emailList != null" was true at the else if here it can't be different than that. This should be removed IMHO as it is DEAD CODE.
                {
                  response.getOutputStream().print("0 ");
                }

                response.getOutputStream().print("...blah blah blah...");
                response.getOutputStream().print("...blah blah blah...");

                if (emailList != null)  //#6 Here we check again if primary condition is fulfilled: "emailList != null".
                                        //#7 If "emailList != null" is not "true" we wouldn't even be in this "else if" block.This should be removed IMHO
                {
                  response
                      .getOutputStream()
                      .print("...blah blah blah...");

                  for (int i = 0; i < emailList.size(); i++)
                  {
                    email = (EmailMessage) emailList.get(i);

                    if (email != null)
                    {
                      response.getOutputStream().print(outputEmailAddressAsHTML(email, i).toString());
                    }
                  }
                }

                response.getOutputStream().print("..lots.of.blah blah blah...");
              }
...


texts:
Following is my attempt for a simple implementation for the std string class. Please review my changes and share your feedback.

string.h

class string
{
    char *pcString;
    int iCapacity;
    const static int npos = -1;
public:
    string(void);
    string(int);
    string(const char*);
    string(const string&);
    string& string::operator=(const string &strInstance);
    string& string::operator+(const string &strInstance);
    int find(const char*);
    bool empty() const;
    int size() const;
    char* data() const;
    ~string(void);
};

string.cpp

#include "string.h"
#define INITIAL_SIZE 15

/* Default Constructor */
string::string(void)
{
    pcString = new char[INITIAL_SIZE];
    memset(pcString, 0, INITIAL_SIZE);
    iCapacity = INITIAL_SIZE;
}

string::string(int iSize)
{
    pcString = new char[iSize];
    memset(pcString, 0, iSize);
    iCapacity = iSize;
}

string::string(const char *pcValue)
{
    if(pcValue)
    {
        int iSize = strlen(pcValue) + 1;
        pcString = new char[iSize];
        memset(pcString, 0, iSize);
        iCapacity = iSize;
        memcpy(pcString, pcValue, strlen(pcValue));
    }
}

/* Copy Constructor */
string::string(const string &strInstance)
{
    if(strInstance.empty() == false)
    {
        this->pcString = new char[strInstance.size() + 1];
        this->iCapacity = strInstance.size() + 1;
        memset(this->pcString, 0, this->iCapacity);
        memcpy(this->pcString, strInstance.data(), this->iCapacity);
    }
}

/* empty() */
bool string::empty() const
{
    if(this->pcString)
    {
        if(memcmp(this->pcString, "", strlen(this->pcString)) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* '=' operator */
string& string::operator=(const string &strInstance)
{
    if(strInstance.empty() == false)
    {
        this->iCapacity = strInstance.size() + 1;
        delete this->pcString;
        this->pcString = new char[this->iCapacity];
        memset(this->pcString, 0, this->iCapacity);
        memcpy(this->pcString, strInstance.data(), this->iCapacity - 1);
    }
    return *this;
}

/* '+' operator */
string& string::operator+(const string &strInstance)
{
    int iNewSize = strInstance.size() + this->size() + 1;
    char *pcTemp = new char[iNewSize];
    _snprintf(pcTemp, iNewSize, "%s%s", this->data(), strInstance.data());
    string *pStrResult = new string(pcTemp);
    return *pStrResult;
}

/* size() */
int string::size() const
{
    if(this->pcString)
    {
        return strlen(this->pcString);
    }
    else
    {
        return 0;
    }
}

/* data() */
char * string::data() const
{
    if(this->pcString)
    {
        return this->pcString;
    }
    else
    {
        return NULL;
    }
}

int string::find(const char *pcInputString)
{
    char *pcSubstrResult = strstr(this->pcString, pcInputString);
    if(pcSubstrResult)
    {
        return (this->size() - strlen(pcSubstrResult));
    }
    else
    {
        return string::npos;
    }
}

string::~string(void)
{
    delete this->pcString;
}


texts: Adding two numbers, each digit as a single element of array

texts:
After failing to answer an interview question, I went back home and coded the answer for my own improvement.
The questions was: Given two arrays containing a number, but with each element of the array containing a digit of that number, calculate the sum and give it in the same format.There must be no leading zeros in the resulting array.

My main concern is that I am being redundant with my logic, or that my code is not clear.

 int *sumOfTwo(int *a1,int *a2, int lengthOfA1, int lengthOfA2, int *lengthDest) {

      //I assume there is error checking for null pointers, etc.
      int *answer;
      int maxSize, minSize, diff;
      int a1IsLongest = TRUE;
      if(lengthOfA1 > lengthOfA2) {
          maxSize = lengthOfA1;
          minSize = lengthOfA2;
          a1IsLongest = TRUE;
      }
      else {
          maxSize = lengthOfA2;
          minSize = lengthOfA1;
          a1IsLongest = FALSE;
      }
      diff = maxSize - minSize;
      answer = malloc(maxSize * sizeof(int));
      int i, extraTen, result;
      extraTen = 0;

      *lengthDest = maxSize;
      //printf("This is lengthDest: %d\n", *lengthDest);

      for (i = maxSize-1; i >= 0; i--) {

          //add numbers, check if bigger than 10
         //check if arrays are of different sizes we want to access
         //the end from each, so need to account for this.

          if(diff == 0) {
              //arrays are equal in size
              result = a1[i] + a2[i] + extraTen;
              extraTen = 0;
          }
          else{
              //arrays are different sizes
              if(! ((i - diff) < 0)) {
                  if(a1IsLongest) {
                      result = a1[i] + a2[i - diff] + extraTen;
                      extraTen = 0;
                  }
                  else {
                      result = a1[i - diff] + a2[i] + extraTen;
                      extraTen = 0;
                  }
              }
              else {
                  if(a1IsLongest) {
                  result = a1[i] + extraTen;
                  extraTen = 0;
              }
              else {
                  result = a2[i] + extraTen;
                  extraTen = 0;
              }
          }
      }

      //the new malloc can only happen here
      if (result >= 10) {
         //check if at beginning of array
         if(i == 0) {

              maxSize = maxSize + 1;
              *lengthDest = maxSize;
              //printf("This is lengthDest: %d\n", *lengthDest);

              //overflowing, need to realloc
              int *temp = malloc(maxSize * sizeof (int));
              int j;
              //copy old elements into new array
              for(j = 0; j < maxSize; j++) {
                  //printf("index: %d\n", j);
                  if(j == 0) {
                      temp[j] = 1;
                  }
                  else if(j == 1) {
                      temp[j] = result % 10;
                  }
                  else {
                      temp[j] = answer[j-1];
                  }
              }

              free(answer);
              answer = temp;
              return answer;
          }
          else{
              //printf("in the else of the i equals 0.\n");
              answer[i] = result % 10;
              extraTen = 1;
          }
      }
      else {
         //printf(" results is less than 10\n");
         answer[i] = result;
     }
 }
 return answer;
}


texts: strReadLine function (read line by line from a string)

texts:
I'm new to C language and want to read a string line by line, I made this function and want to know what do you think about it, can I rely on it a production environment ?

/**
 * this function is not thread safe,
 */
char* strReadLine(char* text)
{

    static char* text2;
    static int start = 0;
    static int length = 0;
    int startTemp;
    int lineLength = 0;
    char* line = (char*) 0;

    startTemp = start;
    //not thread safe but at least make an error
    if(start != 0 && text2 != text){
        fprintf(stderr, "thread safe guerd fired by strReadLine function\n");
        exit(EXIT_FAILURE);
    }
    text2 = text;
    //thread safty end

    //if new string
    if(length == 0 || start == 0) length = strlen(text);
    if(!length) return (char*) 0;//the string is 0 length

    for(int x = startTemp; x < length; x++){
        start++;
        lineLength++;
        if(  text[x] == '\n'){
            line = malloc(lineLength);//not lineLength+1 because I will remove the \n with \0
            strncpy(line, text + (startTemp) , lineLength);
            line[lineLength - 1] = '\0';
            break;
        }
    }

    //if end of file && not the last line
    if(start == length && !line){
        start = 0;
        line = (char*) 0;
    }

    return line;
}

I have tested it with this text file

line1
line2
line3

line5
سطر6
line7

(line 4 is empty and line 6 contains non Latin characters stored in more than 1 byte in UTF-8 encoding)

like this, and it worked as expected

//char* input;this points to the string that is read from the file(I omitted the reading code)
char* line;
int x = 0;
while( (line = strReadLine(input)) ){
    x++;
    printf("%s\n",line);
    if(x == 300){printf("emergency break\n");break;}
}

x = 0;
while( (line = strReadLine(input)) ){
    x++;
    printf("%s\n",line);
    if(x == 300){printf("emergency break\n");break;}
}


texts: Bad practices in this procedure to calculate player statistics?

texts:
I recently self-taught myself MySQL as quickly as possible because it was needed for a project that I'm working on. Now that I've got some time I've been working on improving some thrown together SQL procedures. I've already done a few things, like logic improvements and removal of sub-queries, but I'm wondering if anyone can quickly skim through the procedure and point out anything specifically bad that I might have missed.

CREATE PROCEDURE `userstatsUpdate`(IN userauth VARCHAR(32))
BEGIN

DECLARE mapcount INT DEFAULT 0;
DECLARE stagecount INT DEFAULT 0;
DECLARE bonuscount INT DEFAULT 0;

DECLARE mapmult FLOAT DEFAULT 0;
DECLARE stagemult FLOAT DEFAULT 0;
DECLARE bonusmult FLOAT DEFAULT 0;

DECLARE pc FLOAT DEFAULT 0;

DECLARE stagerecs INT DEFAULT 0;
DECLARE bonusrecs INT DEFAULT 0;
DECLARE maprecs INT DEFAULT 0;
DECLARE tops INT DEFAULT 0;

DECLARE p_comps FLOAT DEFAULT 0;
DECLARE p_tops FLOAT DEFAULT 0;
DECLARE counter INT DEFAULT 0;
DECLARE ranknum INT DEFAULT 0;

DECLARE userID INTEGER DEFAULT 0;

SELECT playerID INTO userID FROM cs_players WHERE cs_players.userauth = userauth;

WHILE counter < 10 DO

    SET ranknum = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid=cs_maps.mapid WHERE stage = 0 AND rank = counter+1 AND playerid = userID AND active = 1);

    SET p_tops = p_tops + (((10-counter)+(10-counter+2)*30)*ranknum);
    SET counter = counter + 1;

END WHILE;

SELECT count(*),
COALESCE(
(count(*)*((difficulty+4)/5)),0)
AS points INTO mapcount, mapmult from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage = 0 AND playerid = userID AND cs_maps.active = 1;
SELECT count(*), COALESCE(
(count(*)*((difficulty+4)/5)),0)
 AS points INTO stagecount, stagemult  from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 0 AND playerid = userID AND cs_maps.active = 1;
SELECT count(*), COALESCE(
(count(*)*((difficulty+4)/5)),0)
AS points INTO bonuscount, bonusmult from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 1 AND playerid = userID AND cs_maps.active = 1;
SET maprecs = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage = 0 AND rank = 1 AND playerid = userID AND cs_maps.active = 1);
SET stagerecs = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 0 AND rank = 1 AND playerid = userID AND cs_maps.active = 1);
SET bonusrecs = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 1 AND rank = 1 AND playerid = userID AND cs_maps.active = 1);
SET tops = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage = 0 AND rank <= 10 AND rank > 0 AND playerid = userID AND cs_maps.active = 1);
SET @TotalStage = (SELECT sum(checkpoints) FROM cs_maps WHERE mtype = 0 AND active = 1);
SET @TotalBonus = (SELECT sum(cp_bonus) FROM cs_maps  WHERE active = 1);
SET @TotalMaps = (SELECT COUNT(*) FROM cs_maps WHERE active = 1);

SET @div1 = ((mapcount*2)+stagecount+(bonuscount*1.5));
SET @div2 = ((@TotalMaps*2)+@TotalStage+(@TotalBonus*1.5));

SET pc = @div1/@div2;

SET p_comps = (mapmult * 50) + (bonusmult * 20) + (stagemult * 5);

INSERT INTO cs_userstats(playerid, c_maps, c_stages, c_bonuses, wr_m, wr_s, wr_b, wr_top, p_top, p_comp, percomp) VALUES (userID, mapcount, stagecount, bonuscount, maprecs, stagerecs, bonusrecs, tops, p_tops, p_comps, pc)
ON DUPLICATE KEY UPDATE c_maps = mapcount, c_stages = stagecount, c_bonuses = bonuscount, wr_m = maprecs, wr_s = stagerecs, wr_b = bonusrecs, wr_top = tops, p_top = p_tops, p_comp = p_comps, percomp = pc;

END$$


texts: Matching URIs with regexes for Apache CXF InInterceptor

texts:
In my project I need to compare the URI with 15+ regex patterns. Currently I have used a if ladder to execute the appropriate code if any of them gets matched.

     if (uri.matches(Constants.GET_ALL_APIS_STORE_REGEX)) {
        long lastUpdatedTime = InBoundETagManager.apisGet(null, null, tenantDomain, null);
        String eTag = ETagGenerator.getETag(lastUpdatedTime);
        if (eTag.equals(ifNoneMatch)) {
            message.getExchange().put("ETag", eTag);
            generate304NotModifiedResponse(message);
        }
        message.getExchange().put("ETag", eTag);
    } else if (uri.matches(Constants.GET_API_FOR_ID_REGEX)) {   //        /apis/{apiId}
        apiId = UUIDList.get(0);
        String requestedTenantDomain = RestApiUtil.getRequestedTenantDomain(tenantDomain);
        long lastUpdatedTime = InBoundETagManager.apisApiIdGet(apiId, requestedTenantDomain, uri);
        String eTag = ETagGenerator.getETag(lastUpdatedTime);
        handleInterceptorResponse(message, ifNoneMatch, eTag);
    } else if (uri.matches(Constants.GET_SWAGGER_FOR_API_ID_REGEX)) {   //  /apis/{apiId}/swagger
        apiId = UUIDList.get(0);
        long lastUpdatedTime = InBoundETagManager.apisApiIdSwaggerGet(apiId, tenantDomain);
        String eTag = ETagGenerator.getETag(lastUpdatedTime);
        if (lastUpdatedTime == 0L) {
            log.info("No last updated time available for the desired API swagger json file");
        }
        handleInterceptorResponse(message, ifNoneMatch, eTag);
    }........

This code is related to a apache CXF InInterceptor and regexes are as follows:

public static final String GET_ALL_APIS_STORE_REGEX="^.+/api/am/store/v0.10/apis";
public static final String GET_API_FOR_ID_REGEX="^.+/api/am/store/v0.10/apis/(\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})$";
public static final String GET_SWAGGER_FOR_API_ID_REGEX = "^.+/api/am/store/v0.10/apis/(\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})/swagger$";
public static final String GET_THUMBNAIL_FOR_API_ID_REGEX = "^.+/api/am/store/v0.10/apis/(\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})/thumbnail$";
public static final String GET_DOCUMENTS_FOR_API_ID_REGEX = "^.+/api/am/store/v0.10/apis/(\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})/documents$";


texts: Setting selected elements in a UI tree widget

texts:
I have a Swing vector-program similar to Dia targeting RAD. There are some plug-ins that let you

create structures like Rectangle, Text and Circle but also complex types like Table-Columns.
generate files like Spring-Roo-Script, grails-script, SQL-Files and svg-Files.

In the Center you have the Drawing-Panel (DrawPanel), on the right side you have the component-tree.

In the DrawPanel class, this is the function select that I need a review for. This function changes the selected nodes in the Tree on the right.

/** The main tab where paint areas are. Never null. */
@Inject
Tab tab;

public void select(Set<? extends TreeNode> newSelection,
        boolean layersModified) {
    boolean inAssertMode = false;
    assert inAssertMode = true;
    if (inAssertMode && getSelection().equals(newSelection)) {
        if (!layersModified) {
            throw new UnnecessaryOperationException("Select tree Nodes",
                    getSelection(), newSelection);
        }
        LOG.severe("I did not noticed about changed selection, "
                + "you only notify about modified layers!");
    }
    Set<TreePath> c = new HashSet<>();
    for (TreeNode newSelected : newSelection) {
        c.add(new TreePath(newSelected));
    }
    TreePath[] array = c.toArray(new TreePath[0]);
    setSelectionPaths(array);
    if (layersModified) {
        tab.getCurrentDrawPanel().notifyLayersModified();
    }
}

As you will notice, the code above is only executed if asserations are enabled.


texts:
I've been writing a simple code just for fun:

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

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

Fields:

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

One handler:

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

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

Another handler:

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

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

I would like you to consider the following issues:

Is the...

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

... the best way to do this?


texts:
Follow up to Duplicate like a weapon, arrays like heaven.

@rolfl suggested in chat that I try to complete this challenge again in a Java 8 friendly way. I took the opportunity to also employ the algorithm suggested in this brilliant answer.

I'm not familiar with Java 8 features, but am definitely interested in using it more and finding the best ways to implement it.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;

public class ArrayAbsurdityJava8 {
    public static void main(String[] args) throws IOException {
        Files.lines(new File(args[0]).toPath())
                .filter(s -> !s.isEmpty())
                .forEach(ArrayAbsurdityJava8::printDuplicate);
    }

    private static void printDuplicate(String line) {
        int length = Integer.parseInt(line.split(";")[0]);
        int total = Arrays.stream(line.split(";")[1].split(","))
                .mapToInt(Integer::parseInt)
                .sum();

        System.out.println(total - (length - 1) * (length - 2) / 2);
    }
}

This ended up shorter than I expected. Is this best? I was thinking of doing it my way as well, but the boolean comparison requires a for loop (am I wrong?).


texts:
I have a bunch of voxel having an int value inside a 16^3 grid. I want to merge individual voxels with the same int value together in order to create the least possible amount of boxes the fastest way possible.

Here is my algorithm (kotlin) :

fun convert (grid: VoxelGrid): List<Box> {
    val dim = grid.dimension
    val boxes = mutableListOf<Box>()

    for (width in dim - 1 downTo 1) {
        for (height in dim - 1 downTo 1) {
            for (depth in dim - 1 downTo 1) {
                val dims = Vec3(width, height, depth)
                for (x in 0 until (dim - width)) {
                    for (y in 0 until (dim - height)) {
                        for (z in 0 until (dim - depth)) {
                            val min = Vec3(x, y, z)
                            val box = Box(min, min + (dims))

                            if (!contains(boxes, box)) {

                                val voxels = box.voxels()
                                val first = voxels[0]
                                val value = grid[first.x, first.y, first.z]
                                if (value != 0 && voxels.all {
                                            grid[it.x, it.y, it.z] == value
                                        }) {
                                    boxes.add(box)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return boxes
}

private fun contains(boxes: MutableList<Box>, other: Box): Boolean {
    for (existing in boxes) {
        if (existing.intersects(other)) {
            return true
        }
    }

    return false
}

Here is a link to the helper classes

This works, but for a 16^3 grid (the last test case) it takes around 8s to complete which is way too long.

In order to optimize, I think that before calling convert(), I could group every voxel by their int value, then compute the AABB for each group and only call the algorithm for each AABB. This could work pretty well but for values that are spread out around the original grid.

Is there any other way to optimize this?


texts:
Ruby code below seems to be not so dry. Can you please help me reduce the code.

self.value = case self.type
when 'fast'
  Increment.first.max_hours * Incrementor.first.fast_completion_day
when 'super_fast'
  Increment.first.max_hours * Incrementor.first.super_fast_completion_day
when 'ludicrous'
  Increment.first.max_hours * Incrementor.first.ludicrous_completion_day
else
  Increment.first.max_hours * Incrementor.first.budget_completion_day
end

I think we can use Ruby metaprogamming here to reduce the code. But I am not very good with ruby meta programming at the moment.


texts: Matrix to calculate effects using delta method

texts:
I have written some code to calculate effects using the Delta method.

I have a dataframe dpcp with variables x1, x2, x3, x4 and a matrix of 1000 draws from a multivariate normal, m4[1000,4].

This code works to calculate the effects, but it runs very slowly - it currently takes upwards of 5 hours for only 2000 observations.  How can I improve the runtime?

n=nrow(dpcp)
for (i in 1:n)

 {

     for (j in 1:1000)
      {
     marg_effects[i,j]=(m4[j,1]*dpcp[i,]$x1)+(m4[j,2]*dpcp[i,]$x2)+(m4[j,3]*dpcp[i,]$x3)+(m4[j,4]*dpcp[i,]$x4)
 }
   }


texts:
The other week I faced the struggle of scraping dynamically generated content. So I used the selenium library with combination of requests & bs4, the thing is I am unsure of the quality of the implementation as I just learned how to use those tools. I want to have a general feedback on the way I used the libraries, the quality of my code and the logic behind it.

Link to GitHub README.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import selenium.common.exceptions
import requests
from bs4 import BeautifulSoup
from time import sleep

def scraper():
    opts = Options()
    opts.add_argument('--headless')
    driver = webdriver.Chrome(r'C:\Users\leagu\chromedriver.exe', options=opts)

    pos = input('Enter your desired position: ')
    URL = 'https://remote.co/remote-jobs/search/?search_keywords='+pos.replace(' ', '+')
    driver.get(URL)

    # Scroll to the bottom of the page
    while True:
        try:
            WebDriverWait(driver, 5).until(
                ec.text_to_be_present_in_element(
                    (By.CLASS_NAME, 'load_more_jobs'),
                    'Load more listings')
                )
            loadMore = driver.find_element_by_class_name('load_more_jobs')
            loadMore.click()
        except:
            try: # can't locate element - click the close on the popup add
                WebDriverWait(driver, 5).until(
                    ec.presence_of_element_located((By.CLASS_NAME, 'portstlucie-CloseButton'))
                    )
                addClose = driver.find_element_by_xpath('//*[@id="om-oqulaezshgjig4mgnmcn-optin"]/div/button')
                addClose.click()
            except: # Timeout / can't locate add - break
                break

    # Find all the job listings
    listings = driver.find_elements_by_class_name('job_listing')

    if len(listings) == 0:
        print(f'There are 0 jobs found by {pos} criteria. Please use different wording.')
        sleep(5)
        scraper()
    else:
        scrapeN = input(f"There are {len(listings)} number of jobs for the {pos} position. If u wish to view a portion of them enter the number of the jobs to view else write 'max': ")
        if scrapeN.lower() == 'max':
            scrapeN = len(listings)
        scrapeN = input(f"There are {len(listings)} number of jobs for the {pos} position. If u wish to view a portion of them enter the number of the jobs to view else write 'max': " )
        print('\n')

    for i in range(int(scrapeN)): # Iterate trough all the job listings
        URL = listings[i].find_element_by_tag_name('a').get_attribute('href')
        html = requests.get(URL)
        soup = BeautifulSoup(html.content, 'html.parser')

        jobT = soup.find('h1', class_='font-weight-bold').text
        jobPD = soup.find('time').text
        link = soup.find('a', class_='application_button')['href']

        print(f'Job - {jobT}. This job was {jobPD}.\nMore information about the job at {URL}. \nLink for application - {link}', end='\n\n')

if __name__ == '__main__':
    scraper()


texts: c# best way to declare a class-level value in base class and set it at derived classes

texts:
I have a root class and I'd like to add an indicator to it (property, static field, readonly field, virtual method or something like that), that should give me the same string value for every instance of that class, I would rather prefer to get that value without instantiating that class. GetObjType() virtual method is my current implementation of it but I am thinking there may a better way of doing this. Can you think of a better way of doing this, like class level singleton fields or something like that.

public abstract class CoreEntity
{
    public int Id { get; set; }
    public abstract string GetObjType();
}
public class DepartmanBase : CoreEntity
{
    public override string GetObjType()
    {return "DEPARTMAN";}
    public string DepartmanName { get; set; }
    public int ManagerId { get; set; }
    //Obj Type should be set as "DEPARTMAN" here and should be same in both derived classes
}
public class Departman : DepartmanBase
{
}
public class DepartmanView : DepartmanBase
{
    public string ManagerName { get; set; }
}

public class Personnel : CoreEntity
{
    public override string GetObjType() {return "PERSONEL";}
    public string PersonnelName { get; set; }
}

public class Repository<T>
    where T : CoreEntity , new()
{
    public void DoSomething()
    {
        string objType = new T().GetObjType();
        Console.WriteLine("Object Type for: " + typeof(T).Name  + " is " + objType);
    }
}

void Main()
{
    var d = new Repository<Departman>();
    var dv = new Repository<DepartmanView>();
    var p = new Repository<Personnel>();

    d.DoSomething();
    dv.DoSomething();
    p.DoSomething();
}


texts: lowest common ancestor with square root decompostion

texts:
This is my implementation of lowest common ancestor problem,I tried to solve it using square root decomposition

  pre processing time : O(n)

  query time:O(sqrt(h))
  h -> height of tree

This was LCA on spoj

Well i added comments in my code and
My approach very well explained here with every line of code https://www.geeksforgeeks.org/sqrt-square-root-decomposition-set-2-lca-tree-osqrth-time/

You can see in the comments of spoj that many people O(n) query is getting accepted.
But mine is O(sqrt(n)) and is not accepted getting TLE.

Please help me where i am doing wrong ?

#include<bits/stdc++.h>
using namespace std;
#define MAXN 2000
int block_sz;
int depth[MAXN];
int parent[MAXN];
int jump_parent[MAXN];
int hmax;
///jump_parent is first ancestor
///of current node

vector <int> adj[MAXN];
void addEdge(int u,int v){
    adj[u].push_back(v);
    adj[v].push_back(u);
}

int lca_naive(int u,int v){
    if(u==v){
        return u;
    }
    if(depth[u]>depth[v])
        swap(u,v);
    v=parent[v];
    return lca_naive(u,v);
}
// precalculating the required parameters
// associated with every node
void dfs(int cur,int prev){
    depth[cur]=depth[prev]+1;
    parent[cur]=prev;
    //hmax=max(height,hmax);
///suppose if h=9,then sqrt(h)=3
///in that case total blocks will be
///0 to 3-1
/// so rem will be zero for only first element in the current block
    if(depth[cur] % block_sz == 0){
        jump_parent[cur]=parent[cur];
    }
    else{
        jump_parent[cur]=jump_parent[prev];
    }
    for(int i=0;i<adj[cur].size();i++){
        if(adj[cur][i]!=prev){
            dfs(adj[cur][i],cur);
        }
    }
}
int lcasqrt(int u,int v){
    while(jump_parent[u]!=jump_parent[v]){
        if(depth[u]>depth[v])
            swap(u,v);
        v=jump_parent[v];
    }
    return lca_naive(u,v);
}
void preprocess(int height){
    block_sz=sqrt(height);
    depth[0]=-1;

    dfs(1,0);
}
///seperate dfs to calculate height
void dfs_height(int cur,int prev,int height){
    hmax=max(height,hmax);
    for(int i=0;i<adj[cur].size();i++){
        if(adj[cur][i]!=prev)
            dfs_height(adj[cur][i],cur,height+1);
    }
}
int main(int argc, char const *argv[])
{
    // adding edges to the tree
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        for(int i=1;i<=n;i++){
            int m;
            cin>>m;
            for(int j=1;j<=m;j++){
                int v;
                cin>>v;

                adj[i].push_back(v);
            }
        }
        dfs_height(1,0,0);
        preprocess(hmax);
        dfs(1,0);
        int q;
        cin>>q;
        for(int i=0;i<q;i++){
            int u,v;
            cin>>u>>v;
            cout<<lcasqrt(u,v)<<endl;

        }

    }
}


texts:
Can this be improved?

foreach (Gift gift in usedGifts)
{
    foreach (GiftTransaction GiftTransaction in gift.GiftTransactions)
    {
        if (!string.IsNullOrEmpty(giftTransaction.GiftId) &&
            !orderList.Where(b => b.GiftId == giftTransaction.GiftId).Any())
        {
            Order order = OrderHelper.PopulateSingleOrder(orderRepository, sessionRepository, giftTransaction.GiftId);
            if (order != null)
                orderList.Add(order);
        }
    }
    giftReferenceList.Add(gift.GiftReference);
}


texts:
This code is supposed to asynchronously load a queue from a generating function.

#include <queue>
#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <stdexcept>

using namespace std;

template <typename Container>
struct LoadAsync {

    LoadAsync( size_t queue_size, function<Container()> f )
        : find_next( f ), size( queue_size ),
          worker_thread( &LoadAsync<Container>::worker_thread_function, this )
    {
        // first, build the basics
        unique_lock<mutex> lk( m );
        cv_init.wait( lk, [this] { return this->qued.size() >= this->size; } );
    }

    LoadAsync( const LoadAsync& ) = delete;

    void worker_thread_function()
    {
        while ( true ) {
            unique_lock<mutex> lk( m );
            cv.wait( lk, [this] { return this->qued.size() < this->size; } );
            while ( this->qued.size() < this->size ) {
                try {
                    qued.emplace( find_next() );
                } catch (domain_error) {
                    this->size--;
                }
            }
            lk.unlock();
            cv_init.notify_one();
        }
    }

    Container pop_front()
    {
        unique_lock<mutex> lk( m );
        cv_init.wait( lk, [this] { return this->qued.size() >= this->size; } );
        if (this->qued.size() == 0)
            throw out_of_range("out of range");
        auto front = move( qued.front() );
        qued.pop();
        lk.unlock();
        cv.notify_one();
        return front;
    }

  private:
    size_t size;
    queue<Container> qued;
    function<Container()> find_next;
    thread worker_thread;
    mutex m;
    condition_variable cv;
    condition_variable cv_init;
};

int main()
{
    auto func = []() {
        static int which = 1;
        if ( which < 10 )
            return which++;
        else
            throw domain_error("out of range");
    };

    LoadAsync<int> la( 3, func );

    for ( int i = 0; i < 11; ++i ) cout << la.pop_front() << endl;

}

Is this a good approach?  Are there any gotchas here in using condition_variables?  Are there any long bottlenecks here?  Is waiting on a condition variable an immediate thing?


texts: define a lisp function, that takes fsm , a transition and state-index and return the state obtained by the transition from the state

texts:
The state machine has the below specifications
    (defparameter *test-machine*
(make-fsm
:alphabet '(a b)
:table '((2 1) (0 2) (1 0))
:initial 0
:accepting '(2)))

The FSM in the function is:
 [1]> (fsm-alphabet *test-machine*)
(A B)
[2]> (fsm-initial *test-machine*)
0
[3]> (fsm-accepting *test-machine*)
(1)

The transition of the function is - the element of the alphabet of fsm
the state index of the function is the index of the current state in the list of states
below is the function output
 [3]> (transition-function *test-machine* 0 'a)
2
[4]> (transition-function *test-machine* 0 'b)
1
[5]> (transition-function *test-machine* 2 'b)
0

the built-in function position will return the index of an element in a list if that element exists.
For example, (position '3 '(1 2 0 2 3 5 6)) will return 4.


texts: Is it needed to "beautify" this Stack implementation?

texts:
I'm just learning OOP, and I have an assignment to create a Stack. I came up with the following. Is it "beauty" enough, or to "schooly". Where can I evolve?

This is the class:

class Stack
{
    private int _length;
    private List<int> _members = new List<int>();

    public Stack()
    {
        _length = 10;
    }

    public Stack(int length)
    {
        _length = length;
    }

    public List<int> Members
    {
        get { return _members; }
    }

    public int Length
    {
        get { return _members.Count; }

    }

    public bool IsEmpty
    {
        get { return (_members.Count == 0); }
    }

    public void Push(int member)
    {
        if (_members.Count < _length) _members.Add(member);
        else throw new Exception("The Stack is full.");
    }

    public int Pop()
    {
        if (!IsEmpty)
        {
            int last_one = _members[_members.Count - 1];
            _members.RemoveAt(_members.Count - 1);
            return last_one;
        }
        else throw new Exception("The Stack is empty.");
    }

}

And this is my Form:

public partial class Form1 : Form
{
    Stack verem = new Stack(20);
    Random rnd = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void refreshStack()
    {
        lbStack.Items.Clear();
        foreach (int member in verem.Members)
        {
            lbStack.Items.Insert(0, member);
        }
    }
    private void btnIsEmpty_Click(object sender, EventArgs e)
    {
        MessageBox.Show(verem.IsEmpty.ToString());
    }

    private void btnLength_Click(object sender, EventArgs e)
    {
        MessageBox.Show(verem.Length.ToString());
    }

    private void btnPush_Click(object sender, EventArgs e)
    {
        verem.Push((int)rnd.Next());
        refreshStack();
    }

    private void btnPop_Click(object sender, EventArgs e)
    {
        verem.Pop();
        refreshStack();
    }

}


texts: Angular2 and RxJS passing objects around with a service

texts:
Let's say I want to share an object between multiple components. This service will allow components to send or receive the object.

This functionality allows for an object to be Globally Accessible. The service should also allow multiple global objects and a way to unsubscribe.

The full example is here.

import { Injectable } from '@angular/core';
import {
  Subject,
  BehaviorSubject,
  Subscription } from 'rxjs';

@Injectable()
export class GlobalService {
  private subjects: object = {};

  subscribe<T>(key:string, fn: (value: T) => void, unsubscribe: Subject<any>): Subscription {
    this.putSubject<T>(key);
    return this.subjects[key]
               .takeUntil(unsubscribe)
               .subscribe({ next: fn });
  }

  emit<T>(key: string, value: T): void {
    this.putSubject<T>(key);
    this.subjects[key]
        .next(value);
  }

  private putSubject<T>(key: string): void {
    if (!this.subjects[key]) {
      this.subjects[key] = new BehaviorSubject<T>(null);
    }
  }
}

Any comments are welcome!


texts: 12-column CSS grid system similar to Bootstrap


texts: Return array with products of old array except i

texts:
Coding problem:

  Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

My solution:

arr = np.array([1, 2, 3, 4, 5])

def coding_solution(_arr):
    ind = 0
    new_arr = []
    for n in range(len(_arr)):
        v = 1
        for m, i in enumerate(_arr):
            v *= i if m != ind else 1
        new_arr.append(v)
        ind += 1
    return np.array(new_arr)

Output: [120, 60, 40, 30, 24]

Is there a faster or less space consuming solution? It takes longer to run then I would've expected or would think is acceptable.


texts: Function that loads a random image using an array of paths to images

texts:
I have created a program that generates a random image from a folder of all the world's flags. First, it generates an image as it loads, then it can keep randomizing the shown image if the user clicks on a button. Currently, I have created a method called "ImageGenerator" and call that method both in Form1() and my button click method (view code: https://pastebin.com/qzWXqP0P).

public partial class Form1 : Form
{
    public void ImageGenerator()
    {

        string[] flagImageSources = new string[196];

        StreamReader flagImageSourceReader = File.OpenText("flagImageSourceFile.csv");

        for (int i = 0; i < flagImageSources.Length; i++)
        {
            string s = flagImageSourceReader.ReadLine();
            flagImageSources[i] = s;
        }

        Random numberGenerator = new Random();
        int imageNumber = numberGenerator.Next(0, 196);

        string flagImageSrc = flagImageSources[imageNumber];

        flagPictureBox.ImageLocation = @flagImageSrc;
    }

    public Form1()
    {
        InitializeComponent();

        ImageGenerator();
    }

    private void submitBtn_Click(object sender, EventArgs e)
    {
        ImageGenerator();
    }
}

To me it feels like the linked code is rather inefficient as it recreates the array flagImageSources (which contains the paths to each flag image) every time a new image is to be generated in the picture box. How can I run the code on lines 6 through 13 only once, and then just run the code on lines 16 through 21 when randomizing images?


texts:
In this example I've a refresh method that might be called by multiple threads. Requirements are:

refresh() method must be processed by only one thread at a time (blocking)
If already a thread is waiting, skip any new thread tries to acquire the lock to avoid processing multiple times

The refresh() method not returning anything nor changing state for the calling thread (fire and forget). So it is not necessary that it's called for every thread, instead, if multiple thread ask for a refresh it should only be executed once.

I'm trying to use a Semaphore with 1 permit for this task. If the semaphore has any queued threads I'm just returning, otherwise the thread will acquire the lock.

class Scratch {

    private final Semaphore refreshLock = new Semaphore(1);

    public void refresh() {
        System.out.println("call refresh()");
        try {
            synchronized (refreshLock) {
                if (refreshLock.hasQueuedThreads()) {
                    System.out.println("skip this thread ... " + Thread.currentThread().getId());
                    return; // don't put one more to the queue
                }
            }

            // wait till release of lock
            System.out.println("wait for lock release, queue: " + refreshLock.getQueueLength());
            refreshLock.acquire();

            try {
                System.out.println("process ... " + Thread.currentThread().getId());
                Thread.sleep(5000);
                System.out.println("### DONE");
            } finally {
                refreshLock.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class Task implements Runnable {
        private int taskId;
        private Scratch scratch;

        Task(int id, Scratch scratch) {
            this.taskId = id;
            this.scratch = scratch;
        }

        @Override
        public void run() {
            System.out.println("Task ID : " + this.taskId + " performed by " + Thread.currentThread().getName());
            try {
                Thread.sleep(300 + taskId * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            scratch.refresh();
        }
    }

    public static void main(String[] args) {
        Scratch scratch = new Scratch();
        ExecutorService service = Executors.newFixedThreadPool(10);
        IntStream.range(0, 12).forEach(i -> service.submit(new Task(i, scratch)));
        service.shutdown();
    }
}


texts:
I am hoping someone can help me tidy up my code (for a practical for university). The practical is to use the random number generator to produce 100 integers (all between 1 and 10) and store them in an array. We then need to scan the array and print out how often each number appears. Following this, we needed to create a horizontal bar chart using asterisks to show how often each number appears, before finally printing out which number appeared the most.

My code works and produces the correct results:

import java.util.Random;

public class Practical4_Assessed
{

public static void main(String[] args)
{

    Random numberGenerator = new Random ();
    int[] arrayOfGenerator = new int[100];
    int[] countOfArray     = new int[10];
    int count;

    for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
    {
        count = numberGenerator.nextInt(10);
        countOfArray[count]++;
        arrayOfGenerator[countOfGenerator] = count + 1;
    }

    int countOfNumbersOnLine = 0;
    for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
    {
        if (countOfNumbersOnLine == 10)
        {
            System.out.println("");
            countOfNumbersOnLine = 0;
            countOfOutput--;
        }
        else
        {
            if (arrayOfGenerator[countOfOutput] == 10)
            {
                System.out.print(arrayOfGenerator[countOfOutput] + "  ");
                countOfNumbersOnLine++;
            }
            else
            {
                System.out.print(arrayOfGenerator[countOfOutput] + "   ");
                countOfNumbersOnLine++;
            }
        }
    }

    System.out.println("");
    System.out.println("");

// This section

    for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
        System.out.println("The number " + (countOfNumbers + 1) + " occurs " + countOfArray[countOfNumbers] + " times.");

    System.out.println("");

    for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
    {
        if (countOfNumbers != 9)
                System.out.print((countOfNumbers + 1) + "   ");
        else
                System.out.print((countOfNumbers + 1) + "  ");

        for (int a = 0; a < countOfArray[countOfNumbers]; a++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }

 // To this section

    System.out.println("");

    int max = 0;
    int test = 0;
    for (int counter = 0; counter < countOfArray.length; counter++)
    {
        if (countOfArray[counter] > max)
        {
            max = countOfArray[counter];
            test = counter + 1;
        }
    }

    System.out.println("The number that appears the most is " + test);

}
}

However, I know that the section that tells how often a number occurs and the section that prints out the asterisks both start with the same for statement (I have marked them off in the code with comments). Can anyone advise me how I could do this using just one for statement? It seems quite straightforward, and yet I just can't get it to work!

Additionally, I am sure there are plenty of other areas that the code could be improved on. Feel free to suggest any improvements!


texts: JavaScript closure: code trivia to keep the event handler separate

texts:
Note: This was originally posted at SO, and as per the recommendation moving to this form.

In my effort to learn JS on the backdrop of SVG development, I got lot of help from SO so far. The answer to previous query was the best to understand closure; its usage and caveats in very short time. While continuing on the same line, I was trying to breakdown the below function so that it is more readable and easy to expand. It was part of an answer given by @Phrogz. I could not think a way to keep the onmove closure outside the loop.

If someone can help me with a pseudo code/skeleton of how can it be done without too many variable to retain the state (like button click state while moving etc), it would clarify many of my doubts regarding how the closure can be assigned etc. You may also break the function into 3 event handlers (mousedown, mousemove, mouseup). I could not think a way to do this while keeping the context (mousemove only triggers when the mouse is down, as it is within the closure).

I use jQuery typically in my projects, so if that helps to make the above code more maintainable, that would help too.

for (var a=svg.querySelectorAll('.drag'),i=0,len=a.length;i<len;++i){
        (function(el){
            var onmove; // make inner closure available for unregistration
            el.addEventListener('mousedown',function(e){
                el.parentNode.appendChild(el); // move to top
                var x = el.tagName=='circle' ? 'cx' : 'x';
                var y = el.tagName=='circle' ? 'cy' : 'y';
                var mouseStart   = cursorPoint(e);
                var elementStart = { x:el[x].animVal.value, y:el[y].animVal.value };
                onmove = function(e){
                    var current = cursorPoint(e);
                    pt.x = current.x - mouseStart.x;
                    pt.y = current.y - mouseStart.y;
                    console.log("pt.x:" + pt.x + "pt.y:" + pt.y);
                    var m = el.getTransformToElement(svg).inverse();
                    m.e = m.f = 0;
                    pt = pt.matrixTransform(m);
                    el.setAttribute(x,elementStart.x+pt.x);
                    el.setAttribute(y,elementStart.y+pt.y);
                    var dragEvent = document.createEvent("Event");
                    dragEvent.initEvent("dragged", true, true);
                    el.dispatchEvent(dragEvent);
                };
                document.body.addEventListener('mousemove',onmove,false);
            },false);
            document.body.addEventListener('mouseup',function(){
                document.body.removeEventListener('mousemove',onmove,false);
            },false);
        })(a[i]);
    }


texts: Program that multiplies numbers over and over

texts:
Would appreciate a review on this. The program does work as it is intended to. However I am unsure if there is a more elegant or better way to execute this process with less code.

def main():

    print ('This program takes two numbers and multiplies them.')
    print ('the result is multiplied by a third number')
    print ('entered by the user too')

    procedure()

def procedure():

    n = float(input('Enter a number: '))
    n2 = float (input('Enter a number: '))
    value = n * n2
    y = value
    print value

    n3 = float(input('Multiply by: '))

    while n3 != '0':

        op = n3 * y
        y = op
        print y

        n3 = float(input('Multiply by: '))

main()


texts:
In order to divide an IEnumerable in C# by a predicate, I implemented the following (in a static class):

public static IEnumerable<IEnumerable<T>> SplitBeforeIf<T>(this IEnumerable<T> input, Func<T, bool> pred)
{
    //This exists to store the predicate satisfier, which I kept as
    //the first T in the inner IEnumerable (except, maybe the first one).
    T predSatis = default(T);
    while(input.Any())
    {
        var temp = input.TakeWhile(v => !pred(v));
        //I was told that the below is the best test for default-ness.
        //(I assume that pred(default(T)) is always false.)
        if(predSatis == null || predSatis.Equals(default(T)))
            yield return temp;
        else
            yield return (new List<T>{predSatis}).Concat(temp);

        input = input.SkipWhile(v => !pred(v));
        predSatis = input.FirstOrDefault();
        input = input.Skip(1);
    }
    if(predSatis != null && !predSatis.Equals(default(T)))
        yield return new List<T>{predSatis};
}

This returns as follows:

new List<int>{1,2,3,4,5}.SplitBeforeIf(v => v % 2 == 0) gives {{1}, {2,3}, {4,5}}
new List<int>{6,1,2,3,4,5}.SplitBeforeIf(v => v % 2 == 0) gives {{}, {6, 1}, {2,3}, {4, 5}}
new List<int>{1,2,3,4,5,6}.SplitBeforeIf(v => v % 2 == 0) gives {{1}, {2,3}, {4,5}, {6}}.

I have 3 questions (besides any other comments on the code):

I see that, despite my best efforts, this is \$O(n^2)\$. Why? Can this be improved for a generic IEnumerable?
This does not support a stateful predicate or a stateful IEnumerable input. Can this be remedied?
This looks awfully like Clojure's partition-by. How does Clojure avoid the first issue (it may also have the second, but functional programming dislikes state anyway)?

Being a little pedantic about these things, I also would prefer solutions that don't accumulate values into another data structure (just to see if full laziness is possible).


texts:
I need to display a path within a GUI application. Displaying the whole path would be an overkill, so I made a custom path shortener.

def cut_path(path):
    ''' This function takes a path and outputs the path cut with the ... after the
     the first folder after the first character and completes the name with the filename or the last folder
    Example:
    C:/Users/Mauro/Desktop/DenoiseAvg/DenoiseAverage/test_cut_path.py
    C:/Users/.../test_cut_path.py
     '''
    endidx = 5
    char = path[endidx]
    while char != '/' and endidx < len(path):
        endidx += 1
        char = path[endidx]

    inpath = path[:endidx + 1 ]

    rpath = path[::-1]
    idx = 1
    char = rpath[idx]
    while char != "/" and idx < len(rpath):
        idx += 1
        char = rpath[idx]

    endpath = path[len(path) - idx - 1 : ]

    outpath = inpath + "..." + endpath
    return outpath

Pastebin for syntax highlighting

Is there a shorter, more readable, pythonic way to do it? Is there a way to limit how many characters the path would be long? How would you do it?


texts: Android - perform an action in background every few minutes

texts:
I've written the code to perform some action every 5 minutes, regardless if the application is currently on the foreground or not. I'd like to get a feedback about correctness - have I chosen the right API to do the work and is it implemented correctly?

This is the code:

PeriodicActionFacade.java which is the entry point to the feature (its start and stop methods can be bound to buttons):

class PeriodicActionFacade {
    private final Context context;
    private final PeriodicExecutor executor;

    PeriodicActionFacade(final Context context) {
        this.context = context;
        this.executor = PeriodicExecutor.INSTANCE;
    }

    void start() {
        context.startService(new Intent(context, PeriodicActionService.class));
    }

    void stop() {
        executor.terminate();
    }
}

PeriodicActionService which is starting the PeriodicExecutor as the foreground service:

public class PeriodicActionService extends IntentService {

    private static final int NOTIFICATION_ID = 1;
    private final PeriodicExecutor executor;

    public PeriodicActionService() {
        super(PeriodicActionService.class.getSimpleName());
        executor = PeriodicExecutor.INSTANCE;
    }

    @Override
    protected void onHandleIntent(@Nullable final Intent intent) {
        startForeground(NOTIFICATION_ID, buildNotification());
        executor.executeBlocking();
        stopForeground(true);
        stopSelf();
    }

    private Notification buildNotification() {
        return new NotificationCompat.Builder(this, NotificationChannels.PERIODIC_ACTION)
                .setContentTitle("Ongoing periodic action")
                .setContentText("Ongoing periodic action")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();
    }
}

PeriodicExecutor which is responsible for executing the action every 5 minutes unless terminate is called:

enum PeriodicExecutor {
    INSTANCE;

    private boolean isRunning;
    private CountDownLatch latch;

    void executeBlocking() {
        isRunning = true;
        while (isRunning) {
            latch = new CountDownLatch(1);
            performAction();
            try {
                latch.await(5, TimeUnit.MINUTES);
            } catch (InterruptedException ignored) { }
        }
    }

    private void performAction() {
        // Here I'm performing the action
        Log.i(PeriodicExecutor.class.getSimpleName(), "I'm performing periodic action!");
    }

    void terminate() {
        isRunning = false;
        latch.countDown();
    }
}


texts:
I have written a small plugin for nagios to check a WebDAV server. It is supposed to connect using a username and password and upload & delete a test file

This is my code:

#!/bin/bash
#Exit codes
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

FILENAME=/tmp/test_monitor
FILE=test_monitor
HOSTNAME=$1
USERNAME=$2
PASSWORD=$3
WEBDAVDIR=$4

# Verify the type of input and number of values
# Display an error message if the (input) is not correct
# Exit the shell script with a status of 1 using exit 1 command.
[ $# -ne 4 ] && { echo "Usage: $0 <hostname> <username> <password> <webdav_dir>"; exit 1; }

# create temp file
truncate -s 1M /tmp/test_monitor

# connect to server and upload file
curl --fail -T $FILENAME -u $USERNAME:$PASSWORD http://$HOSTNAME/$WEBDAVDIR/

status=$?
case $status in
    0)
        echo "OK - File uploaded on WebDAV Server: $HOSTNAME"
        # remove test file
        curl --fail -X DELETE -u $USERNAME:$PASSWORD http://$HOSTNAME/$WEBDAVDIR/$FILE
        exit $STATE_OK
        ;;
    1)
        echo "CRITICAL - Cannot upload file on $HOSTNAME"
        exit $STATE_CRITICAL
        ;;
    6)
        echo "CRITICAL - Could not resolve host $HOSTNAME"
        exit $STATE_CRITICAL
        ;;
    26)
        echo "CRITICAL - Cannot open $FILENAME for upload"
        exit $STATE_CRITICAL
        ;;
    22)
        echo "CRITICAL - The requested URL returned error"
        exit $STATE_CRITICAL
        ;;
    127)
        echo "CRITICAL - Command not found"
        exit $STATE_CRITICAL
        ;;
    *)
        echo "UNKNOWN - "
        exit $STATE_UNKNOWN
esac

Can you suggest any improvements?


texts:
I created this program to print the number of vowels of a given text in C; it is only a small exercise. I consider a vowel only the letters "aeiou", both in upper case and lower case.

I provided a small command line interface: if you give -h or --help you get the help message, if you give the text (e.g. vowel "This is a text") it directly prints the number of vowels. If you run the program without any argument or text, it reads from the stdin until the user types CTRL-D two times.

Examples:

user@computer:$ ./vowels
This is
a
text
4
user@computer:$ ./vowels "This is a text"
4

The source code is organized in a main.c and a Makefile.

Makefile

.PHONY = clean all

PROGNAME = vowels

CC ?= gcc

CFLAGS = -Wall -Wextra

all : $(PROGNAME)

$(PROGNAME) : main.o
    $(CC) -o $(PROGNAME) $^

clean :
    $(RM) *.o $(PROGNAME)

main.c

#include <stdio.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h> /* For tolower(). */

#define BUFFER_SIZE 1024

/* It returns true if the given character is a vowel.
 *
 * Arguments:
 *      - chr : the character to check.
 *
 * Return value:
 *      True if 'chr' is a vowel, otherwise false.
 *
 * Notes:
 *      The vowels considered are English vowels (a, e, i, o, u), both in
 *      upper case and lower case.
 */
bool is_vowel(char chr)
{
        static const char VOWELS[] = "aeiou";

        chr = tolower(chr);

        char *result = strchr(VOWELS, chr);

        return (!result) ? false : true;
}

/* It returns the number of vowels found in a null terminated byte string.
 *
 * Arguments:
 *      - str : the null terminated byte string.
 *
 * Return value:
 *      It returns the number of vowels found in the string.
 *
 * Warning:
 *      The behavior is undefined if str is not a pointer to a null-terminated
 *      byte string.
 */
int vowels_in(char *str)
{
        int vowels = 0;

        while (*str) {
                if (is_vowel(*str))
                        vowels++;

                str++;
        }

        return vowels;
}

/* It prints the help message.
 */
void print_help(void)
{
        static const char message[] =
"usage: vowels [-h|--help] <text>\n\n"
"It shows the number of vowels (aeiou) found in a given text. If you don't\n"
"specify text in the command line, the program reads text from stdin.\n\n"
;

        printf("%s", message);
}

int main(int argc, char *argv[])
{
        char buffer[BUFFER_SIZE];
        int vowels = 0;

        if (argc == 2) {
                if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
                        print_help();
                        return 0;
                } else {
                        vowels = vowels_in(argv[1]);
                        printf("%d\n", vowels);
                }
        } else if (argc == 1) {
                size_t chars;

                /* Repat until the user type CTRL-D or there is an error. */
                do {
                        chars = fread(buffer, sizeof(char), BUFFER_SIZE, stdin);

                        vowels += vowels_in(buffer);
                } while (chars == BUFFER_SIZE);

                printf("\n%d\n", vowels);
        } else {
                fprintf(stderr, "Invalid options; see 'vowels --help'.\n");
                return -1;
        }

        return 0;
}


texts:
Question

http://www.ioinformatics.org/locations/ioi13/contest/day2/cave/cave.pdf

Code

#include "cave.h"
#include <cstdio>
#include <cstring>
using namespace std;

const int MAXN = 5001;
int status[MAXN] , door[MAXN] , guess[MAXN];

void exploreCave(int N){
  memset(door , -1 , sizeof(door));
  for(int n = 0 ; n < N ; n++){
    int r = tryCombination(status);
    int low = 0 , high = N - 1;
    while(low != high){
      bool changed = false;
      int a = low , b = (low + high) / 2;
      for(int i = 0 ; i < N ; i++){
        if(i >= a && i <= b){
          if(door[i] != -1){
            guess[i] = status[i];
          }
          else {
            guess[i] = !status[i];
            changed = true;
          }
        }
        else guess[i] = status[i];
      }
      int K = r;
      if(changed) K = tryCombination(guess);
      if(r == n){
        if(K > n || K == -1)
          high = b;
        else low = b + 1;
      }
      else {
        if(K == n) high = b;
        else low = b + 1;
      }
    }
    door[low] = n;
    if(r == n) status[low] = !status[low];
  }
    answer(status , door);
}

Issue

While this is a working and correct code, I runs at O(NlogN) time(I think).  Is there a possible way to further shorten the time complexity?  This code uses binary search.


texts: Finding overlapping time intervals for two games

texts:
I am trying to learn Java by doing some (easy) ACM TCPC problems. The problem is finding number of overlapping times intervals. If there a one, a fight will happen between the two games connected to those intervals.

Example

Input

1    // this is the number of cases.
3    // the number of time intervals
1 5  // The first intervals is [1, 5]
1 2  // ...
2 4

The comment are mine.

Output:

  Case 1: 3

I'm looking for a review in terms of best practices, things I should or shouldn't do, or things I should do in another way.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Compo {
  public static void main(String[] args) throws IOException {
    File fin = new File("./compo.in");
    numberOfFight(fin);
  }

  private static int numberOfFight(File fin) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(fin))) {
      int numberOfCases = Integer.parseInt(br.readLine());
      int i = 0;
      int numberOfGame = 0;
      String line;

      while (i < numberOfCases) {
        numberOfGame = Integer.parseInt(br.readLine());
        List<int[]> games = new ArrayList<int[]>(numberOfGame);
        for (int j = 0; j < numberOfGame; j++) {
          line = br.readLine();

          int[] game = new int[2];
          game[0] = Integer.parseInt(line.split(" ")[0]);
          game[1] = Integer.parseInt(line.split(" ")[1]);
          games.add(game);
        }

        int fights = 0;
        for (int j = 0; j < numberOfGame - 1; j++) {
          for (int k = j + 1; k < numberOfGame; k++) {
            if (fight(games.get(j), games.get(k))) {
              fights++;
            }
          }
        }
        i++;
        System.out.println("Case "+i+": "+fights);
      }
    }
    return 0;
  }

  private static boolean fight(int[] game1, int[] game2) {
    // Check if the games overlap
    return ((game1[0] <= game2[0]) && (game2[0] <= game1[1])) || ((game1[0] <= game2[1]) && (game2[1] <= game1[1]));

  }
}


texts:
I've been trying to learn async coding recently. I've managed to get it to work and the UI thread doesn't block like it does if I don't make the code async. I realise this is a very contrived example, but is this how async should be done?

public partial class MainWindow : Window
 {
  public MainWindow()
  {
     InitializeComponent();
  }

  private async void Button_Click(object sender, RoutedEventArgs e)
  {
     string outputString = (await Authentication(usernameTextBox.Text)) ? "Name exists" : "Name does not exist";

     MessageBox.Show(outputString);
  }

  private Task<bool> Authentication(string username)
  {
     return Task.Run(() => CheckIfNameExistsInDatabaseOnServer(username));
  }

  private bool CheckIfNameExistsInDatabaseOnServer(string username)
  {
     //Pretend to pass details and wait for a response
     Thread.Sleep(5000);

     return (username == "Will");
  }
}


texts:
I am learning algorithms and have implemented the Rabin-Karp string search algorithm.   I didn't implement a rolling HashCode, but it's judged correct by this online judge.

It's slower than the str.indexOf() implementation (7ms, compared to 4 ms). Can this be improved? What is the time complexity for this?

class Solution {
public int strStr(String haystack, String needle) {
    if (haystack == null || needle == null)
        return -1;
    int needleHash = hashCode(needle);
    int plen = needle.length();
    boolean t = true;
    int tlen = haystack.length() - needle.length() + 1;
    for (int i = 0; i < tlen; i++) {
        String sub = haystack.substring(i, plen + i);
        int haystackHash = hashCode(sub);
        if (haystackHash == needleHash) {
            for (int j = 0; j < plen; j++) {
                char[] charN = needle.toCharArray();
                char[] charH = sub.toCharArray();
                if (charN[j] != charH[j]) {
                    t = false;
                }
            }
            if (t == true) {
                return i;
            }
        }
    }
    return -1;
}

public int hashCode(String value) {
    int h = 777;
    if (value.length() > 0) {
        char val[] = value.toCharArray();

        for (int i = 0; i < val.length; i++) {
            h = 31 * h + val[i];
        }
    }
    return h;
  }
}


texts: Handling data returned from fetch_assoc()

texts:
I connected to the db, pull the data using fetch_assoc() (fetch_all(NUMB) is not available on the machine we are working with else this would be less of an issue). I get the returned data and load it into an array. However, it ends up in as an numeric array embedded inside another assoc array. What is the best way to have get the returned data in one, single, simple ASSOC array?

/**
* @Param $conn object [required], $tableName string [required]
* @Return $clmNames array
*/
public function getColumnName($conn = NULL, $tableName = NULL )
{
    if ( !is_object( $conn ) || !is_string( $tableName ) )
    {
        //params are not of correct type. This will eventually throw an error instead of printing to screen
        echo("Error: getColumnName returning false");
        return false;
    }

    //create SQL query
    $stmt = "SELECT column_name FROM information_schema.columns WHERE table_name =  '". $tableName ."' ORDER BY ordinal_position";
    //create query
    $query = $conn->query($stmt);

    //execute query
    $tmp = array();
    while ($row = $query->fetch_assoc())
    {
        //load all returned rows into an array
        $tmp[] = $row;
    }

    //clear memory
    $query->free();unset($query);

    //reCreate Array as a single assoc array instead of a double enbedded one.
    $clmNames = array();
    foreach( $tmp as $tmpKey=>$tmpValue )
    {
        foreach( $tmpValue as $tmpValueKey=>$tmpValueValue )
        {
            $clmNames[] = $tmpValueValue;
        }
    }

    return  $clmNames;
}

The above returns the data correctly. However, I would like to be able to remove the entire foreach dealing with $tmp and $clmNames if possible.