texts: Parallel reduction by key implementations

texts:
I have an implementation of the reduction approach used in this document. Furthermore, I extended (crudely) this so I can reduce-by-key.

In my setup I can assume that a key array variable is constant through subsequent calls to a reduction kernel and that it is sorted in increasing order, and can thus pre-process and make any assumptions about the reduction necessary. I can further assume that each individual key will only ever be seen at the block level and as such I do not need to consider reduction across blocks.

To extend the approach used in the above document, I have padded data (with -1) such that each warp only deals with a single key value, and then the results of each individual warp's reduction is atomically added to the output array. However, this is inefficient as I have to launch many times more threads that are really necessary, and most are inactive.

An example key:

[0 0 0 0 0 0 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...

Below is the setup I have.

__global__ void reduce(int N, int* key, float* out)
  {
    int i = blockIdx.x * blockDim.x + ti;
    if (i < N)
      {
        int ti = threadIdx.x;
        int li = ti % warpSize;

        // code which computes a value per thread to be reduced,
        // for threads where key[i] == -1, val = 0.f
        float val = 123.45f;

        // reset out to zero ready for atomic addition later
        if (li == 0)
          out[key[i]] = 0.f;
        __syncthreads();

        // warp reduction
        int offset = 0;
        for (offset = warpSize / 2; offset > 0; offset /= 2)
          val += __shfl_down(val, offset);

        // atomically update out with each warp's result
        if (li == 0)
          atomicAdd(&out[key[i]], val);
      }
   }

What improvements could be appropriate for such a reduce-by-key implementation? For example, I think I should be using __ballot to only reduce those with keys matching a predicate, and could therefore remove my padding with -1s, although can't get my head around it to actually implement it.


texts: Python List Continuation with multiple lambdas applied

texts:
I'm attempting to apply multiple filters and maps to a list and attempted to refactor into something i believe is more readable. In my code, I am reading a file to create a list of terms, then munging it into something I will feed into another script.

Please note my terminology in the title might be wrong, but please feel free to correct.

Originally, I had something that looked like this:

random_substring = lambda word: word[:(random.randrange(len(word) - 2) + 1)]

only_longer_words = lambda word: len(word) > 2

terms = []

#File manipulation that adds words to terms

terms = filter(only_longer_words, terms)
terms = map(random_substring, terms)
terms = filter(only_longer_words, terms)

#Save terms to file

After refactoring, I created a ChainList which inherits from list:

class ChainList(list):
    def filter(self, function):
        return ChainList(filter(function, self))

    def map(self, function):
        return ChainList(map(function, self))

    def uniquify(self):
        return ChainList(OrderedDict.fromkeys(self))

and use it as such:

terms = ChainList()

working_list = (
    terms.filter(only_longer_words)
         .map(random_substring)
         .filter(only_longer_words)
         .uniquify()
)

The intent is to make it easy to chain operations on lists. It works, but as a Python beginner, wanted a review.


texts: Efficiently checking if a number is divisible by 3

texts:
I'm looking for code review, best practices and optimizations.

public final class DivThreeEfficiently {

    private DivThreeEfficiently() {}

    /**
     * Returns true if the input number is divisible by three.
     * Else returns false.
     *
     * @param n     the input number
     * @return      true if input number is divisible by three
     */
    public static boolean isMultipleOfThree(int n) {
        if(n < 0) n = -n;

        int evenCtr = 0;
        int oddCtr = 0;

        while (n != 0) {
            if ((n & 1) == 1) {
                oddCtr++;
            }
            n = n>>1;
            if ((n & 1) == 1) {
                evenCtr++;
            }
            n = n>>1;
        }

        return evenCtr == oddCtr;
    }
}

public class DivThreeEfficientlyTest {

    @Test
    public void testEvenNegative() {
        assertTrue(DivThreeEfficiently.isMultipleOfThree(-3));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(-6));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(-12));
    }

    @Test
    public void testEvenPositive() {
        assertTrue(DivThreeEfficiently.isMultipleOfThree(0));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(3));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(6));
    }

    @Test
    public void testOddNegative() {
        assertFalse(DivThreeEfficiently.isMultipleOfThree(-1));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(-4));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(-11));
    }

    @Test
    public void testOddPositive() {
        assertFalse(DivThreeEfficiently.isMultipleOfThree(1));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(4));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(11));
    }
}


texts: Rendering the periodic table in C++ using SFML

texts:
I have created this as an example. It uses SFML as its core dependency along with JSON for modern C++ to load the elements from a file.

Basically what happens is when an object that contains an instance of sf::Drawable is created, its constructor will be responsible for adding it to the draw list.  Its destructor is responsible for removing it from the list.

I am interested in if this is a good approach to dealing with the objects in my program that will need to be rendered or if I should be extending sf::Drawable class directly.

I am also interested in the overall code quality of the entire project. I am aware of the assignment and copy constructors that do nothing.  I am relatively new to C++ (1 semester).

Drawables.cpp

#include "Drawables.hpp"

namespace {
    std::vector<std::shared_ptr<sf::Drawable>> drawList;
}

std::vector<std::shared_ptr<sf::Drawable>>& getDrawList()
{
    return drawList;
}

Element.cpp constructor and destructor

#include "Element.hpp"

#include <exception>

Element::Element()
{
    drawable = std::shared_ptr<sf::RectangleShape>( new sf::RectangleShape(sf::Vector2f{49, 49}) );
    drawable->setFillColor(sf::Color::Green);
    getDrawList().push_back(drawable);
}

Element::~Element()
{
    // Remove it's drawable from the drawList
    for(int i = getDrawList().size() - 1; i >= 0; --i) {
        if(dynamic_cast<sf::RectangleShape*>(getDrawList()[i].get()) == drawable.get())
        {
            getDrawList().erase(getDrawList().begin() + i);
        }
    }
}

Client.cpp draw function

void Client::draw()
{
    while(window.isOpen()) {
        window.clear();
        for(std::shared_ptr<sf::Drawable> obj : getDrawList()) {
            window.draw(*obj);
        }

        window.display();
    }
}


texts: Count the number of occurrences of a word

texts:
I was selected for the third round of MS internships for third years. We were surprisingly asked a very easy question: “Make a program that counts the number of times the WORD "a" or "A" occurs”. I  wrote the code below and was rejected from attending the final interview.

What is wrong with my code? Please tell me how to improve it. People who used Char[] instead of string and those who didn't check for first and last words to be "A" were all selected.  The condition for commas before and after 'a' was also ignored. What is the error?
Is str.at(i) not good enough...? I know even if we use str[i] it is interpreted as str.operator[](i), so I'm preventing the overhead conversion, right?

#include<iostream>
#include<ctype.h>
#include<string>

using namespace std;

int main()
{

    string str;

    getline(cin,str);

    int i;
    int count=0;
    int l=str.length();

    for(i=1;i<l-1;i++)
    {
        if(toupper(str.at(i))=='A')
            if(str.at(i-1)==' ' && str.at(i+1)==' ')
                    count++;
    }

    if(toupper(str.at(0))=='A' && str.at(1)==' ')
        count++;

    if(toupper(str.at(l-1))=='A' && str.at(l-2)==' ')
        count++;

    cout<<"Count is "<<count<<endl;
    return 0;

}


texts:
I have just began porting an old project to ASP.NET MVC . In the end, I'll have a lot of controller methods like the one below, called by AJAX requests done by JQGrid objects in the pages:

AJAX request:

  /UserRole/RolesByUserGridData?userId=2&_search=false&nd=1407171194811&rows=10&page=1&sidx=RoleName&sord=asc

Controller code:

public ActionResult GetRolesByUserGridData(MvcJqGrid.GridSettings gridSettings, int userId)
    {
        IQueryable<Role> allRoles = _roleRepository.GetAsQueryable(where:null, includeProperties:"");
        IQueryable<UserRole> userRolesByUser = _repository.GetAsQueryable(where: c => c.UserId == userId, includeProperties: "Role");

        var gridItems = from role in allRoles
                        join userRole in userRolesByUser on role.Id equals userRole.RoleId into loj
                        from item in loj.DefaultIfEmpty()   // LEFT OUTER JOIN equivalent
                        select new UserRoleByUserViewModel
                        {
                            IsRoleAssociatedWithUser = (item.UserId == userId),
                            RoleName = role.Name
                        };

        SortOrder sortOrder = gridSettings.SortOrder != "desc" ? SortOrder.Asc : SortOrder.Desc;

        var pagedOrderedItems = PagingHelper<UserRoleByUserViewModel>.GetAsOrderedPagedList(
            gridItems, sortOrder, gridSettings.SortColumn,
            gridSettings.PageIndex, gridSettings.PageSize);

        var jsonData = new
        {
            total = pagedOrderedItems.TotalItemCount / gridSettings.PageSize + 1,
            page = gridSettings.PageIndex,
            records = pagedOrderedItems.TotalItemCount,
            rows = (
                from c in pagedOrderedItems
                select new
                {
                    id = "",
                    cell = new[]
                    {
                        "Edit",
                        "Details",
                        c.IsRoleAssociatedWithUser.ToString(),
                        c.RoleName
                    }
                }).ToArray()
        };

        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

My goal is to return IEnumerable from repositories and have fairly dumb controllers.

How would you suggest refactoring this?

Ideally, the code in my controller method should be:

public ActionResult GetRolesByUserGridData(MvcJqGrid.GridSettings gs, int userId)
{
   var json = _userRoleService
      .GetRolesByUser()
      .ToOrderedList(“Id”, “Asc”)
      .ToPagedList(gs.PageIndex, gs.PageSize)
      .ToJsonData();
   return Json(jsonData, JsonRequestBehavior.AllowGet);
}

where ToOrderedList(), ToPagedList() and ToJsonData() would be extension methods to IQueryable<>, placed outside the Web project.

But it's still not clear to me where should the ViewModels live in this scenario:

A. Have them in the Service layer, which is in a different project - but then they lose all the logic related to Data Annotation, or I need to reference MVC in the Service layer, which seems weird.

B. Have them in the Web project - but why shouldn't the service be aware of the ViewModel and only retrieve the data that the ViewModel needs? Is it really necessary to create a new DTO object only to pass data from the service to the controller?


texts:
This is small piece of bigger puzzle, but usable by its own.
It an attempt to have a nonblocking queue with "unlimited" (besides memory size) buffer length.

Got unit-tests 100% statement coverage, it looks that it's ok, but I'm very new to Go and concurrency so I might miss something.

import "sync"

// Message and MessageQueuer are interfaces, defined in other file

type msgQueue struct {
    input, output     chan Message
    buffer            []Message
    head, tail, count int
    immediateClose    bool
    done              sync.WaitGroup
}

func NewQueue() MessageQueuer {
    mq := &msgQueue{
        input:  make(chan Message),
        output: make(chan Message),
        buffer: make([]Message, 16),
    }

    mq.done.Add(1)

    go mq.magicBuffer()

    return mq
}

func (mq *msgQueue) In() chan<- Message {
    return mq.input
}

func (mq *msgQueue) Out() <-chan Message {
    return mq.output
}

func (mq *msgQueue) Len() int {
    return mq.count
}

func (mq *msgQueue) Close() {
    close(mq.input)
}

func (mq *msgQueue) CloseAndWait() {
    close(mq.input)
    mq.done.Wait()
}

func (mq *msgQueue) ClearAndClose() {
    mq.immediateClose = true
    mq.count = 0
    close(mq.input)
}

func (mq *msgQueue) enqueue(msg Message) {
    if mq.head == mq.tail && mq.count > 0 {
        buffer := make([]Message, len(mq.buffer)*2)

        copy(buffer, mq.buffer[mq.head:])
        copy(buffer[len(mq.buffer)-mq.head:], mq.buffer[:mq.head])

        mq.head = 0
        mq.tail = len(mq.buffer)

        mq.buffer = buffer
    }

    mq.buffer[mq.tail] = msg
    mq.tail = (mq.tail + 1) % len(mq.buffer)
    mq.count++
}

func (mq *msgQueue) dequeue() Message {
    msg := mq.buffer[mq.head]

    mq.head = (mq.head + 1) % len(mq.buffer)
    mq.count--

    return msg
}

func (mq *msgQueue) shutdown() {
    defer mq.done.Done()

    if mq.immediateClose {
        mq.buffer = nil
    }

    for mq.count > 0 {
        mq.output <- mq.dequeue()
    }

    close(mq.output)
}

func (mq *msgQueue) magicBuffer() {
    for {
        if mq.count == 0 {
            msg, open := <-mq.input

            if open && !mq.immediateClose {
                mq.enqueue(msg)
            } else {
                mq.shutdown()

                return
            }
        } else {
            select {
            case msg, open := <-mq.input:
                if open && !mq.immediateClose {
                    mq.enqueue(msg)
                } else {
                    mq.shutdown()

                    return
                }

            case mq.output <- mq.buffer[mq.head]:
                // dequeue
                mq.head = (mq.head + 1) % len(mq.buffer)
                mq.count--
            }
        }
    }
}


texts: Can I use IDisposable by treating abstract concepts such as colors as resources?

texts:
There are the following class:

class ConsoleForegroundColor : IDisposable
{
    public ConsoleForegroundColor(ConsoleColor color)
    {
        OriginalColor = Console.ForegroundColor;
        Console.ForegroundColor = color;
    }

    public ConsoleColor OriginalColor { get; set; }

    public void Dispose()
    {
        Console.ForegroundColor = OriginalColor;
    }
}

This has the following uses:

Console.WriteLine("display with default color");
using (new ConsoleForegroundColor(ConsoleColor.Green))
{
    Console.WriteLine("display with green");
}
Console.WriteLine("display with default color");

This source code changes the console font color to the specified color when creating an instance and restores it when discarded.

I think it's possible to think of the colors drawn on the console as resources, so I don't think it's so different from the original use of IDisposable. Is the use of IDisposable like this source code a source that is difficult to understand and maintain? If you have a better think, please tell me.


texts: If zero found in Matrix. make entire row & column zero

texts:
Problem is - If in an MxN matrix, a zero is encountered, the entire row and entire column should be set to zero.

Example -

8   4   2
2   3   7
1   0   1
9   8   4

Should become:

8   0   2
2   0   7
0   0   0
9   0   4

I encountered this problem today and came up with a solution.
I'm hoping for some feedback regarding the time/space complexity and how efficient my solution is :

Code -

 public static void zeroMatrix(int[][] arr1)
{
    ArrayList<Integer> coord = new ArrayList<>();

    int row = arr1.length;
    int column = arr1[0].length;
    for(int i=0; i < row; i++)
    {
        for(int j=0; j < column; j++)
        {
            if(arr1[i][j]==0)
            {
                coord.add((10*i) + j);
            }
        }
    }

    for(int n : coord)
    {
         int j=n%10;
         int i=n/10; int k=0;
        int l=0;
        while(k<row)
        {
            arr1[k][j]=0;
            k++;
        }
        while(l<column)
        {
            arr1[i][l]=0;
            l++;
        }
    }
}

What I'm doing is:

Saving the coordinates of found zeroes in an ArrayList as a two
digit integer.
Taking out ones and tens places from the stored
list (which are the coordinates) and running a loop over the found
zeroes only.
Then making the corresponding rows and columns 0


texts: Print length of longest sequence of consecutive numbers

texts:
Problem H (Longest Natural Successors):

  Two consecutive integers are natural successors if the second is the
  successor of the first in the sequence of natural numbers (1 and 2 are
  natural successors). Write a program that reads a number N followed by
  N integers, and then prints the length of the longest sequence of
  consecutive natural successors.

  Example:

Input  7 2 3 5 6 7 9 10
Output 3

This is my code so far:

  import java.util.Scanner;

    public class Conse {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     Scanner scan = new Scanner(System.in);
     int x=scan.nextInt();
     int[] array= new int[x];
     for(int i=0;i<array.length;i++)
         array[i]=scan.nextInt();
     System.out.println(array(array));
      }
public static int array(int[] array){
    int count=0,temp=0;
    for(int i=0;i<array.length;i++){
        count=0;
        for(int j=i,k=i+1;j<array.length-1;j++,k++)
            if(array[j]-array[k]==1)
                count++;
            else{if(temp<count)
                temp=count;
            break;}
        }
    return temp+1;
 }

  }


texts: Checking whether an image is part of another

texts:
I have the following code (slightly modified for simplicity). It checks whether a given image A (the template) is part of another image B. To handle different sizes, image B is scaled as long as a match is found or some minimum/maximum image size is reached.

The naive implementation for this is quite straight forward but I'm not happy with it:

The code within the two while loops is almost identical.
Handling scaling down and scaling up in two different loops is inefficient in a lot of cases (e.g. when the first iteration of the second while loop would find a match but we still need to go through all iterations of the first one).

Can you offer some suggestions on how to improve my code?

double bestMatch = 0;

while (image.width() > MIN_IMAGE_WIDTH) {
   match = match(image, template); // for the sake of simplicity let this return a double
   if (match > bestMatch) {
      bestMatch = match;
   }
   if (match.maxVal >= threshold) {
      foundMatch = true;
      break;
   }
   image = scaleImage(image, 0.9);
}

image = originalImage;
while (image.width() < MAX_IMAGE_WIDTH) {
   match = match(image, template);
   if (match > bestMatch) {
      bestMatch = match;
   }
   if (match.maxVal >= threshold) {
      foundMatch = true;
      break;
   }
   image = scaleImage(image, 1.1);
}

// do something with bestMatch


texts: Javascript Stringify Nested Objects with Loop References

texts:
I created these functions that will take any object and stringify it, and can then de-stringify it later.

function stringify(objectToCopy, exceptionClasses = []) {

    // Listify.
    var objects = [];

    var que = [objectToCopy];
    while(que.length > 0){
        var o = que.pop();
        objects.push(o);
        var propNames = Object.getOwnPropertyNames(o);
        for (let i = 0; i < propNames.length; i++) {
            const n = propNames[i];
            var property = o[n];
            if (
                typeof property == "object" && property != null &&
                objects.indexOf(property) == -1 &&
                que.indexOf(property) == -1 &&
                exceptionClasses.indexOf(property.constructor.name) == -1
            ) {
                que.push(property);
            }
        }
    }

    // Stringify.
    var stringifiedList = [];

    for (let i = 0; i < objects.length; i++) {
        const o = objects[i];

        var temp = {
            "className": o.constructor.name,
            "properties": [],
        };

        var propNames = Object.getOwnPropertyNames(o);
        for (let i = 0; i < propNames.length; i++) {
            const n = propNames[i];
            var property = o[n];
            if (typeof property == "object" && property != null){
                if (exceptionClasses.indexOf(property.constructor.name) == -1) {
                    temp.properties.push({
                        "isObject": true,
                        "name": n,
                        "content": objects.indexOf(property), // content will here refer to the index of where the object is.
                    });
                }
            }else{
                var content = JSON.stringify(property);
                if (content == null) {
                    content = null; // Converts from undefined to null.
                }
                temp.properties.push({
                    "isObject": false,
                    "name": n,
                    "content": content,
                });
            }
        }

        stringifiedList.push(temp);
    }

    //
    return JSON.stringify(stringifiedList);
}
function deStringify (string) {
    var stringifiedList = JSON.parse(string);

    // Listify.
    var objects = [];
    for (let i = 0; i < stringifiedList.length; i++) {
        const data = stringifiedList[i];

        var cleanName = /[a-zA-Z_$][0-9a-zA-Z_$]*/.exec(data.className).toString();

        if (cleanName != data.className) {
            throw "ERROR: Class name validation failed."
        }

        var newObject = Object.create(eval(cleanName).prototype);
        objects.push(newObject);
    }

    // Destringify
    for (let i = 0; i < stringifiedList.length; i++) {
        const data = stringifiedList[i];
        const obj = objects[i];

        for (let j = 0; j < data.properties.length; j++) {
            const property = data.properties[j];
            if (property.isObject){
                obj[property.name] = objects[property.content];
            }else{
                obj[property.name] = JSON.parse(property.content);
            }
        }
    }

    return objects[0];
}

// Testing.
var a = [6,5,4,3];
var b = [a, a, "alpha", "beta"];
b.push(b);
a.push(b);

var s = stringify(a);
console.log(deStringify(s));

/* Output:
(5) [6, 5, 4, 3, Array(5)]
    0:  6
    1:  5
    2:  4
    3:  3
    4:  Array(5)
        0:  (5) [6, 5, 4, 3, Array(5)]
        1:  (5) [6, 5, 4, 3, Array(5)]
        2:  "alpha"
        3:  "beta"
        4:  (5) [Array(5), Array(5), "alpha", "beta", Array(5)]
        length: 5
        __proto__:  Array(0)
    length: 5
    __proto__:  Array(0)
*/

The reason I don't only use JSON.stringify() is because it does not conserve the prototype, and also does not support loop references. Is this approach hacky? Is there something about the objects I duplicate that I am missing when I only duplicate its properties? I know this code doesn't work for DOM objects or objects related to webgl.


texts:
I made a settings class for my own C# application. My main goal was to reach this class from every other class (this is why I choose the Singleton pattern). I also wanted to distinguish the different type of settings, so I added GeneralSettings and made it public. Do you know any other ways which I can tell apart the different type of settings? I thought about namespaces, but those are not allowed in classes.

I also wanted to make sure that I can restore its state if the user don't want to save the changes made in the settings dialog. What is your opinion about my implementation? Now I need to call SetRestorePoint and if I want to discard changes Restore.

public class Settings : ISerializable
{
    private Settings ()
    {
    }
    static private Settings _instance = null;
    static private Settings _restoreInstance = null;
    static public  Settings Get //Singleton
    {
        get
        {
            if (_instance == null)
                _instance = new Settings ();

            return _instance;
        }
        private set { }
    }

    public void SetRestorePoint ()
    {
        _restoreInstance = DeepClone (_instance);
    }
    public Settings Restore ()
    {
        _instance = _restoreInstance;
        return _instance;
    }

    public GeneralSettings General = new GeneralSettings ();

    [Serializable]
    public class GeneralSettings
    {
        public bool isAutomaticSave = false;
    }

    private static T DeepClone<T>(T obj)
    {
        using (var ms = new System.IO.MemoryStream ())
        {
        var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
        formatter.Serialize (ms, obj);
        ms.Position = 0;

        return (T) formatter.Deserialize (ms);
        }
    }
    //serialization...
}

How have people implemented Settings in bigger software?


texts:
Here is a "Roman Numerals" kata implementation. Given a decimal number one has to return a corresponding roman number.

I have following questions:

Is memory management correct? Here I assume that the caller is responsible for freeing memory.
Does this code conform to c code style?
Does it look like idiomatic c?

Thanks!

toRoman.h:

char * toRoman(int n);

typedef struct DecimalToRoman {
    int decimal;
    const char * roman;
} DecimalToRoman;

toRoman.c:

char * toRoman(int n) {
    if (n < 1) return NULL;

    const DecimalToRoman numbers[] = {
        { 1000, "M"  },
        {  900, "CM" },
        {  500, "D"  },
        {  400, "CD" },
        {  100, "C"  },
        {   90, "XC" },
        {   50, "L"  },
        {   40, "XL" },
        {   10, "X"  },
        {    9, "IX" },
        {    5, "V"  },
        {    4, "IV" },
        {    1, "I"  }
    };

    size_t resultLen = 1;
    int tmp = n;
    for (size_t i = 0; i < sizeof numbers / sizeof(DecimalToRoman) && tmp; i++) {
        while(tmp >= numbers[i].decimal) {
            tmp -= numbers[i].decimal;
            resultLen += strlen(numbers[i].roman);
        }
    }

    char * result = malloc(resultLen);
    if (result == NULL) {
        perror("allocate");
        return NULL;
    }
    memset(result, '\0', resultLen);

    for (size_t i = 0, r = 0; r < sizeof numbers / sizeof(DecimalToRoman); r++) {
        while (n >= numbers[r].decimal) {
            n -= numbers[r].decimal;

            int j = 0;
            while (numbers[r].roman[j])
                result[i++] = numbers[r].roman[j++];
        }
    }
    return result;
}


texts:
I am learning redux by doing a small project. Everything is working fine, but I need to know how I can refactor such code. For this situation, it might be good to use if conditions like I have done, but what if I need to handle 7-8 languages? It won't be viable to use else if for 7 times. What is the proper way to handle such situation?

import { FRENCH } from '../../public/messages/fr';
import { ENGLISH } from '../../public/messages/en';

const initialState = {
  lang: FRENCH.lang,
  messages: FRENCH.messages
};
export const localeReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'LOCALE_SELECTED':
    if (action.locale === 'fr') {
      return { ...initialState, lang: FRENCH.lang, messages: FRENCH.messages };
    } else if (action.locale === 'en') {
      return { ...initialState, lang: ENGLISH.lang, messages: ENGLISH.messages };
    } break;
    default:
      return state;
  }
};


texts:
This module has a ensure_downloaded function which takes a slice of Urls. It downloads all of the urls to a local downloads folder (if they aren't already downloaded) and returns.

use curl::easy::Easy;
use failure::Error;
use pbr::{ProgressBar, Units};
use std::fs::{rename, DirBuilder, File};
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use url::Url;

/// Return the local path where the given url will be stored.
pub fn downloaded_path(url: &Url) -> PathBuf {
    PathBuf::from("downloads")
        .join(url.host_str().unwrap())
        .join(&url.path()[1..])
}

/// Ensure that all the urls are downloaded into a local downloads directory.
pub fn ensure_downloaded(urls: &[&Url]) -> Result<(), Error> {
    // There is a single progress bar, the individual urls all contribute to it
    let mut progress = ProgressBar::new(0);
    progress.set_units(Units::Bytes);
    progress.set_max_refresh_rate(Some(Duration::from_millis(100)));
    let progress = Arc::new(Mutex::new(progress));

    // The following explicitly typed so that the closures have the correct error return type
    // and ? will work.
    let handles: Result<Vec<thread::JoinHandle<Result<(), Error>>>, Error> = urls.into_iter()
        // skip files which already exist
        .map(|url| (url, downloaded_path(url)))
        .filter(|(_, path)| !path.exists())
        .map(|(url, path)| {
            // ensure directory exists to contain the file
            DirBuilder::new()
                .recursive(true)
                .create(path.parent().unwrap())?;

            let mut easy = Easy::new();
            easy.url(url.as_str())?;
            easy.progress(true)?;

            let progress = progress.clone();

            // Create the file with a .tmp suffix
            // so if the download gets interrupted, we won't think it finished
            let mut temp_path = path.as_os_str().to_owned();
            temp_path.push(".tmp");
            let mut file = File::create(temp_path.clone())?;

            Ok(thread::spawn(move || {
                let mut transfer = easy.transfer();

                // curl doesn't accept actual errors of any sort returned here
                // so we just panic if we can't write for some reason
                transfer.write_function(|data| Ok(file.write(data).unwrap()))?;

                // We keep track of the last know total/completed
                // so we can adjust the progress bar
                let mut last_total = 0;
                let mut last_completed = 0;

                transfer.progress_function(move |total_download, completed_download, _, _| {
                    if let Ok(mut progress) = progress.lock() {
                        let total_download = total_download as u64;
                        let completed_download = completed_download as u64;

                        progress.total += total_download - last_total;
                        progress.add(completed_download - last_completed);

                        last_total = total_download;
                        last_completed = completed_download;
                    }

                    true
                })?;

                transfer.perform()?;

                // Only after completion, we rename the file to the target

                rename(temp_path, path)?;

                Ok(())
            }))
        })
        .collect();

    for handle in handles? {
        match handle.join() {
            Ok(result) => result?,
            Err(error) => return Err(format_err!("Thread failed {:?}", error)),
        }
    }

    Ok(())
}


texts:
MS SQL Server, no loops.  ;)

WITH Numbers AS (
    SELECT 1 as Number
    UNION ALL
    SELECT Number+1 FROM Numbers WHERE Number < 100
)
SELECT CASE
    WHEN Number % 15 = 0 THEN 'FizzBuzz'
    WHEN Number % 5 = 0 THEN 'Buzz'
    WHEN Number % 3 = 0 THEN 'Fizz'
    ELSE CAST(Number as varchar)
END AS FizzBuzz
FROM Numbers;

Execution time ~5ms.

With performance being the most important concern, could this be made better?


texts: Indeterminate-length big-endian to little-endian conversion in Python

texts:
I have a need to convert wire encoding (big-endian) to little-endian in Python.

The conversion needs to happen as a separate function; I am not allowed to change the function that reads the byte stream because it will break a lot of other functions.

The best I can think of is this:

def be_to_le(value: int) -> int:
    assert isinstance(value, int)
    numbytes = len(f"0{value:x}") >> 1
    if numbytes == 1:
        return value
    rslt = 0
    for b in value.to_bytes(numbytes, byteorder="little"):
        rslt <<= 8
        rslt |= b
    return rslt

Is there a better way?


texts: Task based GameObject recorder for networked game

texts:
I've recently been dipping my toes in to async code so I'm not 100% sure if there's a better way to do this, or if I'm going to run into problems down the road.

I plan on using the following class in Unity. I'll be capturing a minimal amount of game state data every frame (between 25-100 bytes). I add the data to a queue and when it reaches around 1kb, I give it to my client object to serialize and send it to a server via tcp. I've called each data holding queue a 'chunk'. (Packet probably would have been better)

I need to minimize blocking of Unity's main thread, I don't want there to be any opportunity for my client tasks to block the game thread so this class is supposed to act as a layer between the two. Recorder is probably a bad name for it.

Everything works right now, I'm just unsure if theres a better way to (nearly) asynchronously pass data through queues for processing between threads.

This class will be used like so:

Recorder recorder = new Recorder();
recorder.StartRecording(client, 30); //30 frames per chunk

...

//every frame
recorder.Record(frameData);

...

recorder.StopRecording();

frameData is any serializable class or struct.
I have my own

public class Recorder<T> {

    private BlockingCollection<Queue<T>> dataQueue;
    private BlockingCollection<T> receivingQueue;
    private int chunkSize;
    private CancellationTokenSource cts;
    private Client client;

    public Recorder(Client _client, int _chunkSize) {
        dataQueue = new BlockingCollection<Queue<T>>();
        receivingQueue = new BlockingCollection<T>();
        client = _client;
        chunkSize = _chunkSize;
        cts = new CancellationTokenSource();

    }

    public void StartRecording() {
        CancellationToken token = cts.Token;
        Task.Factory.StartNew(() => QueueFillerTask(token), token);
        Task.Factory.StartNew(() => DataSendingTask(token), token);
    }

    public void StopRecording() {
        cts.Cancel();
    }

    public void Record(T obj) {
        receivingQueue.Add(obj);
    }

    private void QueueFillerTask(CancellationToken token) {
        while (true) {

            Queue<T> chunk = new Queue<T>();

            try {
                while (chunk.Count < chunkSize) {
                    T obj = receivingQueue.Take(token);
                    chunk.Enqueue(obj);
                }
                dataQueue.Add(chunk);
                Logger.Log("Chunk added");
            } catch (System.OperationCanceledException e) {
                if (chunk.Count > 0) { //Put the incomplete chunk in the dataqueue.
                    dataQueue.Add(chunk);
                }
                Logger.Log("Recording ended");
                break;
            }
        }
    }

    private void DataSendingTask(CancellationToken token) {
        try {
            while (true) {
                Queue<T> data = dataQueue.Take(token);
                client.PackAndShip(data);
            }

        } catch (System.OperationCanceledException e) {
            bool moreData;
            do {
                Queue<T> remainingItem;
                moreData = dataQueue.TryTake(out remainingItem);
                if (moreData) {
                    client.PackAndShip(moreData);
                }
            } while (moreData);
            Logger.Log("Sending ended");
        }
    }

}


texts: Exception handling and general check in Java

texts:
Are the catch statements ok or must I put in a println()? In general, is the code good-looking enough?

    public void music(String song) {
        try {
    File soundFile = new File(song);
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    // load the sound into memory (a Clip)
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);

    // play the sound clip
    clip.start();
    }
    catch (IOException e) {
    }
    catch (LineUnavailableException e) {
    }
    catch (UnsupportedAudioFileException e) {
    }
}


texts:
I have this program finding 2 numbers in the array (unsorted) so that its sum equal to the target sum. Here is my program:
vector<int> findNumbers(vector<int>& nums, int target)
    {
        vector<int> result;
        for(int i = 0; i < nums.size() - 1; i++)
            for(int j = i + 1; j < nums.size(); j++)
                if(nums[i] + nums[j] == target)
                {
                    result.push_back(i);
                    result.push_back(j);
                    return result;
                }
        return result;
    }

But in the last line, the return result doesn't seem to do anything, because when the numbers are found it is already return before it, but if I remove it, it will cause error. Does the last line slow my program down?


texts:
I'm sure there's a better way to approach the following. I'm writing a plugin where users can enter settings in the following format:

Setting: "object1setting -> object2setting"

It's done this way to allow for multiple objects to be passed within the same JS call. I'm breaking the the strings apart at the "->" symbol and saving them, however there are many settings and I'm thinking there has to be a more efficient way of writing this:

// START PLUGIN, SETUP DEFAULT OPTIONS, EXTEND OPTIONS TO "O" .....
// I'VE JUST PULLED SOME RANDOM SETTINGS AS AN EXAMPLE.

bg_x_speed_in_set = o.bg_x_speed_in.toString().split("->"), // X PROPERTY SPEED IN
bg_x_speed_out_set = o.bg_x_speed_out.toString().split("->"), // X PROPERTY SPEED OUT
bg_y_speed_out_set = o.bg_y_speed_out.toString().split("->"), // Y PROPERTY SPEED OUT

...
// ETC

This continues on and gets lengthy. Everything works perfectly in all browsers. I'm just trying to clean up the code.


texts:
Wrote a small bash-script today that downloads the latest swedish wordpress archive , extracts it and writes wp-config.php

Would appreciate any feedback that could improve it / prettify it.

The script assumes that the database name & the username is always the same.

#!/bin/bash

#Download wordpress tar.gz
echo "Laddar ner senaste wordpress på svenska"
tarfile=$(curl -s https://sv.wordpress.org/ | grep -ioE "https:\/\/sv.wordpress.org\/wordpress-[0-9].[0-9].[0-9]-sv_SE.tar.gz")
wget $tarfile -O senaste_wp.tar.gz
tar xvfz senaste_wp.tar.gz -C ./
rm senaste_wp.tar.gz

# Move the wordpress files to this dir
mv wordpress/* .
rm -r wordpress

# Get wordpress salts
salts=$(curl https://api.wordpress.org/secret-key/1.1/salt/)

# Read userinput
read -p "Ange databasanvändare : " dbuser
read -p "Ange databaslösenord : " dbpass

# Write wp-config.php
cat > wp-config.php << EOF
define('DB_NAME', '$dbuser');
define('DB_USER', '$dbuser');
define('DB_PASSWORD', '$dbpass');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');

$salts

\$table_prefix  = 'wp_';

define('WP_DEBUG', false);

if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

require_once(ABSPATH . 'wp-settings.php');
EOF


texts:
This my first real program in python. I welcome harsh criticism.  I tried to make it as efficient as possible. Trying to balance speed and readability as well.  My program takes a file of text and parses and counts the frequency of the length of each word.
An important specification I left out is I'm using 2.7 or earlier and not 3.x.

This example below isn't perfect for my code b/c I scale my y axis by 20's so if the frequency isn't higher then it won't be printed out. I wanted to demonstrate quickly what it was doing. Otherwise copy and paste this into a file and load it as an argument. http://www.archives.gov/exhibits/charters/declaration_transcript.html

For example:

  If the this was the text that I used to parse into my file as an argument.

This would be the dictionary:

  1:1, 2:5, 3:3, 4:6, 5:1, 8:1

I then take this data make a histogram. I count "&" as a word of zero length. I used a time function to determine the speed, just to give me idea of what was faster.

  #!/usr/bin/python
"""
The program reads all the input, splitting it up into words, and computes the length of each word. Punctuation marks should not be included as a part of the word, so "it's" should be counted as a three-character word, and "final." should be counted as a five-character word.
The example text includes a "word" of zero length (the "tr(x) + " | ")
"); your solution should handle this.
When all input has been processed ,the program should print a table(Histogram) showing the word count for each of the word lengths that has been encountered.
"""

import sys
import time
from string import punctuation as punc
from string import maketrans as trans
import operator
lengthDict = {}

def insert_Dict(word):
    lengthDict[word] = lengthDict.get(word, 0) + 1

def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
        return ret
    return wrap

def roundup(x):
    return x if x % 100 == 0 else x + 100 - x % 100

@timing
def main():
    fileName = sys.argv[1]

    openFile = open(str(sys.argv[1]))

    readString = openFile.read()

    out = readString.translate(trans("",""), punc)

    for word in readString.split():
       if word in punc:
           #print(word)
           insert_Dict(0)

    for word in out.split():
        #print(word)
        insert_Dict(len(word))

    maxDomain = max(lengthDict.keys())
    maxRange = max(lengthDict.values())
    roundedMaxRange = roundup(maxRange)

    for x in range(roundedMaxRange,0, -20):
        newStr = ""
        if x % 100 == 0:
            newStr = newStr + str(x) + " -|"
        elif x % 20 == 0:
            newStr = newStr + "     |"
        else:
            newStr = newStr + "      "

        for domain in range(maxDomain + 1):
            if lengthDict.get(domain) >= x and lengthDict.has_key(domain) :
                    newStr = newStr + ('***')
            else:
                newStr = newStr + '   '

        print(newStr)

    print('     -|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|-')
    print '      0',
    for x in xrange(1, 16):
        print "",
        print x,

    print

if __name__ == '__main__':
    print('This program is being run by itself')
    main()
else:
    print('I am being imported from another module')


texts: Determining the region from several sources of information

texts:
The task is to determine the region by comparing three sources of information taking into account the coefficients of their importance.

//GetRegionIdByKeywordAsync returns region id by string name, if the region could not be determined, 0 will return

//The received identifiers can completely or partially coincide, or be absolutely different
int regionIdByIp = await GetRegionIdByKeywordAsync(regionByIpStr);
int regionIdByPhone = await GetRegionIdByKeywordAsync(regionByPhoneStr);
int regionIdByInput = await GetRegionIdByKeywordAsync(regionByInputStr);

var weights = new List<KeyValuePair<int, int>>
{
  //Each source of information has its own importance coefficient, determined manually
  new KeyValuePair<int, int>(regionIdByIp, 5),
  new KeyValuePair<int, int>(regionIdByPhone, 3),
  new KeyValuePair<int, int>(regionIdByInput, 4)
};

//The final decision is determined by the search for a region that has the highest score in the total
int regionId = weights.Where(x => x.Key != default(int)).GroupBy(kvp => kvp.Key).OrderByDescending(x => x.Sum(y => y.Value)).Select(x => x.Key).FirstOrDefault();

Do you see any improvement / issue?


texts: "Suspicious comparison of integer references" while checking for a monotonically increasing sequence

texts:
I have the following code which iterates on an Integer[] and makes sure that the the values in the array are in ascending order and that there are no neighbouring duplicates:

Integer previous = null;
for (Integer tb : trancheBoundaries) {
    if (previous == tb) {
        throw new IllegalThresholdConfigurationException("Two boundaries are the same");
    } else if (previous != null && previous > tb) {
        throw new IllegalThresholdConfigurationException("Previous is larger than current - tranche boundaries must be in ascending order");
    } else {
        previous = tb;
    }
}

I am getting a warning from Sonar warning of "suspicious comparison of integer references" on the first if clause.

I know why I am getting this, but in a situation like this, is it bad practice? I think it's ok because I know that I will always be comparing the same instances.


texts: Probability that Three Pieces Form a Triangle

texts:
I wrote some code to estimate the solution to the following problem:

If you break a line segment at two random points, what is the probability that the new line segments can form a triangle?

The code is relatively simple, and it works. However, I can't shake the feeling that each of the three functions I've created could be written more "Pythonically." For example, the first function (can_form_triangle) explicitly writes out the combinations of pairs from (a, b, c) and then compares them to the element of (a, b, c) which is not in the pair. There must be a way to express this more succinctly, more elegantly — more Pythonically.
To be clear, I'd just like advice on refactoring the code to be more elegant/Pythonic. I am not looking for advice on how to change the actual functionality to solve the problem more efficiently.
Here's the code:
#!/usr/bin/python3

from random import random

def can_form_triangle(a, b, c):
    '''Determines if lengths a, b, and c can form a triangle.

    Args:
        a, b, c: Number representing the length of a side of a (potential) triangle

    Returns:
        True if all pairs from (a, b, c) sum to greater than the third element
        False otherwise
    '''
    ab = a + b
    ac = a + c
    bc = b + c

    if (ab > c and ac > b and bc > a):
        return True

    return False

def try_one_triangle():
    '''Simulates breaking a line segment at two random points and checks if the segments can form a triangle.

    Returns:
        True if the line segments formed by breaking a bigger line segment at two points can form a triangle
        False otherwise
    '''
    first_point = random()
    second_point = random()
    sorted_points = sorted((first_point, second_point))

    return can_form_triangle(sorted_points[0], sorted_points[1] - sorted_points[0], 1 - sorted_points[1])

def estimate_triangle_probability():
    num_success = num_attempts = 0
    for _ in range(10000000):
        num_success += 1 if try_one_triangle() else 0
        num_attempts += 1

    print('Success:', num_success)
    print('Attempts:', num_attempts)
    print('Ratio:', num_success / (num_attempts))

if __name__ == '__main__':
    estimate_triangle_probability()


texts:
I would like to hear other people's opinion on how I unit tested a functionality in a Backbone Model. As you see below, the code under test, upon being called to toggle, toggles its completed state and saves the new state:

// js/models/todo.js

  var app = app || {};

  // Todo Model
  // ----------
  // Our basic **Todo** model has `title` and `completed` attributes.

  app.Todo = Backbone.Model.extend({

    // Default attributes ensure that each todo created has `title` and `completed` keys.
    defaults: {
      title: '',
      completed: false
    },

    // Toggle the `completed` state of this todo item.
    toggle: function() {
      this.save({
        completed: !this.get('completed')
      });
    }

  });

To unit test this, as you can see below, I stub Backbone.sync method and make sure that the Model is saved with the correct state:

describe("todo", function() {
    it("should save the toggled completed state", function() {
        var stub = sinon.stub(Backbone, "sync", function(method, model) {
            expect(model.get("completed")).to.equal(true);
        });

        var todo = new app.Todo({completed: false});

        todo.toggle();

        expect(stub.calledOnce).to.equal(true);

        Backbone.sync.restore();
    });
});


texts: Build SQL query criteria from form input

texts:
I am using a <form> to send various input parameters as a GET to retrieve data from a very simple two table MySQL db.

After filtering the inputs (resulting in $inputs), I'm using the following code to build the WHERE clause which I've adapted from a MATLAB function we use to build XQueries.

It works fine, but I'm just curious if there's a better way to do this in PHP, or if there is common practice for doing such.

public function parseInvoiceConstraints($inputs) {

    //pulled from different location but literals for this example
    $invTable = "invoices"
    $custTable = "customers"

    //used for queries
    $constraints = "";
    $sql_conj = "WHERE ";

    //parseargs into SQL WHERE
    foreach ($inputs as $param => $val) {
        if ($val == false) {
            continue;
        }
        switch ($param) {
            case 'inv_num':
                $constraints = "$constraints"
                        . "$sql_conj"
                        . "$invTable.$param=$val";
                $sql_conj = " AND ";
                break;
            case 'name':
                $constraints = "$constraints"
                        . "$sql_conj"
                        . "$custTable.$param LIKE \"%$val%\"";
                $sql_conj = " AND ";
                break;
            case 'customer_id':
                $constraints = $constraints
                        . "$sql_conj"
                        . "$invTable.$param=$val";
                $sql_conj = " AND ";
                break;
            case 'pcs':
                $constraints = $constraints
                        . "$sql_conj"
                        . "$invTable.$param=$val";
                $sql_conj = " AND ";
                break;
            case 'tag_num':
                $constraints = $constraints
                        . "$sql_conj"
                        . "$invTable.$param=$val";
                $sql_conj = " AND ";
                break;
        }
    }
    return $constraints;
}

For the URL:

/invoice.php?inv_num=&name=gon&customer_id=&pcs=2&tag_num=72

the function will return:

WHERE customers.name LIKE "%gon%" AND invoices.pcs=2 AND invoices.tag_num=72


texts:
I have written this code for practice. Here we will enter the number by which we want to shift alphabets.
For eg.

  Enter by how many numbers you want to shift alphabets: 4

  Enter string: Programmer C++

  Encrypted String: Lnkcnwiian Y++

  Decryted String: Programmer C++

Review this code and suggest better C++11 and C++14 alternatives.

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>

class Cipher
{
    unsigned n;
    const std::vector<char> alphabetL { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
      'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
      'X', 'Y', 'Z' };
    const std::vector<char> alphabetS { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
      'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
      'x', 'y', 'z' };
    std::unordered_map<char, char> shiftByNL;
    std::unordered_map<char, char> shiftByNS;

  public:
    Cipher(unsigned n = 0);
    std::string encrypt(std::string&);
    std::string decrypt(std::string&);

  private:
    char byValue(const char); //Find by value
};

Cipher::Cipher(unsigned n)
{
    for (int i = 0; i < n; i++)
    {
        shiftByNL.insert(std::make_pair(alphabetL[i], alphabetL[(26 - n) + i]));
        shiftByNS.insert(std::make_pair(alphabetS[i], alphabetS[(26 - n) + i]));
    }
    for (int i = n; i < 26; i++)
    {
        shiftByNL.insert(std::make_pair(alphabetL[i], alphabetL[i - n]));
        shiftByNS.insert(std::make_pair(alphabetS[i], alphabetS[i - n]));
    }
}

char Cipher::byValue(const char value)
{
    for (auto itL = shiftByNL.begin(), itS = shiftByNS.begin();
          itL != shiftByNL.end(), itS != shiftByNS.end(); ++itL, ++itS)
    {
        if (itL->second == value)
        {
            return itL->first;
        }
        else if (itS->second == value)
        {
            return itS->first;
        }
    }
    //not an alphabet
    return value;
}

std::string Cipher::encrypt(std::string& original)
{
    std::string encrypted;
    std::size_t len = original.length();
    for (std::size_t i = 0; i < len; i++)
    {
        if (original[i] == ' ')
        {
            encrypted = encrypted + ' ';
        }
        else if (shiftByNS.find(original[i]) != shiftByNS.end())
        {
            auto search = shiftByNS.find(original[i]);
            encrypted = encrypted + search->second;
        }
        else if (shiftByNL.find(original[i]) != shiftByNL.end())
        {
            auto search = shiftByNL.find(original[i]);
            encrypted = encrypted + search->second;
        }
        else //not an alphabet
        {
            encrypted = encrypted + original[i];
        }
    }
    return encrypted;
}

std::string Cipher::decrypt(std::string& encrypted)
{
    std::string decrypted;
    std::size_t len = encrypted.length();
    for (std::size_t i = 0; i < len; i++)
    {
        if (encrypted[i] == ' ')
        {
            decrypted = decrypted + ' ';
        }
        else
        {
            char key = byValue(encrypted[i]);
            decrypted = decrypted + key;
        }
    }
    return decrypted;
}

int main()
{
    unsigned num;
    std::cout << "Enter by how many numbers you want to shift alphabets: ";
    std::cin >> num;
    std::cin.ignore();
    Cipher cipher(num);
    std::string str;
    std::cout << "Enter string: ";
    std::getline(std::cin, str);
    std::string res = cipher.encrypt(str);
    std::cout << "Encrypted String: ";
    std::cout << res << '\n';
    std::cout << "Decryted String: ";
    std::string decrypted = cipher.decrypt(res);
    std::cout << decrypted << '\n';
}


texts: Type & Thread-safe Logger Implementation

texts:
So I had previously posted this question and asked for some feedback regarding my (now) header-only logging system and figured it would be a good time to go back to the changes I made it and see if it can be further improved before starting a larger project.

#pragma once

/*
Header only logging system.
Should be thread-safe and type-safe, as well as easier to use.
Hopefully no major errors to deal with.
*/

// Standard Headers.
#include <ostream>
#include <variant>
#include <memory>
#include <utility>
#include <mutex>
#include <array>
#include <string_view>

// Everything will take place in this namespace, so we can use the Logger:: prefix for functions.
namespace Logger {
    // Various logging severity levels.
    enum class Level {
        Info, Debug, Warning, Error, Fatal
    };

    class Log {
    public:
        // Takes standard streams cout, cerr, etc.
        explicit Log(std::ostream& p_stream) : m_log(&p_stream) {}

        // Create logger using std::make_unique<std::ofstream>(...) so ownership is passed.
        explicit Log(std::unique_ptr<std::ostream> p_stream) : m_log(std::move(p_stream)) {}

        template <typename T>
        inline void info(T&& p_message);

        template <typename T>
        inline void debug(T&& p_message);

        template <typename T>
        inline void warning(T&& p_message);

        template <typename T>
        inline void error(T&& p_message);

        template <typename T>
        inline void fatal(T&& p_message);

    private:
        template <typename T>
        void log(T&& p_msg) const {
            auto const t_lock = std::lock_guard(*m_lock);
            std::visit([&](auto&& p_ptr) {
                (*p_ptr) << p_msg;
            }, m_log);
        };

        std::ostream& stream() const {
            return std::visit([](auto&& ptr) -> std::ostream& {
                return *ptr;
            }, m_log);
        }

        template <typename T>
        inline void add(Logger::Level p_level, T&& p_message);

        std::variant<std::unique_ptr<std::ostream>, std::ostream*> m_log;
        std::unique_ptr<std::mutex> m_lock = std::make_unique<std::mutex>();
        std::array<std::string_view, 5> m_levels = { "Info", "Debug", "Warning", "Error", "Fatal" };
    };

    template <typename T>
    void Log::add(Level p_level, T&& p_message) {
        auto const f_lock = std::lock_guard(*m_lock);
        stream() << m_levels[static_cast<size_t>(p_level)] << ": " << p_message << '\n';
    }

    template <typename T>
    inline void Log::info(T&& p_message) {
        add(Level::Info, p_message);
    }

    template <typename T>
    inline void Log::debug(T&& p_message) {
        add(Level::Debug, p_message);
    }

    template <typename T>
    inline void Log::warning(T&& p_message) {
        add(Level::Warning, p_message);
    }

    template <typename T>
    inline void Log::error(T&& p_message) {
        add(Level::Error, p_message);
    }

    template <typename T>
    inline void Log::fatal(T&& p_message) {
        add(Level::Fatal, p_message);
    }
}

Is this thread-safe? Is it type-safe? How can I improve on it? What have I done badly? What have I done correctly so I know to keep that for the future?

Thank you!


texts: Reverse in terms of fold-right and fold-left

texts:
Exercise 2.39

  Complete the following definitions of reverse
  (exercise 2.18) in terms of fold-right
  and fold-left from exercise 2.38:

(define (reverse sequence)
  (fold-right (lambda (x y) <??>) nil sequence))
(define (reverse sequence)
  (fold-left (lambda (x y) <??>) nil sequence))

I wrote this answer:

(define (fold-right op initial seq)
  (define (rec rest)
    (if (null? rest)
        initial
        (op (car rest)
            (rec (cdr rest)))))
  (rec seq))

(define (fold-left op initial seq)
  (define (iter result rest)
    (if (null? rest)
        result
        (iter (op result (car rest)) (cdr rest))))
  (iter initial seq))

(define (reverse sequence)
  (fold-right (lambda (x y)
                (append  y (list x))) null sequence))

(define (reverse-l sequence)
  (fold-left (lambda (x y) (cons y x)) null sequence))

(define a (list 1 2 3 4 5))


texts:
I have code that take in a URL (via URL or String) and returns the status code.  I am new to web development, so it is very possible that I may be taking a poor approach at this.  One thing I don't like about my code is the need for the InetSocketAddress to be hardcoded, but I have not been able to find a way around this short of passing it in as parameters. As an inexperienced programmer and complete newbie to web development, what improvements to the following code would you suggest?

import java.io.IOException;
import java.net.*;

public class HttpStatusCodeRequester {
    public static int getHttpStatusCode(URL url) {
        try {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.mycompany.com", 8099));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            connection.disconnect();
            return responseCode;
        } catch (IOException e) {
            System.err.println("HTTP Status Code Request failed for " + url + " in HttpStatusCodeRequester.getHttpStatusCode(URL)!");
            e.printStackTrace();
            return -1;
        }
    }

    public static int getHttpStatusCode(String url) {
        try {
            return getHttpStatusCode(new URL(url));
        } catch (MalformedURLException e) {
            System.err.println("Malformed URL passed into HttpStatusCodeRequester.getHttpStatusCode(String)!");
            e.printStackTrace();
            return -1;
        }
    }
}


texts: Worksheetfunction.Vlookup value on error

texts:
I have this function (wb is a public workbook variable):

Function GetTiersAccount(TiersName As String, Clients As Boolean) As Long

If Clients = True Then
    On Error GoTo ERRRRR
    GetTiersAccount = WorksheetFunction.VLookup(TiersName, wb.Sheets(1).Range("A1:B13"), 2, False)
    Exit Function
Else
    On Error GoTo ERRRRR
    GetTiersAccount = WorksheetFunction.VLookup(TiersName, wb.Sheets(1).Range("D1:E94"), 2, False)
    Exit Function
End If

ERRRRR:
GetTiersAccount = 471

End Function

I feel like the way I have managed to deal with worksheetfunction.vlookup error unelegant. However I want Gettieraccount to return 471 on vlookup error.

There must be a better way to do that.
Thanks in advance.


texts:
An algorithm to reverse characters of each word in a sentence.
What would be your concerns regarding the following solution?

Example input: "I love New York"
output: "I evol weN kroY"

public class Main {
    public static void main(String[] args) throws IOException {
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        final String words = bufferedReader.readLine().trim();
        final char[] reversedWord = reverseWords(words.toCharArray());

        bufferedWriter.write(reversedWord);

        bufferedReader.close();
        bufferedWriter.close();
    }

    private static char[] reverseWords(char[] input) {
        int startIndex = 0;
        int endIndex = 0;
        while (endIndex < input.length) {
            final boolean isLastWord = endIndex == input.length - 1;
            if (input[endIndex] == ' ' || isLastWord) {
                if (isLastWord) {
                    endIndex++;
                }
                reverseWord(input, startIndex, endIndex);
                startIndex = ++endIndex;
            } else {
                endIndex++;
            }
        }
        return input;
    }

    private static void reverseWord(char[] word, int startIndex, int endIndexExclusive) {
        final int wordLength = (endIndexExclusive - startIndex);
        for (int i = 0; i < wordLength/2; i++) {
            final char temp = word[startIndex + i];
            word[startIndex + i] = word[endIndexExclusive - i - 1];
            word[endIndexExclusive - i - 1] = temp;
        }
    }
}

Unit tests would be like:

public class QuestionOneTest {
    @Test
    public static should_reverse_chars() {
        // given
        final String input = "I love New York";

        // when
        final char[] reversed = QuestionOne.reverseWords(input.toCharArray());

        // then
        assert String.copyValueOf(reversed).equals("I evol weN kroY");
    }
}


texts:
I wrote a program that read a csv file that contain 100 rows that look like:
1;S****L;SCHOOL
2;*A*G*A*;HANGMAN

then try to guess the letters like in a hangman game. My scope is to count every right and wrong letters and then sum them up. The code works fine, I get around 1670 right + wrong attempts to guess the letters. My approach was to create a dictionary in which I store all the letters from the alphabet and read every words from the file then sum every appearance of a letter and store them in the dictionary. Somethin like
{
   "A" : 30,
   "B" : 40
}

Then I sort the dict based on every letter occurrence and first try to guess the letter with the most apparace.
My question. Is something that I can improve in order to get a smaller number of attempts?
import csv

INPUT_FILE = "words.csv"

def oppenFile():        # function to read the file
    with open(INPUT_FILE, "r", encoding="utf-8") as words:
        reader = list(csv.reader(words, delimiter=";"))
        return reader

def letterCount():      # function that count every the letter in the file and return a dict: {A : 2}
    letters = dict.fromkeys("QWERTYUIOPĂÎASDFGHJKLȘȚÂZXCVBNM", 0)
    words = oppenFile()
    for w in range(len(words)):
        for l in list(words[w][2]):
            if l not in list(words[w][1]):
                letters[l] += 1
    return letters

def checkLetters(word, wholeWord, letters):     # function that solve a word return the number of right + wrong attempts
    attempts = 0
    for letter, key in letters.items():
        if letter in wholeWord and letter not in word:
            attempts += 1
            index = [i for i, lit in enumerate(wholeWord) if lit == letter]
            letters[letter] -= len(index)
            for j in range(len(index)):
                word = word[:index[j]] + letter + word[(index[j] + 1):]

        elif '*' not in word:
            break
        else:
            attempts += 1
    return attempts

def hangman():
    words = oppenFile()
    numberOfAttempts = 0
    letters = letterCount()

    for i in range(len(words)):
        letters = dict(sorted(letters.items(), key=lambda x: x[1], reverse=True)) # sort the dict

        numberOfAttempts += checkLetters(words[i][1], words[i][2], letters)

    print(f"{numberOfAttempts} right + wrong attempts")

if __name__ == "__main__":
    hangman()


texts: Create a dictionary from a list of key and multi list of values in Python

texts:
I have a list of key:
list_date = ["MON", "TUE", "WED", "THU","FRI"]

I have many lists of values that created by codes below:
list_value = list()
for i in list(range(5, 70, 14)):
    list_value.append(list(range(i, i+10, 3)))

Rules created that:

first number is 5, a list contains 4 items has value equal x = x + 3, and so on [5, 8, 11, 14]

the first number of the second list equal: x = 5 + 14, and value inside still as above x = x +3
[[5, 8, 11, 14], [19, 22, 25, 28], [33, 36, 39, 42], [47, 50, 53, 56], [61, 64, 67, 70]]

I expect to obtain a dict like this:
collections = {"MON":[5, 8, 11, 14], "TUE" :[19, 22, 25, 28], "WED":[33, 36, 39, 42], "THU":[47, 50, 53, 56], "FRI":[61, 64, 67, 70]}

Then, I used:
zip_iterator = zip(list_date, list_value)
collections = dict(zip_iterator)

To get my expected result.
I tried another way, like using the lambda function.
for i in list(range(5, 70, 14)):
    list_value.append(list(range(i,i+10,3)))
    couple_start_end[lambda x: x in list_date] = list(range(i, i + 10, 3))

And the output is:
{<function <lambda> at 0x000001BF7F0711F0>: [5, 8, 11, 14], <function <lambda> at 0x000001BF7F071310>: [19, 22, 25, 28], <function <lambda> at 0x000001BF7F071280>: [33, 36, 39, 42], <function <lambda> at 0x000001BF7F0710D0>: [47, 50, 53, 56], <function <lambda> at 0x000001BF7F0890D0>: [61, 64, 67, 70]}

I want to ask there is any better solution to create lists of values with the rules above? and create the dictionary collections without using the zip method?


texts: Keeping just the rare characters in a long string

texts:
I'm working on The Python Challenge. The current code iterates over a 98,766-character string before printing an 8-character string. Current execution time is between 7 and 10 seconds.

How can I optimize my current code and what rookie mistakes am I making that may be adding to the execution time?

import urllib.request
import re

url = 'http://www.pythonchallenge.com/pc/def/ocr.html'

x = urllib.request.urlopen(url).read().decode('utf-8')

text = (re.findall(r'<!--(.*?)-->', x, re.DOTALL))[1]

# source contains two adjacent html comments
# returns second comment

s = ''
for i in text:
    if text.count(i) < 10:
        s += i
print(s)


texts:
I have a question regarding optimizing a php email class. It's basically a wrapper class than needs to be able to accept different objects and always output an email. I'm trying to make it generic, in it's current form it's working but I still feel like it may be to tightly coupled. I was hoping someone here could make some suggestions on how to improve it. I would really appreciate it.

    require_once 'PHPMailerAutoload.php';

    class Email{

    public $fromEmailAddress;
    public $displayName;
    public $body;
    public $toEmailaddress;

    public function sendEmail(Email $email){

        $mail = new PHPMailer;
        $mail->isSMTP(); // Set mailer to use SMTP
        $mail->Host = 'exploud-xxxxx.ny.xxxxxx.com'; // Specify main and backup server
        $mail->setFrom($this->fromEmailAddress, $this->displayName);
        //$mail->addAddress($email);
        $mail->addAddress($this->toEmailaddress); // Add a recipient
        $mail->addCC($this->fromEmailAddress);

        $mail->WordWrap = 50; // Set word wrap to 50 characters
        $mail->isHTML(true); // Set email format to HTML
        $mail->Subject = "Load Tender " . " - " . $this->displayName;
        $mail->Body = $this->body;

        if (!$mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
            exit;
        }
        return true;

    }

}

Different php file, auto load the Email class:
Take the Bill of Lading object that was created and email it

$bol = new Email();

$bol->body="Bill of Lading body";
$bol->displayName='Jon jonhnson';
$bol->fromEmailAddress = 'jraxxxxor@xxxxxx.com';
$bol->toEmailaddress = 'jraxxxxor@axxxxxandxxxs.com';

$bol->sendEmail($bol);
/**
 *
 *
 */

Take the tender object and email it
    $tender = new Email();

$tender->body="Tender body";
$tender->displayName='Jon jonhnson';
$tender->fromEmailAddress = 'jraynor@aol.com';
$tender->toEmailaddress = 'jraxxor@xxxxxxx.com';

$tender->sendEmail($tender);


texts: Random generation java logic used in Nifi

texts:
I was just reviewing the source code of Nifi, see explanation and public version of the source. This got me wondering whether there are any obvious improvements here to increase the performance of the random generation.
As there are many people using this, the size of the random array could be anything, but probably it usually be somewhere in the range of 100b to 10mb. The message generation frequency will typically be between 1 and 1000 times per second.
private static final char[] TEXT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-_=+/?.,';:\"?<>\n\t ".toCharArray();
private byte[] generateData(final ProcessContext context) {
    final int byteCount = context.getProperty(FILE_SIZE).asDataSize(DataUnit.B).intValue();

    final Random random = new Random();
    final byte[] array = new byte[byteCount];
    if (context.getProperty(DATA_FORMAT).getValue().equals(DATA_FORMAT_BINARY)) {
        random.nextBytes(array);
    } else {
        for (int i = 0; i < array.length; i++) {
            final int index = random.nextInt(TEXT_CHARS.length);
            array[i] = (byte) TEXT_CHARS[index];
        }
    }

    return array;
}

Just looking at this with my experience in other languages, I would think the inside of the loop is the most interesting. E.g. by avoiding to generate all numbes one by one, or indexing so many individual times into the set of characters.
I am looking for tips that may/will improve the speed without changing the behavior of the code too much, though some compromise on quality of randomness should be acceptable.  If it looks great, then that would be also good to know of course.
----g
Update
Though I did not write these lines I do understand them. Furthermore I believe I am a maintainer of the code. Based on the suggestions here I will test the options presented and aim to improve the code and submit a pull request. (I have submitted earlier improvements to the Nifi project, so on a project level I should definitely be considered a maintainer). - Of course it would be more practical if I wrote the code myself, but based on the help section the context in which I ask this question should be OK.


texts: A function that finds the kth smallest integer in array A (unsorted), of size n

texts:
int kth_smallest_number(int A[], int n, int k){
    /*kth smallest number is smaller than pr equal to n-k numbers in A*/
    int smaller_than_count;
    int i,j;
    for(i=0; i<n; i++){
        /*Check whether the number A[i] satisfies
        the condition*/
        smaller_than_count = 0;
        for(j=0; j<n; j++){
            if(A[i]<=A[j]){
                smaller_than_count++;
            }
        }
        if(smaller_than_count == n-k){
            return A[i];
        }
    }
}

I just wanted to know if this solution is right, I am not worried about efficiency right now just correctness.


texts: Avoiding pointers in this C++ linked list

texts:
As I know it is not good idea to have so many pointers in c++ code.
But I have written this simple implementation of linked list in c++ and there are many pointers in it, how can I improve that?
Also as I tried I can not use functions in algorithm module on this linked list, how can I make this class compatible with those?

template <typename T>
class linkedlist {
private:
    struct node {
        node() : T() {
        }

        node(node * prev, node * next, const T & data) :
                prev(prev), next(next), data(data) {
        }

        node * next;
        node * prev;
        T data = T();
    };

    node first;
    node last;

public:
    linkedlist() :
            first(nullptr, &last, T()),
            last(&first, &last, T()) {
    }

    class iterator {
        friend class linkedlist;
    private:
        node * current_node;

    public:
        iterator(node * current_node) : current_node(current_node) {
        }

        T & operator*() {
            return current_node->data;
        }

        const T & operator*() const {
            return current_node->data;
        }

        iterator & operator++() {
            current_node = current_node->next;
            return *this;
        }

        bool operator!=(const iterator & other) {
            return current_node != other.current_node;
        }
    };

    void add(const T & data) {
        node * new_node = new node(last.prev, &last, data);
        new_node->prev->next = new_node;
        new_node->next->prev = new_node;
    }

    bool remove(iterator & iterator) {
        if (iterator.current_node == &first || iterator.current_node == &last)
            return false;
        node *to_remove = iterator.current_node;
        to_remove->prev->next = to_remove->next;
        to_remove->next->prev = to_remove->prev;
        delete to_remove;
        return true;
    }

    iterator begin() {
        return iterator(first.next);
    }

    iterator end() {
        return iterator(&last);
    }

    iterator find(const T & data) {
        for (iterator it = begin(); it != end(); ++it) {
            if (*it == data) {
                return it;
            }
        }
        return end();
    }
};


texts:
I recently joined the website www.hackerrank.com for programming challenges, and one of them was a time conversion from 12 hour to 24 hour. Rather than using the Date class, I decided to write the code for it, and in the end I came up with this:

String time = new Scanner(System.in).nextLine();
String suffix = time.substring(time.length()-2);
time = time.replace(suffix, "");
String[] hms = time.split(":");
if (suffix.equals("PM")) {
    hms[0] = String.valueOf(Integer.parseInt(hms[0])+12);
    hms[0] = hms[0].equals("24") ? "12" : hms[0];
}
else if (suffix.equals("AM")) {
    hms[0] = hms[0].equals("12") ? "00" : hms[0];
}
System.out.println(String.join(":", hms));

And the code passed all the test cases proposed by the website. Is there any way that my code can be improved?


texts:
Introduction

The function divides a range given by a begin_iterator and an end_iterator into n sub-ranges of the same format, where the sub-ranges must be as equally sized as possible.

Example

Consider a set of size 10:

  \$\{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 \}\$

The output would be is a set of n = 3 sub-ranges:

  \$\{ \{ 0, 3 \}, \{ 4, 6 \}, \{ 7, 9 \} \}\$

Where each sub-set is as even as possible, in the previous example the sets have sizes 4, 3, and 3, respectively; that is the most even way to distribute 10 elements into 3 sub-sets.

Review goals

Efficiency
Correctness

Implementation

The oringinal code contained an issue which I missed by pure luck. Here is the fixed working code; the changes do not invalidate the present answer.

#include <vector>   // std::vector<T>
#include <iterator> // std::distance(), std::next()

template <typename Iterator>
decltype( auto ) divide_work( Iterator begin, Iterator end, std::size_t n )
{
    using size_type = std::size_t;

    auto sz = std::distance( begin, end );
    auto element_per_group_count = sz / n;
    auto remaining_element_count = sz % n;

    std::vector<std::pair<Iterator, Iterator>> ranges;
    ranges.reserve( n );

    if ( remaining_element_count == 0 )
    {
        --element_per_group_count;

        ranges.emplace_back( std::make_pair( std::next( begin, 0 ),
            std::next( begin, element_per_group_count ) ) );

        for ( auto i = 1U; i < n; ++i )
        {
            auto first = std::next( ranges[ i - 1 ].second, 1 );
            ranges.emplace_back( std::make_pair( first,
                std::next( first, element_per_group_count ) ) );
        }
    }
    else
    {
        ranges.emplace_back( std::make_pair( std::next( begin, 0 ),
            std::next( begin, element_per_group_count ) ) );

        for ( auto i = 1U; i < remaining_element_count; ++i )
        {
            auto first = std::next( ranges[ i - 1 ].second, 1 );
            ranges.emplace_back( std::make_pair( first,
                std::next( first, element_per_group_count ) ) );
        }

        --element_per_group_count;

        for ( auto i = ranges.size(); i < n; ++i )
        {
            auto first = std::next( ranges[ i - 1 ].second, 1 );
            ranges.emplace_back( std::make_pair( first,
                std::next( first, element_per_group_count ) ) );
        }
    }
    return ranges;
}

Output


texts: JavaScript Priority Queue implementation using a binary heap

texts:
I'm currently going over Robert Sedgewick's Algorithms book. For the implementation of A priority queue using a binary heap I implemented the code using ES6. I believe to have more experience with Ruby but I have come to enjoy working with ES-6 using classes.
I would like feedback on how can the code be improved, if there is anything that can be optimized, if am following best practices or if I'm breaking any principles.
 class Heap {
      constructor() {
        this.n = 0;
        this.pq = [];
      }

      size() {
        return this.n;
      }

      isEmpty() {
        this.n === 0;
      }

      swim(k) {
        while(k > 1 && this.less(Math.floor(k / 2), k)){
          this.exch(Math.floor(k / 2), k);
          k = Math.floor(k / 2)
        }
      }

      sink(k) {
        while(2 * k <= this.n) {
          let j = 2 * k;

          if(this.pq[j + 1] != null) {
            if(k > 1 && this.less(j, j + 1)){
              j++;
            }
          }

          if(this.pq[k] > this.pq[j]) {
            break;
          }
          this.exch(k, j)
          k = j
        }
      }

      insert(v) {
        this.pq[++this.n] = v;
        this.swim(this.n);
      }

      delMax() {
        let max = this.pq[1];
        this.exch(1, this.n--);
        this.pq[this.n + 1] = null;
        this.sink(1);
        return max;
      }

      less(i, j) {
        return this.pq[i] < this.pq[j];
      }

      exch(i, j) {
        let temp = this.pq[i];
        this.pq[i] = this.pq[j];
        this.pq[j] = temp;
      }
    }

Here is some tests:
let heap = new Heap();
heap.insert("t")
heap.insert("p")
heap.insert("r")
heap.insert("n")
heap.insert("h")
heap.insert("o")
heap.insert("a")
heap.insert("e")
heap.insert("i")
heap.insert("g")
heap.insert("s")

console.log(heap.isEmpty())
console.log(heap.size())
heap.delMax()
console.log(heap.pq)


texts: Ensuring valid origin and destination countries

texts:
Having the following code in PHP 5.2, where:

$row: Is an array that contains some things, but the ones that are interesting for the post are country_from and country_to, which are country names.
$pBCountries: Array containing strings with country names. Here's the content of the array: http://pastebin.com/f241JeqV

The function is very easy. It checks if the countries (country_from and country_to) are included on the array $pBCountries. If the countries are not found, it appends the "not found country name" to the array $notFoundArray, which is returned at the end of the function.

function countryChecker($row, $pBCountries)
{
    $notFoundArray = array();
    $c_fromFound = false;
    $c_toFound = false;
    foreach ($pBCountries as $country) {
        if (in_array($row["country_from"], $country)) {
            $c_fromFound = true;
        } elseif (in_array($row["country_to"], $country)) {
            $c_toFound = true;
        }
    }
    if ($c_fromFound == false) {
        array_push($notFoundArray, $row["country_from"]);
    }
    if ($c_toFound == false) {
        array_push($notFoundArray, $row["country_to"]);
    }
    return $notFoundArray;
}

The function works perfectly, but I'm pretty sure I can make it shorter and prettier.

PS: I can't update the PHP version as it's not my own machine.


texts:
Below is my solution to LC #494: Target Sum (given a list of numbers and a target integer, find out how many different ways the numbers can be subtracted from the total sum to result in the target sum).

There's one very common pattern in Python here that I question, and it's the use of for num in nums[1:]:. Iterating over nums[1:] is very explicit and readable, but it results in the creation of a whole new array when that really isn't our intention. That also means additional wasted time and wasted memory.

I used to always do for i in range(1, len(nums)): in these situations, but I see most other people using nums[1:]. Would love to hear thoughts on that.

And if there's a cleaner way to write this without having to initialize the counts hash from nums[0] separately from the body of the loop, that'd be great too. I couldn't think of a cleaner way.

class Solution:

    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        counts = {nums[0]: 1, -nums[0]: 1}
        if nums[0] == 0:
            counts[0] += 1
        for num in nums[1:]:
            keys = list(counts)
            new = {}
            for key in keys:
                if key + num not in new:
                    new[key + num] = 0
                if key - num not in new:
                    new[key - num] = 0
                new[key + num] += counts[key]
                new[key - num] += counts[key]
            counts = new
        return counts[S] if S in counts else 0
```


texts: Formatting mm:ss to string with Javascript

texts:
I have a function that takes a time of minutes and seconds, and converts it to a string in the following way: '0:30' would become '30 Seconds', '1:30' would become '1 minute 30 seconds', '2:01' would become '2 minutes 1 second', etc.  My function works fine, but I'm wondering if there are areas for improvement.

function formatTime(formattedTime) {
  let minStr, secStr;
  let minNum = formattedTime.split(':')[0];
  let secNum = formattedTime.split(':')[1];
  if (minNum === '1') {
    minStr = 'minute';
  } else {
    minStr = 'minutes';
  }
  if (secNum === '01') {
    secStr = 'second';
    secNum = '1';
  } else {
    secStr = 'seconds';
  }
  if (minNum === '0') {
    return `${secNum} ${secStr}`;
  } else if (secNum === '00') {
    return `${minNum} ${minStr}`;
  } else {
    return `${minNum} ${minStr} ${secNum} ${secStr}`;
 }
}


texts: Displaying a CSV file as an HTML table in a CRUD page

texts:
<?php
            // Read all lines of the CSV file into an array
            // The "file" function in PHP returns an array of all the lines in the file listed
            $lines = file('passes.csv',FILE_IGNORE_NEW_LINES);

            // Counter variable for line number
            $i = 0;

            //Iterate over the array of lines
            foreach($lines as $line) {
                $parts = explode(',',$line);
                $type = $parts[0];
                $site_name = $parts[1];
                $site_address = $parts[2];
                $contact_no = $parts[3];
                $customer_no = $parts[4];
                $details = $parts[5];
                $email = $parts[6];
                $phone = $parts[7];
                $tech = $parts[8];
                echo '
';
                echo    "$type	";
                echo    "$site_name	";
                echo    "$site_address	";
                echo    "$contact_no	";
                echo    "$customer_no	";
                echo    "$details	";
                echo    "$email	";
                echo    "$phone	";
                echo    "$tech	";
                echo    " 	";
                echo '
';

                $i++; // increment line number
            }
            ?>

This is slow. also it would be awesome if someone could tell me how to do this dynamically with different csv file.


texts:
Here is a REPL of the code. The idea here is to learn how the basic insertion sort algorithm works rather than to use existing sort libraries.

How can it be clearer and more efficient?

function insertionSort(array)
{
    for(var i = 1; i < array.length; ++i)
    {
        var currentItem = array[i];

        for(var j = i - 1; j >= 0; --j)
        {
            if(array[j] <= currentItem) break;
            array[j + 1] = array[j];
        }

        array[j + 1] = currentItem;
    }

    return array;
}

//test
var initialArray = [ 2, 4, 6, 8, 0, 5, 2, 5, 7, 8, 4, 7, 9 ];
var solutionArray = [ 0, 2, 2, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9 ];

var sortedArray = insertionSort(initialArray);

var passed = JSON.stringify(sortedArray)==JSON.stringify(solutionArray);
console.log('passed:' + passed);


texts: Routing Java objects using conditional consumers

texts:
As per a previous question here and answers I got, I used it to get a new implementation. I found that I have to make two implementations match once "to ignore other consumers after matching once" and match all "to execute all consumers its filter matching the input", and made a common interface to abstract usage of two implementations:

Common interface

public interface Router<T> {
Router<T> chain(Predicate<T> p, Consumer<T> c);
Consumer<T> toConsumer();
}

Match All:

public interface RouterMatchAll<T> extends Consumer<T>, Router<T> {
static <T> RouterMatchAll<T> of(Predicate<T> p1, Consumer<T> c1) {
    BiFunction<Predicate<T>, Consumer<T>, RouterMatchAll<T>> preFun = (p, c) -> i -> Optional
            .ofNullable(i).filter(p).ifPresent(c);
    return preFun.apply(p1, c1);
}

@Override
public default RouterMatchAll<T> chain(Predicate<T> p, Consumer<T> c) {
    return this.andThen(RouterMatchAll.of(p, c))::accept;
}

@Override
public default Consumer<T> toConsumer() {
    return this;
}

}

Match Once:

public interface RouterMatchOnce<T> extends Function<Optional<T>, Optional<T>>,
    Router<T> {

static <T> RouterMatchOnce<T> of(Predicate<T> p1, Consumer<T> c1) {
    BiFunction<Predicate<T>, Consumer<T>, RouterMatchOnce<T>> preFun = (p,
            c) -> o -> {
        if (o.filter(p).isPresent()) {
            c.accept(o.get());
            return Optional.empty();
        }
        return o;
    };
    return preFun.apply(p1, c1);

}

@Override
public default RouterMatchOnce<T> chain(Predicate<T> p, Consumer<T> c) {
    return this.andThen(RouterMatchOnce.of(p, c))::apply;
}

@Override
public default Consumer<T> toConsumer() {
    return i -> this.apply(Optional.ofNullable(i));
}

}

For MatchAll, I used Consumer to use its andThen, which consumes the same input. For MatchOnce, I had to use Function<Optional,Optional> and its andThen, use the output of first function to be used in next function, and I needed to change the data to Optional.empty() after consuming once to not consume it then.

Concerns I want your feedback about:

toConsumer() in RouterMatchAll is just return this and I don't like it but couldn't find another option for abstraction.
Names are not nice as it is not a router any more. It has to be something like filter, interceptor, or ConditionalConsumer. Please suggest a name for these interfaces, chain, and toConsumer methods.

Usage of the above:

Predicate<Integer> p1 = (Integer i) -> {
    System.out.println("call p1");
    return i < 5;
};
Predicate<Integer> p2 = (Integer i) -> {
    System.out.println("call p2");
    return i > 5;
};
Consumer<Integer> c1 = i -> System.out.println("less");
Consumer<Integer> c2 = i -> System.out.println("more");

Router<Integer> routerMatchAll = RouterMatchAll.of(p1, c1)
        .chain(p2, c2);
IntStream.range(0, 10).boxed().forEach(routerMatchAll.toConsumer());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
Router<Integer> routerMatchOnce = RouterMatchOnce.of(p1, c1).chain(p2,
        c2);
IntStream.range(0, 10).boxed().forEach(routerMatchOnce.toConsumer());

Output:

  call p1
  less
  call p2
  call p1
  less
  call p2
  call p1
  less
  call p2
  call p1
  less
  call p2
  call p1
  less
  call p2
  call p1
  call p2
  call p1
  call p2
  more
  call p1
  call p2
  more
  call p1
  call p2
  more
  call p1
  call p2
  more
  >>>>>>>>>>>>>>>>>>>>>>
  call p1
  less
  call p1
  less
  call p1
  less
  call p1
  less
  call p1
  less
  call p1
  call p2
  call p1
  call p2
  more
  call p1
  call p2
  more
  call p1
  call p2
  more
  call p1
  call p2
  more


texts:
this is the code I wrote

import React from 'react';
import {defaultMemoize} from 'reselect';
import PropTypes from 'prop-types';

class PropsDataAdapter extends React.PureComponent {
  static propTypes = {
    propDataAdapter: PropTypes.func,
    children: PropTypes.node,
    propsEqualityChecker: PropTypes.func, //if not provided equality check will be this.props !== nextProps same as for PureComponent
  };

  constructor(props) {
    super(props);
    this.setUpAdapterFunction(props);
  }

  componentWillReceiveProps(nextProps) {
    const props = this.props;
    if (props.propDataAdapter !== nextProps.propDataAdapter) {
      this.setUpAdapterFunction(nextProps);
    }
  }

  setUpAdapterFunction(props) {
    this.propsDataAdapterFunc = defaultMemoize(props.propDataAdapter, props.propsEqualityChecker);
  };

  render() {
    const ChildComponent = this.props.children;
    return (<ChildComponent {...this.propsDataAdapterFunc(this.props)}/>);
  }
};

export default PropsDataAdapter;

what it does is rather then wrapping functions in defaultMemoize use this component which will wrap around the component which need adapted props
default memoize used to will have cache size of 1 provide propsDataAdapter for adaption of props whatever props provided will be provided as arguments to adapter.
Usage goes like this

 <PropsDataAdapter
    propDataAdapter={adaptPropsForChildren}
  >
    {ChildComponent}
  </PropsDataAdapter>);

Does it seem as a good way what this component does is just uses defaultMemoize so that you dont have to think about calculations in constructor or componentWillRecieveProps or memoizing themselves you just need to write an adapter function which will do that for you in which you can use _map/Object.assign and create new references.


texts: Fast incremental backup algorithm using RSYNC

texts:
I'm running a simple Bash script that uses rsync to do an incremental backup of my web server every hour. What I'm looking for is an efficient algorithm to delete the proper backups so that in the end I keep:

Hourly backups for 24 hours.
Daily backups for 1 week.
Weekly backups for 1 month.
Monthly backups from that point on.

I'll figure out when to delete the monthly backups based upon when I run out of space. So we're not worried about that. I'm also familiar with the various wrappers for rsync like rdiff-backup and rsnapshot but those aren't necessary. I prefer to write code myself whenever possible even if it means reinventing the wheel sometimes. At least that way if I get a flat tire I know how to fix it :)

Here's the actual commented code that runs every hour:

#if it's not Sunday and it's not midnight
if [ $(date +%w) -ne 0 ] && [ $(date +%H) -ne 0 ]; then
    #remove the backup from one day ago and one week ago
    rm -rf $TRG1DAYAGO
    rm -rf $TRG1WEEKAGO
fi

#if it's Sunday
if [ $(date +%w) -eq 0 ]; then
    #if it's midnight
    if [ $(date +%H) -eq 0 ]; then
        #if the day of the month is greater than 7
        # we know it's not the first Sunday of the month
        if [ $(date +%d) -gt 7 ]; then
            #delete the previous week's files
            rm -rf $TRG1WEEKAGO
        fi
    #if it's not midnight
    else
        #delete the previous day and week
        rm -rf $TRG1DAYAGO
        rm -rf $TRG1WEEKAGO
    fi
fi

Basically:

If it's not Sunday and it's not 3am:

  - delete the backup from one day ago

  - delete the backup from one week ago

If it is Sunday:

    If it is Midnight:

        If the day of the month is greater than 7:

            -delete the backup from one week ago

    Else (if it's not Midnight)

      - delete the backup from one day ago

      - delete the backup from one week ago

That seems to work but I'm wondering if anyone can come up with a simpler, more efficient algorithm or add any ideas for a better way of accomplishing this.


texts: Function in a board game with chests and bandits

texts:
This function is part of a python board game program. The game is a board game with chests and bandits hidden throughout the board. The function is dedicated to the "easy" section of the game (where it is a 8x8 grid).

def easy_level(Coins):
#This function is for the movement of the game in easy difficulty
    while  True:
        oldcurrent=current
        boardeasy[oldcurrent[0]][oldcurrent[1]]='*'
        table_game_easy()
        boardeasy[oldcurrent[0]][oldcurrent[1]]=' '

        n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 8 \n')
        n=n.split()
        if n[0].lower() not in ['up','left','down','right']:#Validates input
            print('Wrong command, please input again')
            continue
        elif n[0].lower()=='up':
            up(int(n[1].lower()),8)#Boundary is set to 8 as the 'easy' grid is a 8^8
        elif n[0].lower()=='down':
            down(int(n[1].lower()),8)
        elif n[0].lower()=='left':
            left(int(n[1].lower()),8)
        elif n[0].lower()=='right':
            right(int(n[1].lower()),8)

        print("5 chests left")
        print("8 bandits left")
        print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
        if current[0] == Treasure1_Row and current[1] == Treasure1_Col\
           or current[0] == Treasure2_Row and current[1] == Treasure2_Col\
           or current[0] == Treasure3_Row and current[1] == Treasure3_Col\
           or current[0] == Treasure4_Row and current[1] == Treasure4_Col\
           or current[0] == Treasure5_Row and current[1] == Treasure5_Col\
           or current[0] == Treasure6_Row and current[1] == Treasure6_Col\
           or current[0] == Treasure7_Row and current[1] == Treasure7_Col\
           or current[0] == Treasure8_Row and current[1] == Treasure8_Col\
           or current[0] == Treasure9_Row and current[1] == Treasure9_Col\
           or current[0] == Treasure10_Row and current[1] == Treasure10_Col:
            print("Hooray! You have found booty! +10 gold")
            Coins = Coins+10 #Adds an additional 10 points
            print("Coins:",Coins)

        if current[0] == Bandit1_Row and current[1] == Bandit1_Col\
             or current[0] == Bandit2_Row and current[1] == Bandit2_Col\
             or current[0] == Bandit3_Row and current[1] == Bandit3_Col\
             or current[0] == Bandit4_Row and current[1] == Bandit4_Col\
             or current[0] == Bandit5_Row and current[1] == Bandit5_Col:
            print("Oh no! You have landed on a bandit...they steal all your coins!")
            Coins = Coins-Coins #Removes all coins
            print("Coins:",Coins)

        boardeasy[current[0]][current[1]]='*'#sets value to players position


texts: Multiple permission checks in web app automated tests

texts:
I am writing automated tests for a web app and at one point I need to make sure that a user can only engage in activities allowed by a set permission. I have written all the standalone methods that perform the required tests and now I need to group all of them together and test. I came up with something that looks like this:

public boolean hasPermissions(String permissions, File file) {

    if ("Read Only".equals(permissions)) {

        return !canCreateNewFolder() && !canAddFiles() && !canAddLink() && canCopyMultipleItems() && !canMoveMultipleItems()
                && !canDeleteMultipleItems() && canDownloadMultipleItems() && canDownload(file) && canViewDetails(file)
                && !canEdit(file) && canCopy(file) && !canMove(file) && !canHide(file) && !canDelete(file);

    } else if ("Read and Add Only".equals(permissions)) {

        return canCreateNewFolder() && canAddFiles() && canAddLink() && canCopyMultipleItems() && !canMoveMultipleItems()
                && !canDeleteMultipleItems() && canDownloadMultipleItems() && canDownload(file) && canViewDetails(file)
                && !canEdit(file) && canCopy(file) && !canMove(file) && !canHide(file) && !canDelete(file);

    } else if ("Full Access".equals(permissions)) {

        return canCreateNewFolder() && canAddFiles() && canAddLink() && canCopyMultipleItems() && canMoveMultipleItems()
                && canDeleteMultipleItems() && canDownloadMultipleItems() && canDownload(file) && canViewDetails(file) && canEdit(file)
                && canCopy(file) && canMove(file) && canHide(file) && canDelete(file);

    } else {
        throw new UnsupportedOperationException("Unsupposrted permission");
    }

}

While this solution works with no issues, it somehow doesn't look right.

So just wanted to ask for another opinion on this design.


texts: A fixed max size container class containing unique elements with functions like push_back and pop_back and is iterate-able

texts:
template <class T, int max_size>
class FixedSizedUniqueStack
{
    std::vector<T> m_vec;
    std::unordered_set<T> m_uset;
public:
    FixedSizedUniqueStack():m_vec(max_size){}
    bool push(T& x)
    {
        bool success = true;
        if(m_uset.insert(x)) m_vec.push_back(x);
        else success = false;
        return success;
    }
    void pop()
    {
        if(m_vec.size() > 0)
        {
            m_uset.erase(m_vec.back());
            m_vec.pop_back();
        }
    }
};