texts: Multiple emails and attachments, reusing memory stream

texts:
I am generating a pdf form based on user input from an MVC website form. The pdf is genrated using the Foxit .NET SDK, then attached to three separate emails, generated using Postal. It has been requested that the file not be saved to disk at any stage.

I have not worked a lot with files or MemoryStreams before so would just like to know if my code is following the standard practices for managing memory and performance etc.

MergeDocument document = new MergeDocument(); // The PDF File Object
// ... Populate and create the pdf file

// Generate and Send the emails
// To the user
dynamic useremail = new Email("FormSubmitted");
useremail.To = User.EmailAddress;
useremail.Attach(new Attachment(new MemoryStream(document.Draw()), "OrderForm.pdf"));
useremail.Send();

// To the Vendor
dynamic vendoremail = new Email("FormSubmittedVendor");
vendoremail.To = Vendor.EmailAddress;
vendoremail.Attach(new Attachment(new MemoryStream(document.Draw()), "OrderForm.pdf"));
vendoremail.Send();

// To us
dynamic internalemail = new Email("FormSumbittedUs"); // To: is hardcoded in view.
internalemail.Attach(new Attachment(new MemoryStream(document.Draw()), "OrderForm.pdf"));
internalemail.Send();

Is it ok to create new MemoryStream objects for each email?


texts:
So I am working on writing a discord bot with discord.py.

I decided, rather than making a serie of if/elif, to map the messages to the functions in a dictionnary, like so:

my_dict = { "!trigger": func }

I then wanted to parse this dictionnary into an async for loop, but ran into some problems. To face those problems, I decided to write a dict() subclass, which I called AsyncDict. I just want to know if this is safe to work like this, or not? The main purpose of this little class is to avoid errors like "an async for loop needs an item that defines the function __aiter__"

AsyncDict class:

class AsyncDict(dict):
    def __init__(self, *args, **kwargs):
        super(AsyncDict, self).__init__(*args, **kwargs)

    async def items(self):
        items = super().items()
        for item in items:
            yield item

    async def keys(self):
        keys = super().keys()
        for key in keys:
            yield key

    async def values(self):
        values = super().values()
        for value in values:
            yield

Once this is done, I just create my dictionary "as usual":
calls = AsyncDict([("!ping", ping)])

Here is the relevant code in my main.py:

import discord
import asyncio

async def ping(message):
    await client.send_message(message.channel, 'pong')

calls = AsyncDict([("!ping", ping)])

@client.event
async def on_message(message):
    async for k, v in calls.items():
        if message.content.startswith(k):
            await v(message)

I just want to know if it's "safe" to work like this (cf.: AsyncDict)? I'm quite new to asynchronous development and I don't know if I'm missing something.


texts:
This is a challenge I found here. You're suppose to list how many steps it takes to convert a number to a palindromic number, where each step consists of adding number to the reverse of itself. For example, 196196871 takes 151 steps and gives me 3588816724276188853.

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

public class Main {

    private Scanner in = new Scanner(System.in);

    public Main() {
        String input = in.nextLine();
        ArrayList< Long > targets = new ArrayList< Long >();

        // Checks if the ENTER key was pressed. ENTER is the exit key of this program.
        while(!input.equals(""))
        {
            targets.add(Long.parseLong(input));
            input = in.nextLine();
        }

        for(long target : targets)
            System.out.println(target + " gets palindromic after " + getPalSteps(target) + " steps: " + convertToPal(target));
    }

    public long reverse(long number) {
        long reverse = 0;
        long n = number;
        while (n != 0)
        {
            reverse *= 10;
            reverse = reverse + n % 10;
            n /= 10;
        }
        return reverse;
    }

    public boolean palindrome(long number) {
        return reverse(number) == number;
    }

    public long convertToPal(long number) {
        if (number == 196)
            return -1;

        while (!palindrome(number))
        {
            number = reverse(number) + number;
        }

        return number;
    }

    public long getPalSteps(long number) {
        int steps = 0;

        if (number == 196)
            return -1;

        while (!palindrome(number))
        {
            number = reverse(number) + number;
            steps++;
        }

        if(steps > 10000)
            System.out.println("Lychrel number!");

        return steps;
    }

    public static void main(String[] args) {
        new Main();
    }

}


texts: Refactor two methods with similar logic but handling different entities

texts:
We have three methods, the first calls the second one. How would you refactor so the third one can call the second one too as they have similar code?
public async Task UnpublishPersonAsync(string id)
{
    await QueueAndUpdateStatusAsync(id, PersonStatus.Unpublishing, QueueNames.Unpublish);
}

private async Task QueueAndUpdateStatusAsync(string id, PersonStatus status, string queueName)
{
    var personDto = await _cosmosDbService.GetItemAsync<PersonDto>(id, id);
    var operationIsValid = ValidateOperation(status, personDto);

    if (operationIsValid)
    {
        personDto.Status = status;
        personDto = await _cosmosDbService.UpdateItemAsync(id, id, personDto);
        var person = _mappingService.MapToPerson(personDto);

        await _queue.PublishToStorageQueueAsync(person, queueName);
    }
    else
    {
        throw new InvalidOperationException();
    }
}

public async Task DeletePersonAsync(string id, bool deleteAssociatedData)
{
    var personDto = await _cosmosDbService.GetItemAsync<PersonDto>(id, id);
    var operationIsValid = ValidateOperation(PersonStatus.Deleting, personDto);

    if (operationIsValid)
    {
        personDto.Status = PersonStatus.Deleting;
        personDto = await _cosmosDbService.UpdateItemAsync(id, id, personDto);
        var person = _mappingService.MapToPerson(personDto);

        var deleteCommand = new DeletePersonCommand()
        {
            Person = person,
            DeleteAssociatedData = deleteAssociatedData
        };

        await _queue.PublishToStorageQueueAsync(deleteCommand, QueueNames.Delete);
    }
    else
    {
        throw new InvalidOperationException();
    }
}

I thought about using generics and make it optional, but it seems that's not possible. By the way, PublishToStorageQueueAsync is already generic for the first argument.


texts:
Here is my memcpy algorithm I've been working on:
static void* memcpy(void* destination, const void* source, size_t size) {
        char* dest = (char*)destination;
        const char* src = (const char*)source;

        //check if length is greater than 16 bytes
        if ((size - 16) < 33) {
            while (size > 15) {
                //wtf even is this, assembly in c++? am i a assembly developer too now?
                auto val = _mm_loadu_si128((__m128i*)(src));
                _mm_storeu_si128((__m128i*)dest, val);
                dest += 16;
                src += 16;
                size -= 16;
            }
        }
#ifdef __AVX512__
        else if((size - 32) < 65){
            while (size > 31) {
                //wtf even is this, assembly in c++? am i a assembly developer too now?
                auto val = _mm256_loadu_si256((__m256i*)(src));
                _mm256_storeu_si256((__m256i*)dest, val);
                dest += 32;
                src += 32;
                size -= 32;
            }
        }
        else if(size > 65 ) {
            while (size > 31) {
                //wtf even is this, assembly in c++? am i a assembly developer too now?
                auto val = _mm512_loadu_si512((__m512i*)(src));
                _mm512_storeu_si512((__m512i*)dest, val);
                dest += 32;
                src += 32;
                size -= 32;
            }
        }
#else
        else if (size > 32) {
            while (size > 31) {
                //wtf even is this, assembly in c++? am i a assembly developer too now?
                auto val = _mm256_loadu_si256((__m256i*)(src));
                _mm256_storeu_si256((__m256i*)dest, val);
                dest += 32;
                src += 32;
                size -= 32;
            }
        }

#endif

        while (size--) {
            *dest++ = *src++;
        }

        /*if (length > 16) {
            src += length - 16;
            dest += length - 16;
            auto val = _mm_loadu_si128((__m128i*)(src));
            _mm_storeu_si128((__m128i*)(dest), val);
        }
        else {
            for (; index < length; ++index) {
                *dest++ = *src++;
            }
        }*/

        return destination;
    }

I don't think my cpu supports AVX 512 so I disabled it for now. I'm trying to get this algorithm as close to std::memcpy as I can, but I'm not there just yet. Any ideas on how I can make this faster?
Here are the times I tested with 999,999 iterations and averaged the result:
Copying 1361 bytes:

Mine ms: 0.000233
C++ STL ms: 0.000230

As you can see they are really close, but I know I can make it faster.


texts: Compare Collection with the information in DB using EF and LINQ

texts:
I want to inform the Receivers about new contracts we have this week. After I sent the Emails, the Information about sent contracts are stored in MS SQL Database.

To avoid that someone become the same Email about contract more than one time I perform this steps:

I have the Collection with new contracts as the input
I read the information from DB using Entity Framework about sent Emails
If the Emails was already sent I add new Instance to the sent Emails Collection

After that, I remove the contracts from input collection that are already in sent collection:

public Collection<Contract> GiveContractsThatWereNotSent(Collection<Contract> newThisWeekContracts)
{
   var contractsWereSent = new Collection<Contract>();

   using (var accountingEntities = new AccountingEntities())
   {
      foreach (Contract newContract in newThisWeekContracts)
      {
         bool found = (from sent in accountingEntities .Tbl_SentProtocol
                       where
                          sent.CONTRACT_NO == newContract.ContractNo
                          && sent.CONTRACT_NO_ALT == newContract.ContractNoAlt
                        select sent ).Any();

         if (found)
         {
            contractsWereSent.Add(newContract);
         }
      }
   }

   foreach (Contract contract in contractsWereSent)
   {
      newThisWeekContracts.Remove(contract);
   }

   return newThisWeekContracts;
}


texts:
I have an array that I am shifting by a certain number of spaces.  I am wondering if there is an better way to do the shift with less touches.  Here is my code

function rotate_array(array, shift){

    if(array.length -1 <= shift){
        shift %= array.length;
    }
    for(var i =0; i < shift; i++){
        var first = array[0];
        for(var j =0; j < array.length -1 ;j++){
            array[j] = array[j+1]
        }
        array[array.length - 1]  = first
    }
}

 var array = [4,2,1,3,5];
 rotate_array(array, 22);

  for(var i =0; i < array.length; i++){
    console.log(array[i])
 };


texts: select_best: yet another partitioning algorithm

texts:
The title is somewhat a misnomer; my apologies. The goal of the procedure is to partition a range of first, last by mid for the postcondition

max(first, mid) <= min(mid, last)

The actual code (best_n.h):

#include <algorithm>
#include <iterator>

#if !defined(BidirectionalIterator)
#define BidirectionalIterator typename
#endif

template <BidirectionalIterator I>
void select_best(I first, I mid, I last) {
    using T = typename I::value_type;
    while (first != mid) {
        T pivot = *first;
        I pp = std::partition(first, last, [pivot](T elt) { return elt < pivot; });
        if (pp == first) std::advance(pp, 1);
        if (std::distance(first, pp) > std::distance(first, mid)) last = pp;
        else                                                      first = pp;
    }
}

Works fine if I didn't mistype anything.

Questions:

Seeking overall improvements.
What is a right name?
Currently void. Is there anything useful to return?
I don't like passing lambda to std::partition. Any suggestions to avoid it?
A performance is weird. Regardless of a pivot selection strategy, an execution time stays pretty much constant as a function of mid. Obviously outperforms std::partial_sort for somewhat sizable initial ranges, but loses badly for short ones. Any suggestions?

PS: I have benchmarks if anybody's interested.

PPS: I am well aware of the beautiful best 2 Stepanov's approach. Challenging everybody to generalize it.


texts:
I have a has_many through relationship between my cities and travels that looks like this:

class Travel < ActiveRecord::Base
  has_many :cities, through: :destinations
end
class City < ActiveRecord::Base
  has_many :travels, through: :destinations
end

And on my Travel controller I have a method to join all its cities names:

  def city_names
    self.cities.map { |e| e.name }.join(', ')
  end

I installed the bullet gem and it tells me that this is a n+1 query and suggests that I add the includes method on the query, but as far as I can tell this method will only work if I call it directly on the Travel class.


texts: Project Euler #357: Prime generating integers

texts:
Project Euler Problem 357 asks:

  Consider the divisors of 30: 1,2,3,5,6,10,15,30.
  It can be seen that for every divisor d of 30, $$d+30/d$$ is prime.

  Find the sum of all positive integers n not exceeding 100 000 000
  such that for every divisor d of n, $$d+n/d$$ is prime.

import time
start = time.time()

import math

def divisor_generator(n):
    '''Generates the divisiors of input num'''
    large_divisors = []
    for i in range(1, int(math.sqrt(n) + 1)):
        if n % i == 0:
            yield i
            if i*i != n:
                large_divisors.append(n / i)
    for divisor in reversed(large_divisors):
        yield divisor

def is_prime(n):
    '''simple prime tester'''
    if n == 2 or n == 3 :
        return True
    for i in range(2,int(n**(1/2))+1):
        if n % i == 0:
            return False
    return True

def test_condition (divisor_array, num):

    ''' Testing the condition of d+n/d by taking the input as array of divisor and num'''

    if len(divisor_array) %2 != 0: # the divisors of num = d3 is [1,d2,d3], and d2*d2=d3 hence d2+d3/d2 = 2d2 which is not prime
        return False
    if sum(divisor_array) %2 != 0: # the divisors of num = d4, [1,d2,d3,d4] (1+d4)=Prime and (d2+d3)==Prime hence sum([1,d2,d3,d4]) must be even
        return False
    if len(divisor_array)%2 == 0:
        for i in range(len(divisor_array)//2):
            if is_prime(divisor_array[i] + divisor_array[-i-1]) == False:
                return False
        return True

Count = 0
for num in range(2,31,2): #since for odd num we do not have prime numbers

    divisor_list_num = list(divisor_generator(num))

    if test_condition(divisor_list_num,num) == True:

        Count += num

print(Count)
end = time.time()
print(end-start,"sec")

It's good up to \$\text{num} = 10^6\$ but then it gets slow after that.  I find that at it takes 16 min to find the \$\text{num} < 10^7\$.

How can I inrease the speed of my code ?


texts: Apply stock quote changes using observer pattern

texts:
I am implementing observer pattern(refering codeproject) for stock quote update. I have created an interface for Subject and Observer. I have created instances for Subject and Observer and also the functionality to register, notify and update. Kindly let me know the approach is correct

public  interface IObserver
    {
        void update(double value);
    }
}

//subject

public interface ISubject
    {
         void Register(IObserver o);
         void UnRegister(IObserver o);
         void notify();

    }

//Observer instance

public class InfosysStock : IObserver
    {
        private ISubject _subject;
        private double _latestvalue = 0;
        public InfosysStock(ISubject subject)
        {
            _subject = subject;
            _subject.Register(this);
        }

        public void update(double value)
        {
            _latestvalue = value;
            display();
        }

        private void display()
        {
            Console.WriteLine("The latest value is : " + _latestvalue);
        }

        public void unsubscribe()
        {
            _subject.UnRegister(this);

        }
    }

//Subject Instance

public class StockMarket : ISubject
    {

        List<IObserver> observers = new List<IObserver>();
        public int _stockvalue = 0;

        public void setValue(int v)
        {
            _stockvalue = v;
            notify();
        }

        public void notify()
        {
            foreach (var observer in observers)
            {
                observer.update(_stockvalue);
            }
        }

        public void Register(IObserver o)
        {
            observers.Add(o);
        }

        public void UnRegister(IObserver o)
        {
            int idx = observers.IndexOf(o);

            observers.RemoveAt(idx);

        }

    }

Finally the main class

StockMarket stockmarket = new StockMarket();
InfosysStock infy = new InfosysStock(stockmarket);
stockmarket.setValue(15);
stockmarket.setValue(21);

            infy.unsubscribe();
            Console.ReadLine();


texts: PLZ HELP MEH IMPROVA MEH LOLCAT CODEZ, WHUCH CALCULUTS FAWCTORIALS

texts:
SUNCE MEH BEEN WRUTEN CODEZ IN MUNY DIFFRNT PROGRAMMING LANGUAGES, MEH THOUGHTZ THAT ME TRY TO WRITE CODEZ IN AN ESOTERIC LANGUAGE. MEH CODEZ CALCULUTS A FAWCTORIAL OF UH USR INPUTTED NUMBAH IN LOLCODE, LOL.

SOME OF MEH QUSTIONS:

IZ MEH CODEZS A IDMITIC LOLCAT PROGUM?
IZ THERE A GOODER WAY OF WRUTING MEH factorial FUNCSHUNS?

TRANSLATION:

Since I've been writing and trying programs in many different languages, I thought I'd give esoteric language a crack. So I used LOLCODE to write a program that calculates the  factorial of a user given number:

Questions for consideration:

Is my LOLCODE code idiomatic to the LOLCODE language?
Is there a easier way to write my factorial function?

LOLCAT.lol

BTW Calculates the factorial for a user given integer

BTW Author: Pythonic
BTW Version: 1.0

HAI 1.2
HOW DUZ I factorial YR n
    BOTH SAEM n AN 0, O RLY?
        YA RLY
            FOUND YR 1
        NO WAI
            FOUND YR PRODUKT OF n AN factorial DIFF OF n AN 1
    OIC
IF U SAY SO

HOW DUZ I main
    I HAS A user_input

    VISIBLE "ENTER AN NUMBAH"
    VISIBLE "TO FINDZ ITZ FAWCTORIAL:: "

    GIMMEH user_input

    VISIBLE "DE FAWCTORIAL OF " user_input " IZ:: " factorial user_input
    VISIBLE "KTHXBYE!"
IF U SAY SO

main
KTHXBYE

For those of you who are not fortunate enough to have a LOLCODE compiler, here is a link to a REPL.IT of the code.

NOTE: All answer must be given in proper LOLCODE English, with an optional translation in regular English. Failure to do so will result in me releasing my LOLCATS upon you....


texts: Language switcher, consulting browser's localStorage

texts:
I'm using angular 6 and ngx-translate. This is my switch language function

  switchLanguage(language: string) {
    this.translate.use(language);
    if (language !== 'ar' && document.getElementsByTagName('html')[0].hasAttribute('dir')) {
      document.getElementsByTagName('html')[0].removeAttribute('dir');
    } else if (language === 'ar' && !document.getElementsByTagName('html')[0].hasAttribute('dir')) {
      document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl');
    }
    // if this line worth it?
    if (language !== JSON.parse(localStorage.getItem('lang'))) {
    localStorage.setItem('lang', JSON.stringify(language));
    }
  }

I'm asking about this line in particular

if (language !== JSON.parse(localStorage.getItem('lang')))

If I don't use it, it means that if the language is english and you switch it to english, the localStorage is going to be updated. If I use it however, it means that, every time you switch a language, it's going to read  localstorage to check its value before updating.

Is the cost of just setting the language better than the cost of checking it first?

This method is getting called whenever you switch the language and in app.ts constructor, so basically on every page load. Is there a better way to do it?


texts: Multithreading, shared queue as synchronization point

texts:
I have two threads, one produces images and one processes them. For the synchronization, I created a class where you can set and get images, and it always waits until an image is available or a worker thread is not busy anymore.

Additionally, a call to SetFinish stops both threads, while a call to Clear clears the currently (not yet processed) image.

Do you see any problems with this code (mainly threading issues)?

Header:

#ifndef SHARED_QUEUE_H_
#define SHARED_QUEUE_H_

#include <memory>
#include <condition_variable>

struct ImageData;

class SharedQueue {
public:
  void SetFinish();
  bool GetImage(std::shared_ptr<const ImageData> &image);
  void SetImage(std::shared_ptr<const ImageData> image);
  void Clear();

private:
  std::condition_variable image_available_;
  std::condition_variable image_processed_;
  std::shared_ptr<const ImageData> next_image_;
  bool stop_{false};
  std::mutex mutex_;
};

#endif  // SHARED_QUEUE_H_

Implementation:

#include "shared_queue.h"

void SharedQueue::SetFinish() {
  { // Store flag and wake up the thread
    std::lock_guard<std::mutex> lock(mutex_);
    stop_ = true;
  }
  image_available_.notify_one();
  image_processed_.notify_one();
}

bool SharedQueue::GetImage(std::shared_ptr<const ImageData> &image) {
  {
    std::unique_lock<std::mutex> lock(mutex_);
    image_available_.wait(lock, [this]{
      return (next_image_.get() != nullptr || stop_);
    });

    if (stop_)
      return false;

    image = next_image_;
    next_image_.reset();
  }
  image_processed_.notify_one();
  return true;
}

void SharedQueue::SetImage(std::shared_ptr<const ImageData> image) {
  { // Store image for processing and wake up the thread
    std::unique_lock<std::mutex> lock(mutex_);
    image_processed_.wait(lock, [this]{
      return (next_image_.get() == nullptr || stop_);
    });

    if (stop_)
      return;

    next_image_ = image;
  }
  image_available_.notify_one();
}

void SharedQueue::Clear() {
  {
    std::unique_lock<std::mutex> lock(mutex_);
    next_image_.reset();
  }
  image_processed_.notify_one();
}


texts: Is there any better way to insert and retrieve data into SPList?

texts:
I am using this code to insert and retrieve:

namespace Gridwebpart.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                SPWeb site = SPContext.Current.Web;
                SPList list = site.Lists["GridList"];
                SPListItemCollection items = list.Items;
                DataTable dt = items.GetDataTable();
                Gridnames.DataSource = dt;
                Gridnames.DataBind();

            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SPWeb site = SPContext.Current.Web;
            SPList list = site.Lists["GridList"];
            SPListItemCollection items = list.Items;
            //SPListItem item = list.GetItemById(1);
            SPListItem item = items.Add();
            item["Title"] = txtName.Text;
            item["Description"] = txtDescription.Text;
            item["IS Sharepoint 2010 Developer"] = chkbox.Checked;
            item.Update();
            site.AllowUnsafeUpdates = false;
            txtName.Text = "";
            txtDescription.Text = "";
             chkbox.Checked=false;
             items = list.Items;
             DataTable dt = items.GetDataTable();
             Gridnames.DataSource = dt;
             Gridnames.DataBind();
        }
    }
}


texts: Translating warning codes as messages to be printed

texts:
I am writing an X application with Xlib in C, and this code is for error handling and error printing.

How to make it simpler and clearer without using a large amount of fprintf?

int XB3DS_Warn_Code (int Warn_Code)
{
  switch(Warn_Code)
  {
    case WARN_Failed_To_Connect_To_Display:
      fprintf(stdout, "[  WARNING  ]: Failed to connect to display.\n");
      break;
    case WARN_Width_Or_Height_Is_Unacceptable:
      fprintf(stdout, "[  WARNING  ]: Width or height is unacceptable.\n");
      break;
    case WARN_No_Visual_Is_Matched_For_Screen:
      fprintf(stdout, "[  WARNING  ]: No visual is matched for screen.\n");
      break;
    case WARN_The_Window_Mode_Is_Unacceptable:
      fprintf(stdout, "[  WARNING  ]: The window mode is unacceptable.\n");
      break;
    case WARN_Insufficient_Memory_To_Allocate:
      fprintf(stdout, "[  WARNING  ]: Insufficient memory to allocate.\n");
      break;
  }
  return Warn_Code;
}


texts: Signal simulation through Python scripts using shared memory for testing a C application

texts:
This is bit long, but I need to explain something before I can ask for actual reviews/advice.

I have to test generated C code from Matlab Simulink model. I can create a executable binary from those.  I need to test this application using tests developed using Python scripting.

I came up with following approach: inter-process communication using shared memory.

I planned to write a DLL or a shared object, which enables the communication between the tests scripts and the application.  This DLL will be used via both Python scripts and application to interact with each other

Here's my DLL code, which uses boost::interprocess shared memory.

int create_shmem(const char* shmem_name, long long length  )
{
    try{
       // remove_shmem(shmem_name);
        boost::interprocess::shared_memory_object shm
                          (boost::interprocess::create_only,
                           shmem_name,
                           boost::interprocess::read_write);
      //Set size
      shm.truncate(length);
      return 1;
      }
      catch(...){
        std::cerr << "Error Creating Shared Memory : " << shmem_name << std::endl;
      }
      return 0;
}

int remove_shmem(const char* shmem_name )
{
    try {
        boost::interprocess::shared_memory_object::remove(shmem_name);
        return 1;
    }
    catch(...){
        std::cerr << "Error Removing Shared Memory : "<< shmem_name << std::endl;
    }
    return 0;
}

int write_shmem(const char* shmem_name, char* shmem)
{
      try{
            boost::interprocess::shared_memory_object shm
            (boost::interprocess::open_only, //Open if already created
                 shmem_name,
             boost::interprocess::read_write);

      //Map the whole shared memory in this process
            boost::interprocess::mapped_region region
                (shm,
                boost::interprocess::read_write
                );

            std::memcpy(region.get_address(), shmem, region.get_size());
            return 1;
      }
      catch(...){
         std::cerr << "Error Writing to Shared Memory " << shmem_name << std::endl;
      }
      return 0;
}

int read_shmem( const char* shmem_name, char *shmem )
{
      //Open already created shared memory object.
     // Same process might not be calling it, so create new object
     try{
            boost::interprocess::shared_memory_object shm (
                boost::interprocess::open_only,
                    shmem_name,
                    boost::interprocess::read_only);

      //Map the whole shared memory in this process
            boost::interprocess::mapped_region region
                (shm,
                     boost::interprocess::read_only
                );

      //CAUTION : No check is performed
    std::memcpy(shmem, reinterpret_cast<char*> (region.get_address()),
                       region.get_size());

      return 1;
      }

      catch(...){
      std::cerr << "Error Reading from Shared Memory " << shmem_name << std::endl;
      }

   return 0;
}

The application needs simulation of around 1.5K different signals of different data types all packed in a C struct.

My initial though is to created a shared memory and write the simulated signals on to it which the application can fetch and accordingly shows the output by writing back to same shared memory which is again read from test scripts.

Any help/advice regarding underlying issues/failure and improvement will be much appreciated.

I can post my ctypes Python interface if required.


texts:
I got a 2D grid (n x n matrix). The user selects his player in this 2D grid and after that selects another node in this grid to mark his destination position. The player is allowed to move horizontally, vertically or if the player is standing in one of the 4 corners of this grid also diagonally. Also the player can only reach the selected destination if there are no other nodes in the grid blocking the way.

I need to know whether the player can reach the destination or not. To summarize the following needs to be solved:

  Input:

  Start (row: Int, column: Int)
  Destination (row: Int, column: Int)
  func isValidMove(from: Start, to: Destination) -> Bool

I have a working implementation however I am more than unhappy with the current state. I think there should be a way more declarative and mathematically correct way to achieve that.

This is what I came up with:

private func isValidHorizontal(move: GameMove, board: GameBoard) -> Bool {
    guard let start = move.start else { return false }
    guard start.row == move.end.row else { return false }

    var from: Int = start.column
    var to: Int = move.end.column + 1
    if start.column < move.end.column {
        from += 1
    } else {
        from = move.end.column
        to = start.column
    }

    for column in from..<to {
        if board.tileType(at: GameBoardPosition(row: start.row, column: column)) != .empty {
            return false
        }
    }
    return true
}

private func isValidVertical(move: GameMove, board: GameBoard) -> Bool {
    guard let start = move.start else { return false }
    guard start.column == move.end.column else { return false }

    var from: Int = start.row
    var to: Int = move.end.row + 1
    if start.row < move.end.row {
        from += 1
    } else {
        from = move.end.row
        to = start.row
    }

    for row in from..<to {
        if board.tileType(at: GameBoardPosition(row: row, column: start.column)) != .empty {
            return false
        }
    }

    return true
}

private func isValid(position: GameBoardPosition, on board: GameBoard) -> Bool {
    return position.row >= 0 && position.row <= board.rows - 1 && position.column >= 0 && position.column <= board.columns - 1
}

private func isValidDiagonal(move: GameMove, board: GameBoard) -> Bool {
    guard let start = move.start else { return false }
    var currentPosition = start

    var walkingIncrement: WalkingIncrement!
    if start.row == 0 && start.column == 0 {
        walkingIncrement = WalkingIncrement(dx: 1, dy: 1)
    } else if start.row == 0 && start.column == board.columns - 1 {
        walkingIncrement = WalkingIncrement(dx: -1, dy: 1)
    } else if start.row == board.rows - 1 && start.column == 0 {
        walkingIncrement = WalkingIncrement(dx: 1, dy: -1)
    } else if start.row == board.rows - 1 && start.column == board.columns - 1 {
        walkingIncrement = WalkingIncrement(dx: -1, dy: -1)
    } else {
        return false
    }

    currentPosition = currentPosition.walk(increment: walkingIncrement)
    while(isValid(position: currentPosition, on: board) && currentPosition != move.end) {
        if board.tileType(at: currentPosition) != .empty {
            return false
        }

        currentPosition = currentPosition.walk(increment: walkingIncrement)
    }

    return true
}

Do you have any advice for me to solve this more practical ?

As asked in the comments I provided a sample playground with a self contained example to better understand the problem and to get a compilable example:Playground Gist


texts: Does this class-adding slow page rendering?

texts:
Can you suggest ways of making this more efficient?  I don't want to repeat this example for all of my tags that need a class added, if there is a better way.

$("#menu").find("div:nth-child(2), div:nth-child(3), div:nth-child(4), div:nth-child(5), div:nth-child(6), div:nth-child(7)").addClass("menuDivs");


texts:
I ask if the following code need some refactoring :

public static int InsertBonus(DataTable dt, int month, int year)
{

    int affectedRow = -1;
    using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["xxx"].ToString()))
    {
        using (IfxTransaction tran = con.BeginTransaction())
        {
            try
            {
                StringBuilder cmdTxt = new StringBuilder();

                cmdTxt.Append(" DELETE FROM rh7uiw WHERE bonus_mon = ? AND bonus_year = ? ");
                using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
                {
                    myIfxCmd.CommandType = CommandType.Text;
                    myIfxCmd.Parameters.Add("bonus_mon", IfxType.Integer);
                    myIfxCmd.Parameters.Add("bonus_year", IfxType.Integer);
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    myIfxCmd.Parameters[0].Value = ((object)month) ?? DBNull.Value;
                    myIfxCmd.Parameters[1].Value = ((object)year) ?? DBNull.Value;
                    affectedRow = myIfxCmd.ExecuteNonQuery();
                }

                cmdTxt.Length = 0;
                cmdTxt.Append(" INSERT INTO rh7uiw (emp_num,bonus_year,bonus_mon,bonus_value,bonus_no,rr_code) VALUES(?,?,?,?,?,?) ");

                using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
                {
                    myIfxCmd.CommandType = CommandType.Text;
                    myIfxCmd.Parameters.Add("emp_num", IfxType.Integer);
                    myIfxCmd.Parameters.Add("bonus_year", IfxType.Integer);
                    myIfxCmd.Parameters.Add("bonus_mon", IfxType.Integer);
                    myIfxCmd.Parameters.Add("bonus_value", IfxType.Integer);
                    myIfxCmd.Parameters.Add("bonus_no", IfxType.Integer);
                    myIfxCmd.Parameters.Add("rr_code", IfxType.Integer);
                    foreach (DataRow r in dt.Rows)
                    {
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        myIfxCmd.Parameters[0].Value = (r["emp_num"]) ?? DBNull.Value;
                        myIfxCmd.Parameters[1].Value = (r["year"]) ?? DBNull.Value;
                        myIfxCmd.Parameters[2].Value = (r["month"]) ?? DBNull.Value;
                        myIfxCmd.Parameters[3].Value = (r["bonus_al"]) ?? DBNull.Value;
                        myIfxCmd.Parameters[4].Value = 1;
                        myIfxCmd.Parameters[5].Value = 1;
                        affectedRow = myIfxCmd.ExecuteNonQuery();
                    }
                }
                tran.Commit();
                con.Close();
                con.Dispose();
                return affectedRow;

            }
            catch
            {
                tran.Rollback();
                throw;
            }
        }
    }
}


texts:
So I'm using the event emitter as some sort of an event bus(If I'm allowed to call it that).

The problem I've stumbled upon is that my listeners might want different data than another listener. Since I don't want to add too much and listener specific information where things get emitted. I'm using this solution, but it feels very repetitive and not too clean.

My service function

async function updateUserStatus(userId, action) {
  const [ updatedUser ] = await User.update({ id: userId }, { status: userActions[action] });

  switch (action) {
    case actions.activate:
      UserEventEmitter.emit('user:activated', updatedUser.id);
      break;
    case actions.reject:
      UserEventEmitter.emit('user:rejected', updatedUser.id );
      break;
  }

  return updatedUser;
}

The event dispatcher/configurator

UserEventEmitter.on('user:activated', sendWelcomeMailToUser);
UserEventEmitter.on('user:activated', addActivatedComment);
UserEventEmitter.on('user:rejected', addRejectedComment);

The event listeners/handlers

async function addActivatedComment({ userId }) {
  try {
    await addComment({
      userId,
      translationKey: Enums.TIMELINE_USER_ACTIVATED
    });
  } catch (error) {
    throw new SomeGoodError(error)
  }
}

async function addRejectedComment({ userId }) {
  try {
    await addComment({
      userId,
      translationKey: Enums.TIMELINE_USER_REJECTED
    });
  } catch (error) {
    throw new SomeGoodError(error)
  }
}

function addComment({ supplierSupplierId, translationKey }) {
  return Timeline.create({
    user_id: userId,
    status: translationKey
  });
}

The addRejectedComment and addActivatedComment basically does the same thing with one different property. I don't want to send that property from the service because then my other listeners would get that property too.


texts: Managing user defined and default values for instance attributes

texts:
The following works as expected but I wonder if there is a more idiomatic way to check the input kwargs against the user-required (non-defaulted) arguments.

It is written in this way: so that as I continue to develop and modify my script and add attributes, I simply need to add them to the class variable defaults = {'A':None, 'B':0, 'C':0} and set it to None if the user is required to specify it. I also like that managing this as a class variable is visible at this time.

I've included a modified adaptation from item #6 in this excellent answer that makes sure all of the arguments end up as either floats or np.arrays with all the same length.

If they are: the attributes are set to default or user values and .ok set to True
If not: attributes are not set to defaults or user values and .ok remains False

In this example, a value for A is required of the user. They may enter values for B and C but if not those are initialized to 0.0. Any extra arguments such as D=42 will just be ignored.

import numpy as np

class O(object):
    defaults = {'A':None, 'B':0, 'C':0}
    required = [key for (key, value) in defaults.items() if value == None]
    ok       = False

    def __init__(self, **kwargs):
        if not all([key in kwargs for key in self.required]):
            print('problem, something required is missing')
        setup = self.defaults.copy()
        for (key, value) in kwargs.items():
            if key in setup:
                setup[key] = kwargs[key]  # user specified overrides default
        setup = self.fixem(setup)
        if setup:
            for (key, value) in setup.items():
                setattr(self, key, value)
            self.ok = True
        else:
            print('something did not work')

    def fixem(self, setup):
        # adapted from https://codereview.stackexchange.com/a/233169/145009
        results        = None
        keys, values   = zip(*setup.items())
        arrays         = list(map(np.atleast_1d, values))
        sizes_ok       = len(set(map(np.size, arrays)).difference(set((1,)))) <= 1
        all_1d         = set(map(np.ndim, arrays)) == set((1,))
        all_good_types = all(array.dtype in (np.int64, np.float64) for array in arrays)
        if all([sizes_ok, all_1d, all_good_types]):
            arrays = [array.astype(float) for array in arrays]  # make all arrays np.float64
            values = list(map(lambda x: float(x) if len(x) == 1 else x, arrays)) # downcast length=1 arrays to float
            results = dict(zip(keys, values))
        return results

# TESTING:

attrs = ('A', 'B', 'C')

print('\nBEGIN good seup testing: ')

o = O(A=42)
print("\nEXPECT:[('A', 42.0), ('B', 0.0), ('C', 0.0)]")
print('GOT:  ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])

o = O(A=[1, 2, 3], B=np.exp(1), C=np.array([2, 3, 4]))
print("\nEXPECT:[('A'. array([1., 2., 3.])), ('B', 2.718281828459045), ('C', array([2., 3., 4.]))]")
print('GOT:  ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])

print('\nBEGIN bad seup testing: \n')

o = O(B=42)
print('\nEXPECT:[] (i.e. nothing!)')
print('GOT:  ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])

o = O(A=[1, 2, 3], B=[1, 2, 3, 4])
print('\nEXPECT:[] (i.e. nothing!)')
print('GOT:  ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])

OUTPUT:

BEGIN good seup testing:

EXPECT:[('A', 42.0), ('B', 0.0), ('C', 0.0)]
GOT:   [('A', 42.0), ('B', 0.0), ('C', 0.0)]

EXPECT:[('A'. array([1., 2., 3.])), ('B', 2.718281828459045), ('C', array([2., 3., 4.]))]
GOT:   [('A', array([1., 2., 3.])), ('B', 2.718281828459045), ('C', array([2., 3., 4.]))]

BEGIN bad seup testing:

problem, something required is missing
something did not work

EXPECT:[] (i.e. nothing!)
GOT:   []
something did not work

EXPECT:[] (i.e. nothing!)
GOT:   []


texts:
Please could somebody verify that my method of implementing Smart Pointer is correct, and if there is maybe a more efficient way of achieving it.

#ifndef SHARED_PTR
#define SHARED_PTR

#include <iostream>
#include <mutex>

using namespace std;

template <class T>
class RCObject
{
    T* rawObj;
    unsigned int count;
    mutex m_Mutx;

public:
    RCObject() :rawObj(nullptr), count(0){}

    ~RCObject()
    {
        deref();
    }

    RCObject(T* _rawObj):rawObj(_rawObj)
    {
        count = 0;
    }

    int getCount() const
    {
        return count;
    }

    T* get()
    {
        if (rawObj != nullptr) {
            return rawObj;
        }
        return nullptr;
    }

    void ref()
    {
        m_Mutx.lock();
        count++;
        m_Mutx.unlock();
    }

    void deref()
    {
        m_Mutx.lock();
        count--;
        m_Mutx.unlock();
        if (count == 0)
        {
            delete rawObj;
            count = 0;
        }
    }
};

template <class T>
class SharedPtr
{
    RCObject<T>* m_Rc;
public:
    SharedPtr(T* rawObj)
    {
        m_Rc = new RCObject<T>(rawObj);
        m_Rc->ref();
    }

    ~SharedPtr()
    {
        m_Rc->deref();
    }

    SharedPtr()
    {
        m_Rc = new RCObject<T>();
    }

    SharedPtr(const SharedPtr& rhs)
    {
        m_Rc = rhs.m_Rc;
        m_Rc->ref();
    }

    SharedPtr& operator= (const SharedPtr& rhs) {
        if (this != &rhs) {
            m_Rc->deref();
            m_Rc = rhs.m_Rc;
            m_Rc->ref();
        }
        return *this;
    }

    int getRefCount()
    {
        return m_Rc->getCount();
    }

    T* get() const
    {
        return m_Rc->get();
    }
    T* operator->() {
        return m_Rc->get();
    }
};
#endif


texts: IEnumerable Extensions Linq AllOrDefault() Each()

texts:
I recently decided to try and write my own implementation of Linq, which then lead me on to trying to solve some of the problems we have in our code base at work. Our code is littered with the following (obviously a simplified example):

        var items = new List<string> { "apple", "dog", "chair" };

        if (items != null && items.Any())
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }

Essentially each time we are iterating over a collection we check to make sure the collection is not null and it actually contains at least one item.

I decided to write the following extension methods to alleviate this mess (the ML suffix on the methods was to differentiate from Linq [mostly for testing]):

        public static class EnumerableExtensions
        {
            public static IEnumerable<T> AllOrDefaultML<T>(this IEnumerable<T> items)
            {
                if (items.IsNullML()) return new List<T>();

                return items;
            }

            public static IEnumerable<T> AllOrDefaultML<T>(this IEnumerable<T> items, Func<T, bool> predicate)
            {
                items = items.AllOrDefaultML();

                if (!items.AnyML()) return new List<T>();

                return items.Where(predicate);
            }

            public static IEnumerable<T> EachML<T>(this IEnumerable<T> items, Action<T> fn)
            {
                var e = items.GetEnumerator();
                while (e.MoveNext())
                {
                    fn(e.Current);
                }
                return items;
            }

            public static bool IsNullML(this object item)
            {
                return item == null;
            }

            public static bool IsNullOrEmptyML<T>(this IEnumerable<T> items)
            {
                return !items.AnyML();
            }

            public static bool AnyML<T>(this IEnumerable<T> items)
            {
                if (items.IsNullML()) return false;

                return items.Count() > 0;
            }

            public static bool AnyML<T>(this IEnumerable<T> items, Func<T, bool> predicate)
            {
                if (items == null) return false;

                items = items.Where(predicate);

                return items.Count() > 0;
            }
        }

Essentially with these methods I can write the above code as the following:

        var items = new List<string> { "apple", "dog", "chair" };

        foreach (var item in items.AllOrDefaultML())
        {
            Console.WriteLine(item);
        }

Or even integrate the Each() method:

        var items = new List<string> { "apple", "dog", "chair" };

        items.AllOrDefaultML().EachML(i => Console.WriteLine(i));

I'm not sure how I feel about the above, but you get the idea.

I've also added a predicate to AllOrDefaultML() which works if the sequence is null:

        foreach (var item in items.AllOrDefaultML(i => i.Length == 5))
        {
            Console.WriteLine(item);
        }

Linq has a FirstOrDefault() method, why not have an AllOrDefault() which returns you an empty sequence if it's null and doesn't have any items?

I'm hoping to get some insight in to the question above, and also wondering if anyone else has implemented anything like this before? Has it cleaned up your code much? Is it easier to read? Is it confusing for colleagues (particularly new start) who aren't totally aware of what's happening? Is there anything fundamentally wrong with what I have here?


texts: Python example to save file with same name like `somefile(n).txt`

texts:
My little Python scriptie needs to save a file to the CWD, but sometimes the file already exists.

I found this short and clever example to string concatenate a time signature to the name here on SE. But I wanted to make the file name look pretty,

import os
import fnmatch
import re

somefiles = []
myfiles = []
root = "./"
onefn = False

for item in os.listdir(root):
    if os.path.isfile(os.path.join(root,item)):
        somefiles.append(item)

for fname in somefiles:
    if fnmatch.fnmatch(fname, 'somefile(*).txt'):
        myfiles.append(fname)
    elif fname == 'somefile.txt':
        onefn = True

if len(myfiles) > 0:
    maxnum = re.search(r'\(([0-9]+)\)', max(myfiles))
    with open('somefile(%s).txt' % (str(int(maxnum.group(1)) + 1),), 'w') as f:
        f.write("This is some text in a new file.")
elif onefn:
    with open('somefile(1).txt', 'w') as f:
        f.write("This is sommore text in a new file.")
else:
    with open('somefile.txt', 'w') as f:
        f.write("This is enuf text in a new file.")

This is a beast, but it will write somefile(n).txt.
Any recommendations to make it less beastly?


texts: A function for convenient string concatenation with variadic templates

texts:
I wrote this function for string concatenation some time ago.

Jo() stands for "Join". The name is shortened on purpose, because this function is used very often.

It offers a stream-like functionality: Jo("i = ", i) = cout << "i = " << i
and returns a const char * to internal buffer.

const char * is used instead of std::string because I interact with C apis a lot and writing .c_str() each time is tedious.

I know that you can achieve same result by converting arguments to std::string one by one and concatenating them instead of using this function, but it would require a lot more code.

It's intended to be used in a single thread only, thus there are no mutextes or something similar.

Here is the code:

#include <cstdio>
#include <sstream>
#include <initializer_list>

namespace Internal
{
    // In real code those are declared `extern` and initialization is moved from .h into .cpp
    std::stringstream ss;
    const std::stringstream::fmtflags stdfmt = ss.flags();
}

// Jo() resets stringstream flags before performing concatenation.
// Jo_() does not.

template <typename ...P> const char *Jo_(P &&... p)
{
    // Multiple buffers to allow use of multiple Jo()'s in a single expression.
    static constexpr int ret_buffers_c = 32;
    static std::string ret_buffers[ret_buffers_c];
    static int ret_pos = 0;

    Internal::ss.clear(); // Clear the error flags.
    Internal::ss.str(""); // Clear stringstream contents.

    // Push all objects to stringstream.
    std::initializer_list<int>{(Internal::ss << p, 0)...};

    // Save to buffer and return a pointer.
    ret_buffers[ret_pos] = Internal::ss.str();
    const char *ret = ret_buffers[ret_pos].c_str();
    ret_pos = (ret_pos + 1) % ret_buffers_c;
    return ret;
}

template <typename ...P> const char *Jo(P &&... p)
{
    Internal::ss.flags(Internal::stdfmt);
    return Jo_((P &&) p...);
}

// Example usage:
int main()
{
    for (int i = 1; i <= 10; i++)
        std::puts(Jo(i, " * ", i+1, " = ", i*i+i));
    return 0;
}

Is there anything I can improve about those functions?

I'm especially concerned about this line: std::initializer_list<int>{(Internal::ss << p, 0)...};
It looks a bit dirty, but I don't know any better alternative.


texts: Finding cost of tile to cover W x H floor

texts:
I am new to C++ and programming in general. After reading through my first book, I decided to take on some programming exercises and test what I learned. The exercise is phrased as follows:

  Find Cost of Tile to Cover W x H Floor - Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user.

This is the code I wrote for it:

#include <iostream>

using namespace std;

int main() {

    double StartSquare, cost, width, height;    // Starting square meters and cost. Width and height of floor.

    cout << "Enter value of 1 pack of tiles: ";
    cin >> cost;

    cout << "Now enter the square metres covered by the pack: ";
    cin >> StartSquare;

    cout << "What is the width of your room? ";
    cin >> width;
    cout << "Now enter the height:\n";
    cin >> height;

    cout << "You need to cover a total of " << width * height << " square metres.\n";
    cout << "The total cost will be: " << (width * height) * cost << endl;

    return 0;
}

It does what I need it to, I just want to know whether it can be improved upon. This also brings me to question of: How do I self-review my own code? I don't want to have to constantly be asking a review of my code and rather self-assess it myself.


texts: Utility function to split a number into n parts in the given ratio

texts:
I wrote a small utility function that divides a total into n parts in the ratio given in load_list. Numbers in each part should be positive integers. It supports an optional min_num argument that, when specified, puts at least min_num in each of the n parts before distributing the rest.  Please review.

def reduce_ratio(load_list, total_num, min_num=1):
  """
  Returns the distribution of `total_num` in the ratio of `load_list` in the best possible way
  `min_num` gives the minimum per entry
  >>> reduce_ratio([5, 10, 15], 12)
  [2, 4, 6]
  >>> reduce_ratio([7, 13, 30], 6, 0)
  [1, 2, 3]
  >>> reduce_ratio([7, 13, 50], 6)
  [1, 1, 4]
  >>> reduce_ratio([7, 13, 50], 6, 3)
  Traceback (most recent call last):
    ...
  ValueError: Could not satisfy min_num
  >>> reduce_ratio([7, 13, 50], 100, 15)
  [15, 18, 67]
  >>> reduce_ratio([7, 13, 50], 100)
  [10, 19, 71]
  """
  num_loads = [ [load, min_num] for  load in load_list ]
  yet_to_split = total_num - ( len(num_loads) * min_num )
  if yet_to_split < 0:
    raise ValueError('Could not satisfy min_num')
  for _ in range(yet_to_split):
    min_elem = min(num_loads, key=lambda (load, count): (float(count)/load, load))
    min_elem[1] += 1
  reduced_loads = map(itemgetter(1), num_loads)
  if sum(reduced_loads) != total_num:
    raise Exception('Could not split loads to required total')
  return reduced_loads


texts:
This code was to create how many people enter the "building" so there will be someone clicking the button "count". I am still improving. Please let me know your honest opinions!

from tkinter import *
import math

win = Tk()

global counter
counter = 0

def closewindow():
    exit()

def continuewindow():
    global counter
    counter+=1
    print ("Total number of people entering: ")
    print (counter)

b1 = Button(win,text="Count",command=continuewindow)
b2= Button(win,text="Exit",command=closewindow)

b1.pack(side=LEFT)
b2.pack(side=LEFT)
mainloop()


texts:
I have a model called Document, in this I have a method that I use throughout my website to get the full path to the specific document:

public function getDocument($documentName = true)
{
    $documentName = $documentName ? $this->name : null;

    return storage_path('app/' . $this->getPath() . $documentName);
}

public function getPath()
{
    return "{$this->stream->token}/{$this->unique_id}/";
}

I use it like this (example):

$documentPath = $this->document->getDocument();

However, as you can see, the document path is made up of:

$this->stream->token/$this->unique_id/

Where $this->stream->token is calling a relationship in my Document model.

public function stream()
{
    return $this->belongsTo(Stream::class);
}

Now the method works - I can use the getDocument() to get the full path to the actual file (or just the folder, if I pass in false).

However, this code is called from multiple places at different times - and because the folder structure is dependent on the stream_token, it makes a query to get the associated stream on each request.

Solution(s)?

I have tried adding a $with = ['stream'] property to my Document model, so  the associated stream is always loaded when fetching the model - but this I don't believe is a good option either, since then all the other queries I have for the document model, that don't care about the stream property make an extra query.

What else can I do to improve the method and keep the # of queries to the database to a minimum?


texts:
My goal is to obtain the nth weekday of a given month. Parameters are a date from a given month and the nth weekday I'm trying to obtain. It returns the Nth Weekday of the month if it exist and returns DateTime.MinValue othewise. For my purposes weekdays are M-F.

Is there a more elegant or efficient way to implement this logic? My implementation feels crude, basically a while loop that counts weekdays until it finds the desired date or the end of the month.

    public static DateTime getNthWeekdayOfMonth(DateTime date, int nthWeekday)
    {
        //Valid inputs are greater than 0 but less than 24
        if (nthWeekday > 23 || nthWeekday < 1)
            return DateTime.MinValue;

        //start with 1st day of month from date param
        DateTime currentDay = new DateTime(date.Year, date.Month, 1);

        int i = 0;
        while(i < nthWeekday && currentDay.Month == date.Month)
        {
            if (currentDay.DayOfWeek != DayOfWeek.Saturday && currentDay.DayOfWeek != DayOfWeek.Sunday)
            {
                i++;
                if(i == nthWeekday)
                    return currentDay;
            }
            currentDay = currentDay.AddDays(1);
        }
        return DateTime.MinValue;
    }

Usage

var date1 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 22);
//returns DateTime.MinValue
var date2 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 21);
//returns 8/31/2015
var date3 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 1);
//returns 8/3/2015


texts: Grokking the basics of BlockChain with Python

texts:
As I was streaming I had a brilliant visitor suggest we write a blockchain in Python.

So we did.

Note that there is no validation or voting simulated here.

Here's the results, in package/blockchain.py:

from __future__ import annotations
# https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
from oscrypto.symmetric import aes_cbc_pkcs7_encrypt as encrypt # type: ignore

class Node:
    __slots__ = 'prior_node', 'data', 'hash'
    prior_node: Node
    data: bytes
    hash: bytes

    def __init__(self, prior_node, key, data):
        self.prior_node = prior_node
        self.data = data
        if prior_node is None:
            init_vector = bytes(16)
        else:
            init_vector = _ensure_byte_length(prior_node.hash, 16)
        key = _ensure_byte_length(key, 32)
        self.hash = encrypt(key, data, init_vector)[1]

    def __repr__(self):
        return f'Node<{self.data}\n{self.hash}\n{self.prior_node}>'

def _ensure_byte_length(bytes_, length):
    return bytes(bytes_.ljust(length, b'\x00')[:length])

class Chain:
    __slots__ = 'nodes'
    def __init__(self, key: bytes, data: bytes):
        self.nodes = Node(None, key, data)

    def __repr__(self):
        return f'Chain:\n{self.nodes}'

    def new_node(self, key, data):
        self.nodes = node = Node(self.nodes, key, data)
        return node

    def __len__(self):
        length = 0
        nodes = self.nodes
        while nodes:
            length += 1
            nodes = nodes.prior_node
        return length

def main():
    chain = Chain(b'the key', b'here is a bit of data')
    chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
    chain.new_node(b'hunter2', b'and finally here is some more')
    print(chain)

if __name__ == '__main__':
    main()

And here's a tiny test, tests/test_blockchain.py:

from package.blockchain import Chain

def test_blockchain():
    chain = Chain(b'the key', b'here is a bit of data')
    chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
    chain.new_node(b'hunter2', b'and finally here is some more')
    assert len(chain) == 3

Note that we did require oscrypto and openssl to run this.

Ran coverage with pytest under Python 3.7. Ran with black and mypy as well.


texts:
How can I make this sort faster and better?

function OrderBy(a,b) {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
}

SortBy = function($th) {
    var $tbody = $th.closest('tbody');
    var $table = $tbody.parent();
    $tbody.detach();
    $('#Processing').show('fast',function () {
        var column = $th.index();
        var rows = $tbody.find('tr').get();
        rows.sort(function(rowA,rowB) {
            var keyA = $(rowA).children('td').eq(column).text();
            var keyB = $(rowB).children('td').eq(column).text();
            return OrderBy(keyA,keyB);
        });
        $.each(rows, function(index,row) {
            $tbody.append(row);
        });
        $table.append($tbody);
    });
};


texts:
I have the following code working on a WordPress plugin. But there's no WP issue, the matter is:
can I trust @get_headers to perform most of times?

public function enqueue()
{
    $http = is_ssl() ? 'https:' : 'http:';
    $url = "$http//netdna.bootstrapcdn.com/font-awesome/3.2.0/css/font-awesome.min.csss";
    if( $this->get_http_response_code( $url ) ) {
        my_load_external_script();
    }
    else {
        my_load_local_script();
    }
}

/**
 * Problem with getting header, return false
 *
 * otherwise return if headers are 200 or not
 *
 * @param  $url     string
 * @return boolean
 */
private function get_http_response_code( $url )
{
    $headers = @get_headers( $url );
    if( !$headers )
        return false;

    return substr( $headers[0], 9, 3 ) === '200';
 }

The current requirement for running WordPress is PHP 5.2.4 or greater. As I understand it, there's no 100% guarantee, but for having a plugin running in the wild I'd prefer the less problematic path. I've checked the following Stack Overflow Q&A's, but haven't come to any conclusion:

get_headers is throwing a warning instead of just returning false?
Can I try/catch a warning?


texts:
I have an application that has a form. Validation and data insertion works fine. However, it bulks out my controller. I've always been told skinny controllers.

For example:

class myController extends BaseController
{
    public function store(myRequest $request)
    {
        $company_id = Company::insertGetId([
            'name'      => $request->name,
            'contact'   => $request->contact,
            'email'     => $request->email,
            'telephone' => $request->telephone,
        ]);

       $this->handleQuestion($request->question_one, '1', $company_id->id);
       $this->handleQuestion($request->question_two, '2', $company_id->id);
       $this->handleQuestion($request->question_three, '3', $company_id->id);
       $this->handleQuestion($request->question_four, '4', $company_id->id);
       $this->handleQuestion($request->question_five, '5', $company_id->id);
       $this->handleQuestion($request->question_six, '6', $company_id->id);
       $this->handleQuestion($request->question_seven, '7', $company_id->id);

       Outstanding::create([
            'company_id' => $company_id->id,
       ]);
    }

    public function handleQuestion($answer, $q_id, $company_id)
    {
        if( $question ) {
            CompanyAnswers::create([
                'company_id'  => $company_id,
                'question_id' => $q_id,
                'answer'      => $answer,
            ]);
        }
    }
}

The database schema has been created with a 2NF relation in mind.

companies

id (PK)
name
contact
email
telephone

company_answers

id (PK)
company_id (FK)
question_id (FK)
answer

outstanding_companies

id (PK)
company_id (FK)
question_id (FK)
answer

How is the application intended to work?

When the form is filled out, we create the company.
We ask seven questions - questions are not mandatory. (This is why we have a company_answers table - to avoid redundant data.) The results of the questions are stored in company_answers.
We insert the application in outstanding_companies so we know that this application is outstanding and needs attention.

My Problem

Have I totally misunderstood database normalisation and hindered myself by adding more code to handle data insertion?
If I have understood database normalisation, what is a better approach for handling the data insertion?
Is skinny controllers true? If so, where do I put data insertion logic?


texts: Aggregate summary counts for an array of error objects

texts:
I'm doing some refactoring of someone else's code, and just want a second opinion, because of course I think my work makes it better, but some validation (or correction) would be helpful.

Starting with an array like this:

errorLog: [{
 errorCode: 11,
 errorDescription: "abc",
 date: "2017-01-01",
 severity: "H"
},{
 errorCode: 11,
 errorDescription: "abcd",
 date: "2017-01-02",
 severity: "H"
},{
 errorCode: 99,
 errorDescription: "abcd",
 date: "2017-01-02",
 severity: "H"
}]

and trying to get results like this:

errorSummary: [{
 errorCode: 11,
 severity: "H",
 count: 2
},{
 errorCode: 99,
 severity: "H",
 count: 1
}]

this is the existing code:

//instead of this, which is hard to reason about and debug (and includes a line that will never rturn true: if (hardErrorsSorted.includes...)):
let hardErrors = testData.filter(ts1 => ts1.severity === 'H');
let hardErrorsSorted = hardErrors.sort(this.mySorter);
for (let i = 0; i < hardErrorsSorted.length; i++) {
  if (i != hardErrorsSorted.length - 1) {
    if (hardErrorsSorted[i].errorCode != hardErrorsSorted[i + 1].errorCode) {
      let errorCount = this.getCount(hardErrorsSorted, hardErrorsSorted[i].errorCode);
      this.errorDataList.push({
        errorCode: hardErrorsSorted[i].errorCode,
        errorCodeType: 'H',
        errorCodeTotalCount: errorCount
      });
    }
  } else {
    if (hardErrorsSorted.includes(hardErrorsSorted[i].errorCode, 0)) {
    } else {
      let errorCount = this.getCount(hardErrorsSorted, hardErrorsSorted[i].errorCode);
      this.errorDataList.push({
        errorCode: hardErrorsSorted[i].errorCode,
        errorCodeType: 'H',
        errorCodeTotalCount: errorCount
      });
    }
  }
}

and my refactoring:

//use something like this, which is much easier to grasp at a glance, doesn't jump around, and is DRYer
let hardErrorCodes = testData.filter(ts => ts.severity === 'H').map(v => v.errorCode);
let hardErrorCounts = {};

//sum up the unique errors
for (let error of hardErrorCodes) {
  if (!(error in hardErrorCounts)) {
    hardErrorCounts[error] = 0;
  }
  hardErrorCounts[error]++;
}

//add the summed error counts to the master list
for (let error in hardErrorCounts) {
  this.errorDataList.push({
    errorCode: error,
    errorCodeType: "H",
    errorCodeTotalCount: hardErrorCounts[error]
  });

What do you all think? Is this a helpful refactor, or a waste of time?


texts:
In a Swift project, I have a class should be used as a singleton:

  class NearFieldManager : NSObject{
  static let shared = NearFieldManager()
  var dataToTransfer:Any!
 }

This class helps me communicate between several nearby devices and the dataToTransfer is some information each device is advertising about itself.
What makes me wondering about this class is that each time I call it goes like this:

let manager = NearFieldManager.shared
shared.dataToTransfer = "some data"

First, I am creating a reference to the manager and line after it I set some value on its property. How can I improve this design?


texts: Remove repetitive strings from a given sentence efficiently

texts:
I recently gave a test on HackerRank:

  Given a string, return the most concise string that can be formed from it.

  For example:

string = 'watson  Represents|watson represents|Watson represents a first step into cognitive systems, a new era of computing.|first step into  Cognitive|Cognitive Systems; a new era|what does watson represent'

  The following string contains many duplicates like "Watson represents." We have to ignore extra spacing between characters or lower/upper case. "watson  Represents" and "watson represents" are the same thing.
  Semicolons and commas represent the same thing. For example, "Cognitive Systems; a new era" is present inside "Watson represents a first step into cognitive systems, a new era of computing."
  Your final string should not contain any duplicates. Ignore lowercase/uppercase or extra space if you have any.

My answer:

watson = 'watson  Represents|watson represents|Watson represents a first step into cognitive systems, a new era of computing.|first step into  Cognitive|Cognitive Systems; a new era|what does watson represent'

import re

watson = re.sub(r';', r',', watson)  #replace the semicolon with colon
watson = watson.strip().split('|')
removeWatson = list(watson)

for i in range(len(watson)):

    for j in range(len(watson)):

        if j == i:
            continue

        if " ".join(watson[i].strip().lower().split()) in " ".join(watson[j].strip().lower().split()):
            removeWatson[i] = ''

print "|".join(filter(None, removeWatson))

My answer is definitely inefficient and I am wondering if you can suggest an alternative way of solving this problem.

Most concise string:

  Watson represents a first step into cognitive systems, a new era of computing.|what does watson represent


texts: Simple addition calculator accepting addition expressions

texts:
Maybe someone can help me to optimize the calculate method. I think that it can be simplified from that what I have now.

The objective is: grab a string via the incoming argument of the calculate method and get the amount of it or difference (based on the sign standing between numbers). Count of numbers should be  2.

My function, method and constructor are working fine, but I think it is too lengthy/complex for such a simple task.

function Calculator() {

  this.calculate = function(sum) {
    this.summ = 0;

    this.sumArr = sum.split(' '); // make array from string to clear from non-numbers values
    this.newSum = this.sumArr.filter(function(number) {
      return number > 0;
    });

    for (var i = 0; i < this.sumArr.length; i++) { // based on the sign standing between numbers calculate it
      if (this.sumArr[i] == '+') {
        return this.summ = parseInt(this.newSum[0]) + parseInt(this.newSum[1]);
      } else if (this.sumArr[i] == '-') {
        return this.summ = parseInt(this.newSum[0]) - parseInt(this.newSum[1]);
      }
    }
  };
};

var calc = new Calculator;

console.log(calc.calculate("3 + 7")); // 10
console.log(calc.calculate("3 - 7")); // -4


texts: A Tumbler, or a format-preserving-encryption shuffle

texts:
I wanted to implement a simple algorithm for encoding id of entries in a database to avoid:

Storing the UID (unique id) in the table along with the id
Complex and costly algorithm.
Users to give meaning to the id in the sense:

Yeah if this id is bigger than that id it was inserted later in the DB
I can probably get the previous and the next element by adding one to my id

So I need two inputs:

One id
The domain of my id, or the maximum number of entries in that table.

A nice kind of algorithms for this purpose is a FFX algorithm (Format Preserving Encryption). But they usually rely on complex hash function such as SHA or MD5. In my case I just want a very simple simple algorithm that I could implement in MySQL as a generated column for instance.

So I wrote this code:

import math

class Tumbler:
    def __init__(self, maximum, rounds=12):
        bits = math.ceil(math.log(maximum, 2))
        u, v = bits // 2, bits - bits // 2
        self.u = u
        self.v = v
        self.bits = bits
        self.rounds = rounds
        self.maximum = maximum

    def hash(self, x, m):
        """ Jenkins Hash 32bits."""
        x = (x + int('7ed55d16', 16)) + (x << 12)
        x = (x ^ int('c761c23c', 16)) ^ (x >> 19)
        x = (x + int('165667b1', 16)) + (x << 5)
        x = (x + int('d3a2646c', 16)) ^ (x << 9)
        x = (x + int('fd7046c5', 16)) + (x << 3)
        x = (x ^ int('b55a4f09', 16)) ^ (x >> 16)
        return x % m

    def split(self, x, u):
        return (x >> u, x & (2 ** u - 1))

    def _encrypt(self, x, nonce=1):
        for i in range(self.rounds):
            a, b = self.split(x, self.v)
            c = a ^ self.hash(b * i + nonce, (2 ** self.u - 1))
            x = b << self.u | c
        return x

    def _decrypt(self, x, nonce=1):
        for i in reversed(range(self.rounds)):
            b, c = self.split(x, self.u)
            a = c ^ self.hash(b * i + nonce, (2 ** self.u - 1))
            x = (a << self.v) | b
        return x

    def encrypt(self, x, nonce=1):
        while True:
            x = self._encrypt(x, nonce)
            if x <= self.maximum:
                return x

    def decrypt(self, x, nonce=1):
        while True:
            x = self._decrypt(x, nonce)
            if x <= self.maximum:
                return x

Here an output:

>>> t = Tumbler(162)
>>> [(i, t.encrypt(i), t.decrypt(t.encrypt(i))) for i in range(min(16, t.maximum))]

[(0, 48, 0),
 (1, 97, 1),
 (2, 80, 2),
 (3, 159, 3),
 (4, 95, 4),
 (5, 3, 5),
 (6, 38, 6),
 (7, 108, 7),
 (8, 50, 8),
 (9, 162, 9),
 (10, 24, 10),
 (11, 94, 11),
 (12, 69, 12),
 (13, 126, 13),
 (14, 43, 14),
 (15, 120, 15)]

Another example would be to shuffle a deck of 52 cards:

shuffling_method = 1
t = Tumbler(52, shuffling_method)
[(i, t.encrypt(i), t.decrypt(t.encrypt(i))) for i in range(t.maximum)]

If I want another shuffle set, I could use a different shuffling_method.

And of course I could use a better hashing function:

import hashlib

class Tumbler2(Tumbler):
    def hash(self, x, m):
        return int(hashlib.md5(bytes(str(x))).hexdigest, 16) % m


texts: Locating a PID based on an IP address and port

texts:
I wrote a simple Python app that is given an IP address and port and the app then finds the PID listening on that IP:PORT.

I would like to hear constructive criticism regarding the bellow code.

import argparse
import sys
import socket
import subprocess
import os

def is_legal_ip(address):
    ip = address.split(":")
    pieces = ip[0].split('.')
    if len(pieces) != 4:
        return False
    try:
        return all(0<=int(p)<256 for p in pieces)
    except ValueError:
        return False

def parse_arguments():
    if len(sys.argv) > 2 or len(sys.argv) == 1:
        print("Please provide a single argument.")
        exit(1)

    parser = argparse.ArgumentParser("Returns a PID listenning on IP:PORT")
    parser.add_argument('ip_port', metavar='IP:PORT', type=str, nargs=1, help='local address')
    args = parser.parse_args()

    if (is_legal_ip(args.ip_port[0]) == False):
        print("Invalid IP address.")
        exit(1)

    return(args.ip_port[0])

def address_to_pid(ip_port):
    devnull = open(os.devnull, 'w')
    output = subprocess.check_output("netstat -nptl".split(), stderr = devnull).splitlines()
    devnull.close()

    for line in output[2::]:
        raw_line = line.split()
        if raw_line[3] == ip_port:
            if raw_line[6] == "-":
                return "No PID listening on address"
            else:
                return raw_line[6].split(r"/")[0]

def main():
    ip_port = parse_arguments()

    print address_to_pid(ip_port)

if __name__ == "__main__": main()


texts:
I'm not sure if my lock usage is correct and safe. I wanted to know what will be best approach to deal with situation when one thread have to wait for being initialized by another so I written this test:

import java.util.concurrent.locks.ReentrantLock
import java.util.{TimerTask, Timer, Date}
import scala.concurrent.{ExecutionContext, Future, Await}
import scala.concurrent.duration.Duration

class I{
  private var i:Int = 0
  def inc() = i+=1
  def value = i
}

trait Test {
  def doSomething():Unit
  def initialize(i:I):Unit
  def result:Int
}

case class TestLocks() extends Test{
  var ref:I = null

  val lock = new ReentrantLock
  val refInitialized = lock.newCondition()

  def doSomething(){
    lock.lock()
    try {
      if(ref==null) { refInitialized.await() }
      ref.inc()
    }
    finally {
      lock.unlock()
    }
  }

  def initialize(i:I){
    lock.lock()
    try{
      ref = i
      refInitialized.signal()
    }
    finally {
      lock.unlock()
    }
  }

  def result = ref.value
}

case class TestPromises() extends Test{
  val iPromise = concurrent.promise[I]
  def doSomething(){
    val i = Await.result(iPromise.future,Duration.Inf)
    i.inc()
  }

  def initialize(i:I){
    iPromise.success(i)
  }

  def result = Await.result(iPromise.future,Duration.Inf).value
}

object TestRunner{
  def apply(test:Test):Long = {

    val initializationTimeout = 10
    val timer = new Timer()
    timer.schedule(new TimerTask {
      def run(){
        test.initialize(new I)
      }
    },initializationTimeout)

    val start = new Date().getTime

    1 to 1000000 foreach (i=>{
      test.doSomething()
    })
    val end = new Date().getTime

    val duration = end-start-initializationTimeout
//    Console.println(test+" result: "+test.result+" in: "+duration+"ms")
    duration
  }
}

object Tests {
  def run() {

    def average(l: => Long) =
    {
      val vals = 1 to 100 map(_=>{l.toDouble})
      vals.sum/vals.length
    }

    def averageAsync(l: => Long) =
    {
      import ExecutionContext.Implicits.global
      val futs = 1 to 100 map(_=>{Future{l.toDouble}})
      val valsFut = Future.sequence(futs)
      val vals = Await.result(valsFut,Duration.Inf)
      vals.sum/vals.length
    }

    Console.println("Locks: "+average(TestRunner(TestLocks()))+"ms")
    Console.println("Promises: "+average(TestRunner(TestPromises()))+"ms")

    Console.println("A Locks: "+averageAsync(TestRunner(TestLocks()))+"ms")
    Console.println("A Promises: "+averageAsync(TestRunner(TestPromises()))+"ms")
  }
}

which outputs:

  Locks: 28.0ms
  Promises: 68.5ms
  A Locks: 49.87ms
  A Promises: 2307.84ms

what indicates that I have to use locks in "hot zones" and now I want to ensure if those tests are correct. Or maybe I should handle this "wait if uninitialized" case in any other way?


texts:
I have click event handlers for two buttons. The code is working well, but I want to apply the DRY principle. How should I rewrite the following code in the button_click event handler so that I don't have to repeat in all my 10 buttons?

private void CreateWindows(UserControl ux, Form rpt, object sender, ItemClickEventArgs e)
{
    ux.Show();

    rpt.SuspendLayout();
    rpt.ControlBox = false;
    rpt.TopLevel = false;
    rpt.WindowState = FormWindowState.Maximized;
    rpt.MdiParent = this;
    rpt.Show();
    rpt.ResumeLayout();

    dock1.SuspendLayout();
    dock1.Controls.Clear();
    dock1.Controls.Add(ux);
    dock1.ResumeLayout();
}

private BaseDocument FindDocument<T>() where T : Form
{
    foreach (BaseDocument document in dxDocumentManager.View.Documents) {
        if (document.Form is T) {
            return document;
        }
    }
    return null;
}

private void button1_ItemClick(object sender, ItemClickEventArgs e)
{
    dxRpt12MonthsItemPurchaseAnalysisByAmount filter = new formFilter1();

    BaseDocument document = FindDocument<formReport1>();

    if(document != null)
    {
        tabbedView1.Controller.Activate(document);
        if (this.ActiveMdiChild is formReport1)
        {
            filter.Focus();
        }
    }
    else
    {
        CreateWindows(new formFilter1(), new formReport1(), sender, e);
    }
}

private void button2_ItemClick(object sender, ItemClickEventArgs e)
{
    fmSalesInvoiceSearch filter = new formFilter2();

    BaseDocument document = FindDocument<formReport2>();

    if (document != null)
    {
        tabbedView1.Controller.Activate(document);
        if (this.ActiveMdiChild is formReport2)
        {
            filter.Focus();
        }
    }
    else
    {
        CreateWindows(new formFilter2(), new formReport2(), sender, e);
    }
}


texts: Two similar factory classes to instantiate services

texts:
I'm working on building a library to help you bootstrap the development of a Java API. The premise is, you can have your controllers implement interfaces like IGetController<SomeEntity> or IListController<SomeEntity>.  These interfaces have default methods to implement their endpoint, and use a service factory to get the appropriate service to do the bulk of the work.  These services are also interfaces, and have default methods which get a repository (by calling getRepository on the IBaseService they extend).  There's a lot of "magic" going on here to inspect the genericInterfaces on the class, and then getting the type arguments to determine what entity we're working with.

The problem I'm having is consolidating my factories.  Take a look at these two factory classes:

GetServiceFactory:

package apibuilder.service.factory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import apibuilder.entity.BaseEntity;
import apibuilder.service.IGetService;

public class GetServiceFactory {
    private static final Map<Type, IGetService<? extends BaseEntity>>
            registrationMap = new HashMap<>();

    public static <T extends BaseEntity> IGetService<T> getService(final Type entityType) {
        if (registrationMap.containsKey(entityType)) {
            //noinspection unchecked
            return (IGetService<T>) registrationMap.get(entityType);
        }
        return null;
    }

    public static <T extends BaseEntity> void registerServices(final IGetService<T>[] services) {
        for (IGetService<T> service : services) {
            Type entityType = ((ParameterizedType) service.getClass().getGenericInterfaces()[0])
                    .getActualTypeArguments()[0];
            registrationMap.put(entityType, service);
        }
    }
}

ListServiceFactory:

package apibuilder.service.factory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import apibuilder.entity.BaseEntity;
import apibuilder.service.IListService;

public class ListServiceFactory {
    private static final Map<Type, IListService<? extends BaseEntity>>
            registrationMap = new HashMap<>();

    public static <T extends BaseEntity> IListService<T> getService(final Type entityType) {
        if (registrationMap.containsKey(entityType)) {
            //noinspection unchecked
            return (IListService<T>) registrationMap.get(entityType);
        }
        return null;
    }

    public static <T extends BaseEntity> void registerServices(final IListService<T>[] services) {
        for (IListService<T> service : services) {
            Type entityType = ((ParameterizedType) service.getClass().getGenericInterfaces()[0])
                    .getActualTypeArguments()[0];
            registrationMap.put(entityType, service);
        }
    }
}

As you can see, they're nearly identical.  They create a map to get the proper service per entity, and then have methods to build the map, and get a service from the map.  I feel like these can be consolidated into some sort of BaseServiceFactory, but I'm having a hard time actually pulling it off.


texts: Determining if an answer can be generated

texts:
How can I improve my code below for the following question?  While it works, I am not satisfied with how it looks; I was hoping I can somehow keep it recursive, and have the ans filled up inside the function, and reduce the number of return statements that I have.  Treat this like an interview problem.

Worst case: \$O(2^n)\$? Please verify and elaborate

Space complexity: \$O(1)\$

  Problem:

  You have four integers, a, b, c, d, and the goal is to make a == c and
  b == d, given that you are only allowed to do a+b, b, or a, b+a at any
  given transformation.

  For example, if a = 1, b = 2, c = 3, and d = 8
  you can start with (1, 2), change it to (3, 2), change that to (3, 5),
  and then change that again to (3, 8) to succeed.

  static int ans = 0;
  public static void ablehelper(int a, int b, int c, int d){
      if(a != c && (b + a) > c){
          return;
      }
      if(b != d && (b + a) > d){
          return;
      }
      if(a == c && b == d){
          ans = 1;
          return;
      }
      ablehelper(a + b, b, c, d);
      ablehelper(a, b + a, c, d);

  }
  public static String able(int a, int  b, int c, int d){
      ablehelper(a, b, c, d);
      if(ans == 1){
          return "Able to generate";
      }else{
          return "Not table to generate";
      }
  }

Update:

As per one of the algorithms described below, I wrote this:

public static String betterSolution(int a, int b, int c, int d){
          while( c > a || d > b){
              if(c > d){
                  c = c-d;
              }else{
                  d = d-c;
              }
          }
          if( c == a &&  d == b){
              return "Able to generate";
          }else{
              return "Not able to generate";
          }
      }


texts:
I would like to ask 2 questions about the modularization of an F# file. The code is just a working example of prime factorization, but that's not the main topic. I have a main file (PrimeFactors.fs), a different file for its mocked version (PrimeFactorsMock.fs), and a test file (PrimeFactorsTests.fs):

PrimeFactors.fs

namespace PrimeFactors

module PrimeFactors =

    type IPrimeChecker =
        abstract member IsPrime : int64 -> int64 -> bool

    type PrimeFactors() =
        interface IPrimeChecker with
            member this.IsPrime number i =
                number % i = 0L

        member this.CheckPrimes number i acc =
            match i with
                | _ when i > (number |> float |> sqrt |> int64)   -> number::acc
                | _ when (this :> IPrimeChecker).IsPrime number i -> this.CheckPrimes (number / i) i (i::acc)
                | _                                               -> this.CheckPrimes number (i + 1L) acc

        member this.Of number =
            if number = 1L then
                [||]
            else
                this.CheckPrimes number 2L [] |> List.toArray

PrimeFactorsMock.fs

namespace PrimeFactors
open PrimeFactors

module PrimeFactorsMock =
    type PrimeFactorsMock() =
        inherit PrimeFactors()

        let mutable stepCount = 0L

        interface IPrimeChecker with
          member this.IsPrime number i =
            stepCount <- stepCount + 1L
            number % i = 0L

        member this.StepCount number =
            stepCount <- 0L
            this.Of number |> ignore
            stepCount

PrimeFactorsTests.fs

namespace PrimeFactors

open PrimeFactors
open NUnit.Framework
open FsUnit
open PrimeFactorsMock

[<TestFixture>]
module PrimeFactorTests =

    [<TestCase(1L, [||])>]
    [<TestCase(2L, [|2L|])>]
    [<TestCase(3L, [|3L|])>]
    [<TestCase(4L, [|2L; 2L|])>]
    [<TestCase(6L, [|3L; 2L|])>]
    [<TestCase(8L, [|2L; 2L; 2L|])>]
    [<TestCase(16L, [|2L; 2L; 2L; 2L|])>]
    [<TestCase(773L, [|773L|])>]
    [<TestCase(8L, [|2L; 2L; 2L|])>]
    let prime_factors_of_number number expect =
        PrimeFactors().Of number |> should equal expect

    [<TestCase(1L, 0L)>]
    [<TestCase(4L, 1L)>]
    [<TestCase(773L, 26L)>]
    let step_count_of_number number stepCount =
        PrimeFactorsMock().StepCount number |> should equal stepCount

What I like in that solution it's mock version is separated rightly from the initial class. So I only have to redefine IPrimeChecker.IsPrime, not the this.CheckPrimes, and possible all the inner functions. So I made IsPrime, and only IsPrime, virtual. It's a poor man's mocking.

My question is about mocking with object expression if that could be achieved without creating the PrimeFactorsMock.fs, and less coding. If we redefine the whole PrimeFactorsMock in the test file, it doesn't count (at least make it smaller). The goal is to make the IsPrime function interchangeable in the test file without much hassle.

The other question is I would like to use active patterns for IsPrime. So I can use pattern matching with (|Prime|NonPrime|) in the this.CheckPrimes part. Restriction is that have to be same as interchangeable as the already implemented virtual IsPrime.


texts:
I recently created a library in C, which creates and stores binary arrays. My library uses the standard fixed data types and allocates no more than 8 bytes for a binary array (8 bytes = 64-bit unsigned long long number). It also sets the binary equivalent at the bit level using the setBitsAt() method to make it quite efficient.

I want to know if there is a more efficient way of creating and storing binary arrays in C.

BinaryLibrary4C

Code snippet to create/store a binary array:

uint8_t* getBinaryArray(uint64_t num)
{
    int8_t encodeBitIndex = 0,byteIndex = -1;
    int8_t encodeBits = getEncodingBits(num);

    binaryArrayLen = getBytes4mBits(encodeBits);
    binaryArrayLen = (binaryArrayLen <= 0 || binaryArrayLen > BYTE) ? 0x1 : binaryArrayLen; /*Sanity check for size > 64bits*/

    int8_t bitIndex = 0,binValue;
    uint8_t *binaryArray = (uint8_t*)malloc(binaryArrayLen); /*Dynamic Array to store binary equivalent*/

    memset(binaryArray,0x0,binaryArrayLen); /*Set 0 as initial value to Array*/

    /*Storing binary equivalent in 1-bit each of binaryArray*/
    for (encodeBitIndex = 0; encodeBitIndex < encodeBits; encodeBitIndex++,bitIndex++)
    {

        if(isNextByte(encodeBitIndex))
        {
            byteIndex += 1;
            bitIndex = 0; /*-_- reset bitIndex for every byte*/
        }

        binValue = ((num >> encodeBitIndex) & 1) ?  1 : 0;
        setBitsAt((binaryArray + byteIndex),binValue,bitIndex,encodeBits);
    }
    return binaryArray;
}

void setBitsAt(uint8_t *dest,uint64_t bits,uint8_t at,uint8_t nBits)
{
    uint64_t mask = ((~0ULL) >> (sizeof(uint64_t) * BYTE - nBits)) << at;
    *dest = (*dest & ~mask)|((bits<<at) & mask);
}

const int8_t getEncodingBits(uint64_t num)
{
    return getRoundedBits((int8_t)fabs(floor(negLog2(num) - 1) + 1));
}

long double negLog2(uint64_t num)
{
    long double negLogVal = 0.0f;
    negLogVal = (num < 0) ? (sizeof(num) * BYTE) : (log2l(1.0L) - log2l(num));
    return isNumInMaxRange(num) ?  fabs(negLogVal) + 1 : negLogVal;
}

bool isNumInMaxRange(uint64_t num)
{
    return ((num == (UINT8_MAX  + 1U) || num == (UINT16_MAX  + 1U) || num == (UINT32_MAX  + 1ULL))) ?  true : false;
}

const int8_t getRoundedBits(int8_t bits)
{
    int8_t roundedBits;
    for(roundedBits = BYTE; roundedBits <= QWORD; roundedBits+=BYTE)
    {
        if(bits >= 0 && bits <= roundedBits)
            return roundedBits;
    }
    return -1;
}


texts: Converting a ResourceSet of bitmaps into a sorted List

texts:
I have a map. It can be zoomed-in and out. At first, I used one large image. Scrolling the mouse wheel defined the desired zoom level. Every scrolling created a new instance of the image in the desired dimensions. This approach was horribly slow.

So I gave up the possibility of zooming into any level, and created a list of predefined available zoom levels, ranging from 35% to 100% with 5% intervals, and then up to 300% with 50% intervals. For each zoom level, I have created a copy of the original image with the appropriate dimensions. The image name corresponds to its dimensions, so a 35% image is called "35.jpg". I added the images to the project's resources in a dedicated folder. Visual Studio automatically inserts an underline before the object's name because it starts with a number, so the object that represents the file is called "_35". So now, after the desired zoom level has been determined by the mouse wheel, the corresponding image is loaded from the resources. Performance has improved significantly.

Some of the application's components need a list of all available zoom levels. For example, for a ComboBox that allows the user to select a specific zoom level, rather than reach it through the mouse wheel. Therefore, when loading the form, a List<float> is initialized with all available zoom dimensions, so a 35% zoom is saved as 0.35 (a floating point representation is required by most components that uses the list) . The initialization is done by importing the names of the objects from the resources.

Here is the method that extracts file names and parse them into float. I feel it is not well written but I cannot point to a specific problem. I would love to hear your opinion. Thanks!

private static void InitializeZoomFactorsList()
{
    ResourceSet images = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
    List<string> names = images.Cast<DictionaryEntry>().Select(item => item.Key.ToString()).ToList();
    List<float> factors = names.ConvertAll<float>(delegate(string i) { return float.Parse(i.Substring(1, i.Length - 1)) / 100; });
    factors.Sort(); // because the list was strings, 300 came before 90, so after the parsing, I sort it by the value.
    zoomFactorsList = factors;
}


texts: Remove multiple array elements by indices

texts:
I prepared a method to make possible to select elements of the array except for some indexes.

def array_except(array, *indexes)
  indexes =
    indexes
      .flat_map { |e| e.is_a?(Range) ? e.to_a : e }
      .map { |e| e.negative? ? e + array.length : e }

  array.values_at(*((0...array.length).to_a - indexes))
end

It works in such a way:

> a = ["a", "b", "c", "d", "e", "f", "g", "h"]
array_except(a, 1, -1, 2..3, -4..-2)
=> ["a"]
> array_except(a, 1, 2)
=> ["a", "d", "e", "f", "g", "h"]
> array_except(a, -2..-1)
=> ["a", "b", "c", "d", "e", "f"]

I feel like it might be done with a lower level of complexity.
I spent a day playing with #each_with_object([]) but can't find the proper way.
Maybe someone has any thoughts?


texts: Project Euler # 30 Digits fifth power in Python

texts:
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

  \$1634 = 1^4 + 6^4 + 3^4 + 4^4\$
  \$8208 = 8^4 + 2^4 + 0^4 + 8^4\$
  \$9474 = 9^4 + 4^4 + 7^4 + 4^4\$

  As 1 = 1^4 is not a sum it is not included.

  The sum of these numbers is \$1634 + 8208 + 9474 = 19316\$.

  Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

from time import time

def powers(n, power):
    """Assumes n and power integers > 0.
    generates all numbers up to n if total(n digits ** power) = number."""
    nums_pows = {number: sum(int(digit) ** power for digit in str(number)) for number in range(2, n)}
    return (x for x, y in nums_pows.items() if x == y)

if __name__ == '__main__':
    start_time = time()
    print(sum(powers(1000000, 5)))
    print(f'Time: {time() - start_time} seconds.')


texts: Counting how many questions in each category are tagged

texts:
I have a homepage that shows how many questions are in a certain category which is done through tagging. The functionality is working great, it tells me how many of each there are.

However, newrelic's agent is telling me that there can be anywhere from 16-24 database calls per request, which seems excessive to me. How can I make this better? I just picked up rails a month or two ago, if that is relevant.

  def index

    @multiple_choice_questions           = MultipleChoiceQuestion.all
    @published_multiple_choice_questions = MultipleChoiceQuestion.all.published

    ## Get number of questions that are tagged with foundation
    @foundation_mcqs = MultipleChoiceQuestion.tagged_with(["foundation"], :wild => true).all
    @published_foundation_mcqs = MultipleChoiceQuestion.tagged_with(["foundation"], :wild => true).published

    @anatomy_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["anatomy", "foundation", "sem1"], :match_all => true).published.size
    @behavioral_sciences_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["behavioral science", "foundation", "sem1"], :match_all => true).published.size
    @biochemistry_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["biochemistry", "foundation", "sem1"], :match_all => true).published.size
    @community_medicine_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["community medicine", "foundation", "sem1"], :match_all => true).published.size
    @embryology_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["embryology", "foundation", "sem1"], :match_all => true).published.size
    @histology_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["histology", "foundation", "sem1"], :match_all => true).published.size
    @microbiology_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["microbiology", "foundation", "sem1"], :match_all => true).published.size
    @pathology_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["pathology", "foundation", "sem1"], :match_all => true).published.size
   @sem1_pharma_mcq = MultipleChoiceQuestion.tagged_with(["pharmacology", "sem1"], :match_all => true).published.size
    @physiology_sem_one_foundation_mcq = MultipleChoiceQuestion.tagged_with(["physiology", "foundation", "sem1"], :match_all => true).published.size
    ##
    #

  end

published is a scope defined in the model file, by the way.

scope :published, -> { where(published: true) }


texts: A simple testable standalone DLL for die rolling

texts:
I've decided to challenge myself by writing a test standalone DLL with the objective of making all of its publicly-exposed objects able to be as intuitive and as simple-to-use as possible.

I've decided to try and create some objects that might be used in a game, like a deck of cards and a die.

Here's my Die for example:

public class Die
{
    private readonly Random _random;
    private readonly int _numberOfSides;

    public Die(int numberOfSides)
    {
        if(numberOfSides < 2)
            throw new ArgumentException(string.Format(GameComponentsResources.InvalidNumberOfSides, numberOfSides));

        _numberOfSides = numberOfSides;
        _random = new Random();
    }

    public int Roll()
    {
        return _random.Next(1, _numberOfSides);
    }
}

So obviously the random part of this is untestable unless I write a non-deterministic test, which I don't want to do.

If this was standard enterprise code I was writing, I'd mock the Random and inject it. However, let's say someone shelled out some cash for my GameComponents library. Do I think they would consider it a good product if they have to instantiate and pass in a random just to get a die for their game? Nah. I'd rather keep it concise and intuitive, like this: var die = new Die(6); or at the very most var die = dieCollection.GetDie(6);

So standard constructor injection is out of the picture for now. Property injection is better, but I still don't want to start depending on a container and writing a bootstrapper for something that is basically encapsulating a random.

I was thinking about getting hold of a seed value and passing it around (but without forcing consumers to pass in a seed value, unless they really wanted to), so I can get some deterministic values for my test, but the only way I can think to do this while maintaining good encapsulation is making a method like this:

protected virtual long GetSeed() //could be a property too
{
    return Environment.TickCount; //or whatever
}

...and then inheriting from it and overriding it in my tests. I could also do this for the Random itself. But that's generally a legacy code refactoring technique. Do I really want my shiny new code to rely on this?

I'd like to see some solutions where I can get near-100% test coverage (i.e. not creating more layers but still ultimately resulting in an area of code deemed "untestable") and maintain a simple, intuitive quasi-API as possible.