texts:
I tested this program on Smooth-CoffeeScript

I just wanted to have as many eyes on this as I could to learn about coffeescript;

Is there anything I should do to improve it?

Am I using the tools available to me adeptly? (i.e. good variable naming, layout, commenting, etc.)

userQuestion   = '¿ what is 2 + 2 ?'
correctLength = 1
correctAnswer = '4'
correctAnswerMsg = "That's correct!"
closeMsg = "Almost there!"
digitsOnlyMsg = "Digits only!"
singleDigitMsg = "Single digit!"
tryAgainMessage = "Try again!"

prompt userQuestion, '', (answer) ->  # the answer can not be set as a variable here
                                      # (answer) grabs the answer from the console
  userEntry = answer                  # -> casts that answer down to the rest of the indent to be used plainly
                                      # at least that's how I think it works :/

  show userEntry  # the user's answer always shows on the first line

  if userEntry.length isnt correctLength  # .length only works when comparing the length of a string to an integer
    show singleDigitMsg

  userEntry = (Number) userEntry
  correctAnswer = (Number) correctAnswer  # now we convert our user entry and our correct answer into integers so the math functions work

  if userEntry is correctAnswer
    show correctAnswerMsg
    exit program

  else if userEntry is correctAnswer - 1 or userEntry is correctAnswer + 1
    show closeMsg

  else if isNaN(userEntry)
    show digitsOnlyMsg

  else  # this only shows when the user types in 1, 2, or 6-9. Or multiple characters with a digit, like '-4'
    show tryAgainMessage


texts: Encoding and assigning the result to a label

texts:
I have to do some encoding and then assign the result to a label. Is there a more optimal (or concise) way to write this?

// encoding fix
NSString *correctStringTitle = [NSString stringWithCString: [[item objectForKey:@"main_tag"] cStringUsingEncoding:NSISOLatin1StringEncoding]
                                                  encoding: NSUTF8StringEncoding];

cell.titleLabel.text = [correctStringTitle capitalizedString];


texts: Do I always have to return something in an anonymous function?

texts:
I have inherited this snippet of jQuery JavaScript and am currently brushing up on my jQuery. NetBeans IDE complains that Anonymous function does not always return a value. So there is not always an explicit exit point.

I am aware that the $() shortcut is not being used. This is because it is running within a WordPress environment and needs to be in no-conflict mode.

function init() {

    jQuery("#post").submit(function(_e) {
        // Make sure question is supplied
        var contents;
        if(window.tinyMCE && document.getElementById("content").style.display=="none") { // If visual mode is activated.
            contents = tinyMCE.get("content").getContent();
        } else {
            contents = document.getElementById("content").value;
        }

        if(!contents) {
            alert(msg_enter_question);
            _e.preventDefault();
            _e.stopPropagation();
            return true;
        }

        // We must have atleast 2 answers.
        var answer_count = 0
        jQuery(".answer").each(function() {
            if(this.value) answer_count++;
        });
        //if(answer_count < 2) {
        //  alert("<?php //_e("Please enter atleast two answers"); ?>");
        //  _e.preventDefault();
        //  _e.stopPropagation();
        //  return true;
        //}

        //A correct answer must be selected.
        var correct_answer_selected = false;
        jQuery(".correct_answer").each( function(_e) {
            if(this.checked) {
                correct_answer_selected = true;
                return true;
            }
        });
        if(!correct_answer_selected) {
            alert(msg_correct_answer);
            _e.preventDefault();
            _e.stopPropagation();

        }
    });
}
jQuery(document).ready(init);

My question is - do I always have to return something in an anonymous function? I.e. is NetBeans right to complain?


texts:
Sometimes when designing a fluent-api it's important to build an object in a specific way/sequence.

I tried to create such a guided builder and came-up with this:

public class Query
{
    public static IFrom Build() { return new Builder(); }

    public class Builder : IFrom, IWhere, ISelect, ICreate
    {
        public IWhere From() { return this; }
        public ISelect Where() { return this; }
        public ICreate Select() { return this; }

        public Query Create() { return new Query(); }
    }

    public interface IFrom { IWhere From(); }
    public interface IWhere { ISelect Where(); ICreate Select();  }
    public interface ISelect { ICreate Select(); }
    public interface ICreate { Query Create(); }
}

Usage:

var query1 = Query.Build().From().Where().Select().Create();

or

var query2 = Query.Build().From().Select().Create();

Without manual casting you are guided through the creation process so everything stays fluent. Or maybe there are better ways to suggest the fluent path?


texts: Count swaps needed to order a list of integers

texts:
I wrote this code since I'm going through the hackerrank challenges, however, it takes way too long to run.
Its function is described on the title, but just to clear it up, we need to count the minimum amount of swaps needed to order a set of ascending integers.

def minimumSwaps(arr):
    count = 0
    correct = [(x+1) for x in range(len(arr))]
    while arr != correct:
        for i in arr:
            if i != arr.index(i)+1:
                a = i
                b = arr[i-1]
                arr[i-1] = a
                arr[arr.index(i)] = b
                count += 1
                break
    return count
if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().rstrip().split()))
    res = minimumSwaps(arr)
    print(str(res))


texts:
I am writing a logging framework for iOS. The idea is to create a behavior similar to NSLog to print the log message and some metadata to the console.

The following struct shall hold the data of a log entry:

public enum LogLevel: Int {

    case highlight = 4
    case debug = 3
    case info = 2
    case warning = 1
    case error = 0

}

public struct LogEntry {

    let date: Date
    let file: String
    let function: String
    let line: Int
    let logLevel: LogLevel
    let text: String

    var metaText: String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss"
        return "\(dateFormatter.string(from: self.date)): \((self.file as NSString).lastPathComponent):\(self.line) \(self.function): "
    }

}

The struct can then be printed with the following function (simplified):

public class QLog {

    static func log(_ logEntry: LogEntry) {
        print("\(logEntry.metaText)\(logEntry.text)")
    }

}

Of course I want to log from any point in my code like QLogDebug("Test"). So, I added the following global functions (I got the idea from https://github.com/goktugyil/QorumLogs):

public func QLogHighlight<T>(date: Date = Date(), file: String = #file, function: String = #function, line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: date, file: file, function: function, line: line, logLevel: LogLevel.highlight, text: "\(object)"))
}

public func QLogDebug<T>(date: Date = Date(), file: String = #file, function: String = #function, line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: date, file: file, function: function, line: line, logLevel: LogLevel.debug, text: "\(object)"))
}

public func QLogInfo<T>(date: Date = Date(), file: String = #file, function: String = #function, line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: date, file: file, function: function, line: line, logLevel: LogLevel.info, text: "\(object)"))
}

public func QLogWarning<T>(date: Date = Date(), file: String = #file, function: String = #function, line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: date, file: file, function: function, line: line, logLevel: LogLevel.warning, text: "\(object)"))
}

public func QLogError<T>(date: Date = Date(), file: String = #file, function: String = #function, line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: date, file: file, function: function, line: line, logLevel: LogLevel.error, text: "\(object)"))
}

Now, this is a bit ugly because the function signatures are very long as well as the initialization of the LogEntry object. Also, all five functions are the same except the function name and the log level.

So, are there any possibilities to shorten / simplify this code? Can I somehow shorten the signatures? Can I define the functions without copy-pasting them?


texts: Inefficient binary search? Hackerrank - Climbing the Leaderboard

texts:
I'm learning Golang and have been trying to get 100% on the following Hackerrank practice challenge: Climbing the Leaderboard

The code passes ~8 of 11 tests. The Hackerrank tests are time-bound and my code is not efficient enough to past the most intensive tests.

I'm removing duplicates from the scores using a map. Then work through each of Alice's scores to find the index of each one by doing a binary search. Given that Alice's scored are sorted, I re-use the index for the next search.

Any ideas?

package main

import (
    "fmt"
)

func main() {

    // example 1
    scores := []int32{100, 100, 50, 40, 40, 20, 10}
    alice := []int32{5, 25, 50, 120}
    r := climbingLeaderboard(scores, alice)
    for a, v := range r {
        fmt.Printf("Position: %d alice[a]: %d\n", v, alice[a])
    }
    fmt.Printf("\n")
}

func removeDuplicates(a []int32) []int32 {
    r := []int32{}
    seen := map[int32]int32{}
    for _, val := range a {
        if _, ok := seen[val]; !ok {
            r = append(r, val)
            seen[val] = val
        }
    }
    return r
}

func getMidPoint(start, end int) int {
    i := end - start
    if i%2 == 0 {
        return i/2 + start
    }
    return (i+1)/2 + start
}

// 100 100 50 40 40 20 10
// 100 50 40 20 10
// 0   1  2  3  4
func binarySearch(scores []int32, v int32, i int) int {
    var mid int
    start := 0
    end := i

    for true {
        if end-start == 1 {
            //fmt.Printf("1 - v: %d start: %d end %d\n", v, start, end)
            if v < scores[end] {
                return end + 2
            } else if v < scores[start] {
                return start + 2
            }
            return 1
        }
        if end == 0 {
            return 1
        }

        mid = getMidPoint(start, end)

        if v > scores[mid] {
            end = mid
        } else if v < scores[mid] {
            start = mid
        } else {
            // v == scores[mid]
            //fmt.Printf("2 - v: %d start: %d end %d\n", v, start, end)
            return mid + 1
        }
    }
    return end
}

// attempt 3 - binary search
func climbingLeaderboard(originalScores []int32, alice []int32) []int32 {

    r := make([]int32, len(alice))

    //create scores and remove dups
    scores := removeDuplicates(originalScores)
    i := len(scores)

    for a, v := range alice {
        // fmt.Printf("1 - i: %d a: %d alice[a]: %d\n", i, a, alice[a])
        i = binarySearch(scores, v, i-1)
        r[a] = int32(i)
    }

    return r
}


texts: A way to do this without a lot of variables and casting?

texts:
Currently I have this code:

float tileX = (float)rectangle.X / (float)newTileSize;
float tileY = (float)rectangle.Y / (float)newTileSize;

int xOrigin = (int)Math.Round(tileX) * newTileSize;
int yOrigin = (int)Math.Round(tileY) * newTileSize;

// Same idea for the next 4 lines

float tileWidth = (float)rectangle.Width / (float)newTileSize;
float tileHeight = (float)rectangle.Height / (float)newTileSize;

int selectorWidth = (int)Math.Round(tileWidth) * newTileSize;
int selectorHeight = (int)Math.Round(tileHeight) * newTileSize;

The reason for the first two lines is because if I don't cast them as a float it does integer division and I was a floating point value instead so I can round it in the next two lines.

This code is fine I guess it just seems like there would be a better way to do it without so much casting. Just seems rather verbose if that makes any sense.

Thanks.


texts:
I am trying to make a very simple error handler that would catch and handle all kinds of errors in both development and production environments. The idea is to keep it as simple as possible yet useful in the production environment.

In order to do so I am converting all errors into exceptions. Then I will need just a single function to handle both errors and exceptions.

Then, according to my principles of error handling

in the dev environment, it should just echo the error information out, and
in the prod environment, the error information has to be logged and a generalized error message has to be shown on-screen.

It am going to distinguish the modes using display_errors php.ini parameter and also consider all CLI scripts to be in the dev mode too.

set_error_handler(function ($level, $message, $file = '', $line = 0)
{
    throw new ErrorException($message, 0, $level, $file, $line);
});

set_exception_handler(function ($e)
{
    if (ini_get('display_errors') || php_sapi_name() === 'cli') {
        echo $e;
    } else {
        error_log($e);
        header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
        echo "
500 Internal Server Error

              An internal server error has been occurred.

              Please try again later.";
    }
});

There is vast room for improvement, like to create distinct exception classes for each error type (such as DeprecatedErrorException, NoticeErrorException etc.) or, based on the severity, to decide whether the script execution has to be terminated or not. Or a more creative/user-friendly error message. But I am not sure if I should include all that in a simple demonstration example. What are essential additions or modifications could be made to this code?


texts: Filtering data from an exisiting table using psycopg2+sqlalchemy

texts:
I am using psycopg2 & sqlalchemy to connect to a database and extract information from a table as follows:
def db_connection():
        eng = db.create_engine('my_URI')
        conn = eng.connect()
        return eng, conn

def table_conn():
    engine, connection = db_connection()
    metadata = db.MetaData()

    admin_table = db.Table(
        'myTableName',
        metadata,
        autoload=True,
        autoload_with=engine
    )
    return engine, connection, admin_table

def get_table_data(user_id):
    _, connection, table_data = table_conn()

    # first filter using user_id and sort the data by datetime column
    query = db.select([table_data]).where(
        table_data.columns.user_id == user_id,
    ).order_by(
        table_data.columns.created_at.desc()
    )
    result = connection.execute(query).fetchall()

    # 5th element is time
    # filtering the data to find data that has been saved at the same time
    # making it the latest data
    time = result[0][5]
    time_filtering_query = db.select([table_data]).where(
        table_data.columns.created_at == time
    )
    time_result = connection.execute(time_filtering_query).fetchall()
    return time_result

The functions: db_connection() & table_conn() are connecting to the database and the table respectively.
In the get_table_data function, I am doing the following:

Use the user_id to filter the table
Order the table in desc order on the created_at column (which is the 5th column of the table)
Extract the first created_at value (which is result[0][5] in the code above)
And use this extracted value to filter the table again

In the code, I am hardcoding the column index in the result[0][5] part. Is there a way the above code can be modified to avoid hardcoding of the values and filter the values, if possible, based on the column names or in any other neater way?


texts: Javascript singleton to notify different objects of changes in viewport size

texts:
I'm working on a singleton object to manage size changes in the viewport, I wanted it to be a singleton because there may be different unrelated objects that need to be notified when a change in viewport dimensions has occurred.
So I came up with this solution based on the singleton design pattern found in here.

var CAResizeManager = ( function () {

    var instance;

    function init() {

        var o_actions   = [];
        var o_cache_pos = {};
        var o_timeout;

        /*
         * Custom 'addEvent' function;
         */
        addEvent( window, 'resize', function () {

            /*
             * Clear timeout if resize is called severla times in short timespan.
             */
            clearTimeout( o_timeout );

            o_timeout = setTimeout( function () {

                var o_viewport_size = getViewportSize();
                /*
                 * Loop through the actions array to pass new viewport size;
                 */
                for ( var i = o_actions.length - 1; i >= 0; i-- ) {
                    var o_func = o_actions[ i ];

                    if ( o_func ) {
                        o_func( o_viewport_size );
                    }
                }

            } ,300 );

        } );

        return {
            addAction: function ( arg_func ) {

                /*
                 * Generates a unique id to identify action.
                 */
                var i_id = Math.random().toString().replace( '0.', '' );

                o_actions.push( arg_func );

                /*
                 * Store position in an object to avoid looping through the
                 * actions array.
                 */
                o_cache_pos[ i_id ] = o_actions.length === 0 ? 0 : o_actions.length - 1;

                /*
                 * Return id to external object.
                 */
                return i_id;
            },
            removeAction: function ( arg_id ) {

                var i_index = o_cache_pos[ arg_id ];

                /*
                 * Check if id exists;
                 */
                if ( i_index ) {
                    return;
                }

                /*
                 * Remove action from array
                 */
                o_actions.splice( i_index, 1 );

                /*
                 * Delete positon from cache;
                 */
                delete o_cache_pos[ arg_id ];

            }
        };
    }

    return {
        getInstance: function () {

            if ( !instance ) {
                instance = init();
            }

            return instance;

        }
    }

} )();


texts: Random walk generator - looking for optimizations (Python)

texts:
I just started learning Python and this is the first code I wrote. It's a Random Walk generator. I think I got it to work pretty well but I'm also sure there are more effective and less clunky ways to do this. Could you give me some tips on what to change to make the code shorter/more optimized and just objectively more "pythonian" and better?
# Random Walk in two dimensions

import random

steps = "a"
maximal = "a"
minimal = "a"
Xstep = 0
Ystep = 0
StepSize = 0
PosNeg = 0

def new_line():
    print(" ")

def invalid_enter_number():
    print("Invalid input! Enter a number.")
    new_line()

def invalid_enter_positive():
    print("Invalid input! Enter a positive number.")
    new_line()

new_line()
print("Random Walk in two dimensions")
new_line()

while type(steps) != int:
    try:
        steps = int(input("How many steps should be done? "))
        while steps <= 0:
            invalid_enter_positive()
            steps = int(input("How many steps should be done? "))
    except:
        steps = ValueError
        invalid_enter_number()
        continue

while type(maximal) != int:
    try:
        maximal = int(input("How big is the biggest possible step? "))
        while maximal <= 0:
            invalid_enter_positive()
            maximal = int(input("How big is the biggest possible step? "))
    except:
        maximal = ValueError
        invalid_enter_number()
        continue

if maximal != 1:
    while type(minimal) != int:
        try:
            minimal = int(input("How big is the smallest possible step? "))
            while minimal <= 0 or minimal >= maximal:
                if minimal <= 0:
                    invalid_enter_positive()
                    minimal = int(input("How big is the smallest possible step? "))
                else:
                    print("Number must be smaller than the biggest possible step!")
                    new_line()
                    minimal = int(input("How big is the smallest possible step? "))
        except:
            minimal = ValueError
            invalid_enter_number()
            continue
else:
    minimal = 1

new_line()
print("Number of steps:", steps)

if maximal != 1:
    print("Step size range:", minimal, "-", maximal)
else:
    print("Step size: 1")

new_line()
print("Steps:")

while steps > 0:
    StepSize = random.randint(minimal, maximal)
    PosNeg = random.randint(0, 1)
    chance = random.randint(0, 1)
    if chance == 0 and PosNeg == 0:
        Xstep += StepSize
    elif chance == 0 and PosNeg == 1:
        Xstep -= StepSize
    elif chance == 1 and PosNeg == 0:
        Ystep += StepSize
    else:
        Ystep -= StepSize
    print("X:", Xstep, " Y:", Ystep)
    steps -= 1


texts:
I'm working now on project, which is need some read more functionality and I tried to write this jquery plugin and share it in my github account.

Here is the full listing of code:

;(function ( $, window, document, undefined ) {

function get_link(readmore_wrap_class, readmore_class, readmore_text ) {
    return $('<a/>')
                .addClass(readmore_wrap_class)
                .prop('href', '#')
                .html(
                    $('<span/>')
                        .addClass(readmore_class)
                        .text(readmore_text)
                    );
}

function get_first_p(text, sentences_number) {
    var paragraph = text.find('p:first-child').clone();

    return paragraph
            .text(
                paragraph
                    .text().split('.', sentences_number)
                    .join('. ') + '. '
            );

}

$.fn.readmore = function (options) {
    var settings = $.extend({
        sentences_number: 3,
        readmore_text: 'Read more.',
        readmore_toggle_text: 'Read less.',
        readmore_wrap_class: 'readmore_link_wrap',
        readmore_class: 'readmore_link',
        bidirectional: false
    }, options);

    return this.each(function(index) {

        var text = $(this),

            // replace default settings with per text data attributes
            sentences_number     = text.data('sentences_number')     || settings.sentences_number,
            readmore_text        = text.data('readmore_text')        || settings.readmore_text,
            readmore_toggle_text = text.data('readmore_toggle_text') || settings.readmore_toggle_text,
            readmore_wrap_class  = text.data('readmore_wrap_class')  || settings.readmore_wrap_class,
            readmore_class       = text.data('readmore_class')       || settings.readmore_class,
            bidirectional        = text.data('bidirectional')        || settings.bidirectional;

            link = get_link(readmore_wrap_class, readmore_class, readmore_text),
            first_p = get_first_p(text, sentences_number);

        /*
        Copy first paragraph
        Save only first `sentences_number` sentences
        Add link `read more`
        Hide Original paragraphs
        On click on `read more` link delete rirst extra paragraph
        Show original paragraphs
        if bidirectional
            add 'readless' link to whole text
            On click to it delete it and run readmore again (go to 1 step)
         */
        text.find('p').hide();

        link
            .appendTo(first_p)
            .on('click', function(event) {
                first_p.remove();
                text.find('p').show();

                if (bidirectional) {
                    get_link(readmore_wrap_class, readmore_class, readmore_toggle_text)
                        .appendTo(text)
                        .on('click', function(event) {
                            $(this).remove();
                            text.readmore();

                            event.preventDefault();
                        });
                }

                event.preventDefault();
            });

        text.prepend(first_p);
    });
};

($('.readmore').length !== 0) && $('.readmore').readmore();

// end of jquery plugin wrap
})( jQuery, window, document );

Codereview goals:

What I have missed?
What can I improve?


texts: Creating a percentage complete method for a form

texts:
I am a relatively new Rails developer and doctor doing research. In my Rails based research projects I often have questionnaires for which I provide a "% complete" parameter.

Here is an example.  You can see that each of the score attributes is given a value and then I can create a %. It looks awful and very un-Ruby-like. I would be keen once and for all to get an experts view and give me some steerage on how this could be cleaned up.

This method is in the Patient class:

 def percent_complete(user, patient)
   score = Score.where(user_id: user.id, patient_id: self.id).first
  if score.nil?
    return "0"
  end
  @status = 0
   score_array = [score.dx1, score.dxcon1, score.db1, score.dbcon1, score.biopsy, score.mgt]
   score_array.each do | element|
    if element == score.dx1
      @status = @status + 20
    elsif element == score.db1
      @status = @status + 20
    elsif element == score.dxcon1
      @status = @status + 20
    elsif element == score.dbcon1
      @status = @status + 20
    elsif element == score.biopsy
      @status = @status + 10
    elsif element == score.mgt
      @status = @status + 10
    end
   end
  @status
 end

Each Score belongs to a Patient (the Patient has many scores). Each Score belongs to a User (a User has many scores).

  score.dx1, score.dxcon1, score.db1, score.dbcon1, score.biopsy, score.mgt

These are the Score class attributes:

dx1 = diagnosis1 (string)
dxcon1 = diagnostic confidence1 (integer)
db1 = disease behaviour1 (string)
dbcon1 = confidence on disease behaviour (integer)
biopsy = should you biopsy? (boolean)
mgt = management (string)

I am now trying something like this:

 def percent_complete(user, patient)
    score = Score.where(user_id: user.id, patient_id: self.id).first
    if score.nil?
      return "0"
    end
    score_completeness = [score.dx1, score.dxcon1, score.db1, score.dbcon1, score.biopsy, score.mgt]
    @status = 0
    score_completeness.each do | field |
       @status += (100/6.0) unless field.blank?
    end
   @status
 end


texts: Speeding up Project Euler 43 - sub-string divisibility

texts:
The number, 1406357289, is a 0 to 9 pandigital number because it is
  made up of each of the digits 0 to 9 in some order, but it also has a
  rather interesting sub-string divisibility property.

  Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way,
  we note the following:

  d2d3d4=406 is divisible by 2
  d3d4d5=063 is divisible by 3
  d4d5d6=635 is divisible by 5
  d5d6d7=357 is divisible by 7
  d6d7d8=572 is divisible by 11
  d7d8d9=728 is divisible by 13
  d8d9d10=289 is divisible by 17

  Find the sum of all 0 to 9 pandigital numbers with this property.

Project Euler 43

from itertools import permutations
from primes import primes_upto
from collections import Counter
from timeit import default_timer as timer

start = timer()
def follows_property(n):
    divisors = primes_upto(17)
    for k in range(7):
        if int(n[k:(k+3)]) % divisors[k] != 0:
            return False
    return True

ans = 0
digits = Counter(range(10))

start = timer()

for combo in permutations(range(10), 9):
    num = ''.join([str(x) for x in list(combo)])
    if follows_property(num):
        missing = int(list((digits - Counter(sorted([int(k) for k in str(num)]))).elements())[0])
        num = int(num)
        ans += int("%d%d" % (missing, num))

elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Is this a safe/correct way to make a python LogHandler asynchronous?

texts:
I'm using some slow-ish emit() methods in Python (2.7) logging (email, http POST, etc.) and having them done synchronously in the calling thread is delaying web requests.  I put together this function to take an existing handler and make it asynchronous, but I'm new to python and want to make sure my assumptions about object scope are correct.  Here's the code:

def patchAsyncEmit(handler):
    base_emit = handler.emit
    queue = Queue.Queue()
    def loop():
        while True:
            record = queue.get(True) # blocks
            try :
                base_emit(record)
            except: # not much you can do when your logger is broken
                print sys.exc_info()
    thread = threading.Thread(target=loop)
    thread.daemon = True
    thread.start()
    def asyncEmit(record):
        queue.put(record)
    handler.emit = asyncEmit
    return handler

That let's me create an asynchronous LogHandler using code like:

handler = patchAsyncEmit(logging.handlers.HttpHandler(...))

I've confirmed the messages are sent, and not in the calling thread, but I want to make sure I'm getting only one queue and only one thread per Handler, and that I'm not at risk of those somehow going out of scope.

Am I off base or did I get that okay?


texts:
I have written the following function to be a general "error logging" solution for my Windows API projects. Basically, given a Windows system error code (a la GetLastError()), it will log the error message into a file:

#include <Windows.h>
#include <strsafe.h>

// MAX_PATH for file name, 12 for max signed int in base 10 (-2147483648), 20 for datetime string, 5 for brackets/colon/spaces
#define MAX_DFL_LENGTH (MAX_PATH + 37)

// So that it can be used as a callback if desired
typedef VOID(CALLBACK *ERRORPROC)(DWORD, WCHAR *, INT, HANDLE, BOOL);

/**
 * Logs an error message that occurred elsewhere in the program.
 * PARAMETERS:
 *  dwError - The system error code to process.
 *  wszFileName - The name of the file in which the error occurred (pass __FILEW__)
 *  nLine - The line at which the error was detected (pass __LINE__)
 *  hOutFile - A handle to an already open file for writing the error message to.
 *  fRecoverable - If true, this error is recoverable; return to the calling code. If false, exit after logging the error.
 */
VOID CALLBACK ErrorProc(
    DWORD dwError,
    WCHAR *wszFileName,
    INT nLine,
    HANDLE hOutFile,
    BOOL fRecoverable
)
{
    LPWSTR lpMsgBuf;
    DWORD dwWritten;
    HRESULT hr;
    UINT uLen;
    SYSTEMTIME st;
    WCHAR wszDateFileLine[MAX_DFL_LENGTH];
    CONST WCHAR *wRecovMsg[2] = { L" Not recoverable, exiting program.\r\n", L" Recoverable; continuing execution...\r\n" };

    (VOID)FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dwError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPVOID)&lpMsgBuf,
        0,
        NULL
    );

    GetLocalTime(&st);
    StringCchPrintfW(
        wszDateFileLine,
        MAX_DFL_LENGTH,
        L"[%.4hu-%.2hu-%.2huT%.2hu:%.2hu:%.2hu %s:%d] ",
        st.wYear,
        st.wMonth,
        st.wDay,
        st.wHour,
        st.wMinute,
        st.wSecond,
        wszFileName,
        nLine
    );

    SetFilePointer(hOutFile, 0, NULL, FILE_END);
    hr = StringCbLengthW(wszDateFileLine, (MAX_DFL_LENGTH) * sizeof(WCHAR), &uLen);
    if (SUCCEEDED(hr))
    {
        WriteFile(hOutFile, wszDateFileLine, uLen, &dwWritten, NULL);
    }

    hr = StringCbLengthW(lpMsgBuf, STRSAFE_MAX_CCH * sizeof(WCHAR), &uLen);
    if (SUCCEEDED(hr))
    {
        // Length - 2 WCHARs to not write out the \r\n at the end of the error message.
        WriteFile(hOutFile, lpMsgBuf, uLen - (2 * sizeof(WCHAR)), &dwWritten, NULL);
    }

    WriteFile(hOutFile, wRecovMsg[!!fRecoverable], (36 + (!!fRecoverable * 3)) * sizeof(WCHAR), &dwWritten, NULL);
    LocalFree((HLOCAL)lpMsgBuf);

    if (FALSE == fRecoverable)
    {
        ExitProcess(dwError);
    }
}

While this historically worked well enough for my personal projects, I am wondering if there are any modifications I should make to the presentation or operation of this function before suggesting its addition to a larger Windows project with an entire team of developers.


texts: Using T-SQL SEQUENCE with Entity Framework 6

texts:
After reading many posts about how to handle sequences in EF 6 (see below) I found a way that was working for me. I'm using Code First and want to include the sequence from scratch, so without using migrations (tell me if I'm getting this wrong).

Task was to get an unique and gapless incrementing extra ID for my entity Car, which is not being used as primary key.

Here is what I'm doing now:

Entity:

public class Car
{
    public int Id { get; set; }
    public int CarNr { get; set; }
    public string Name { get; set; }
}

Context:

public class Context : DbContext
{
    public Context() : base()
    {
        SetDefaultConfiguration();
    }

    public Context(string connectionString) : base(connectionString)
    {
        SetDefaultConfiguration();
    }

    public Context(DbConnection existingConnection) : base(existingConnection, true)
    {
        SetDefaultConfiguration();
    }

    public override int SaveChanges()
    {
        SetCarNr();
        return base.SaveChanges();
    }

    public override Task<int> SaveChangesAsync()
    {
        SetCarNr();
        return base.SaveChangesAsync();
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
    {
        SetCarNr();
        return base.SaveChangesAsync(cancellationToken);
    }

    private void SetDefaultConfiguration()
    {
        Database.SetInitializer(new CreateSequenceInitializer());
    }

    public class CreateSequenceInitializer : DropCreateDatabaseIfModelChanges<Context>
    {
        protected override void Seed(Context context)
        {
            context.Database.ExecuteSqlCommand("CREATE SEQUENCE CarNrSequence AS INT START WITH 200000 NO CACHE;");
            base.Seed(context);
        }
    }

    private void SetCarNr()
    {
        var carsToSave = ChangeTracker.Entries().Select(e => e.Entity).OfType<Car>();
        foreach (var c in carsToSave)
        {
            c.CarNr = GetNextSequenceValue();
        }
    }

    public int GetNextSequenceValue()
    {
        var rawQuery = Database.SqlQuery<int>("SELECT NEXT VALUE FOR CarNrSequence;");
        var task = rawQuery.SingleAsync();
        int nextVal = task.Result;
        return nextVal;
    }

    public DbSet<Car> Cars { get; set; }
}

So I'm using a DatabaseInitializer to create the sequence for me and intercept the SaveChanges to insert the extra ID queried from the DB.

Question:
Is there a better way? Is this "save"? What problems do you see?

Thanks!

PS: Here are some links that helped me a lot

https://stackoverflow.com/questions/27077461/how-to-get-next-value-of-sql-server-sequence-in-entity-framework
https://stackoverflow.com/questions/24162895/entity-framework-6-and-sql-server-sequences
https://stackoverflow.com/a/34894274/226278
https://stackoverflow.com/questions/20136504/how-can-set-a-default-value-constraint-with-entity-framework-6-code-first


texts: Grab set of data from database that matches userid and return it to the view

texts:
I want to get the row of data that matches the user ID I have. Then I want to return that view to my view to be displayed in my textboxes for editing.

Here's the action that gets called when a get request to sent to the controller:

public ActionResult EditUserAccount()
{
            UserAccountViewModel editUserAccountViewModel = new UserAccountViewModel();
            db_user user = new db_user();
            editUserAccountViewModel.UserName = UserSession.GetValue(StateNameEnum.UserName, StateNameEnum.UserName.ToString()) as string;
            var Title = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId).Select(x => x.Title).ToString();
            var FirstName = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId).Select(x => x.FirstName).ToString();
            var LastName = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId).Select(x => x.LastName).ToString();
            var PhoneNumber = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId).Select(x => x.PhoneNumber).ToString();
            var AltPhoneNumber = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId).Select(x => x.AltPhoneNumber).ToString();
            var EmailAddress = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId).Select(x => x.EmailAddress).ToString();

            editUserAccountViewModel.Title = Title;
            editUserAccountViewModel.FirstName = FirstName;
            editUserAccountViewModel.LastName = LastName;
            editUserAccountViewModel.PhoneNumber = PhoneNumber;
            editUserAccountViewModel.AltPhoneNumber = AltPhoneNumber;
            editUserAccountViewModel.EmailAddress = EmailAddress;
            return (PartialView("~/Views/Account/UserAccount.cshtml", editUserAccountViewModel));

}

The problem is the repetitious calls to get specific fields from the database so that I can set my viewmodel properties to them. Is there a better way to do this?


texts: Python requests downloading big files in slower speed than wget

texts:
This is a simple toy downloader using python's requests library.
I’ve monitored the download process is slower on an ethernet connected box. The realtime speed is measured both on stdout, using get_net_speed() function, and conky.

I’m using a 4Mbps connection.

When downloading a file using wget, the downloading gets full bandwidth as expected. But when using my own downloader script, it gets highest 1Mbps speed.
Here's the code. Review and optimisation are warmly welcome.

#!/usr/bin/env python3

### get details of a requested file and download if a media one

import requests
import sys
from urllib.parse import urlparse
import socket
import re
import time
import psutil

#===================== Main Routine ===================================

def down_in_chunks(resp,file_name,conSize):
    downloaded = 0
    file_descriptor = open(file_name,'wb')
    chunk_size = 1024 * 1024 # 1MB
    for chunk in resp.iter_content(chunk_size=chunk_size):
        downloaded += int(len(chunk)) # get update how much downloaded
        per_cent = 100 * downloaded / int(conSize)
        speed = get_net_speed()
        print("downloading %.2f pc speed %s" %(per_cent,speed),end='\r')
        file_descriptor.write(chunk)
    file_descriptor.close()

#================== Auxilary Routines ==================================

def get_net_speed():
    rcv = psutil.net_io_counters()
    sp0 = rcv[1]
    time.sleep(1)
    rcv = psutil.net_io_counters()
    sp1 = rcv[1]
    speed = sp1 - sp0
    return convert_size(speed)

def convert_size(file_size):
    for unit in ["B","KiB","MiB","GiB","Tib","PiB","EiB","Zib"]:
        if abs(file_size) <= 1024.0 or abs(file_size) == 0:
            return "%3.1f%s" %(file_size,unit)
        else:
            file_size /= 1024.0
        #return "%3.1f%s" %(file_size,unit)

def get_file_details(resp,url):

    file_type = resp.headers["Content-Type"]

    if re.match(r'^html|text',file_type): # perhaps we're not interested in the page only
        print("header info... ", resp.headers)

    else:
        file_name = url.split("/")[-1]
        print("file name: %s" % file_name)
        conDate = resp.headers["Date"]
        conType = resp.headers["Content-Type"]
        conTn = resp.headers["Connection"]
        conSize = resp.headers["Content-Length"]
        conUnit = resp.headers["Accept-Ranges"]
        humane = convert_size(int(conSize))
        print("time: %s type: %s size: %s (%s) unit: %s connection: %s " %(conDate,conType,conSize,humane,conUnit,conTn))
        return file_name , conSize

# ========== Action ===========

try:

    url = sys.argv[1] # get the url
    urlObj = urlparse(url)
    addr = urlObj.netloc
    ip = socket.gethostbyname(addr.split(":")[0]) # get the ip address
    print("connecting to %s | %s |... " %(addr,ip))
    user_agent = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; hu-HU; rv:1.7.8) Gecko/20050511 Firefox/1.0.4'}
    resp = requests.get(sys.argv[1],stream=True,timeout=15,headers=user_agent) # I'm not a bot Maa'm
    print("status: %s " %(resp.status_code))
    file_name,file_size = get_file_details(resp,url)

    print("downloading.......... %s" %file_name)
    start = time.time()
    down_in_chunks(resp,file_name,file_size)
    end = time.time()
    total_time = end - start
    if total_time >= 60:
        print("download time: %.2f min" %(total_time/60))

    else:
        print("download time: %.2f secs")
    resp.close()

except requests.exceptions.RequestException as E:
    print("Error: ", E)
    sys.exit(0)


texts: Finding common strings among 2 arrays of strings of length 1, sorted alphabetically in O(n) time complexity

texts:
The problem:

  Start with two arrays of strings, a and b, each in alphabetical order,
  possibly with duplicates. Return the count of the number of strings
  which appear in both arrays.

  commonTwo({"a", "c", "x"}, {"b", "c", "d", "x"}) → 2

  commonTwo({"a", "c", "x"}, {"a", "b", "c", "x", "z"}) → 3

  commonTwo({"a", "b", "c"}, {"a", "b", "c"}) → 3

I tried to solve the problem with \$O(n)\$ time complexity:

    public  int commonTwo(String[] a, String[] b) {
    int result=0;
    String prev="";
    for(int i=0,j=0;(i<a.length)&&(j<b.length);)
    {
        if(a[i].charAt(0)<b[j].charAt(0))
        {
            i++;
            continue;
        }
        if(a[i].charAt(0)==b[j].charAt(0))
        {
            if(!(a[i].equals(prev)))
                result++;
            prev=a[i];
            i++; j++;
            continue;
        }
        j++;

    }

    return result;

}

It seems to be working but the code looks somewhat ugly. Please feel free to review or if you have any other elegant solution would appreciate you include it in the review.


texts: VBA Error Handling Sub, Working for all subs

texts:
The idea is to make an error handling procedure, which prints messages in DEV mode and shows MsgBox in PROD mode. Looking for any wise idea to improve it:
Public Const SET_IN_PRODUCTION = False

Sub TestMe()

    On Error GoTo TestMe_Error
    Debug.Print 0 / 0
    Exit Sub

TestMe_Error:
    StandardError Err, "TestMe"

End Sub

Public Sub StandardError(myError As Object, Optional moduleName As String = "")

    If SET_IN_PRODUCTION Then
        MsgBox "Error in " & moduleName & vbCrLf & myError.Description, vbCritical, title:=myError.Number
    Else
        Debug.Print "Error in "; moduleName & vbCrLf & myError.Description
    End If

End Sub

The lines StandardErr Err are to be used for almost any procedure and function in the code, for "advanced" error handling.


texts:
This is a Dockerfile which aims to create a complete environment for the bismon project. I have written it as an exercise and to make it easy for other users to begin with bismon.

FROM ubuntu:latest
MAINTAINER Niklas Rosencrantz (niklasrosencrantz@xyz.com)
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get install --yes software-properties-common
RUN apt-add-repository --yes --update ppa:ubuntu-toolchain-r/test
RUN apt-get update
RUN apt-get install --yes git
RUN apt-get install --yes gcc-snapshot
RUN apt-get install --yes build-essential make gcc-8 cmake
RUN apt-get install --yes ninja-build g++-8 gcc-8-plugin-dev libgccjit-8-dev libgtk-3-dev
RUN apt-get install --yes markdown indent astyle tardy texlive texlive-full hevea
RUN adduser --disabled-password --gecos '' newuser
USER newuser
WORKDIR /home/newuser
RUN git clone https://github.com/ianlancetaylor/libbacktrace.git
RUN cd libbacktrace; ./configure ; make
USER root
WORKDIR /home/newuser/libbacktrace
RUN make install
USER newuser
RUN cd; git clone https://github.com/davidmoreno/onion.git; cd onion; mkdir build; cd build; cmake ..; make
USER root
WORKDIR /home/newuser/onion/build
RUN make install; cp /usr/local/lib/libonion* /usr/lib; cp /usr/local/lib/libbacktrace* /usr/lib
USER newuser
RUN cd; git clone https://github.com/bstarynk/bismon.git; cd bismon; make; touch ~/passwords_BM; chmod u+rw,go-rwx ~/passwords_BM
WORKDIR /home/newuser/bismon


texts: Dynamically choose bean without Qualifier annotation

texts:
I have a service that gets an URL from the user input, extracts the body content of this URL, apply CSS, and finally returns the result as a stream.
The tricky part is that I have different implementations depending on the URL, if the URL is not recognized, then a "default" implementation is used.
To do so, I used a BeanFactory to choose the correct implementation on Runtime.
@Service
@Qualifier("defaultHtmlToHtmlService")
public class DefaultHtmlToHtmlImpl implements HtmlToHtmlService {

    @Override
    public InputStream htmlToHtml(String url) throws IOException {
        Document document = Jsoup.connect(url).get();
        Element content = document.body();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(content.outerHtml().getBytes());
        outputStream.close();

        return new ByteArrayInputStream(outputStream.toByteArray());
    }
}

@Component
public class BeanFactory {

private final HtmlToHtmlService defaultHtmlToHtmlService;

private final HtmlToHtmlService impl1;

private final HtmlToHtmlService impl2;

@Autowired
public BeanFactory(@Qualifier("defaultHtmlToHtmlImpl") HtmlToHtmlService defaultHtmlToHtmlService,
                   @Qualifier("impl1") HtmlToHtmlService impl1,
                   @Qualifier("impl2") HtmlToHtmlService impl2) {
    this.defaultHtmlToHtmlService = defaultHtmlToHtmlService;
    this.impl1 = impl1;
    this.impl2 = impl2;
}

public HtmlToHtmlService getHtmlToHtmlImpl(String url) {
    if (url.contains("some pattern")) {
        return impl1;
    } else if (url.contains("some other pattern")) {
        return impl2;
    } else {
        return defaultHtmlToHtmlService;
    }
}

This is working just fine. However, my issue is that I don't want my BeanFactory to share any information with the rest, but I do not know how to decouple it. Basically, I want to remove the @Qualifier annotation, and not to have to manually enter the new URLs patterns in the Bean Factory in the future when I will get more implementations.
I saw that maybe @PostConstruct annotation or to use static blocks could be the solution, but I am really not sure how to apply it in this case.


texts:
Is it possible to combine these queries into one query? I am trying to see and average all scores but also count and average just the last three based on the same grouping.

This is the main query:

$query4 ="SELECT
studentsisid,coursename,learningoutcomeid,learningoutcomename,count(RecordID) as assessmentcount,
count(if(outcomescore >= 3,outcomescore, NULL)) as over3,
avg(outcomescore) as scoreavg
from studentscores
WHERE studentsisid LIKE '$studentid' AND coursename='$coursename'
Group by studentsisid,coursename, learningoutcomeid
ORDER BY studentname, learningoutcomename";

This is an example of the current sample data based on the query above is below (loid is learningoutcomeid and loname is learningoutcomename)

studentsisid;coursename;loid;loname;assessmentcount;over3;scoreavg
1234;"Course1";"7982";"LearningOutcome1";"1";"1";"3.2"
1234;"Course1";"7995";"LearningOutcome2";"4";"4";"2.5"
1234;"Course1";"7991";"LearningOutcome3";"6";"6";"3.8"
1234;"Course1";"7889";"LearningOutcome4";"1";"1";"3.4"
1234;"Course1";"7839";"LearningOutcome5";"2";"2";"2,6"

The goal is to get something like this where recent over 3 only looks at the last three records for each learningoutcomeid for each student for each course.

studentsisid;coursename;loid;loname;assessmentcount;over3;scoreavg;recentover3;recenscoretavg
1234";"Course1";"7982";"LearningOutcome1";"1";"1";"3.2";"1";"3.2"
1234;"Course1";"7995";"LearningOutcome2";"4";"4";"2.5";"2";"2.5"
1234;"Course1";"7991";"LearningOutcome3";"6";"6";"3.8";"3";"3.2"
1234;"Course1";"7889";"LearningOutcome4";"1";"1";"3.4";"1";"3.2"
1234;"Course1";"7839";"LearningOutcome5";"2";"2";"2,6";"1";"3.2"

This current solution is close but it is only getting the first learningoutcomeid and not the others that match for a particular student for a particular course.

studentsisid;coursename;loid;loname;assessmentcount;over3;scoreavg;recentover3;recentscoreavg
1234";"Course1";"7982";"LearningOutcome1";"1";"1";"3.2";"1";"3.2"


texts: Optimizing Python code that deletes elements from a list

texts:
I've written this program (input : list , output: same list deleting elements without   a specific number of own divisors of each elements).

The problem is that when I insert big numbers, shell spends a lot of time to give me the output (the code works).

def num_divisori(l5,k):
    l2=[]
    for x in l5:
        i=2
        while i<x:
            if x%i==0:
                l2+=[x]
                break
            i=i+1
    return num_div2(l2,k)

def num_div2(l2,k):
    l3=[]
    l4=[]
    for x in l2:
        i=2
        while i<x:
            if x%i==0:
                l3+=[i]
            i=i+1
        if len(l3)==k:
            l4+=[x]
        l3=[]
    return l4

"k" is the specific number of own divisors, l5 the main list

How can I optimize this to save more time?


texts:
I am trying to practice objects and functions (specifically closures & higher order functions) in javascript. There is no specific reason why I chose this program but it struck my mind to work out this one.

The below code is available at my Github and it converts the number to words.

Kindly provide your feedback and suggest which parts of the code can be improved or modified.

// Author       : Harish Narayanan
// Date         : 15 May 2015
// Description  : Code to convert number to words

var ones_teens = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
  'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var scales = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion',
  'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion'
];

function toWords(n) {
  var line;
  if (isNaN(n) || n > 999) {
    return null;
  }

  if (n == 0) {
    line = "";
  } else if (n < 20) {
    line = ones_teens[n];
  } else if (n < 100) {
    line = tens[(n / 10) | 0];
    if (n % 10) {
      line += "-" + ones_teens[n % 10];
    }
  } else {
    line = ones_teens[(n / 100) | 0] + " hundred " + toWords(n % 100);
  }

  return line.trim();
}

function chunkify(n) {
  var numbers = [];
  while (n > 0) {
    numbers[numbers.length] = n % 1000;
    n = Math.floor(n / 1000);
  }
  return numbers;
}

function scalify(item, index) {
  if (item) {
    return item + " " + scales[index];
  }
  return "";
}

function notEmpty(item) {
  return !!item; // using double ! returns boolean value. !!item is not same as item.
}

console.log(chunkify(999999999999999).map(toWords).map(scalify).filter(notEmpty).reverse().join(", "));


texts: Transfer the cell formatting in a legend to a dataset in another sheet

texts:
On Sheet 1 is a legend that contains unique values in Column A every ten rows. To the right of each value in the next five columns over are a series of color filled cells that extend down ten rows to the start of the next unique value. The color fill of each 5x10 area is what I want transferred to the dataset sheet.

The dataset is on Sheet2. The entirety of the paste area is filled with a dummy value so the macro works correctly. In the defined “paste to” columns in the macro I have, every so often, included a value already present in the legend where I want my color fill to be transferred. The “paste to” columns are within the area of paste, so it is possible for highlighted areas to overlap, which is necessary.

Using a macro, I want to copy and paste the 5x10 areas from the legend to the corresponding areas in the dataset sheet. So if a value is present in the dataset sheet and matches one of the unique values in the legend, I want the unique value 5x10 area to be pasted there in order from left to right, top to bottom, overlapping.

I’ve tried using the Find Method to do a lookup against the values in the dataset, and with that an offset function to tell the macro where to paste by cell. While this does work it is process intensive even with only a few columns and a limited legend.

How can I make it more efficient? Can I accomplish what I've explained via a better route? An array? I've toyed with using hex values and converting them into cell fills, if that would in anyway be more advantageous. A user by the name of gizlmeier has already cut my code down in size, however I've noticed the procedure time to be around the same.

Any ideas? Here’s what I have so far:

Sub LegTra3()

Dim i As Integer, j As Integer
Dim RngMap As Range, RngLeg As Range, RngCom As Range, RngTar As Range

Application.ScreenUpdating = False
Application.CutCopyMode = False

Set RngMap = Sheet2.Range("$A$1:$A$100,$D$1:$D$100,$G$1:$G$100") 'Columns spaced closer than width of legend fill to provide for overlap
Set RngLeg = Sheet1.Range("$A$1:$F$41")

For Each RngCom In RngMap
    Set RngTar = RngLeg.Find(What:=RngCom, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    If Not RngTar Is Nothing Then
        For i = 0 To 9 Step 1
            For j = 0 To 4 Step 1
                RngTar.Offset(i, j + 1).Copy
                RngCom.Offset(i, j).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=True, Transpose:=False
            Next j
        Next i
    End If
Next
End Sub


texts:
The aim is to have any strings with integers within to be reorder by these integers.

Let's say you have the following string:

re5 Forty1 cash2 Man3 Booker4

The aim is to have the string order by the integer contained within the string:

Forty1 cash2 Man3 Booker4 re5

I created this function:

def reorder(wordchain):
    from re import findall
    splitchain = wordchain.split()
    entier = findall('\d+',wordchain)
    chaineok = [(a,b) for a,b in zip(entier,splitchain)]
    chaineok.sort(reverse = False)
    chaineok1 = [b[1] for b in chaineok]
    chaineok2 = " ".join(chaineok1)
    return chaineok2

The function is fine, however, there are a few things I would like to improve:

The number of variable; I would like to have less. What should I do?
The number of lines; I feel there can be fewer lines and definitely fewer operations.


texts:
I'm attempting to implement a high resolution class used to time the execution time of functions in Windows. After using this documentation, I have come up with the following:
#include <iostream>
#include <windows.h>

class Timer {

private:

    LARGE_INTEGER start_count;
    LARGE_INTEGER stop_count;

    LARGE_INTEGER tick_freq;

public:
    // Query the tick frequency upon instantiation of the class
    Timer() {
        QueryPerformanceFrequency(&tick_freq);
    }
    // Query performance counter at the start of a block of code
    void start() {
        QueryPerformanceCounter(&start_count);
    }
    // Query the performance counter at the end of a block of code, then calculate time elapsed in seconds
    double stop() {
        QueryPerformanceCounter(&stop_count);
        return (double)(stop_count.QuadPart - start_count.QuadPart) / tick_freq.QuadPart;
    }
};

int main() {
    Timer t;
    t.start();
    // code to be timed
    std::cout << t.stop();
}

I understand that there would be an error of plus or minus the period of each tick. However, various functions I have timed seem to give unexpected results. For example, timing a function that finds the greatest common denominator using Euclid's algorithm consistently uses 100 or 200ns, but appending one int to a vector takes 1600ns. This therefore leads me to the question: how accurate is this timing class, and what can I do to improve it?


texts: MinutesPerDay - Does .NET have anything for it?

texts:
Looking at a code review at work for a Win32 C# code I am seeing some lines like this:

int MinutesPerDay = 1440;
int MinutesPerWeek = 10080;
int MinutesPerMonth = 43200;

and so on ...

I am not sure what is wrong with it but still I feel this is not a good code and design? What do you guys think? Could he do it in a better way?


texts: Custom output stream that acts like std::cout

texts:
I wrote a simple output stream object that from the user point of view should act exactly like the classic std::cout. I need it because I want to customize the printing behavior of my program.

Can you review my code? Do you see anything wrong in it?

File Utils.h:

namespace Utils
{
   static std::ostream& Log;
}

File Utils.cpp:

struct MyStream : std::ostream, std::streambuf
{
public:
   MyStream() : std::ostream(this) { }
   std::streambuf::int_type overflow(std::streambuf::int_type c)
   {
      std::cout << c;
      // My custom operations
      return 0;
   }
};
std::ostream& Utils::Log = MyStream();


texts: Solution for puzzle 3d x 1d = 2d x 2d in Python

texts:
I wanted to resolve the puzzle from this link using Python 3. It works and gives me the correct value but I would like to know if it is possible to resolve this problem with a few lines or how I can improve/optimize my code.

import time
start = time.time()
max=0
gx=0
gy=0
gi=0
gj=0

for i in range(999,99,-1):
    for j in range(9,0,-1):
        mul=i*j

        for x in range(99,9,-1):
            for y in range(99,9,-1):
                mul2=x*y

                if mul==mul2:
                    if mul>max:
                        gx=x
                        gy=y
                        gi=i
                        gj=j
                        max=mul

print ("i: " + str(gi))
print ("j: " + str(gj))
print ("x: " + str(gx))
print ("y: " + str(gy))
print ("max: " + str(max))
end = time.time()
print (end - start)

And this is the result:

i: 992
j: 9
x: 96
y: 93
max: 8928
17.678768157958984


texts: A Lisp version of the Schwartzian transform

texts:
Randal Schwartz stole Lisp's decorate-sort-undecorate idiom when he came up with what we'd later call the Schwartzian transform. All of my Lisp knowledge disappeared through nine half lives, but I gave it a shot in SBCL. I'm aiming for an idiomatic example I can use in a presentation about the history of the Schwartzian transform.

This works (and I know I can generalize it further), but I wonder how Lisp-y it is:

(require :sb-posix)
(defun schwartzian-files-mtime ( glob-pattern )
    (map
        'list
        #'cdr
        (stable-sort
            (map
                'list (
                    lambda (x) (
                        cons
                            (sb-posix:stat-mtime (sb-posix:stat x))
                            x
                        )
                    )
                (directory glob-pattern)
            )
            #'<
            :key
            #'car
        )
    )
)

(schwartzian-files-mtime "/etc/*")


texts: Generalized solution for project euler #1 in haskell with recursion

texts:
checkIfMultiple x [] = False
checkIfMultiple x (n:ns) = x `mod` n == 0 || checkIfMultiple x ns

findMultiples limit ns = [x | x <- [0..limit], checkIfMultiple x ns]

sumMultiples limit ns = sum (findMultiples limit ns)

sumMultiples 999 [3, 5]
Things I am curious about:

Passing down limit and ns from sumMultiples to findMultiples might be redundant. I was wondering, if I could somehow use composition here or some other shortcut.

What is the convention regarding writing out the type in Haskell? Is it always recommended?

Any other suggestion is appreciated, thank you.


texts: Multithreaded search for solutions to an inequality

texts:
This question is related to my previous question on the brute-force search
for a solution to an unsolved mathematical inequality:

$$3^{k}-2^{k}\left\lfloor \left({\tfrac {3}{2}}\right)^{k}\right\rfloor >2^{k}-\left\lfloor \left({\tfrac {3}{2}}\right)^{k}\right\rfloor -2$$

The following code, tested on Ubuntu 16.04, compiles with no warnings or errors using the flags -Wall -std=c++14 -pthread -Ofast using the g++ compiler. I'm using -Ofast because I am trying to squeeze every ounce of performance out of this code (more info here).

I am not 100% sure if this is the proper, fastest, implementation of multithreading. Since I'm new to multithreading, I used this SO question, this page, and this page for learning how to multithread.

For questions about other parts of the code, I explain it way more on my previous question (like why I have a completely separate if-else check).

Let me know how I can improve my use of multithreading in this program.

#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <cmath> (already included from cpp_dec_float.hpp)
#include <iostream>
#include <future>

typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<2000>> arbFloat;

enum returnID {success = 0, precisionExceeded = 1};

arbFloat calcThreeK(const arbFloat & k){
    return pow(3, k);
}

arbFloat calcTwoK(const arbFloat & k){
    return pow(2, k);
}

int main(){
    arbFloat k, threeK, twoK;
    bool isSolution = false;

    for(k = 6; !isSolution; ++k){
        std::future<arbFloat> futureThreeK = std::async(std::launch::async, calcThreeK, k);
        std::future<arbFloat> futureTwoK = std::async(std::launch::async, calcTwoK, k);

        threeK = futureThreeK.get();
        twoK = futureTwoK.get();

        isSolution = threeK - twoK * floor(threeK / twoK) > twoK - floor(threeK / twoK) - 2;
    }

    if(pow(3, k) - (pow(2, k) * floor(pow(1.5, k))) <= pow(2, k) - floor(pow(1.5, k)) - 2){
        std::cout << "Solution at k = " << k << ".\n";
        return returnID::success;
    } else {
        std::cout << "Error: Precision exceeded at k = " << k << ".\n";
        return returnID::precisionExceeded;
    }
}


texts:
Common Lisp does not have a generic copy function for reasons outlined in Kent Pitman's article The Best of Intentions. However, it may still be convenient for rapid prototyping purposes to provide such a function that would recursively copy any given lisp object down to its immutable core objects. In the initial stages of development, this could obviate the need to write or import specialized copiers for complex sequences, arrays, hash tables, and structures.

The following generic methods attempt to specify a function called ucopy (for universal copy) that implements universal recursive copying. An example of use might be to copy an array composed of structures containing a hash table: (setq array1 (ucopy array0)). As this is my first attempt at writing a library(?), I would appreciate corrections, improvements, or any other instructive comments. Thanks.

;;;; Filename: universal-copy.lisp

;;; Deep (recursive) copy of a Common Lisp object.
;;; For example, (ucopy array0) where array0 is an array of structures.
;;; Assumes MOP is loaded.

(defmethod ucopy ((sym symbol))
  "Simply return the symbol."
  sym)

(defmethod ucopy ((num number))
  "Simply return the number."
  num)

(defmethod ucopy ((char character))
  "Simply return the character."
  char)

(defmethod ucopy ((fn function))
  "Simply return the function."
  fn)

(defmethod ucopy ((path pathname))
  "Simply return the path."
  path)

(defmethod ucopy ((seq sequence))
  "Copy a sequence recursively."
  (map (type-of seq) #'ucopy seq))

(defmethod ucopy ((ht hash-table))
  "Copy a hash table recursively."
  (loop with new-ht = (make-hash-table
                        :test (hash-table-test ht)
                        :size (hash-table-size ht)
                        :rehash-size (hash-table-rehash-size ht)
                        :rehash-threshold (hash-table-rehash-threshold ht))
      for key being the hash-key in ht using (hash-value value)
      do (setf (gethash (ucopy key) new-ht) (ucopy value))
      finally (return new-ht)))

(defmethod ucopy ((arr array))
  "Copy an array recursively."
  (let ((new-arr (make-array (array-dimensions arr)
                             :element-type (array-element-type arr)
                             :adjustable (adjustable-array-p arr))))
    (dotimes (i (array-total-size arr))
      (setf (row-major-aref new-arr i)
        (ucopy (row-major-aref arr i))))
    new-arr))

(defmethod ucopy ((struct structure-object))
  "Copy a structure recursively."
  (let ((new-struct (copy-structure struct))
        (slots (class-direct-slots (class-of struct))))
    (dolist (slot slots)
      (let ((slot-name (slot-definition-name slot)))
        (setf (slot-value new-struct slot-name)
          (ucopy (slot-value struct slot-name)))))
    new-struct))

(defmethod ucopy ((inst standard-object))
  "Copy an instance of a class recursively."
  (let ((new-inst (allocate-instance (class-of inst)))
        (slots (class-direct-slots (class-of inst))))
    (dolist (slot slots)
      (let ((slot-name (slot-definition-name slot)))
        (when (slot-boundp inst slot-name)
          (setf (slot-value new-inst slot-name)
            (ucopy (slot-value inst slot-name))))))
    new-inst))


texts: Simplifying the code with same list comprehensions

texts:
I have such method where:

primary_images is dict,
additional is dict,
get_uri_text is some decorating method,
marker is telling how to parse two dicts.

How can I simplify this method?

    @staticmethod
    def decorate_sort_images(primary_images, additional_images, get_uri_text, marker=False):
        srt_keys = sorted(primary_images.keys())
        new_result = OrderedDict()
        if not additional_images:
            #only primary
            for _key in srt_keys:
                new_result[_key] = [get_uri_text(iter_el) for iter_el in primary_images[_key]]
            return new_result
        for _key in srt_keys:
            new_result[_key] = [get_uri_text(iter_el) for iter_el in primary_images[_key]]
            if marker:
                if _key in additional_images:
                    new_result[_key] += [get_uri_text(iter_el) for iter_el in additional_images[_key]]
            else:
                new_result[_key] += [get_uri_text(iter_el) for iter_el in additional_images[_key]]
        return new_result


texts: Small fast pseudorandom number generator in C++

texts:
I've been away from C++ for some time and I'd like to get back up to speed with modern practices, so I implemented a small random number generator described here.

Any advice on this piece of code?

    #include <cstdint>
    #include <cstddef>
    #include <limits>
    #include <random>

// implementation of Bob Jenkins' small prng https://burtleburtle.net/bob/rand/smallprng.html
namespace Random {
    namespace detail {
        using _rand32_underlying = uint32_t;
        using _rand64_underlying = uint64_t;

        template<size_t N> struct rand_type { using type = void; };
        template<> struct rand_type<32> { using type = _rand32_underlying; };
        template<> struct rand_type<64> { using type = _rand64_underlying; };

    }

    // public
    template <size_t N>
    using rand_t = typename detail::rand_type<N>::type;
    using rand32_t = rand_t<32>;
    using rand64_t = rand_t<64>;

    template <size_t N>
    inline rand_t<N> rot(rand_t<N> x, rand_t<N> k) noexcept { return ((x << k) | (x >> (N - k))); }

    template<size_t N>
    class SmallPrng
    {
        public:
            using result_type = rand_t<N>;
            inline rand_t<N> min() { return std::numeric_limits<result_type>::min(); }
            inline rand_t<N> max() { return std::numeric_limits<result_type>::max(); }

            rand_t<N> a, b, c, d;

            inline rand32_t prng32()
            {
                rand32_t e = a - rot<N>(b, 27);
                a = b ^ rot<N>(c, 17);
                b = c + d;
                c = d + e;
                d = e + a;
                return d;
            }

            inline rand64_t prng64()
            {
                rand64_t e = a - rot<N>(b, 7);
                a = b ^ rot<N>(c, 13);
                b = c + rot<N>(d, 37);
                c = d + e;
                d = e + a;
                return d;
            }

        public:
            explicit SmallPrng(result_type seed = 0xdeadbeef) noexcept
            {
                static_assert(!(N != 32 && N != 64), "You can only construct a small prng in 32 or 64 bit mode.");
                a = 0xf1ea5eed;
                b = c = d = seed;
                for(size_t i = 0; i < 20; ++i)
                    (*this)();
            }

            explicit SmallPrng(std::random_device &rd) : SmallPrng(rd()) {}

            inline rand_t<N> operator()() noexcept
            {
                if constexpr(N == 32)
                    return prng32();
                return prng64();
            }
    };
}


texts: Handling multiple IO operations that return optional values

texts:
The following Haskell code reads a Pandoc document from the DB and then serves it to the user after making a transformation, after the first run it is stored in memory via IORef State, inside a [(String, Pandoc)] so the document can be quickly looked up again, without hitting the DB or doing the transformation. I don't feel like this code reflects that this is what is happening that well, there is a lot of handling Maybe's that I feel clouds the actual steps that make up this action.

module Api.ReadDocument (Route, action) where

import Control.Monad.Reader
import Data.Aeson.Types
import Data.Int
import Data.IORef
import Data.List
import Database.Persist.Postgresql (ConnectionPool, fromSqlKey, runSqlPool)
import Servant
import Servant.Auth.Server
import Text.Pandoc (Pandoc, def, readHtml, writeJSON)
--
import Config
import Queries
import State
import Types.DB
import Types.Pandoc

type Route = "read" :> Capture "id" Int64 :> Get '[JSON] Pandoc

action :: IORef State -> ConnectionPool -> AuthResult Account -> Int64 -> Handler Pandoc
action state pool (Authenticated _) id = viaCache state pool id
action _ _ _ = throwAll err401

viaCache :: IORef State -> ConnectionPool -> Int64 -> Handler Pandoc
viaCache state pool id = do
  let key = show id
  state' <- liftIO $ readIORef state
  maybe (retrieve state pool id) (return . snd) $ find ((== key) . fst) (cached state')

retrieve :: IORef State -> ConnectionPool -> Int64 -> Handler Pandoc
retrieve state pool id = do
  doc <- runSqlPool (Queries.getDocumentFromId id) pool
  maybe (throwError err404) (loadDocument state id) doc

loadDocument :: IORef State -> Int64 -> Document -> Handler Pandoc
loadDocument state id doc = do
  let key = show id
      pd = transform . documentBody $ doc
  _ <- liftIO $ updateState (CacheFile (key, pd)) state
  return pd

Previously this was one function, which contained nested case statements like so (pseudo code):

action state pool (Authenticated _) id = do
  state' <- fromState state              -- get the state
  case find id state of                  -- find the data
    Just (_, doc) ->
      return doc                         -- return cached document
    Nothing -> do
      doc <- getDocumentFromId id pool   -- get document from db
      case doc of
        Just d -> do
          let doc = performOp $ d        -- perform computation on doc
          _ <- saveToState state doc     -- save the document to in memory cache
          return doc                     -- serve document
        Nothing ->                       -- document not actually in DB
          throwError err404

This is obviously much more explicit but I didn't like the nested case statements, and obviously there is a bit more to the code than what I have typed out here.


texts:
I have an ASP.NET MVC 5 application that needs to log to the database every request for a specific controller action and every link click that happens on the view of that action. Since the user shouldn't be affected of this operation.

I came up with the following pattern:

For the controller:

//get the repository instance
private RequestsRepository _repo = new RequestsRepository();
public ActionResult Index()
{
    //log the request in a new Task
    Task.Factory.StartNew(() =>
    {
        _repo.RegisterRequest(Request.UserHostAddress, Request.UserAgent);
    });

    return View();
}

For the view (client side):

This is a link

Server side method for link click logging:

public void LinkLogger()
{
    Task.Factory.StartNew(() =>
    {
        _repo.RegisterRequest(Request.UserHostAddress, Request.UserAgent);
    });
}

Repository method:

public void RegisterRequest(string ip, string userAgent)
{
    string sql = @"INSERT INTO RequestsLog (Ip, UserAgent) VALUES (@Ip, @UserAgent)";
    using (var conn = ConnectionStringProvider.GetOpenConnection())
    {
        conn.Execute(sql, new { Ip = ip, UserAgent = userAgent);
    }
}

Is this a right way to implement the requests?


texts:
I want to implement the following function:

// Return true if and only if 's' is numeric including
// leading positive/negative sign, decimal point.
bool isnumeric( const char * s );

It is somewhat similar to strtol() but I don't need to return the number.

My approach is to count various things unless I can bail out:

bool isnumeric( char const * str ) {
  if( !str ) { return false; }
  int signs = 0;
  int decimals = 0;
  int digits = 0;
  int digitsAfterDecimal = 0;

  for( char const * p = str; *p; ++p ) {

    if( (*p == '+') || (*p == '-') ) {
      if( (decimals > 0) || (digits > 0) ) { return false; }
      signs += 1;
      if( signs == 2 ) { return false; }
    }
    else if( *p == '.' ) {
      decimals += 1;
      if( decimals == 2 ) { return false; }
    }
    else if( ! isdigit( *p ) ) {
      return false;
    }
    else {
      digits += 1;
      if( decimals > 0 ) {
        digitsAfterDecimal += 1;
      }
    }
  }
  return (decimals > 0) ? ((digits > 0) && (digitsAfterDecimal > 0))
                        : (digits > 0) ;
}

I also have the following tests:

void test_isnumeric() {
  assert( isnumeric( "42" ) );
  assert( isnumeric( "42.0" ) );
  assert( isnumeric( "42.56" ) );
  assert( isnumeric( "+42" ) );
  assert( isnumeric( ".42" ) );
  assert( isnumeric( "+.42" ) );

  assert( ! isnumeric( "42." ) );
  assert( ! isnumeric( "++42" ) );
  assert( ! isnumeric( "+." ) );
  assert( ! isnumeric( "4+" ) );
}

int main( void ) {
  test_isnumeric();
}

To make it easy to clone and modify, the full code is available here.

Please comment on design, structuring, test coverage etc. Mentioning failing tests are most welcome.


texts:
I need a function that hashes a list of different inputs (integral datatypes, strings, bytearrays) in a recursive manner.

def RecHash(v):
    isSingleElementOfList = False

    if type(v) is list and len(v) == 1:
            isSingleElementList = True

    if type(v) is not list or isSingleElementOfList:   # if v is a single element
        v0 = v
        if isSingleElementOfList: v0 = v[0]

        if type(v0) is bytearray or v0.__class__.__name__ == 'bytes':
            return hash(v0)
        if type(v0) is int:
           return hash(ToByteArray(v0))
        if type(v0) is str:
            return hash(v0.encode('utf-8'))

        return bytes()
    else:                               # if v is a list
        res = bytearray()
        for vi in v:
            res +=  RecHash(vi)     # recursion
        return hash(res)            # hash the concatenated hashes

and the helper function:

def ToByteArray(x):
    q, r = divmod(BitAbs(x),8)
    q += bool(r)
    return ToByteArrayN(x, q)

def ToByteArrayN(x, n):

    B = bytearray()

    for i in range(0, int(n)):
        b = x % 256
        x = x // 256                  # // = integer division => floor
        B.insert(0, b)

    return bytes(B)

def BitAbs(i):
     return i.bit_length()

It is working fine, however, it's very slow (and interestingly, it's not the hash() function that is slowing it down.).

Performance is worst when the list contains mostly numbers, so the ToByteArray function also doesn't seem to perform well.


texts: Finding common ancestor in a binary tree

texts:
Following is a Python program I wrote to find the common ancestor in a binary tree (not BST) with no link to parent node. Please review.

def common_ancestor(N1, N2, head):
    if not head:
        return [None, 0, 0]

    left_status = common_ancestor(N1, N2, head.left)
    if left_status[0]:
        return left_status

    this_status = [None, 0, 0]
    if head == N1:
        this_status[1] = 1
    if head == N2:
        this_status[2] = 1

    right_status = common_ancestor(N1, N2, head.right)
    if right_status[0]:
        return right_status

    combined_status = [None, 0, 0]
    combined_status[1] = left_status[1] or this_status[1] or right_status[1]
    combined_status[2] = left_status[2] or this_status[2] or right_status[2]

    if combined_status[1] and combined_status[2]:
        print "Common Ancestor is %s" % head
        combined_status[0] = head

    return combined_status

if __name__ == "__main__":
    head = some_node
    print common_ancestor(5, 32, head)[0]


texts:
I'm parsing a file made up of various sections. I have a current_section variable that tracks which portion of the file I'm currently processing and the following check_for_next_section method that returns either the next section based on the contents of the current line or current_section if there are no matches based on the contents of the current line.
This method is getting flagged by rubocop for both 'perceived complexity' and 'cyclomatic complexity'. How can I reduce these?
SECTION_HEADERS = {
  hawaii_1: '"[2] For Hawaii, the following Postal Codes are Zone 44 for Ground',
  hawaii_2: '"For Hawaii, the following Postal Codes are Zone 46 for Ground',
  alaska_1: '"[3] For Alaska, the following Postal Codes are Zone 44 for Ground',
  alaska_2: '"For Alaska, the following Postal Codes are Zone 46 for Ground'
}.freeze

def check_for_next_section(line, current_section)
  return :zones if current_section == :preamble && line.starts_with?('Dest. ZIP')
  return :hawaii_1 if current_section == :zones && !line.blank? && line.starts_with?(SECTION_HEADERS[:hawaii_1])
  return :hawaii_2 if current_section == :hawaii_1 && line.starts_with?(SECTION_HEADERS[:hawaii_2])
  return :alaska_1 if current_section == :hawaii_2 && line.starts_with?(SECTION_HEADERS[:alaska_1])
  return :alaska_2 if current_section == :alaska_1 && line.starts_with?(SECTION_HEADERS[:alaska_2])

  current_section
end


texts:
My code have too much nested option processing which makes it ugly. But it has an advantage it has no side effect and typesafe.

package repos

import java.io.{InputStream, File}
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.{Cell, Row, Workbook, Sheet}
import org.apache.poi.xssf.usermodel._
import scala.collection.JavaConversions._

object ExcelRepo{

  def read(binary: InputStream, filename: String) = {
    val excelExtension = "([^\\s]+(\\.(?i)(xls|xlsx))$)"
    val excelData = if(filename.matches(excelExtension)) {

      val xlsExtension = "([^\\s]+(\\.(?i)(xls))$)"
      val xlsxExtension = "([^\\s]+(\\.(?i)(xlsx))$)"

      val workbook:Option[Workbook] = if (filename.matches(xlsExtension)) {
        println("XLS")
        Some(new HSSFWorkbook(binary))
      } else {
        println("XLSX")
        Some(new XSSFWorkbook(binary))
      }

      val data = workbook match {
        case Some(wb: Workbook) =>
          val sheet = Option(wb.getSheetAt(0))
          sheet match {
            case Some(s: Sheet) =>
              val titleRow = Option(s.getRow(0))
              titleRow match {
                case Some(tr:Row) =>
                  val titleCell = Option(tr.getCell(0))
                  val priceCell = Option(tr.getCell(1))
                  (titleCell, priceCell) match {
                    case (Some(tc: Cell), Some(pc:Cell)) =>
                      if (pc.getStringCellValue == "price" && tc.getStringCellValue == "title") {
                        val list:List[(String, Double)] = sheet.get.tail.map{
                         r => (r.getCell(0).getStringCellValue, r.getCell(1).getNumericCellValue)}.toList
                        list
                      } else {
                        List()
                      }
                    case (_,_) => List()
                  }
                case None => List()
              }
            case None => List()
          }
        case None => List()
      }
      data
    } else {
      List()
    }
    excelData
  }

}

This function reads Excel file assuming that it is not null, and returning the List of tuples with (price, title), or empty list if workbook or row or cell is empty.

Is it actually ugly? Should I refactor it? If I should what is the clear and concise way to deal with match Option → getting new Option → match it again → getting new Option ...


texts: Simple grid system made out of CSS columns

texts:
I have been researching and experimenting with HTML5 and CSS3. I was aiming to create a very simple but efficient tiled gallery / grids. So some sort of grid system that I can layout anything inside.

Below is what I have created, what are your opinions? I also have a question, why the distributing of the images change from browser to another?  Is there a way to control it?

Here is a working Fiddle.

HTML:

CSS:
/*Grids System*/
 .grids {
    width: 100%;
    overflow: hidden;
    -webkit-column-count: 3;
    -moz-column-count: 3;
    column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-gap: 10px;
    column-gap: 10px;
}
.grids.twoGrids {
    -webkit-column-count: 2;
    -moz-column-count: 2;
    column-count: 2;
}
.grids.fourGrids {
    -webkit-column-count: 4;
    -moz-column-count: 4;
    column-count: 4;
}
.grids .gridElement {
    margin-bottom: 10px;
    overflow: hidden;
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -ms-backface-visibility: hidden;
}
.grids .gridElement:last-child {
    margin-bottom: 0;
}
.grids .gridElement img {
    min-width: 100%;
}


texts: Logging all API call traffic in Java servlets

texts:
We have a few servlets like the one below, taking JSON request and produce JSON response. And the requirement is to log all API call traffic.

import org.slf4j.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CommentServlet {
  private static final Logger LOG = LoggerFactory.getLogger(CommentServlet.class);
  public void postComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String commentRequested = request.getParameter("comment");
    LOG.info(commentRequested);
    Object postResultModel = processComment(commentRequested);
    JsonUtil.writeResponse(response, postResultModel);
  }
  /**
  * doesn't reallty matter what processComment does
  */
  public Object processComment(String comment) {
    return new Object();
  }
}

import org.slf4j.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JsonUtil {
    private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class);
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    public static void writeResponse(HttpServletResponse response, Object modelObject) throws IOException {
        String modelJson = OBJECT_MAPPER.writeValueAsString(modelObject);
        LOG.info(modelJson);
        response.setContentType("application/json");
        response.getWriter().write(modelJson);
    }
}

if you can mainly review how the logging is done, I'd like feedback on the general approach as much as whether there's any way to improve it.


texts: Finding minimal number of items from an array

texts:
Given an array and a value x, I need an algorithm to find the minimum number of items to pick from the array so that the difference between the sum of those items and x is minimal.

public class Demo {

    static int[] solve(int arr[], int i, int esum, int csum, int size) {

        if (i == 0) {
            return new int[]{Math.abs(esum - csum), size};
        }

        int a1[] = solve(arr, i - 1, esum, csum + arr[i - 1], size + 1);
        int a2[] = solve(arr, i - 1, esum, csum, size);

        if (a1[0] < a2[0]) {
            return a1;
        } else if (a1[0] > a2[0]) {
            return a2;
        } else {
            if (a1[1] < a2[1]) {

                return a1;
            } else {
                return a2;
            }
        }
    }

    public static void main(String[] args) {
        //x = 108
        int arr[] = new int[]{70, 30, 33, 23, 4, 4, 34, 95, -50, -10, -10, -7};
        int a[] = solve(arr, arr.length, 108, 0, 0);
        System.out.println(a[0] + " " + a[1]);

    }
}

The output should be 0,3 (absolute difference), (number of items)

The first preference is the minimum absolute difference, only if there's multiple subsets with the same absolute difference we pick the one with the least number of items.


texts:
I have a start and end date. I would like to return a list of tuples, which have the start and end dates of each month.
Input
start_date = '2020-10-14'
end_date = '2021-03-26'

Output
[('2020-10-14', '2020-10-31'),
 ('2020-11-01', '2020-11-30'),
 ('2020-12-01', '2020-12-31'),
 ('2021-01-01', '2021-01-31'),
 ('2021-02-01', '2021-02-28'),
 ('2021-03-01', '2021-03-26')]

My code
from datetime import datetime, timedelta, date
import calendar

def get_first_day(year, month):
    return f'{year}-{str(month).zfill(2)}-01'

def get_last_day(year, month):
    # https://stackoverflow.com/a/23447523/5675288
    dt = datetime.strptime(f'{year}-{month}', '%Y-%m')
    dt = (dt.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
    return dt.strftime('%Y-%m-%d')

def diff_month(d1, d2):
    # https://stackoverflow.com/a/4040338/5675288
    return abs((d1.year - d2.year) * 12 + d1.month - d2.month)

def add_months(sourcedate, months):
    # https://stackoverflow.com/a/4131114/5675288
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
    return date(year, month, day)

def get_dates(start_date, end_date):
    """get list of tuples of dates
    [
        (start_date, end-of-month),
        (start-of-next-month, end-of-next-month),
        (start-of-next-next-month, end-of-next-next-month),
        ...
        (start-of-last-month, end_date)
    ]
    """
    sd = datetime.strptime(f'{start_date}', '%Y-%m-%d')
    ed = datetime.strptime(f'{end_date}', '%Y-%m-%d')

    diff_months = diff_month(sd, ed)

    first_days = []
    last_days = []

    for month in range(diff_months+1):
        d = add_months(sd, month)
        first_days.append(get_first_day(d.year, d.month))
        last_days.append(get_last_day(d.year, d.month))

    first_days = [start_date] + first_days[1:]
    last_days = last_days[:-1] + [end_date]

    return list(zip(first_days, last_days))

start_date = '2020-10-14'
end_date = '2021-03-26'

print(get_dates(start_date, end_date))

Is there a cleaner / better approach for this?


texts: Find next bigger number with same combination of digits

texts:
Please review my code for a puzzle to find next bigger number with same combination of digits.

so if the number is 156432 the next bigger number is 162345

I wrote a program which is as follows,

// converts a number
// to an number array
// i.e. 13452 = [1,3,4,5,2]
var convertToNumArray =  function(num){

    var numList = [],
        flag = true,
        n = 0;

    do{
         n = num % 10; // get the remainder value
         numList.push(n);
         num = parseInt(num/10); // get the quotient value in division

         if(num <= 0){
             flag = false;
         }

     }while(flag === true);

     numList = numList.reverse();

     return numList;
}

// gets the next value
function getNext(num){
    var numArray = convertToNumArray(num), // gets the number array; example [1,3,4,5,2]
        totalLength = numArray.length - 1,
        nextIndex = 0,
        leastIndex = 0,
        prevDiff = 0,
        diff = 0,
        swapIndex = 0,
        temp = 0,
        str = "";

    // iterate from right most number to find out the
    // number which is less than previous one.
    // for [1,3,4,5,2] the number is 4.
    for(var index = totalLength; index >= 1; index--){
        nextIndex = (index - 1);

        if(numArray[nextIndex] < numArray[index]){
            leastIndex = nextIndex;
            break;
        }else{
            continue;
        }
    }

    // iterate from right to check the number which is closest
    // and greater then the number we found from above loop.
    // so in our case 5 is the closes to 4
    for(index = totalLength; index > leastIndex; index--){
        diff = numArray[index] - numArray[leastIndex];

        if(index === totalLength){
            prevDiff = (diff  < 0) ? 9999 : diff;
            closestNum = numArray[index];
            swapIndex = index;
        }else{
            if(diff >= 0 && diff < prevDiff){
                prevDiff = diff;
                swapIndex = index;
            }
        }

    }
    // as 5 is the closest to 4. Replace them
    // so the conversion will be from [1,3,4,5,2] to [1,3,5,4,2]
    temp = numArray[swapIndex];
    numArray[swapIndex] = numArray[leastIndex];
    numArray[leastIndex] = temp;

    /*
        Now sort the sub array i.e. the numbers falling right
        to the replaced position.
        i.e. [1,3,5,4,2] so the sub array is [4,2].
        so sort in ascending order hence [2,4]
        so the complete number is
        [1,3,5,2,4].
    */

    // bubble sort on sub array
    do{

        for(index = leastIndex + 1; index < totalLength; index++){
            nextIndex = index + 1;
            if(numArray[index] > numArray[nextIndex]){
                 temp = numArray[index];
                 numArray[index] = numArray[nextIndex];
                 numArray[nextIndex] = temp;
            }
        }
        totalLength--;
    }while(totalLength > (leastIndex + 1));

    // convert the array to string
    for(index = 0; index < numArray.length; index++){
        str += numArray[index];
    }

    return parseInt(str);

}// end of getNext

var nr = undefined;

// capturing from commandline
// example : node logic.js 12345
(function(){
    process.argv.forEach(function (val, index, array) {
        if(index === 2)
            nr = array[index];
    });
})();

console.log(nr+" => "+getNext(nr));

When I run the above program
the output is

 E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>node logic.js 156432
 156432 => 162345

 E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>

Please review my code and suggest my any improvements
in the logic or in approach or in the style of coding.

Thanks


texts: Open text file and read data to an arrayfire array using Qt and C++

texts:
I'm currently writing a C++ project with a Qt GUI and would like to read numerical data from user-selected text files through QtFileDialog::getOpenFileName. There are quite a few methods around which use std::vector, but I will be using the arrayfire library and it generally seems to be a bit more convenient to either use C-style arrays instead of std::vector for storing the data in host memory, or to send the data to an arrayfire array directly. This is what I've done here.

The idea is to pull the data into arrayfire arrays that are part of a struct (dataStruct) which is defined as follows:

struct dataStruct{
    af::array d1, d2, d3;
};

To get the filename from the user I call this in the MainWindow instance after a signal from a pushButton in the GUI:

dataStruct dS;
QString tmp =
    QFileDialog::getOpenFileName(this, tr("Open data file"), "C:\\",
                                 tr("Text Files (*.txt)"));
std::string filename = tmp.toStdString();
loadData(filename, dS);

loadData is the function which extracts the data from the text file, and to do so needs to count the number of rows of data. This is done using getNumberOfLines below:

void getNumberOfLines(std::string filename, int &numLines)
{
    std::ifstream in(filename);
    std::string line;

    while(std::getline(in, line))
        numLines  = numLines + 1;
}

And finally, loading the data into the struct arrayfire arrays:

void loadData(std::string filename, structType &dS)
{
    int numLines = 0;
    getNumberOfLines(filename, numLines);

    std::ifstream in(filename);
    std::string line;
    int i = 0;

    af::array data1 = af::constant(0, numLines, f32);
    af::array data2 = af::constant(0, numLines, f32);
    af::array data3 = af::constant(0, numLines, f32);

    while (std::getline(in, line))
    {
        std::istringstream is(line);
        std::string 1_tmp, 2_tmp, 3_tmp;

        is >> 1_tmp >> 2_tmp >> 3_tmp;
        data1(i) = std::stof(1_tmp) * pow(10, -9);
        data2(i) = std::stof(2_tmp);
        data3(i) = std::stof(3_tmp);
        i++;
    }
    dS.d1 = data1;
    dS.d2 = data2;
    dS.d3 = data3;
}

I'm not so happy with getNumberOfLines and loadData because I end up reading the file data twice: First to get the number of rows/lines, the second to extract the data. I think it would be much better if this process could be reduced to a single step somehow.

One thing that I would like to implement is a function similar to getNumberOfLines or extension to loadData that allows the user to select data files with an arbitrary number of columns too. This could involve assigning all data to a single arrayfire array with dimensions given by (numRows, numCols, 1, 1) or similar, and then to split this array by columns later on to get the relevant data. Not sure how to implement this yet, so ideas are welcome!

If there are improvements to the code that other people can spot I'd really appreciate it if they could let me know. This will make up a small part of my first "big" project in C++, so please flag up any screamers that I've adopted when handling data or structuring the code.


texts: Longest Palindromic Substring better approach

texts:
I have encountered to this question and applied a brute force algorithm off top of my head and couldn't find a better optimized solution.

I was hoping I could get some insight to implement a better optimized code in terms of complexity. My solution has \$O(n^2)\$ time and space complexity.

class Solution:

    def longestPalindrome(self, s: 'str') -> 'str':
        if s=="":
            return ""
        else:
           ## Find all the substrings
            arr=[]
            for i in range(len(s)):
                char = s[i]
                arr.append(char)
                for j in range(i+1, len(s)-1):
                    char+=s[j]
                    arr.append(char)

            ##Find the palindrome with a longest length
            max_length = 0
            for j in range(len(arr)):
                if self.isPalindrome(arr[j]):
                    if len(arr[j]) > max_length:
                        max_length = len(arr[j])
                        index = arr[j]
            return index

    def isPalindrome(self,s:'str')->'str':
        if s == s[::-1]:
            return True


texts: Update table with greatest value from itself and another table

texts:
I have two tables A and B with some data and a date (e.g. date of last update). The id is only unique in table A. I want to update table A with the last date (=maximum) for each id.

Table A:

id date maximum
---------------
1  5    NULL
2  6    NULL

Table B:

id date
-------
1  3
1  7
2  20

Result A after Update:

id date maximum
---------------
1  5    7
2  6    20

What I got so far works, but it looks kind of weird:

UPDATE a,b
SET a.maximum = (
  SELECT GREATEST(MAX(b.date),a.date) WHERE a.id=b.id GROUP BY b.id)
WHERE a.id = b.id
;

The double WHERE a.id=b.id confuses me especially. Can this be improved somehow?