texts:
I implemented a custom Sliding Window Spliterator in Java.
Do you have any ideas how this could be improved?

Thinking if replacing the buffer with a plain array could have a positive impact on the performance side of things if done correctly.

I'm not going to use that code in any production system, just exercising.

public class WindowSpliterator<T> implements Spliterator<Stream<T>> {

    static <T> Stream<Stream<T>> windowed(Collection<T> stream, int windowSize) {
        return StreamSupport.stream(new WindowSpliterator<>(stream, windowSize), false);
    }

    private final Queue<T> buffer;

    private final Iterator<T> sourceIterator;
    private final int windowSize;

    private WindowSpliterator(Collection<T> collection, int windowSize) {
        this.buffer = new ArrayDeque<>(windowSize);
        this.sourceIterator = Objects.requireNonNull(collection).iterator();
        this.windowSize = windowSize;
    }

    @Override
    public boolean tryAdvance(Consumer<? super Stream<T>> action) {
        if (windowSize < 1) {
            return false;
        }

        while (sourceIterator.hasNext()) {
            buffer.add(sourceIterator.next());

            if (buffer.size() == windowSize) {
                action.accept(Arrays.stream((T[]) buffer.toArray(new Object[0])));
                buffer.poll();
                return sourceIterator.hasNext();
            }
         }

        if (!buffer.isEmpty()) {
            action.accept(buffer.stream());
        }

        return false;
    }

    @Override
    public Spliterator<Stream<T>> trySplit() {
        return null;
    }

    @Override
    public long estimateSize() {
        return Long.MAX_VALUE;
    }

    @Override
    public int characteristics() {
        return ORDERED | NONNULL;
    }
}


texts:
This is my attempt to format a number and put commas where appropriate. I was wondering if this could be done in a simpler way.

It's used by calling format_string_number("123456789") and prints 123,456,789.

def format_string_number(st):
    inputVal = list(st)
    inputVal.reverse()
    returnVal = []

    for index, value in enumerate(inputVal):
        returnVal.insert(0,value)
        if (index+1) %3 == 0:
            returnVal.insert(0,",")

    if returnVal[0] == ",":
        returnVal.pop(0)

    print("".join(returnVal))


texts: Transformed and stored reversed order digits of an integer to a complete integer number

texts:
Input:
Enter an integer number: 123456 [Any number of digits are allowed]

Output:
Completed integer number : 654321

I have solved this problem by following this strategy:
#include <stdio.h>
int main(void){
//put variables for further proceed
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);
find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(number,value);
}
int get_input_validation(){

int number=0;

while(1){
//Taking input from the user
printf("Enter an integer number: ");
scanf("%d",&number);
if(number<=0){
    printf("Zero and negative numbers are not allowed here\n");
}
else{
    break;
}

}
return number;
}
int find_out_the_number_of_digit(int number){

int count=0;
int value=1;

//Getting total digits of a given integer number
while(number!=0){
    number=number/10;
    count++;
    if(count==1){
        value=1;
    }
    else{
        value=value*10;
    }

   }
   return value;
   }

 int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){
 int complete_integer=0;

 while(number!=0){
    int last_digit=0;

    //get the last digit
    last_digit=number%10;

    //get the quotient
    number=number/10;

    complete_integer=complete_integer+last_digit*value;

    value=value/10;

   }

printf("Completed integer number : %d",complete_integer);
}

I am here for:
What about my indentation and comments? Will I face any problem for some conditions? How can I simplify my solution by reducing too much line of codes in an efficient way?


texts: refactoring common behavior to js object

texts:
I want to refactor this code into js object,
but not sure how. How should I do it?

I initialize an object for every item in the  DS.data_per_folder array.
how can I define it in a higher level? Where should I init it then?

   ..
    DS.data_per_folder[CurrentContextMgr.current.folder.attr('id')] = {
                allAttachments_vector: [],
                allAttachments_vector_counter : 0,
                attachment_position_dict : {},
                extraDetails_dict: {},
                getAttachmentsPerPage: function (pageNum) {
                    var result = this.allAttachments_vector.slice(global_vars.NUM_OF_ATTACH_PER_PAGE * (pageNum - 1), global_vars.NUM_OF_ATTACH_PER_PAGE * (pageNum));
                    return result.length == 0 ? null : result;
                },

                getAttachmentsMarkupPerPage: function (pageNum) {
                    var attachmentsMarkup = "";
                    var attachments = this.getAttachmentsPerPage(pageNum);
                    for (key in attachments) {
                        attachmentsMarkup += attachments[key].attachment_markup + " ";
                    }
                    return (attachmentsMarkup == "") ? "No attachments to display" : attachmentsMarkup;
                },

                pushAttachment: function (attachment, position) {

                    //not in dict yet
                    if (this.attachment_position_dict[attachment.attachmentId] == undefined)
                    {
                    if (position ==  null)
                    {
                    position = this.allAttachments_vector_counter;
                    }

                    this.allAttachments_vector[position] = attachment;

                this.allAttachments_vector_counter++;
                this.attachment_position_dict[attachment.attachmentId] = position;
                //this.extraDetails_dict[attachment.attachmentId] = {};
                }
            },       };
    }
..


texts: jQuery plugin for easy CSS3 transformation

texts:
I wrote it more for educational reasons and less as something that can compete with existing alternatives.

But I enjoyed writing it and wish to get some feedback, JavaScript is my second language :)

(I hope the main issue is lack of comments, but I wonder if there is anything else hairy about the code)

Here is the main plugin code:

(function ($) {
  'use strict';

  /*
   * Base function for all transformations
   */
  function base(property, transformer, params) {

    var value = $.map(params, function (item, index) {
      return transformer.call(this, item);
    }).join(", ");

    return this.each(function () {
      var $this = $(this);
      var existingTransformation = $this.css("transform");
      if (existingTransformation === 'none') {
        existingTransformation = '';
      }
      if (existingTransformation !== '') {
        existingTransformation += ' ';
      }
      $this.css({
        transform: existingTransformation + property + "(" + value + ")"
      });
    });
  };

  /*
   * Numeric to string conversion internal helper functions
   */

  function suffixNumber(param, suffix){
    if (typeof param === "number") {
      param += suffix;
    }
    return param;
  };
  function toDeg(param){
    return suffixNumber(param, "deg");
  }

  function toPx(param){
    return suffixNumber(param, "px");
  }

  function toPc(param){
    return suffixNumber(param, "%");
  }

  function toStr(param){
    return suffixNumber(param, "");
  }

 /*
  * The plugin's outer world functions
  */

  var functionParamTypes = {
    number:toStr,
    length:toPx,
    angle:toDeg
  }

  var functionNames = [
    {
      "name":"matrix",
      "type":functionParamTypes.length
    },
    {
      "name":"translate",
      "type": functionParamTypes.length
    },
    {
      "name":"translateX",
      "type": functionParamTypes.length
    },
    {
      "name":"translateY",
      "type": functionParamTypes.length
    },
    {
      "name":"scale",
      "type": functionParamTypes.number
    },
    {
      "name":"scaleX",
      "type": functionParamTypes.number
    },
    {
      "name":"scaleY",
      "type": functionParamTypes.number
    },
    {
      "name":"rotate",
      "type": functionParamTypes.angle
    },
    {
      "name":"skew",
      "type": functionParamTypes.angle
    },
    {
      "name":"skewX",
      "type": functionParamTypes.angle
    },
    {
      "name":"skewY",
      "type": functionParamTypes.angle
    },
    {
      "name":"matrix3d",
      "type": functionParamTypes.length
    },
    {
      "name":"translate3d",
      "type": functionParamTypes.length
    },
    {
      "name":"translateZ",
      "type": functionParamTypes.length
    },
    {
      "name":"scale3d",
      "type": functionParamTypes.length
    },
    {
      "name":"scaleZ",
      "type": functionParamTypes.length
    },
    {
      "name":"rotate3d",
      "type": functionParamTypes.angle
    },
    {
      "name":"rotateX",
      "type": functionParamTypes.angle
    },
    {
      "name":"rotateY",
      "type": functionParamTypes.angle
    },
    {
      "name":"rotateZ",
      "type": functionParamTypes.angle
    },
    {
      "name":"perspective",
      "type": functionParamTypes.angle
    }
  ];

  $.each(functionNames,function(index, item){
    var name = item.name, type = item.type;
    $.fn[name] = function () {
      return base.call(this, name, type, arguments);
    }
  });

})(jQuery);

Latest version can be found here
Live demo can be found here
Usage example can be found here


texts:
I am going to simulate a particle system, the particles are infinitesimal points which apply forces on the neighbors and I need a fast way of making proximity checks, they are going to have a maximum check radius but not a minimum and will be almost evenly spaced.

The simulation will be very similar to this: https://youtu.be/SFf3pcE08NM

I thought a spatial grid would be the easiest approach for it and I need it to be as cost efficient as possible to matter how ugly it gets.

Is there any optimization I can make on this code?

Is there a way to compute the optimal cell size from the average distance between particles?

_empty_set = set()

class SpatialHash:
    def __init__(self, cell_size=0.1):
        self.cells = {}
        self.bucket_map = {}
        self.cell_size = cell_size

    def key(self, co):
        return int(co[0] / self.cell_size), int(co[1] / self.cell_size), int(co[2] / self.cell_size)

    def add_item(self, item):
        co = item.co
        k = int(co[0] / self.cell_size), int(co[1] / self.cell_size), int(co[2] / self.cell_size)
        if k in self.cells:
            c = self.cells[k]
        else:
            c = set()
            self.cell_size[k] = c
        c.add(item)
        self.bucket_map[item] = c

    def remove_item(self, item):
        self.bucket_map[item].remove(item)

    def update_item(self, item):
        self.bucket_map[item].remove(item)
        self.add_item(item)

    def check_sphere(self, co, radius, exclude=()):
        r_sqr = radius * radius
        for x in range(int((co[0] - radius) / self.cell_size),
                       int((co[0] + radius) / self.cell_size) + 1):
            for y in range(int((co[1] - radius) / self.cell_size),
                           int((co[1] + radius) / self.cell_size) + 1):
                for z in range(int((co[2] - radius) / self.cell_size),
                               int((co[2] + radius) / self.cell_size) + 1):
                    for item in self.cells.get((x, y, z), _empty_set):
                        if item not in exclude and (item.co - co).length_squared <= r_sqr:
                            yield item


texts: isBalanced function for checking if string with brackets is balanced ([{}])

texts:
I wrote simple function for checking if string is balanced (with brackets ([{}])). It takes a string argument and need to return boolean value (true if string is balanced and false if not).

const isBalanced = (string) => {
  const arr = string.split('');
  let open = [];

  const openBrackets = {
    '(': true,
    '[': true,
    '{': true,
  };

  const closedBrackets = {
    ')': '(',
    ']': '[',
    '}': '{',
  };

  for (let i = 0, length = arr.length; i < length; i++) {
    if (openBrackets[arr[i]]) {
      open.push(arr[i]);
    } else if (closedBrackets[arr[i]] && open.pop() !== closedBrackets[arr[i]]) {
      return false;
    }
  }

  return !open.length;
}

console.log(isBalanced('') === true);
console.log(isBalanced('()') === true);
console.log(isBalanced(')()') === false);
console.log(isBalanced(')(') === false);
console.log(isBalanced('()(()()()())') === true);
console.log(isBalanced('[](){}') === true);
console.log(isBalanced('[({})]') === true);
console.log(isBalanced('[(]{)}') === false);
console.log(isBalanced('const sth = () => { animal.sleep();') === false);
console.log(isBalanced('const sth = { bark: animal() }') === true);

Do you think that i could improve it somehow? Can you see any mistakes?


texts:
I am in the need to cache Bitmap's in a memory-optimized way because the API I am building will need to process many colored Bitmap's in parallel and can be used in x86 or x64 compiled applications.

If the API is being used in x86 I can't just store the Bitmap's as they are but need to store them as compressed MemoryStream's otherwise the API would throw an OutOfMemoryException pretty fast.

After storing the "Bitmap's" they will be processed by multiple threads hence thread-safety is a major point.

Any feedback is welcome.

public static class ImageCache
{
    private static int currentId = 0;
    private static readonly object addImageLock = new object();
    private static readonly object releaseImageLock = new object();
    private static readonly ConcurrentDictionary<int, MemoryStream> images = new ConcurrentDictionary<int, MemoryStream>();

    /// <summary>
    /// Release an image based on its id.
    /// </summary>
    /// <param name="id"></param>
    public static void ReleaseIamge(int id)
    {
        lock (releaseImageLock)
        {
            ReleaseMemoryStream(id);
        }
    }

    private static void ReleaseMemoryStream(int id)
    {
        MemoryStream ms = null;
        if (images.TryGetValue(id, out ms) && ms != null)
        {
            images[id].Dispose();
            images[id] = null;
        }
    }

    /// <summary>
    /// Releases all Images
    /// </summary>
    public static void ReleaseAllImages()
    {
        lock (releaseImageLock)
        {
            lock (addImageLock)
            {
                foreach (var id in images.Keys)
                {
                    ReleaseMemoryStream(id);
                }
                images.Clear();
            }
        }
    }

    /// <summary>
    /// Returns a Bitmap from the cache which is identified by an id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public static Bitmap GetBitmap(int id)
    {
        lock (releaseImageLock)
        {
            MemoryStream ms = null;
            if (images.TryGetValue(id, out ms))
            {
                if (ms != null)
                {
                    return (Bitmap)Image.FromStream(ms);
                }
            }
        }
        return null;
    }

    /// <summary>
    /// Adds an Bitmap to the cache
    /// </summary>
    /// <param name="bitmap"></param>
    /// <returns>0 if the Bitmap is null, otherwise a uique id</returns>
    public static int Add(Bitmap bitmap)
    {

        if (bitmap == null)
        {
            return 0;
        }

        var ms = new MemoryStream();
        bitmap.Save(ms, ImageFormat.Tiff);
        var id = 0;
        lock (addImageLock)
        {
            // If the dictionary is empty we can reset the currentId
            if (images.Count == 0)
            {
                currentId = 0;
                id = Interlocked.Increment(ref currentId);
                images.TryAdd(id, ms);
                return id;
            }

            // We don't know how long an application using this is running and how many
            // images having been stored but we don't want to reach int.MaxValue here
            // hence we recycle the Value of a KeyValuePair of the dictionary if the Value
            // will be null.
            id = images.Where(item => item.Value == null).FirstOrDefault().Key;
            if (id == 0)
            {
                id = Interlocked.Increment(ref currentId);
            }

            images[id] = ms;

        }
        return id;
    }
}

Clarifying comments:

  Why don't you use a Guid as id and key in the dictionary?

Well the problem with this is that I need to "mimic" an API we use for our main application in such a way that I can interchange this API and the other API. The other api is a comercial imaging sdk whichs licence doesn't permits the use of it for a sdk/api.


texts:
I'm writing a MVC app, I've put effort into writing index.php since it must be the entrance point (like main for C and Java) imho.
I would like to ensure if someone who were to work on this file wouldn't be confused.

require_once 'App/config.php'; //main constants are defined here
require_once 'App/autoload.php';

if(strpos(URL,'error/'))
    goto start;
try{
    Connection::set(DBMS,HOST,PORT,DB_NAME,DB_USER,DB_PWD,$PDO_OPTIONS);
    DAO::init();

}catch(Exception $e){
    if(!PROD){ //if the app is online PROD=TRUE
        throw $e;

    }else
        header('location: '.WEBROOT.'error/503/',503);

    exit;
}

session_start();

if(!isset($_SESSION['user']))
    $_SESSION["user"] = new Guest;

start:
    try{
        extract($_GET);
        unset($_GET);

        if(isset($controller, $action, $params))
            Dispatcher::dispatch($controller, $action, $params);

        else if (isset($controller, $action))
            Dispatcher::dispatch($controller, $action);

        else if (isset($controller, $params))
            Dispatcher::dispatch($controller, NULL, $params);

        else if (isset($controller))
            Dispatcher::dispatch($controller);

        else
            Dispatcher::dispatch();

        echo Dispatcher::deliver(); //output the response

    }catch(Throwable $t){
        if(!PROD)
            throw $t;

        else if($t instanceof TypeError && strpos($t->getTrace()[0],'Dispatcher.php'))
            header('location: '.WEBROOT.'error/400/',400);

        else if(strpos($t->getMessage(),'not found'))
            header('location: '.WEBROOT.'error/404/',404);

        else
            header('location: '.WEBROOT.'error/503/',503);
    }


texts: Count lines of scala code (omitting empty lines) in a directory, traversing any subdirectories

texts:
I need to simply count lines of Scala code in a project, which includes some package(i.e. directory) hierarchy.

I'm not sure about the performance of the code below. Can you help improve it, if possible?

Also, in Java, we have reduce() in the Stream API, and I didn't find its counterpart in the Scala library, so ended with foldLeft().

import java.io.File
import scala.io.Source

object CountLoc {
  def main(args: Array[String]): Unit = {
    val parentDir: File = new File(System.getProperty("user.dir"))

    def traverse(dir: File): Int = {
      val all = dir.list().map(f => new File(dir.getAbsolutePath + "/" + f))
      val srcs = all.filter(!_.isDirectory).filter(_.getName.endsWith(".scala"))
      val dirs = all.filter(_.isDirectory)
      srcs.foldLeft(0)((i, f) => i + Source.fromFile(f).getLines().filterNot(_.isEmpty).toList.size) +
        dirs.toList.foldLeft(0)((i,d) => i + traverse(d))
    }

    println("LOC: " + traverse(parentDir))
  }
}


texts: Mapping and sorting lists of Haskell tuples

texts:
I'm a newbie with Haskell and I'm trying to learn the language and its idioms while working through a small data analysis project.  The first step of my analysis is to take a very long list of data, generate the set of ngrams from that list, then create a histogram from the generated set of ngrams.

This approach seems to work nicely:

import Data.List
import Control.Arrow

histogram :: Ord a => [a] -> [(a,Int)]
histogram = map (head &&& length) . group . sort

ngrams :: Eq a => Int -> [a] -> [[a]]
ngrams n xs
     | nx == xs  = [xs]
     | otherwise = [nx] ++ (ngrams n (tail xs))
     where nx = take n xs

The next step is divide each ngram frequency by the total number of ngrams and then take the inverse of each of these values.

(//) a b = fromIntegral a / fromIntegral b

mapOverSnd :: (a -> b) -> [(c,a)] -> [(c,b)]
mapOverSnd f = map (fst &&& f . snd)

...

let myData = (long list of values)
let my3grams = ngrams 3 myData
let freq3grams = histogram my3grams
let novelty3grams = mapOverSnd ((1/) . (//(length freq3grams))) freq3grams

My first question is.. is this a reasonable way to be doing this?  Is there a more idiomatic way to accomplish mapOverSnd?  I don't yet have much dexterity wielding higher order structures to accomplish my tasks.

Also, I'd like to sort the resultant structure: first by the value stored in snd, then by the value stored in fst.  I'd like the primary sort to be descending and the secondary sort to be ascending.  This works:

my2TupleOrdering :: (Ord a, Ord b) => (a,b) -> (a,b) -> Ordering
my2TupleOrdering (a1,b1) (a2,b2)
               | b1 < b2   = GT
               | b1 > b2   = LT
               | a1 < a2   = LT
               | a1 > a2   = GT
               | otherwise = EQ

however, I was wondering if there is a more idiomatic way to say "sort this 2-tuple, first by snd descending, then by fst ascending."

I realize these are relatively minor questions, but I'm interested in exploring the expressive power of Haskell and figured 'code review' might be the correct forum.  Thanks!


texts: Task Wrappers for starting operation only if previous task has finished

texts:
I've written these two wrappers around Tasks, to help with common scenarios in our code where methods are called repeatedly, even if the previous operation hasn't completed yet. There are two common scenarios:

An operation is triggered several times by the user (e.g. clicking a checkbox filters a list by its value. User clicks 3 checkboxes in quick succession). In this case, every operation starts a possibly expensive server call, but I only care about the last one.
A periodic operation is triggered by a timer every x seconds, but the operation sometimes takes more than x seconds. In this case, I don't want to start a new operation but to simply skip it, waiting for the next timer event to try again.

The solution I've used for both of these is similar:

public static void ExecuteAndCancelPreviousTask(ref Task previousTask, ref CancellationTokenSource cancellationTokenSource, Action action)
{
    if (previousTask != null && !previousTask.IsCompleted)
        cancellationTokenSource.Cancel();

    cancellationTokenSource = new CancellationTokenSource();
    previousTask = Task.Run(action, cancellationTokenSource.Token);
}

public static void ExecuteIfPreviousTaskComplete(ref Task previousTask, ref CancellationTokenSource cancellationTokenSource, Action action)
{
    if (previousTask != null && !previousTask.IsCompleted)
        return;

    cancellationTokenSource = new CancellationTokenSource();
    previousTask = Task.Run(action, cancellationTokenSource.Token);
}

In both cases, I receive the previously running operation (which can be null, the first time) and the CancellationTokenSource attached to it. In the first case, I use the CTS to cancel the previous operation. In the second, I simply ignore it and skip running the action.

Of course, the Action passed has to be CTS-aware, and check it for cancellation:

public void Timer_Elapsed()
{
    TaskExtensions.ExecuteIfPreviousTaskComplete(ref _pollingTask, ref _pollingCancellationTokenSource, async () =>
    {
        var cts = _pollingCancellationTokenSource;
        var pollingResults = await _service.Poll();
        if (cts.IsCancellationRequested)
           return;
        UpdateFromResults(pollingResults);
    });
}

My questions are:

Do you feel that these methods clearly express their purpose and usage?
I'm a bit leery of the two ref parameters. But since the methods have the update the task and its CTS, I could see no better way.
I don't really have a need for the action to be run on a new thread. I mainly use Task.Run() because I need, well, a Task that can be monitored and cancelled. Should I instantiate the task some other way?
The two methods are almost identical except for the second line of each, but I figured that their usage and intent are clearer when they're separate. Should I merge them? Should I keep them as two distinct public methods, but merge their implementation into a single private method? Or is this overkill for two and a half lines of code?
In the first case, should I wait, after Canceling the task, before creating a new one? Make sure it's ended?
Currently, I'm capturing the CancellationTokenSource at the beginning of my Action so that it doesn't get replaced when the ref is updated. Is this necessary? Or will the capture keep the original value?


texts: VBA code to account for multiple users too heavy on save actions

texts:
I have a worksheet I use with a small handful of colleagues on a daily basis to share information with about orders we place. To make sure we always have the same up to date info we use a shared excel workbook I created. I know this is not preferred, but this is all that is available in my company.

To prevent us from overwriting our existing data with new orders I created this code:

If ActiveWorkbook.MultiUserEditing Then 'in case of multiple users, make sure all data is accepted.
ActiveWorkbook.AcceptAllChanges
End If
ActiveWorkbook.Save 'save to retrieve latest version from server.
Sheets("Database").AutoFilterMode = False 'disengage autofilter so hidden lines won't be overwritten
Dim I As String
If Sheet2.Range("A:A").Find(What:=User(), LookIn:=xlValues) Is Nothing Then
    I = Sheet2.Range("A" & Rows.Count).End(xlUp).Row + 1 'determine next available blank row.
        Else
        I = Sheet2.Range("A:A").Find(What:=User(), LookIn:=xlValues).Row
End If
Range("Database!A" & I).Value = User()
ActiveWorkbook.Save
Dim MyLine(0 To 15) As Variant
MyLine(0) = Application.WorksheetFunction.Max(Range("Database!A:A")) + 1 'determine next available line number and auto-fill on next blank row.
If Range("Form!C6") = "" Then 'if multi-line box is empty, copy over material type box.
MyLine(1) = Range("Form!B3").Value
Else 'if multi-line box is filled, copy over multi-line box.
MyLine(1) = Range("Form!C6").Value
End If
MyLine(2) = Range("Form!B4").Value 'copy over all info filled in the form to next blank row on database
MyLine(3) = Range("Form!B5").Value
MyLine(4) = Range("Form!B6").Value
MyLine(5) = Range("Form!B7").Value
MyLine(6) = Range("Form!B8").Value
MyLine(7) = "LA" & Range("Form!B9").Value
MyLine(8) = Range("Form!B10").Value
MyLine(10) = Range("Form!B11").Value
MyLine(9) = Range("Maintenance!D2").Value 'auto-fill phone number from filtered results on contacts sheet
MyLine(14) = Environ$("UserName") 'Pull username from system
MyLine(15) = Now 'pull current time from system
MyLine(11) = Range("Form!B12").Value
    If Range("Form!B5") = "Stores" Then 'in case of stores orders auto fill PO box and set PO text as black
        MyLine(12) = "None"
        MyLine(13) = "None"
        Range("Database!N" & I).Font.ColorIndex = 0
End If
Range("Database!A" & I & ":Database!P" & I).Value = MyLine
ActiveWorkbook.SaveCopyAs ("C:\Redacted\" & Format(Now(), "DD-MM-YYYY hh mm ss") & ".xlsm") 'save backup with form still filled in, named for current date and time.
   Sheet1.Range("Form!B3:B14").ClearContents
   Sheet1.Range("Form!C3").ClearContents
   Sheet1.Range("Form!C6:C7").ClearContents
   Range("Database!A1").AutoFilter 'switch auto-filter for database back on
    ActiveWorkbook.Save 'save to database to ensure latest version is available.
    Beep 'Audio prompt saying macro is done.
End Sub

My structure includes a fair number of saves to update the server file, as the code runs fairly slowly. If it is interrupted at any point, due to this structure no information will be overwritten. This is all to account for multiple users clicking this button at the same time on different machines, interrupting each others saves.

Currently I get around this by "Claiming" the next available line at the start of the run, and restarting on that line the next time the button is clicked (when someone else's save action is complete) however this is very heavy on Save actions, and due to it being a server located file, this slows down the macro significantly. Is there a better structure I can use to account for multiple users clicking the button at the same time, preventing any information being overwritten at any cost?

PS I know using Activeworkbook and the like is discouraged, and I'm currently reviewing my code to amend this. I'm just looking for ideas about above issue.


texts:
I'm learning RxJava and this is what I attempted to find the mean of 'n' transactions.

List<Transaction> transactions = TransactionsStore.getTransactions();
BigDecimal nTransactions = new BigDecimal(transactions.size());
Observable.from(transactions)
        .map(transaction -> transaction.amount)
        .reduce(BigDecimal::add)
        .map(total -> total.divide(nTransactions, 2, BigDecimal.ROUND_DOWN))
        .map(mean -> String.format("The mean is %s", mean.toPlainString()))
        .subscribe(System.out::println);

I'd like to know if this could be done better.


texts:
I wrote this for a problem in one of the online contest at hackerearth. Problem statement is:

  Input:

    The first line contains the compressed string in form a2b4h5a2

    Expanding it means aabbbbhhhhhaa.

    You have to sort the expansion in increasing order(a-z). ie. aaaabbbbhhhhh

    This is followed by Q that indicates the number of queries.

    Follows Q lines each line contain an integer K.

  Output:

    For every question output the Kth character if it exists else print -1 .

It works correctly as intended, but help me make it faster as it exceeds time limit for that portal.
Any constructive criticism and advice is appreciated. :)

The idea is that, I made a integer array of size 26 to store the respective frequency of characters, thus sorting step is done automatically. Then just started subtracting the frequency value from the query until its zero or negative, that index is the required alphabet.

#include<stdio.h>

int main()
{

   // made a array to store frequency of alphabets

    int ar[26] = {0};
    int n=0, i=0, c=0, Q=0, K=0, m=0, chint=0;
    char str[10000];                   // use to store the compressed format string
    scanf("%10000[^\n]", str);

    for(i=0;str[i];i=i++)
    {
        if((str[i]>='a' && str[i]<='z'))
         {
             ar[m] += n;
             m = str[i]-97;
             n=0;
         }
        else
        {
            chint=(int)str[i]-48;
            n=(n*10)+chint;
        }
    }
    ar[m] += n;

    scanf("%d",&Q);
    while(Q--)
    {
        scanf("%d",&K);
        for(i = 0; i<26; i++)
        {
            K = K - ar[i];
            if(K<=0)
            {
                printf("%c\n", (i+97));
                break;
            }
        }
        if(K>0)
            printf("-1\n");
    }

    return 0;
}


texts: Program to test for divisibility of numbers

texts:
(EDIT: here is the follow up qusetion)

Using this program to test for the smallest number where its permutations or itself is divisible by 10 or less numbers is twice as slow as the fastest program I found doing this (I don't have the source code). How can this program be twice as slow, what optimizations can I do without messing with the compiler flags?

#include <stdio.h>
#include <string.h>
#define MAX 1000000

int main() {
  int N,p[10],n[100];
  int mask[MAX];
  register int i, j, k;

  scanf("%d", &N);
  for(i=0;i<N;i++) scanf("%d", &n[i]);
  memset(mask,0,sizeof(mask));
  i = MAX+1;
  while(--i) {
    k=i;
    p[0]=0;
    p[1]=0;
    p[2]=0;
    p[3]=0;
    p[4]=0;
    p[5]=0;
    p[6]=0;
    p[7]=0;
    p[8]=0;
    p[9]=0;
    while (k>0) {p[k%10]++; k/=10;}

    for(j=1;j<10;j++) if(p[j]>0) {k=j; p[j]--; break;}
    for(j=0;j<10;j++) while (p[j]>0) {k=10*k+j; p[j]--;}
    for(j=0;j<N;j++) if(i%n[j]==0) mask[k]|=(1<<j);
  }
  for(i=1;i<MAX;i++) if(mask[i]==(1<<N)-1) break;
  fprintf(stdout, "%d\n", i);
}

This program uses bitmasks to test all numbers between 1 and MAX for divisibility with the given numbers and then prints out the smallest number whose permutations or itself is divisible by all given numbers. It is not fast enough!

Example input

7
164 278 293 382 483 598 23

This will test all numbers and check which ones are divisible by the given numbers and the output should be 102246.

It is compiled using the GCC compiler with the following flags:

-g -O2 -std=gnu99 -static -lm

Test the code here.


texts: Use of a regex stored inside a YAML file

texts:
I installed settingslogic and in the configuration file I put the regex for the email as follows:

#config/settings.yml
defaults: &defaults

  email_regex: /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i

development:
  <<: *defaults
  # neat_setting: 800

test:
  <<: *defaults

production:
  <<: *defaults

That I load in devise configuration in this way:

#config/initializers/devise.rb
  # Regex to use to validate the email address
  # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
  config.email_regexp = eval Settings.email_regex

It works, but what do you think about that eval? Is it the correct way to convert a string to a regex?


texts:
In a response to this post I wrote a solution in Python. It passed all the test cases given, so I would like help making it more pythonic and reducing the almost repeated lines.

Link to the source of the question on HackerRank.

# input
M, N, rotations = map(int, input().split())
matrix = []
for row in range(M):
    matrix.append(list(map(int, input().split())))

# flatten the rings into a list
layers = int(min(N, M)/2)
ring = [[] for layer in range(layers)]

for level in range(layers):
    top = (N-1) - 2 * level
    side = (M-1) - 2 * level
    for row in range(top):  # right
        ring[level].append(matrix[level][level + row])
    for col in range(side):  # down
        ring[level].append(matrix[level + col][level + top])
    for row in range(top):  # left
        ring[level].append(matrix[level + side][level + top - row])
    for col in range(side):  # up
        ring[level].append(matrix[level + side - col][level])

# rotate each layer
for level in range(layers):
        r = rotations % len(ring[level])
        ring[level] = ring[level][r:] + ring[level][:r]

# fill the array with the rotated elements
for level in range(layers):
    top = (N-1) - 2 * level
    side = (M-1) - 2 * level
    for row in range(top):
        matrix[level][level + row] = ring[level].pop(0)  # right
    for col in range(side):
        matrix[level + col][level + top] = ring[level].pop(0)  # down
    for row in range(top):
        matrix[level + side][level + top - row] = ring[level].pop(0)  # left
    for col in range(side):
        matrix[level + side - col][level] = ring[level].pop(0)  # up

# print the rotated matrix
for row in range(M):
    for col in range(N):
        print(matrix[row][col], "", end="")
    print()


texts: Trying to find a better way of finding something rather then looping through list from top to bottom.

texts:
I am having a slight issue here, i am trying to think of a faster way of finding two elements from 2 different lists that match. The problem is that if i have lists which both have 1000 elements ( rules ) and the very last one [index.1000] matches then in order to find it i have to loop through booth lists from top to bottom. What i have is fine and it works however its not very efficient. Could any one perhaps suggest a better way ? (if there is any ? )

The loop in this meethod is where the iteration through the lists happen. For furthere reference below this method you will find what ContextRule and Context is.

public ContextRule match(Context messageContext, ContextRuleList contextRules) {
    ContextRule matchedContextRule = null;

    for(ContextRule contextRule : contextRules) {
        if(this.match(messageContext, contextRule)) {
            matchedContextRule = contextRule;
            break;
        }
    }
    if(matchedContextRule == null) {
        matchedContextRule = this.getDefaultContextRule();
    }
    return matchedContextRule;
}

match() method which does comparason.

private boolean match(Context messageContext, ContextRule contextRule) {
        return match(contextRule.getMessageContext().getUser(), messageContext.getUser())
                && match(contextRule.getMessageContext().getApplication(), messageContext.getApplication())
                && match(contextRule.getMessageContext().getService(), messageContext.getService())
                && match(contextRule.getMessageContext().getOperation(), messageContext.getOperation());
    }

    private boolean match(String value, String contextValue) {
        return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(contextValue);
    }

Context ( which is an interface )

public interface Context {
  public String getUser();
  public void setUser(String user);
  public String getApplication();
  public void setApplication(String application);
  public String getService();
  public void setService(String service);
  public String getOperation();
  public void setOperation(String operation);
}

And finally ContextRule

public interface ContextRule {
  public Context getMessageContext();
  public int getAllowedConcurrentRequests();
}

any help or suggestions appreciated.


texts:
I've created a small method to test the connection to a database:

public bool TestConnection(string provider, string serverName, string initialCatalog, string userId, string password, bool integratedSecurity)
{
    var canConnect = false;

    var connectionString = integratedSecurity ? string.Format("Provider={0};Data Source={1};Initial Catalog={2};Integrated Security=SSPI;", provider, serverName, initialCatalog)
                                              : string.Format("Provider={0};Data Source={1};Initial Catalog={2};User ID={3};Password={4};", provider, serverName, initialCatalog, userId, password);

    var connection = new OleDbConnection(connectionString);

    try
    {
        using (connection)
        {
            connection.Open();

            canConnect = true;
        }
    }
    catch (Exception exception)
    {

    }
    finally
    {
        connection.Close();
    }

    return canConnect;
}

Despite the method works it doesn t seems right to me. Is any way to test the connection without having to catch the exception?
Is it possible to achieve the same result in a different way?


texts:
How can I refactor this code to be more clean?

  $scope.unreserve = function () {
    var params = {
      'wishlist_product_id' : product.wishlist_product_id
    };

    WishlistService.unreserve(params, function (data) {
      if (data.success) {
        $rootScope.$broadcast('NotificationController.create', {type: 'success', message: 'Unreserve successfully'});
      } else  {
        $rootScope.$broadcast('NotificationController.create', {type: 'error', message: data.error_message});
      }
    });
  };

  $scope.createManualProduct = function () {
    var params = {};

    ProductService.addManualProduct(params, function (data) {
      if (data.success) {
        $rootScope.$broadcast('NotificationController.create', {type: 'success', message: 'Unreserve successfully'});
      } else{
        $rootScope.$broadcast('NotificationController.create', {type: 'error', message: data.error_message});
      }
    });
  };


texts:
I have written a code to retrieve data from xml file. It works but it is really slow. I takes about a minute. This is ok for 1 or some more xml files. But If you have to do it for 1000 it's not a good solution. Is there some way that my code could be adapted or improved to make it faster.

Function

Function that retrieve the information for a given path in string format

function xml_retriever($xml_link,$path){
    $result = file_get_contents($xml_link);
    $xml = simplexml_load_string($result);
    $doc = new DOMDocument();
    $doc = DOMDocument::loadXML($xml);
    $xpath = new DOMXPath($doc);
    $entries = $xpath->query($path);
    $attr = '';
    foreach($entries as $node){
        $attr .= '|'.' '.$node->nodeValue. "\r\n";
        $attr = ltrim($attr, '|');
    }
    return $attr;
}

Function test

Simple test if the function works

# Example query and example path
$esearch_test = "https://www.ncbi.nlm.nih.gov/gene/7128?report=xml&format=text";
$query = "/Entrezgene/Entrezgene_properties/Gene-commentary[3]/Gene-commentary_comment/Gene-commentary[1]/Gene-commentary_comment/Gene-commentary[*]/Gene-commentary_source/Other-source/Other-source_anchor";
# Print the result
echo xml_retriever($esearch_test,$query);

Retrieve all information for every path

Retrieves all information for every term at once.

$esearch_test = "https://www.ncbi.nlm.nih.gov/gene/7128?report=xml&format=text";
$data = array();
foreach ($querys as $key => $value){
    #echo "Key: $key
 Value: $value
\n";
    echo "
$key:
". xml_retriever($esearch_test,$value)."
\n";
    $data[] = xml_retriever($esearch_test,$value);
}

Exception

Function doesn't work for the gene synonyms.

$result = file_get_contents($esearch_test);
$xml = simplexml_load_string($result);
$doc = new DOMDocument();
$doc = DOMDocument::loadXML($xml);

# Add gene synoniem
$GSyn = "";
foreach($doc->getElementsByTagName('Gene-ref_syn_E') as $node) {
    echo "
".$node->nodeValue."
";
    $GSyn .= '|'.' '.$node->nodeValue. "\r\n";
    $GSyn = ltrim($GSyn, '|');
}
# Add data to the array
array_push($data, $GSyn);
# Print result
print_r($data);


texts: is there a more functionally idiomatic way of generating valid dates in f#?

texts:
open System

type Date = System.DateTime

type SafeDate =
    | WorkingDate of Date
    | InvalidDate of Exception

let dateAttempt (x: int, y:int, z:int) =
    try
        let returnDate = Date(z,y,x)
        WorkingDate returnDate
    with
        ex -> InvalidDate ex

let rnd = System.Random(4)

let randomBirthYear() =
    rnd.Next(1904,1954)
let randomBirthMonth() =
    rnd.Next(1,13)
let randomBirthDay() =
    rnd.Next(1,32)

let generateDate() =
    (randomBirthDay(), randomBirthMonth(), randomBirthYear())
    |> dateAttempt

let chooseValidDate d =
    match d with
    | WorkingDate d -> Some d
    | _ -> None

let sampleDobs = [for i in 1 .. 1000 -> generateDate()]

let cleanDates = Seq.choose chooseValidDate sampleDobs


texts: Porting stemming algorithm from Java to Python

texts:
I have ported Stempel stemmer in Java (Apache Lucene) to Python. I come from Java world, so I'm afraid my translation might not be "pythonic" enough.

I would like to hear your feedback on quite representative part of the code, translation of Diff class that applies stemming command (diff) to a string (dest).

 @classmethod
 def apply(cls, dest, diff):
    """
    Apply the given patch string diff to the given string dest
    :param dest: Destination string
    :param diff: Patch string
    :return:
    """
    if diff is None:
        return
    if not isinstance(dest, MutableString):
        raise ValueError
    if not dest:
        return

    pos = len(dest) - 1
    try:
        for i in range(int(len(diff) / 2)):
            cmd = diff[2 * i]
            param = diff[2 * i + 1]
            par_num = ord(param) - ord('a') + 1
            if cmd == '-':
                pos -= (par_num - 1)
            elif cmd == 'R':
                cls.__check_index(dest, pos)
                dest[pos] = param
            elif cmd == 'D':
                o = pos
                pos -= (par_num - 1)
                cls.__check_index(dest, pos)
                dest[pos:o + 1] = ''
            elif cmd == 'I':
                pos += 1
                cls.__check_offset(dest, pos)
                dest.insert(pos, param)
            pos -= 1
    except IndexError:
        # swallow, same thing happens in original Java version
        pass

@classmethod
def __check_index(cls, s, index):
    if index < 0 or index >= len(s):
        raise IndexError

@classmethod
def __check_offset(cls, s, offset):
    if offset < 0 or offset > len(s):
        raise IndexError

Some justifications of decisions I took:

The original implementation uses StringBuffer to manipulate characters in a string. Since Python str type is immutable I used my own class MutableString that behaves like a Python list.
Also, original logic was based on catching IndexOutOfBoundsException. Contrary to Java, Python allows negative indexes in a list and list ranges. Therefore, I've introduces guards like __check_X.
Java implementation uses switch/case/default clause. I translated that to if/elif/else clause in Python.


texts: Implement service with explicit interface implementation

texts:
I would like to implement service with explicit interface implementation.
I don't want to have public methods in service, only possible way to create instance is trough interface.

I am not sure what is best way to call method of same class if method is explicit implementation of interface method.

You can see in my code that I am using "AsIArchiveService" property.

I have public interface in class library:

using Common.Entities;
using System.Threading.Tasks;

namespace Common.Services
{
    public interface IArchiveService
    {
        Task<ArchiveConfiguration> GetConfiguration();

        Task<bool> Update(ArchiveConfiguration machine);
    }
}

Serivice class in main project:

using Common.Configurations;
using Common.Entities;
using Common.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RemoteManager.EntityFramework;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Manager.Services
{
    internal class ArchiveService : IArchiveService
    {
        private readonly IOptions<ApplicationConfiguration> applicationConfiguration;
        private readonly ILogger<ArchiveService> logger;
        private readonly ManagerContext context;
        IArchiveService AsIArchiveService
        {
            get { return this; }
        }

        internal ArchiveService(ManagerContext context, IOptions<ApplicationConfiguration> applicationConfiguration, ILogger<ArchiveService> logger)
        {
            this.applicationConfiguration = applicationConfiguration;
            this.logger = logger;
            this.context = context;
        }

        async Task<ArchiveConfiguration> IArchiveService.GetConfiguration()
        {
            try
            {
                logger.LogInformation($"Start  {nameof(ArchiveService)}:{nameof(AsIArchiveService.GetConfiguration)}");
                if (this.context.ArchiveConfiguration.Count() == 0)
                {
                    var res = this.context.ArchiveConfiguration.Add(new ArchiveConfiguration() { isArchive = true, maxDataSetCount = 20, path = Path.Combine("C:/", "TestArchive") });
                    this.context.SaveChanges();
                }
                var result = this.context.ArchiveConfiguration.First();
                return await Task.FromResult(result);
            }
            catch
            {
                logger.LogError($"Error {nameof(ArchiveService)}:{nameof(AsIArchiveService.GetConfiguration)}");
                throw;
            }
        }

        async Task<bool> IArchiveService.Update(ArchiveConfiguration archive)
        {
            try
            {
                logger.LogInformation($"Start {nameof(ArchiveService)}:{nameof(AsIArchiveService.Update)}");
                this.context.Entry(archive).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                this.context.SaveChanges();
                return await Task.FromResult(true);
            }
            catch
            {
                logger.LogError($"Error {nameof(ArchiveService)}:{nameof(AsIArchiveService.Update)}");
                throw;
            }
        }
    }
}


texts:
I'm writing a Telnet parser in Haskell that can run within any monad that implements some event-handling functions. When it finishes processing a block of input - whether because it read it all or because it was interrupted by an event handler - it returns the remainder of the text and a continuation for more input.

Right now, the code works, but it's pretty ugly. I've tried to make the patterns I saw in the program as obvious as possible, but I'm stymied at the actual refactoring stage.

I'm still pretty new to Haskell, so any feedback and advice on best practices is appreciated!

import qualified Data.ByteString as BS
import           Data.ByteString (ByteString)
import Data.Word (Word8)
import Control.Monad

{-
 - I suspect I can change these datatypes to use something like
 -   data Parser m r = Parser (ByteString -> m r)
 - but I'm not sure how to go about doing that.
 -}
data TelnetParser m = TelnetParser (ByteString -> m (TelnetState m))
type TelnetState m = (ByteString, TelnetParser m)

{-
 - These are the handler functions that the parser requires.
 - These allow you to execute other monadic actions in response to
 - Telnet events.
 -}
class (Monad m) => Telnet m where
  onText    :: Word8 ->          m ()
  onCommand :: Word8 ->          m Bool
  onOption  :: Word8 -> Word8 -> m Bool

  onText _     = return ()
  onCommand _  = return True
  onOption _ _ = return True

readTelnet :: (Telnet m) => ByteString -> TelnetParser m -> m (TelnetState m)
readTelnet str (TelnetParser f)
  | BS.null str = return (str, TelnetParser f)
  | otherwise   = f str

isOption :: Word8 -> Bool
isOption = (`elem` [250..254])

decideContinue :: (Telnet m) => Bool -> ByteString -> TelnetParser m -> m (TelnetState m)
decideContinue True = readTelnet
decideContinue False = curry return

{-
 - These functions implement the various states of the Telnet parser.
 -}

readOption :: (Telnet m) => Word8 -> ByteString -> m (TelnetState m)
readOption cmd str = do
    action <- decideContinue `liftM` onOption cmd ch
    action rest (TelnetParser readText)
  where (ch, rest) = (BS.head str, BS.tail str)

readIAC :: (Telnet m) => ByteString -> m (TelnetState m)
readIAC str
    | ch == 255    = onText ch >> (rest `readTelnet` TelnetParser readText)
    | isOption ch  =              (rest `readTelnet` TelnetParser (readOption ch))
    | otherwise    = do
        action <- decideContinue `liftM` onCommand ch
        action rest (TelnetParser readText)
  where (ch, rest) = (BS.head str, BS.tail str)

readCR :: (Telnet m) => ByteString -> m (TelnetState m)
readCR str
    | ch == 10    = onText 13 >> onText 10 >> (rest `readTelnet` TelnetParser readText)
    | ch ==  0    = onText 13 >>              (rest `readTelnet` TelnetParser readText)
    | otherwise   = onText 13 >>              (rest `readTelnet` TelnetParser readText)
  where (ch, rest) = (BS.head str, BS.tail str)

readText :: (Telnet m) => ByteString -> m (TelnetState m)
readText str
    | ch == 255   =              (rest `readTelnet` TelnetParser readIAC)
    | ch == 13    =              (rest `readTelnet` TelnetParser readCR)
    | otherwise   = onText ch >> (rest `readTelnet` TelnetParser readText)
  where (ch, rest) = (BS.head str, BS.tail str)


texts: Formatting date depending on current date

texts:
I have two screens where I show a message creation time and date. Initially, there was only one screen and I should always show time and show date differently depending on difference between today and the message creation day.

Here is my method:

private final static String TIME_TEMPLATE_TODAY = "HH:mm";

public static String getFormattedDate(Date msgDate, Date currentTime) {
        long daysDiff = Utils.getDaysDiff(currentTime, msgDate);

        String format;
        if (currentTime.getYear() != msgDate.getYear()) {
            format = "dd.MM.yyyy' at '" + TIME_TEMPLATE_TODAY;
        } else if (daysDiff == 0) {
            format = TIME_TEMPLATE_TODAY;
        } else if (daysDiff == 1) {
            format = "'yesterday at " + TIME_TEMPLATE_TODAY;
        } else if (daysDiff > 1) {
            format = "dd.MM' at '" + TIME_TEMPLATE_TODAY;
        } else {
            format = "dd.MM.yyyy";
            Timber.e("Unexpected time diff: %d", daysDiff);
        }

        return new SimpleDateFormat(format, Locale.CANADA).format(msgDate);
    }

And now I should add cases for the second screen: show time only if it is today, otherwise, show only date (or "yesterday") without time.

I came up with solution below:

public static String getFormattedDate(Date msgDate, Date currentTime, boolean alwaysShowTime) {
        long daysDiff = Utils.getDaysDiff(currentTime, msgDate);
        StringBuilder format = new StringBuilder();

        // Add date representation
        if (currentTime.getYear() != msgDate.getYear()) {
            format.append("dd.MM.yyyy'");
        } else if (daysDiff == 1) {
            format.append("'вчера'");
        } else if (daysDiff > 1) {
            format.append("dd.MM");
        } else {
            format.append("dd.MM.yyyy");
            Timber.e("Unexpected time diff: %d", daysDiff);
        }

        // Add time
        if (daysDiff == 0) {
            format.append(TIME_TEMPLATE_TODAY);
        } else if (alwaysShowTime) {
            format.append("' at '")
                    .append(TIME_TEMPLATE_TODAY);
        }

        return new SimpleDateFormat(format.toString(), Locale.CANADA).format(msgDate);
    }

Disadvantages that I see are:

I changed method contract (but it used in 1-2 places, so it is not a big deal in this case)
I need to always pass this third parameter to the method.
I can solve both points creating another method with a previous contract and pass some default value for alwaysShowTime
If some third option appears, I would have to change the contract again, changing Boolean to enum, for example.

What problems or possible optimizations do you see here?
Should I just create a new method and extract some common logic to a private method instead changing existing one?


texts:
Sometimes I have the date as part of the file name.  And then when Emacs autocompletes the file name, it puts the part of the date.  In these situations I have to write the rest of the date manually.  Here is a solution, so that I can press Super+d and the suffix of today's date is written in the buffer.  For example, if point is after "2019", when I press Super+d it becomes "2019-03-09".

(defun make-suffix (word1 word2)
  (cl-labels ((is-prefix (prefix list)
                         (cond ((null prefix) t)
                               ((null list) nil)
                               ((equal (car prefix) (car list))
                                (is-prefix (cdr prefix) (cdr list)))
                               (t nil)))
              (delete-x-elements (x list)
                                 (cond ((= x 0) list)
                                       ((null list) list)
                                       (t (delete-x-elements (- x 1)
                                                             (cdr list)))))
              (make-suffix-rec (l1 l2)
                               (cond ((null l1) l2)
                                     ((is-prefix l1 l2)
                                      (delete-x-elements (length l1) l2))
                                     (t (make-suffix-rec (cdr l1) l2)))))
    (concat (make-suffix-rec (string-to-list word1) (string-to-list word2)))))
(global-set-key (kbd "s-d")
                (lambda ()
                  (interactive)
                  (let ((cw (current-word))
                        (ds (format-time-string "%Y-%m-%d")))
                          (insert (make-suffix cw ds)))))

So what do you think?  Is it a good solution?  Is it the right way to use elisp and Emacs?


texts: Service Locator with Lazy Loading in Swift

texts:
I am experimenting with the ServiceLocator pattern. I'd like to support lazy loading of items.

protocol Resolver {
  func resolve<T> () -> T
}

protocol Register {
  func register<T>(instance: T)
  func register<T>(reference: @escaping () -> T)
}

final class LazyServiceLocator {

  enum ObjectRegistry {
    case instance(Any)
    case reference(() -> Any)

    func unwrap() -> Any {
      switch self {
      case let .instance(instance): return instance
      case let .reference(reference): return reference()
      }
    }
  }

  private lazy var store: Dictionary<ObjectIdentifier, ObjectRegistry> = [:]
}

extension LazyServiceLocator: Resolver {
  func resolve<T>() -> T {
    let key = ObjectIdentifier(type(of: T.self))
    if let item = store[key], let instance = item.unwrap() as? T {
      switch item {
      case .reference: register(instance: instance)
      default: break
      }
      return instance
    } else {
      preconditionFailure("Could not resolve service for \(type(of: T.self))")
    }
  }
}

extension LazyServiceLocator: Register {

  func register<T>(instance: T) {
    let key = ObjectIdentifier(type(of: T.self))
    store[key] = .instance(instance)
  }

  func register<T>(reference: @escaping () -> T) {
    let key = ObjectIdentifier(type(of: T.self))
    store[key] = .reference(reference)
  }
}

This can run with the following in a playground

let foo = LazyServiceLocator()

class Test {
  init() {
    print("Test")
  }
}

class OtherTest {
  init(foo: Test) {
    print("OtherTest")
  }
}

foo.register(instance: Test())
foo.register(reference: {
  return OtherTest(foo: foo.resolve())
})

let bar: Test = foo.resolve()
let boo: OtherTest = foo.resolve()

Commenting out let bar: Test = foo.resolve() still runs the print statement in it's init method, so I can see that works.

Commenting out let boo: OtherTest = foo.resolve() does not run the print statement, so I believe this also works.

I am very new to the pattern and Swift, so would appreciate some feedback on where this can be improved or what I have missed, being new to the language.


texts: Typewriter animation, implemented using recursive asynchronous function

texts:
In this animation, I am wondering if it's a good idea using async/await with recursive calls and the effect may be caused to the javascript event loop.

Core function:

const wait = (ms) => new Promise(r => setTimeout(r, ms));

async function typeWriter(text, n, elementId, waitAfter) {
    const el = document.getElementById(elementId);
    if (n < text.length) {
        requestAnimationFrame(() => {
            el.innerHTML = (text.substring(0, n + 1));
        }
        n++;
        await wait(waitAfter) //wait after letter stroke
        await typeWriter(text, n, elementId, waitAfter) //recursion till text finish
    }
}

Full code

https://github.com/Microsmsm/microsmsm.github.io/blob/master/js/typewriter.js

Result:

https://microsmsm.com/


texts: Script to convert Shift + Spacebar into four spaces on SE

texts:
I've posted this feature request and would like to improve the code involved to handle a few "bugs" (not that it's necessary to provide such code, just for my own practice), but I doubt I'm doing it as efficiently as possible with my updated conditions for the feature:

$("textarea").keydown(function (e) {
    if (e.shiftKey && e.keyCode == 32) {
        var white = " ",
            pad = "    ",
            t = this.value,
            n = this.selectionStart,
            s = this.scrollTop,
            r = [t.slice(0, n), t.slice(n)];
        if (r[0].indexOf(white, r[0].length - 1) !== -1) {
            this.value = r.join(pad);
            this.selectionStart = this.selectionEnd = n + pad.length;
            this.scrollTop = s;
            e.preventDefault();
        }
    }
});

Purpose:

Most importantly, Shift + Spacebar creates 4 spaces, cancelling the default space action.
Also to avoid accidental usage, it should not execute unless the character before the cursor is a space, or empty. (Avoids "XML is..." becoming "XML    is..."). I couldn't figure out how to check for either whitespace OR a new line, so if someone could mention how that's done, it would be helpful, but if not I can always ask on SO.
To avoid a (reported) potential bug:

  the scrollTop property of long textareas must be involved because re-setting the .value to insert the tab can cause a scroll [in some browsers]

Review

I'm looking for general improvements, best practices, shortening opportunities, simplification, etc. I'd particularly like to learn a better method / trick for figuring out if the previous character doesn't contain a non-space character rather than checking for either nothing or a space.


texts:
I have the following code, comparing two lists that contains equally structured tuples:
list_one = [('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aaa','bbb'), ('id_04','aab','bbc')]
list_two = [('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aad','bbd')]

for tupl in list_one:
    for tup in list_two:
        if tupl[0] == tup[0] and (tupl[1] != tup[1] or tupl[2] != tup[2]):
                print("There is a difference on "+
                      "{} between the two lists".format(tup[0]))

this code would print
There is a difference on id_03 between the two lists
which is the expected result.
But I wonder if there is a better way to achieve the same result, maybe whitout iterating through list_two for every item of list_one, but any suggestion will be appreciated.


texts:
I wrote a program sometime ago that reads csv files, sorts, reorders and groups their columns/rows' content (with itertools) and later labels the groups using a dictionary. The groups and dictionary are then flattened and rows of length N (columns) are uploaded to a spreadsheet. This is another function, not specific to that program, to use in this situation.

def digfrom(iterable, *, depth=None, strings=True):
    """
    Dig values from nested iterables, flattening
    the input iterable.

        >>> iterable = [['a'], 'bc', ('de', ['f'])]

        >>> list(digfrom(iterable))
        ['a', 'b', 'c', 'd', 'e', 'f']

    Depth may be limited and "exploding" strings
    is optional.

        >>> list(digfrom(iterable, depth=2))
        ['a', 'b', 'c']

        >>> list(digfrom(iterable, strings=False))
        ['a', 'bc', 'de', 'f']

    """

    exhausted = object()
    iterable_attr = '__iter__'
    iterator_attr = '__next__'

    iterators = [iter(iterable)]

    while iterators:
        it = next(iterators[-1], exhausted)

        if it is exhausted:
            iterators.pop()
            continue

        if hasattr(it, iterable_attr):
            string = isinstance(it, str)

            if not ((string and len(it) <= 1) or
                    (string and not strings)):
                it = iter(it)

        if hasattr(it, iterator_attr):
            iterators.append(it)
            iterators = iterators[:depth]
        else:
            yield it


texts: RSpec test for handling known IP addresses

texts:
I want to replace the array of ips with a method (like known_ips or just ips) but I don't know how.

I'll use this known_ips somewhere else.

describe WelcomeController, type: :controller do
  [
    {
      ip: '73.53.61.23',
      location_name: 'Seattle, Washington, US'
    }, {
      ip: '8.26.157.16',
      location_name: 'San Francisco, California, US'
    }, {
      ip: '174.112.13.21',
      location_name: 'Mississauga, Ontario, CA'
    }
  ].each do |params|
    it 'geolocalizes the visitor based on the ip' do
      allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return params[:ip]
      get :index
      expect(controller.current_location.name).to eq params[:location_name]
    end
  end
end


texts: Adding two big integers represented as strings

texts:
class MyClass{
    static Integer carry = 0;
    public static void main(String args[]){
        String s1 = "7654729850328997631007285998163550104";
        String s2 = "5980139243970186632651869926335829102";
        add(s1, s2);
    }

    public static void add(String a, String b){
        ArrayList<String> res = new ArrayList<String>();
        StringBuilder myString = null;
        int i = a.length() - 1;
        int j = b.length() - 1;
        while(true){
            int i1 = Integer.parseInt(Character.toString(a.charAt(i)));
            int i2 = Integer.parseInt(Character.toString(b.charAt(j)));
            Integer i3  = i1 + i2 + carry;
            if(i3 > 9){
                carry = 1;
                i3 = i3 - 10;
            }else carry = 0;
            res.add(i3.toString());
            i--;j--;
            if(i < 0){
                res.add(carry.toString());
                break;
            }
        }
        Collections.reverse(res);
        for(String r : res){
            System.out.print(r);
        }
    }
}

This program adds 2 numbers whose length is greater than limit of Long. I think my logic is kind of bulky.  Can something be done to improve this?


texts:
Im creating a class that has all of my data in and can see it would quickly become messy.

I feel that there must be a way of making it neater rather than making a new method each time

For example. I have a character that out of the huge skill list each with different values for different things, they just have 1h weapon and shield. I declare this by

Character character = new Character();
character.Skills.Add(Skill.OneHanded());
character.Skills.Add(Skill.Shield());

it also makes it fairly easy if they level up and learn a new skill as i can just do

character.Skills.Add(Skill.Polearm());

however currently my Skill class looks like a mess. (note that there will be many more skills (about 30 in total) and each one will have more attributes such as applicable weapons, level requirements etc, but not currently coded.

public class Skill
{
    public string Description { get; set; }
    public bool Advanced{ get; set; }
    public int PointsToLearn{ get; set; }

    public static Skill OneHanded()
    {
        return new Skill
        {
            Description = "Skill needed for the use of one handed weapons",
            Advanced = false,
            PointsToLearn= 1
        };
    }
    public static Skill TwoHanded()
    {
        return new Skill
        {
            Description = "Skill needed for use of two handed weapons.",
            Advanced= false,
            PointsToLearn = 2
        };
    }
    public static Skill Polearm()
    {
        return new Skill
        {
            Description = "Skill needed for use of polearms",
            Advanced = false,
            PointsToLearn = 3
        };
    }
    public static Skill Shield()
    {
        return new Skill
        {
            Description = "Skill needed to use shields",
            Advanced = false,
            PointsToLearn = 1
        };
    }
    public static Skill ResistMagic()
    {
        return new Skill
        {
            Description = "Negates the first spell cast at the character",
            Advanced = true,
            PointsToLearn = 0
        };
    }
}

As requested the Character class is

class Character
    {
        public List<Skill> Skills = new List<Skill>();
        public int Level { get; set; }
        public string Name { get; set; }
        public int Command { get; set; }
        public int Coordination { get; set; }
        public int Reflex { get; set; }

    }

There are many characters (i guess think fire emblem if you have ever played that) each one can be skilled and levelled (and die) independently . The class is mostly to keep a record of all characters that have joined the players mercenary company, with their current skills, attributes, level etc etc.

It will called when ever a new character joins the company and added to a character list and then remain in the list ready to be called with the attributes of the character when needing to know information about them.

is there a way to simply this? I also got advised I could do

public class Skill
{
    public enum Skills{ OneHanded,TwoHanded,Polearm,Shield};
}

which opens up using Skill.Skills."Skill" but I'm not sure how I would set the data against each of the options.


texts:
I need to save nested data to disk for a project. Right now, my state is a nested record, and has proven to be a pain to serialize. I tried compressing it to a map, but after testing it, I realized my code failed in a unfortunate corner case that proved it to impractical. I decided to take the suggestion to drop using records altogether since I don't need the speed, but found it annoying to write ->-ish pseudo-constructors for everything I needed to represent. I decided to write a macro that takes a vector of keyword fields, and emits a defn that creates an map with the field names mapped to the arguments of the function:

(defmap Hello [:one :two :three])
(->Hello 1 2 3)

{:one 1, :two 2, :three 3}

I decided for the macro to take keywords as arguments so they're introduced to IntelliJ. defrecord doesn't give any hints, so the first time you use a record's fields, they aren't suggested by IntelliJ.

Unfortunately, IntelliJ complains about Hello not existing, and doesn't recognize ->Hello as a declared function, so this isn't very nice to use, but it was a fun little sidetrack. I don't know if I'll actually use it, but it's the most complicated macro I think I've ever written, and I'd like it reviewed.

I'd like to know if I'm doing anything roundabout or overly complicated. I'd also like to know if there's a way to hint to IntelliJ that Hello doesn't need to be defined, and that ->Hello does.

(defmacro defmap
  "Generates a defn that creates a function with the name (str \"->\" map-name) that
    returns a map. The map will have keys of fields, with the values of the arguments passed to the function."
  [map-name fields]
  (let [adjusted-name# (str "->" map-name)
        args# (mapv (comp symbol name)  fields)
        body-map# (into {} (map #(do [% (symbol %2)]) fields args#))]

    `(defn ~(symbol adjusted-name#) ~args# ~body-map#)))


texts: Gson to Model containing several return types for one key

texts:
i just had a problem converting the JSON from Phillips Hue Lights (Response) to a Model. Since it may contain several "unknown" keys in success and/or may contain just a String for success i had to write/use a TypeAdapter and a deserializer aswell. This works but im pretty sure there is a better way to solve this.

Dummy JSONS:

[{"success":{"/config/name":"My bridge"}}]

and

[{
    "success":{"id": "3"}
}]

and

[
{"success":{ "address": "/groups/1/action/on", "value": true}},
{"success":{ "address": "/groups/1/action/effect", "value":"colorloop"}},
{"success":{ "address": "/groups/1/action/hue", "value":6000}}
]

And the JSON with just a String

[{
    "success": "/config/whitelist/1234567890 deleted."
}]

It may also contain "error" but this isnt the problem. Since the object in address is unknown i use a Adapter from https://stackoverflow.com/questions/17627869/simple-way-to-strip-outer-array-of-responses-in-gson which works fine as long as its an Object. Since it may also contain a String i had to create a JsonDeserializer which validates if its a JSONObject and if not, it sets another variable in the Model with the message. It works, but i always have to revalidate if the message or success it set.

This is my JSONDeserializer

public class HueResponseDeserializer implements JsonDeserializer<HueResponse> {
    private final String TAG = HueResponseDeserializer.class.getSimpleName();

    @Override
    public HueResponse deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {

        HueResponse response = new HueResponse();
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject.get("success").isJsonObject()) {
            for (Map.Entry<String, JsonElement> entry : jsonObject.getAsJsonObject("success").entrySet()) {
                response.setSuccess(new HashMap<String, Object>() {{
                    put(entry.getKey(), entry.getValue());
                }});
            }
        } else {
            response.setSuccessMessage(jsonObject.get("success").getAsString());
        }

        if (jsonObject.has("error") && jsonObject.get("error").isJsonObject()) {
            for (Map.Entry<String, JsonElement> entry : jsonObject.getAsJsonObject("error").entrySet()) {
                response.setError(context.deserialize(entry.getValue(), HueResponse.Error.class));
            }
        }
        return response;
    }
}

And my Model

public class HueResponse {

    private Map<String, Object> success;
    private Error error;
    private String successMessage;

    public String getSuccessMessage() {
        return successMessage;
    }

    public void setSuccessMessage(String successMessage) {
        this.successMessage = successMessage;
    }

    public Map<String, Object> getSuccess() {
        return success;
    }

    public Error getError() {
        return error;
    }

    public void setSuccess(Map<String, Object> success) {
        this.success = success;
    }

    public void setError(Error error) {
        this.error = error;
    }

    public static class Error {
        private int type;
        private String address;
        private String description;

        public int getType() {
            return type;
        }

        public String getAddress() {
            return address;
        }

        public String getDescription() {
            return description;
        }

        @Override
        public String toString() {
            return "Type: " + this.type
                    + " Address: " + this.address
                    + " Description: " + this.description;
        }
    }

}


texts: Sending an uptime to a remote server through SSH with the method pxssh

texts:
I have this code that I'm putting into a library script.

The aim of the code is the following:

The method is to connect to a remote server and run uptime on the remote server. The uptime will be displayed on the host machine, to see for how long the server has been running.

The aim in a near future, is to uptime-check several servers and have the results of my program, on the running machine.

I put the the method under a main to not run it when the library is imported.

from pexpect import pxssh
import pexpect

# conn_up is a function for connecting to a remote server and doing an uptime.

def conn_up():
    try:
        s = pxssh.pxssh()
        hostname = '192.168.1.32'
        username = 'pi'
        s.login(hostname, username,ssh_key='/home/miaou/priv_keys')
        s.sendline('uptime')   # run a command
        s.prompt()             # match the prompt
        print(s.before.decode())        # print everything before the prompt.
    except pxssh.ExceptionPxssh as e:
        print("pxssh failed on login.")
        print(e)

if __name__ == '__main__':
    conn_up()

Currently I have only one method, conn_up().

But if I want to create additional methods to broaden the tools available for my administration, should I list them all of them under __name__ == '__main__' or is there a simpler way to call all the future methods all at once?


texts: Calculating Standard Deviation using SQL

texts:
I have been reading a bit about statistics to improve the way I understand data. This is my attempt at calculating Standard Variance using data tables. I solved this simple question:

This is the code I used (I used SEDE to execute it):

CREATE TABLE #Numbers
(
  Number DECIMAL(10,4),
  Variance DECIMAL(10,4)
);
GO
INSERT INTO #Numbers (Number) VALUES
    (23),
    (37),
    (45),
    (49),
    (56),
    (63),
    (63),
    (70),
    (72),
    (82);
GO

DECLARE @Mean DECIMAL(10,4);
SET @Mean = (SELECT SUM (Number) / COUNT(Number) FROM #Numbers);
UPDATE #Numbers
SET Variance = POWER( (@Mean - Number), 2);
DECLARE @StdVariance DECIMAL(10,4);
SET @StdVariance = (SELECT SQRT( SUM(Variance) / COUNT(Number) ) FROM #Numbers);
SELECT
  @Mean AS [Mean],
  @StdVariance AS [Standard Variance];

Output:

(10 row(s) affected)

Mean    Standard Variance
------- -----------------
56.0000 16.8701

(10 row(s) affected)
(1 row(s) affected)

I'm less familiar with SQL Server than other RDBMS, so I want to make sure my use of temp tables and variables is done the "Transact-SQL Way". Is there a cleaner, smarter way to do this?


texts: Macro for rounding with variable precision

texts:
I use the following MY_ROUND macro for rounding:

#define MY_SIGN(inVal) (((inVal)>=0)? 1 : -1)

#define MY_ROUND(inVal,numDig) (((double)(int)((inVal)*pow((double)10,numDig)+MY_SIGN(inVal)*0.5))/pow((double)10,numDig))

Here inVal is the input double to be rounded and numDig is the number of digits (precision) to round for.

Due to the divisions and pow()'s this function is quite slow. Is there any better replacement for this which does not waste that much time?


texts: Get a random event out of a set of mutually exclusive events

texts:
Task:

  Get a random event from a set of collectively exhaustive and mutually
  exclusive events, with this set being represented by a list of tuples
  (name, probability).

  Reminder:

  Collectively exhaustive events means at least one of them must occur.
  Mutually exclusive events means at most 1 of them occurs.
  Collectively exhaustive and mutually exclusive means their probabilities sum up to 1 and only one of them occurs.

Code:

Events definition:

events = [
    ('Win', 0.5),
    ('Loss', 0.3),
    ('Draw', 0.2)
]

Getting the random event:

def get_random_event(events):
    random_number = uniform(0., 1.)
    lower_bound = 0
    for event, prob in events:
        if lower_bound <= random_number <= lower_bound + prob:
            return event
        else:
            lower_bound += prob

Illustration:

0 -- -- Win -- -- 0.5 -- Loss -- 0.8 - Draw - 1

Generate a random number in [0,1] and check where it falls.


texts:
Given two sorted ranges of elements, compute a median of all the elements in O(log(n+m)) time.

This solution contains only one call to std::lower_bound

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

template <typename It1, typename It2>
auto max_end(It1 begin1, It1 end1, It2 begin2, It2 end2) {
    if (begin1 != end1 && begin2 != end2) {
        return std::max(*std::prev(end1), *std::prev(end2));
    }
    if (begin1 != end1) {
        return *std::prev(end1);
    }
    if (begin2 != end2) {
        return *std::prev(end2);
    }
    // both ranges should never be empty
    __builtin_unreachable();
}

template <typename It1, typename It2>
auto min_begin(It1 begin1, It1 end1, It2 begin2, It2 end2) {
    if (begin1 != end1 && begin2 != end2) {
        return std::min(*begin1, *begin2);
    }
    if (begin1 != end1) {
        return *begin1;
    }
    if (begin2 != end2) {
        return *begin2;
    }
    // both ranges should never be empty
    __builtin_unreachable();
}

template<typename RandomAccessIterator1, typename RandomAccessIterator2>
auto median2(RandomAccessIterator1 begin1, RandomAccessIterator1 end1,
              RandomAccessIterator2 begin2, RandomAccessIterator2 end2) {
    static_assert(std::is_same<typename std::iterator_traits<RandomAccessIterator1>::value_type,
                  typename std::iterator_traits<RandomAccessIterator2>::value_type>::value,
                  "Value types of two ranges must be the same");
    ssize_t n1 = std::distance(begin1, end1);
    ssize_t n2 = std::distance(begin2, end2);
    ssize_t mid = (n1 + n2) / 2;
    auto it = std::lower_bound(begin1, end1, 42, [&](const auto & item, int){
        ssize_t i1 = &item - &*begin1;
        ssize_t i2 = mid - i1;
        // make sure i2 is a valid index
        if (i2 < 0) {return false;}
        if (i2 > n2) {return true;}

        return max_end(begin1, begin1+i1, begin2, begin2+i2)
                >= min_begin(begin1+i1, end1, begin2+i2, end2);
    });

    ssize_t i1 = &*it - &*begin1;
    ssize_t i2 = mid - i1;

    if ((n1 + n2) % 2) {
        return min_begin(begin1+i1, end1, begin2+i2, end2);
    }

    return (max_end(begin1, begin1+i1, begin2, begin2+i2) +
            min_begin(begin1+i1, end1, begin2+i2, end2)) / 2;
}

template<typename Rng1, typename Rng2>
auto median2(Rng1 &&rng1, Rng2 &&rng2) {
    using std::begin;
    using std::end;
    return median2(begin(rng1), end(rng1), begin(rng2), end(rng2));
}

int main() {
    std::cout << median2(std::vector<float>{1, 2, 3, 4}, std::vector<float>{}) << '\n';
    std::cout << median2(std::vector<float>{}, std::vector<float>{1, 2, 3, 4}) << '\n';
    std::cout << median2(std::vector<float>{1, 2, 3, 4, 5}, std::vector<float>{}) << '\n';
    std::cout << median2(std::vector<float>{}, std::vector<float>{1, 2, 3, 4, 5}) << '\n';
    std::cout << median2(std::vector<float>{1, 2}, std::vector<float>{3}) << '\n';
    std::cout << median2(std::vector<float>{1, 3}, std::vector<float>{2}) << '\n';
    std::cout << median2(std::vector<float>{1, 2, 3, 4, 5}, std::vector<float>{6, 7, 8, 9, 10}) << '\n';
    std::cout << median2(std::vector<float>{1, 2, 3, 4, 5}, std::vector<float>{6, 7, 8, 9}) << '\n';
    std::cout << median2(std::vector<float>{1, 2, 3}, std::vector<float>{6, 7, 8, 9}) << '\n';
}

Live on Coliru

Solution to the same problem in Python on codereview


texts:
I'm attempting to implement an algorithm that finds all subsets that sum to a number n. Here is my attempt so far:

function combos(n, combo, result){
  combo = combo || [];
  result = result || [];

  if(sum(combo) === n) {

    result.push(combo);
    return;
  }

  if(sum(combo) > n) {
    return;
  }

  for(var i = 1; i <=n; i++) {
    var newArr = combo.concat([i]);
    combos(n, newArr, result);
  }

  return result;
}

function sum(array) {
  if(!Array.isArray(array) || array.length === 0){
    return;
  }

  return array.reduce((element, sum) =>{
    return element + sum;
  }, 0);
}

This gives me all combinations. However, there are some redundant solutions. For example.

n = 3 gives [ [ 1, 1, 1 ], [ 1, 2 ], [ 2, 1 ], [ 3 ] ]. When it should be
[ [ 1, 1, 1 ], [ 1, 2 ], [ 3 ] ].

So my problem is I don't know how to jump out of the recursion and not explore the the full breadth of a particular branch. If that makes sense. Any hints would be appreciated.


texts: Repainting real-time data during a modal loop in a Windows dialog

texts:
The following code will start a timer to continue drawing real-time data (that has been pre-buffered, to be swapped in the gui as fast as it can) to the window during repositioning or inside a menu loop.

// State of the application
static bool running = false;
static uint32_t modalmode = 0, modalcount = 0;
static const UINT_PTR TIMER_ID = 1337;
static const UINT TIMER_INTERVAL = 33;

// Window message handling
LRESULT CALLBACK WindowCallback(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) {
    uint32_t curmodalmode = 0;
    switch(msg) {
        case WM_CLOSE: {
            if(running) {
                running = false;
                ::DestroyWindow(wnd);
            }
        }   break;

        case WM_PAINT: {
            PAINTSTRUCT paint;
            HDC dc = ::BeginPaint(wnd, &paint);
            // Buffer swapping / drawing happens here
            ::EndPaint(wnd, &paint);
        }   return ::DefWindowProcW(wnd, msg, wparam, lparam);

            // The following block handles modal modes
            // like resizing, moving or opening a system menu
        case WM_ENTERMENULOOP:
            if(!curmodalmode)
                curmodalmode = 1;
        case WM_ENTERSIZEMOVE: {
            if(!curmodalmode)
                curmodalmode = 2;
            // Reset the counter and start the timer if entering modal mode
            if(!modalmode) {
                modalcount = 0;
                if(0 == ::SetTimer(wnd, TIMER_ID, TIMER_INTERVAL, nullptr))
                    assert(false);
            }
            modalmode |= curmodalmode;
        }   break;
        case WM_TIMER: {
            ++modalcount;
            // Repaint
            ::SendMessageW(wnd, WM_PAINT, 0, 0);
        }   break;
        case WM_EXITMENULOOP:
            if(!curmodalmode)
                curmodalmode = 1;
        case WM_EXITSIZEMOVE: {
            if(!curmodalmode)
                curmodalmode = 2;
            modalmode &= ~curmodalmode;
            // Kill timer if leaving modal mode
            if(!modalmode)
                if(!::KillTimer(wnd, TIMER_ID))
                    assert(false);
        }   break;
            // End of the modal mode handling

        default: {
        }   return ::DefWindowProcW(wnd, msg, wparam, lparam);
    }

    return S_OK;
}

I specifically want to know if it's a good idea to Send instead of Post the WM_PAINT message to redraw the window, or if there are better, more idiomatic approaches in the Windows API to drawing in real-time during a modal message pump.

I can live with a fixed, lower frame rate (here around 33ms per frame) during a modal loop, since the user is probably occupied with positioning the window or reading through the menu. I can imagine changing the frame rate dynamically according to the cost of handling the GUI interactions, but that's not my concern right now.
Posting the message on the simulation side (pre-buffering) would introduce additional synchronisation (or alternatively flood the message buffer) that I want to avoid: predictable update-times is one of the first goals on the simulation side, the visual update time is secondary.


texts: UnitOfWork without repository and transaction

texts:
I've created the unitofwork class
below:

 public class UnitOfWork : IUnitOfWork
  {
    private AppDbContext _context { get; set; }
    private IDbTransaction _transaction { get; set; }
    private ObjectContext _objectContext { get; set; }
    private bool _isDisposed;
    public UnitOfWork(AppDbContext context)
    {
      _context = context;
    }
    public DbSet<T> Set<T>() where T : class
    {
      return _context.Set<T>();
    }
    public DbEntityEntry<T> Entry<T>(T entity) where T : class
    {
      return _context.Entry(entity);
    }
    public void Begin()
    {
      _objectContext = ((IObjectContextAdapter)_context).ObjectContext;

      if (_objectContext.Connection.State != ConnectionState.Open)
      {
        _objectContext.Connection.Open();
        if(_transaction != null)
        {
          _transaction.Dispose();
        }
        _transaction = _objectContext.Connection.BeginTransaction();
      }
    }
    public void AutoDetectChangesEnabled(bool option)
    {
      _context.Configuration.AutoDetectChangesEnabled = option;
    }
    public void LazyLoadingEnabled(bool option)
    {
      _context.Configuration.LazyLoadingEnabled = option;
    }

    public void SaveChanges()
    {
      _context.SaveChanges();
    }
    public Task SaveChangesAsync()
    {
      return _context.SaveChangesAsync();
    }
    public void Commit()
    {
      _transaction.Commit();
    }
    public void Rollback()
    {
      _transaction.Rollback();
      foreach (var entry in _context.ChangeTracker.Entries())
      {
        switch (entry.State)
        {
          case System.Data.Entity.EntityState.Modified:
            entry.State = System.Data.Entity.EntityState.Unchanged;
            break;
          case System.Data.Entity.EntityState.Added:
            entry.State = System.Data.Entity.EntityState.Detached;
            break;
          case System.Data.Entity.EntityState.Deleted:
            entry.State = System.Data.Entity.EntityState.Unchanged;
            break;
        }
      }
    }
    public void Dispose()
    {
      if (!_isDisposed)
      {
        if (_context != null)
        {
          _context.Database.Connection.Close();
          _context.Dispose();
          _context = null;
        }
        if(_transaction != null)
        {
          _transaction.Dispose();
          _transaction = null;
        }
        _isDisposed = true;
      }
    }
  }
}

usage

without transaction

_unitOfWork.Set<User>().Add(MyModel);

with transaction

_unitOfWork.Begin();
try {
   _unitOfWork.Set<User>().Add(MyModel);
   _unitOfWork.SaveChanges();
   _unitOfWork.Commit();
}
catch {
   _unitOfWork.Rollback();
}

I must close the transaction in dispose?
How can I improve this code?

Observation: I'm use DI with IUnitOfWork, use AutoFac


texts:
I'm trying to change the background color of each .achievement div. The content is being generated dynamically so I can't add a class easily to each one.

I have it working with selectors like .achievements .grid-row:nth-child(odd) .col-1-2:nth-child(even) .achievement but they seem a little bloated. The problem I'm having is that the .achievement div is nested a few deep so I can't just use an :nth-child or :nth-of-type on it.

I'm just checking to see if there is a better way to select those that I'm missing out on.

jsFiddle

HTML

Testing...

Testing...

Testing...

Testing...

CSS

.achievements .grid-row:nth-child(odd) .col-1-2:nth-child(even) .achievement {
    background: #5891bc;
}

.achievements .grid-row:nth-child(even) .col-1-2:nth-child(odd) .achievement {
    background: #96c3e6;
    color: #585858;
}

.achievements .grid-row:nth-child(even) .col-1-2:nth-child(even) .achievement {
    background: #d3dfe7;
    color: #585858;
}


texts:
I am new to Groovy and I am having a little problem with constructors of subclasses. Basically, I have a base abstract class like

class BaseClass {
  def BaseClass(Map options) {
    // Does something with options,
    // mainly initialization.
  }
  // More methods
}

and a bunch of derived classes like

class AnotherClass extends BaseClass {
  // Does stuff
}

I would like to be able to create instances like

def someObject = new AnotherClass(foo: 1, bar: 2)

Unfortunately, Groovy creates automatically all sorts of constructors for AnotherClass, with various signatures - based on the properties of AnotherClass - but will not allow me to just reuse the constructor in BaseClass. I have to manually create one like

class AnotherClass extends BaseClass {
  def AnotherClass(options) {
    super(options)
  }
  // Does stuff
}

It feels repetitive doing so for each subclass, and it is probably the wrong way.

What would be the Groovy way to share some logic in the constructor?


texts: Serializing and deserializing objects in Java

texts:
I have a class that receives an Object object as a parameter. Then, I want to write two functions to serialize, and deserialize the given object respectively.

public class ObjectWrapper implements Serializable {

    private static final long serialVersionUID = 1L;
    private byte[] bytes;
    private Object object;

    public ObjectWrapper(Object object) {
        this.object = object;
    }

    public ObjectWrapper setObject() throws NotSerializableException {
        try {
            return serialize();
        } catch (NotSerializableException e) {
            throw new NotSerializableException("Error setting object");
        }
    }

    public Object getObject()
            throws NotSerializableException, ClassNotFoundException {
        try {
           return deserialize();
        } catch (NotSerializableException e) {
            throw new NotSerializableException("Error getting object");
        } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException();
        }
    }

    private ObjectWrapper serialize()
            throws NotSerializableException {

        try {

            ObjectOutput out = null;

            // Serialize data object to a byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bos);
            out.writeObject(object);

            // Get the bytes of the serialized object
            bytes = bos.toByteArray();

            return new ObjectWrapper(new ObjectBytes(bytes));

        } catch (IOException e) {
            throw new NotSerializableException("Error serializing the object!");
        }

    }

    private Object deserialize()
            throws NotSerializableException, ClassNotFoundException {

         try {

            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInput in = null;
            in = new ObjectInputStream(bis);
            Object obj = in.readObject();
            return obj;

        } catch (IOException e) {
            throw new NotSerializableException(
                "Error deserializing the object!");
        }

    }

}

I also needed to write this class, in order to return an object containing only an array of bytes:

public class ObjectBytes implements Serializable{

    private static final long serialVersionUID = 1L;
    private byte[] object_bytes;

    public ObjectBytes(byte[] object_bytes) {
        this.object_bytes = object_bytes;

    }

    public byte[] getObjectBytes() {
        return object_bytes;
    }

}

What I'm struggling with is the whole process of simplifying this code, because for something this simple, I find it a bit odd to have so much code. How can this be shortened?


texts: Removing stray brackets from in between shortcodes

texts:
I was wondering if someone could point me in the right direction for cleaning up this code.

WordPress uses shortcodes in the form [shortcode] to add extended functionality to posts and pages.

What I am trying to do is to return a string with all of the 'stray' brackets, ones not being used by any of shortcodes, as html entities.

What I have to work with are these variables via WordPress:

$shortcode_tags: an array of all shortcodes as strings (without brackets)
get_shortcode_regex(): combines all registered shortcode tags into a single regular expression. (I am not using this in the code below)

function find_stray_brackets ($content) {
// this code repalces all occurences of every shortcode with special brackets.
// It then replaces remaining 'stray' brackets with the HTML character entitiy.

        global shortcode_tags;
        foreach($shortcode_tags as $k=>$item)
        {

            $pattern='/\[('.$k.'.*?(?=\]))\]/';
            $content=preg_replace($pattern,'*{*$1*}*',$content);
            $pattern='/\[\/('.$k.'.*?(?=\]))\]/';
            $content=preg_replace($pattern,'*{*/$1*}*',$content);

        }

        $content=str_replace('[','&#91;',$content);
        $content=str_replace(']','&#93;',$content);
        $content=str_replace('*{*','[',$content);
        $content=str_replace('*}*',']',$content);

    return($content);
}

The approach is to replace all of the brackets that surround shortcodes with special characters-> replace stray brackets with html entities -> re-insert original brackets

My end goal is to put all of the text between short codes (including before the first and after the last shortcode) into an array. I couldn't get the regex that Wordpress produces to do what I wanted, so wrote my own regex that relies on brackets - this is why I need to deal with the strays.

Here is the regex that WordPress outputs and some sample text with nested shortcodes.


texts: Ruby solution to Project Euler Problem #4: Largest palindrome product

texts:
I've solved the Project Euler Problem #4, but I'd like some tips as to how to make this more efficient. I am a beginner to Ruby, so please be nice about the stupid stuffs (but still tell me about it).
Project Euler 4: Largest palindrome product

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
1

class Euler4
  def isPalindrome(n)
    n == n.to_s.reverse.to_i
  end
end

  puts "Setting Variables"
  x = 999
  y = 999

  highest = 1

  found = false

  while (x > 100 && !found)
    y = 999
    while (y > 100 && !found)
      puts "Working with"
      puts x
      puts " and "
      puts y

      if Euler4.new.isPalindrome(x*y)
        puts "Found Palindrome"
        puts x
        puts y
        puts x*y
        if highest < (x*y)
          highest = x * y
        end
      end
      y = y - 1
    end

    x = x - 1

  end

puts "Highest Found"
puts highest


texts: Function that takes an object and a query obj that tries to regexp matches its values

texts:
I have the follow matcher method that should do:

obj = {eins: 'one', zwei: 'two'}
queryA = {eins: 'one'}
queryB = {eins: 'one', zwei: 'deux'}

matcher(obj, queryA) // true
matcher(obj, queryB) // false

const matcher = curryRight(
  (state, query) =>
    flowRight([
      every(Boolean),
      map(
        (val, key) => {
          return  state[key] && state[key].match(new RegExp(val, 'ig'))
        }
      )
    ])(query)
)

Wanted:
Because I plan on using this function, matcher() in filter(), it should take a query and returns a function which can take an object for equality check against that query. My version above does that, the improvement sought is can we extract the

(val, key) => {
  return  state[key] && state[key].match(new RegExp(val, 'ig'))
 }

out so that I can in the future swap it out for some function which returns a boolean value?

Is there any way that the iteratee inside map may be split into two such that state is passed in separately? That way, I can refactor the .match(...) part out as a standalone function.


texts: Avoid using object to hold int, bool, double application setting values

texts:
I have some code to handle integer, double, Boolean, and string settings. Right now, each setting variant extends an abstract class, where the setting value is stored as an object.

Is there any way to avoid this? What I'd like to do is have IntSetting objects return their Value as an integer, DoubleSetting objects return their Value as a double and so on and so forth.

Here is the code referenced above:

public abstract class ModelSetting
{
    public object Value { get; set; }
    public abstract string ToString();

    public ModelSetting(object value)
    {
        Value = value;
    }
}

public class IntSetting : ModelSetting
{
    public IntSetting(int value)
        : base(value)
    {
    }

    public override string ToString()
    {
        return (bool)Value ? "1" : "0";
    }
}

public class DoubleSetting : ModelSetting
{
    public DoubleSetting(double value)
        : base(value)
    {
    }

    public override string ToString()
    {
        return ((double)Value).ToString("%g");
    }
}