texts:
For setters that set a member collection, I write template functions so as to accept any collection type as input:

class HasItems
{
public:
    template <typename C>
    void items(const C& items) {
        // Copy-and-swap omitted
        m_items.assign(std::begin(items), std::end(items));
    }

private:
    std::vector<Item> m_items;
}

But suppose Item is big, and I want to move them around instead of copy if possible.  And furthermore, suppose someone passed me an xvalue std::vector<Item>; I could just move that whole container into place and avoid touching the elements at all!  That looks like this:

class HasItems
{
public:
    template <typename C>
    void items(C&& items) {
        // Helper function implemented below
        assign(m_items, std::forward<C>(items));
    }

private:
    std::vector<Item> m_items;
}

// Assigns the contents of src to dest, moving as much as possible
template <typename C1, typename C2>
void assign(C1& dest, C2&& src) {
    assign(dest, std::forward<C2>(src), std::is_assignable<C1&, C2&&>{});
}

// Called if we can use operator=
template <typename C1, typename C2>
void assign(C1& dest, C2&& src, std::true_type use_equals) {
    dest = std::forward<C2>(src);
}

// Called if we must use dest.assign()
template <typename C1, typename C2>
void assign(C1& dest, C2&& src, std::false_type use_equals) {
    assign_elements(dest, std::forward<C2>(src), std::is_rvalue_reference<C2&&>{});
}

// Called if we can move the elements
template <typename C1, typename C2>
void assign_elements(C1& dest, C2&& src, std::true_type move) {
    dest.assign(std::make_move_iterator(std::begin(src)),
                std::make_move_iterator(std::end(src)));
}

// Called if we must copy the elements
template <typename C1, typename C2>
void assign_elements(C1& dest, C2&& src, std::false_type move) {
    dest.assign(std::begin(src), std::end(src));
}

Is this a good approach?  In particular, is there a nice way to avoid the tag dispatch on std::is_rvalue_reference<C2&&> in the assign_elements() case?  (It was avoided in the operator= case by using dest = std::forward<C2>(src) instead of using std::move() conditionally.)  It seems to pass my simple set of unit tests.


texts:
I'm trying to merge two nodes. Basically, the idea is to take all children in left and new ones in right. Is there any way to get rid of toAdd variable and do it in a clean way?

I don't want to convert any IEnumerable<T> to List or Array in this merge process.

public IEnumerable<TChild> NodeMerge<TNode, TChild, TKey>(TNode left, TNode right,
Func<TNode, IEnumerable<TChild>> getChildren, Func<TChild, TKey> getKey)
{
    var lChildren = getChildren(left);
    var rChildren = getChildren(right);

    IEnumerable<TChild>[] toAdd = new IEnumerable<TChild>[2];

    // Common Keys between left and right
    toAdd[0] = lChildren.Where(s => rChildren.Select(p => getKey(p)).Contains(getKey(s)));

    // new keys added to right
    toAdd[1] = rChildren.Where(s => lChildren.Select(p => getKey(p)).Contains(getKey(s)) == false);

    return toAdd.SelectMany(s => s);
}


texts:
I need to select a color given a position within a range.

Using the "bwr" colormap shown below, I want to return a blue color for a value at the beginning of the range, a red color for a value at the end of the range, and a suitable interpolated value for values in between.

The lower and upper ends of the range can be anything. From negative to positive numbers, for example [-0.5,0.5] or [0,1] or [-0.2 to 0.6].

Here is my code:

#include <opencv2/core/core.hpp>

cv::Scalar get_colour(double v, double vmin, double vmax)
{
    double r, g, b = 0;
    double dv;

    if (v < vmin)
        v = vmin;
    if (v > vmax)
        v = vmax;
    dv = vmax - vmin;

    if (v < (vmin + 0.5 * dv)) {
        r = 2 * (v - vmin) / dv;
        g = 2 * (v - vmin) / dv;
        b = 1;
    }
    else if (v >= (vmin + 0.5 * dv)) {
        b = 1 + 2 * (vmin + 0.5 * dv - v) / dv;
        g = 1 + 2 * (vmin + 0.5 * dv - v) / dv;
        r = 1;
    }

    return cv::Scalar(b * 255, g * 255, r * 255);
}

Can you check if this function always work good, no matter what range and value I choose, and what can I write better?


texts: Codility cyclic rotation solution in PHP

texts:
Problem statement

A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.

For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.

My Solution

function solution($A, $K) {
   // when array is empty or has only one element
   if(count($A) == 0 || count($A) == 1){
        return $A;
    }
    //runs k times
    for($j=1; $j<=$K; $j++){
        $last_element = $A[count($A)-1];
        //runs for each element
        for($i=(count($A)-1); $i>0; $i--){
            $A[$i] = $A[$i-1];
        }
        $A[0] = $last_element;
    }
    return $A;
}

$A = [1, 2, 3, 4];
$K = 4;
$result = solution($A, $K);
print_r($result);

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


texts: The most efficient way to merge two lists in Java

texts:
I am looking for a way to merge two files with a list of distinct words, one word per line. I have to create a new txt file that would contain all the words of the first list and all the words from the second list. I don't have any other specifications.  The order of words in the result doesn't matter.

public class testMain {

    public static void main(String[] args) {
        File f1=new File("words.txt");
        File f2=new File("words1.txt");
        HashSet <String> hash1=new HashSet<String>();
        HashSet <String> hash2=new HashSet<String>();
        try{
            Scanner s=new Scanner(f1);
            while(s.hasNextLine()){
                hash1.add(s.nextLine());
            }
            s=new Scanner(f2);
            while(s.hasNextLine()){
                hash2.add(s.nextLine());
            }
        }
        catch(FileNotFoundException e){}
        hash1.addAll(hash2);
        Object[]array =hash1.toArray();
        File newFile=new File("mixOfLists.txt");
        try{
        PrintWriter writer=new PrintWriter(newFile);
        for(int i=0; i<array.length; i++){
            writer.println(array[i]);
        }
            writer.close();
        }

        catch(FileNotFoundException e){ System.out.print("No Such File");}
        System.out.print("Done!");
        }

}


texts:
I am loading 3000 individual icons at run time one of my controls uses large icons, the other uses small icons. This works however seems terribly inefficient. The only way I can get the icons to be available in the small/large size is to have multiple image lists and have to load the file twice into each list.

 public partial class Form1 : Form
{

    ImageList imageListSmall = new ImageList();
    ImageList imageListLarge = new ImageList();
    BackgroundWorker IconLoaderBGWorker = new BackgroundWorker();
    DirectoryInfo IconDir = new DirectoryInfo("icons");

    FileInfo[] IconFiles;

    public Form1()
    {

        InitializeComponent();

        // Setup Icon Lists
        imageListSmall.ImageSize = new Size(16, 16);
        imageListSmall.ColorDepth = ColorDepth.Depth32Bit;
        imageListLarge.ImageSize = new Size(32, 32);
        imageListLarge.ColorDepth = ColorDepth.Depth32Bit;

        // Setup Progress bar events and Icon Loader
        IconLoaderBGWorker.DoWork += new DoWorkEventHandler(bg_DoWork);
        IconLoaderBGWorker.WorkerReportsProgress = true;
        IconLoaderBGWorker.ProgressChanged += new ProgressChangedEventHandler(bg_ProgressChanged);
        IconLoaderBGWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

        IconFiles = IconDir.GetFiles("*.png");
        int allFiles = IconFiles.Count();
        progressBar1.Maximum = allFiles;

    }

    private void bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }

    private void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        int i = 0;

        foreach (FileInfo fileinfo in IconFiles)
        {
            imageListLarge.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), Image.FromFile(fileinfo.FullName));
            imageListSmall.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), Image.FromFile(fileinfo.FullName));
            IconLoaderBGWorker.ReportProgress(++i);
            Application.DoEvents();
        }

    }

    private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        object result = e.Result;
        progressBar1.Dispose();
    }
}


texts: designing application using polymorphism

texts:
I have created a polymorphic system, but I don't know whether this is the correct way of doing it. Am I abusing Polymorphism here? Here is the code:

class WriteObj
{
    public string Obj1 { get; set; }
    public string Obj2 { get; set; }
    public string Obj3 { get; set; }
}

The above code is a data object that I am passing around in the methods, since I would be using a List of these objects.

abstract class BaseWriter
{
    public abstract void Write(List<WriteObj> writeObjList);
}

class ConsoleWriter : BaseWriter
{
    public override void Write(List<WriteObj> writeObjList)
    {
        for (int i = 0; i < writeObjList.Count; i++)
        {
            Console.Writeline("I am in Console Writer, parameter: " + writeObjList[i].Obj1);
        }

    }
}

class FileWriter : BaseWriter
{
    public override void Write(List<WriteObj> writeObjList)
    {
        for (int i = 0; i < writeObjList.Count; i++)
        {
            Console.Writeline("I write in file, parameter: " + writeObjList[i].Obj1);
        }
    }
}

class DatabaseWriter : BaseWriter
{
    public override void Write(List<WriteObj> writeObjList)
    {
        for (int i = 0; i < writeObjList.Count; i++)
        {
            Console.Writeline("I write in database, parameter: " + writeObjList[i].Obj2);
        }
    }
}

In my main method I call them like:

    static void main()
    {
        List<WriteObj> col = new List<WriteObj>();
        col.AddRange(new WriteObj[2] { new WriteObj { Obj1 = "this is obj1 iteration 1", Obj2 = "This is obj2 iteration 1" },
            new WriteObj { Obj1 = "this is obj1 iteration 2", Obj2 = "This is obj2 iteration 2" } });

        //some factory will generate these concrete types,
        //but the sake of simplicity I am instantiating it like that.
        BaseWriter a = new ConsoleWriter();
        a.Write(col);

        BaseWriter b = new FileWriter();
        b.Write(col);

        BaseWriter c = new DatabaseWriter();
        c.Write(col);
    }

Is it Ok to pass List of WriteObj in the Write method of the respective concrete implementations?

Update : I have used abstract class because it will be having some methods in it. I haven't mentioned it here for the sake of simplicity.


texts:
I have these classes:

public class DelayReason
{
    public virtual ICollection<WorkOrder> WorkOrders { get; set; }

}
public class WorkOrder
{
    public virtual ICollection<DelayReason> DelayReasons { get; set; }
 //other fields
}

Each DelayReason has 0..* WorkOrders and it's the same for WorkOrders.

This is a data sample:

To do this, I've written this code. Can I optimize that?

  public void DelayReasonAverage()
    {
        List<ReportVM> result = new List<ReportVM>();

        var reasons = _delayReasons.GroupBy(row => row, (k, t) => new
        {
            delayId = k.Id,
            delayTitle = k.Title,
            workOrders = k.WorkOrders,
            count = t.Count()
        }).OrderByDescending(row => row.count).ToList();

        reasons.ForEach(row =>
        {
            var workOrders = row.workOrders.ToList();

            ReportVM reportObj = new ReportVM() { DelayTitle= row.delayTitle };

            for (int i = 0; i < workOrders.Count; i++)
            {
                if (workOrders.Count - 1 > i)
                    reportObj.Count += workOrders[i].CreatedOn.DiffDays(workOrders[i + 1].CreatedOn);
            }
            reportObj.Count = reportObj.Count / row.count;
            result.Add(reportObj);
        });
    }

DiffDays extension Method:

 public static int DiffDays(this DateTime current,DateTime to)
 {
    return to.Subtract(current).Days;
 }

The final results look like this:


texts:
public String getDatePeriodtext(boolean userCanJoinAndLeave, Date startDate, Date endDate) {
    String text;

    if (!userCanJoinAndLeave) {
        text = getText(getLocale(), "no");
    } else if (startDate == null && endDate == null) {
        text = getText(getLocale(), "continuous");
    } else if (startDate == null && endDate != null) {
        text = getText(getLocale(), "to")
                + " "
                + formatDate(endDate);
    } else if (endDate == null) {
        text = getText(getLocale(), "from")
                + " "
                + formatDate(startDate);
    } else {
        text = formatDate(startDate)
                + " "
                + getText(getLocale(), "to")
                + " "
                + formatDate(endDate);
    }

    return text;
}

Some scenarios:

userCanJoinAndLeave = false ==> No
startDate = null and endDate = null ==> Continuous
startDate = 2016-10-31 and endDate = null ==> from 2016-10-31
startDate = null and endDate = 2016-11-01 ==> to 2016-11-01
startDate = 2016-10-31 and endDate = 2016-11-01 ==> 2016-10-31 to 2016-11-01


texts: Storing a fetched list of printers in Angular

texts:
I have a need to store data retrieved my ASP.NET Web Api to stop making redundant API calls for the same data when I navigate through my Angular page.  On my API I have a database which stores a list of printers known to the PC and stores some basic information about them.  Here is the model:

export class Printer
{
    id: number;
    name: string;
    active: boolean;
    blacklisted: boolean;
    default: boolean;
}

This printer data is consumed by several components and as I previously had it each time I needed this data I had to request it from my backend.  Here is my attempt reducing redundant API calls:

import { Injectable } from '@angular/core';
import { Printer } from '../models/printer';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

@Injectable()
export class PrintersService {
  private static readonly apiUrl = "/api/printers";
  private static printers: Observable<Printer[]> = undefined;

  constructor(private http: HttpClient) { }

  getPrinters(refresh: boolean = false): Observable<Printer[]> {
    if (refresh || PrintersService.printers === undefined) {
      this.log("Observable<Printer[]> is undefined or the method requested to refresh");
      this.apiGET();
    } else {
      this.log("Observable<Printer[]> is cached, no API call will be made");
    }

    return PrintersService.printers;
  }

  /*
    Not sure how to get this method to work, I need to get a single
    observable object from my observable array of objects.  For now I'm
    just having everyone retrieve the list and then just search that list
    manually, but it would be really nice if I could just make a call for
    a single object instead of getting the whole mess.

    getPrinter(id: number, refresh: boolean = false): Observable<Printer> {
    if (refresh || PrintersService.printers === undefined) {
      this.apiGET();
    }

    var result: Observable<Printer> = of(null);
    PrintersService.printers.subscribe((printers) => {
      var target = printers.find(p => p.id === id);
      result = of(target);
    });

    return result;
  }*/

  updatePrinter(printer: Printer) {
   PrintersService.printers.subscribe(printers => {
      printers.forEach((element, index) => {
        if (element.id === printer.id) {
          printers[index] = printer;
          this.http.put(PrintersService.apiUrl, printer).pipe(
            tap(_ => this.log(`Updated printer id=${printer.id}`)),
            catchError(this.handleError<any>('updatePrinter'))
          );
        }
      });
    });
  }

  private apiGET(): boolean {
    this.log("GET: " + PrintersService.apiUrl);
    PrintersService.printers = this.http.get<Printer[]>(PrintersService.apiUrl);
    return PrintersService.printers === undefined;
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      this.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    }
  }

  private log(message: string) {
    console.log('PrintersService: ' + message);
  }
}

From my initial testing with this service, it seems to work well.  API calls are being made only when the data needs to be retrieved.  My main concern with all of this is there is a more appropriate way to do this in Angular.  I'm new to front-end stuff, let alone Angular and I don't know what best practices are for this particular scenario.  This is how I'd handle it if I were writing a desktop app, granted I definitely need something in there that causes the data to refresh every now and then.


texts:
This is a question from HackerRank. I have solved it and want to know if it's the best answer I could have given in Python 3.

Sample code:

>>> from collections import Counter
>>>
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>>
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>>
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]

  Task:

  Raghu is a shoe shop owner. His shop has X number of shoes. He has a
  list containing the size of each shoe he has in his shop. There are N
  number of customers who are willing to pay \$X_i\$ amount of money
  only if they get the shoe of their desired size.

  Calculate how much Raghu earned.

  Input format:

  The first line contains the number of shoes.

  The second line contains the space separated list of all the shoe
  sizes in the shop.

  The third line contains N, the number of customers.

  The next N lines contain the space separated values of the shoe size
  desired by the customer and Xi, the price of the shoe.

  Output format:

  Print the amount of money earned by Raghu.

  Sample input:

10
2 3 4 5 6 8 7 6 5 18
6
6 55
6 45
6 55
4 40
18 60
10 50

  Sample output:

200

Is this good? Where can I improve?

from collections import Counter
for _ in range(2):
    shoes = map(int, input().strip().split())
shoes = Counter(shoes)
income = 0
for _ in range(int(input())):
    query = list(map(int, input().split()))
    if query[0] in shoes and shoes[query[0]] > 0:
        shoes[query[0]] -= 1
        income += query[1]
print(income)


texts:
I'm doing some coding challenges to get better practiced at my coding.  I'm trying to do one that requires us to do a ROT13.  I've got the implementation correct, and I just want to know a couple of things.

The space character is showing up as a crazy character in my terminal screen, which I'm assuming is because of character encoding, although I could be wrong.  Also, how does my code look?

#include <iostream>
#include <string>
using namespace std;

const int LOWER_A = 97;
const int LOWER_M = 109;
const int LOWER_N = 110;
const int LOWER_Z = 122;

const int UPPER_A = 65;
const int UPPER_M = 77;
const int UPPER_N = 78;
const int UPPER_Z = 90;

string rot(string input) {
    int inputSize = input.size();
    int index = 0;

    while(index != inputSize) {
        if(input[index] >= LOWER_A && input[index] <= LOWER_M)
            input[index] = input[index] + 13;
        else if(input[index] >= LOWER_N && input[index] <= LOWER_Z)
            input[index] = input[index] - 13;
        else if(input[index] >= UPPER_A && input[index] <= UPPER_M)
            input[index] = input[index] + 13;
        else if(input[index] <= UPPER_N && input[index] <= UPPER_Z)
            input[index] = input[index] - 13;

        index++;
    }
    return input;
}

int main() {
    string plaintext;
    string cypher;

    cout << "input: ";
    getline(cin,plaintext);
    cypher = rot(plaintext);
    cout << cypher << endl;

    return 0;
}


texts: Block_breaker clone in pygame with simple edge detection

texts:
I tried to make this clone of
brick_breaker on my own
in one day. The source code and assets .

However I have some concerns about the code so far:

It uses simple edge detection code (as if ball goes out of screen <600 or <462).
It uses built-in collision detection from pygame.
Simple array for appending blocks.

import pygame,sys,random,time
from pygame.locals import *
pygame.init()
blk=pygame.image.load('block.bmp')    #load blocks image
img=pygame.image.load('back.bmp')     #load background image
thung=pygame.image.load('thung.bmp')  #load player image
gameover=pygame.image.load('go.bmp')
mas=pygame.image.load('masthead.bmp')
soundObj = pygame.mixer.Sound('wall.wav')
back=pygame.mixer.music.load('background.mid')
global windowSurface

windowSurface = pygame.display.set_mode((600, 462), 0, 32)
pygame.display.set_caption('Simple breakout game by piyush')

class pool():
    x=1
    y=1
    dirx=''
    diry=''
    trig=0
    block=[]
    pigger=0

    def trigger(self):
        self.trig=1

    def _init_(self):
        self.x=250
        self.y=250
        dirx='left'
        diry=''
        block=[]
    def movex(self):
        if self.trig==1:
            if self.dirx=='left':
                self.x-=1
            if self.dirx=='right':
                self.x+=1
            if self.x<=0:
                self.dirx='right'
                soundObj.play()
            if self.x==600:
                self.dirx='left'
                soundObj.play()
    def movey(self):
        if self.trig==1:
            if self.diry=='up':
                self.y-=1
            if self.diry=='down':
                self.y+=1
            if self.y==0:
                soundObj.play()
                self.diry='down'
            if self.y>=410:
                self.diry='up'
                self.x=250
                self.y=250

    def drawball(self,surface):
        pygame.draw.circle(surface,(200,100,230),(self.x,self.y),13,0)

    def rev(self):
        if self.diry=='down':
            self.diry='up'
    def drawblock(self,surface):

        for blocks in self.block:
                              surface.blit(blk,blocks)

def play():
    pygame.mixer.music.play(-1, 0.0)

    ball1=pool()
    pygame.init()
    for i in range(10):
            size=i*75
            ball1.block.append(pygame.Rect(size,20,40,40))
    for i in range(10):
            size=i*75
            ball1.block.append(pygame.Rect(size,60,40,40))
    for i in range(10):
            size=i*75
            ball1.block.append(pygame.Rect(size,100,40,40
    ball1.x=400
    ball1.y=200
    ball1.dirx='left'
    ball1.diry='up'
    ball1.pigger=1

    a=300
    b=340
    while True:
        windowSurface.fill((25,25,25))

        pos = pygame.mouse.get_pos()

        a=pos[0]
        for event in pygame.event.get():
             if event.type==QUIT:
                pygame.quit()
                sys.exit()

             if event.type==KEYUP:
                 if event.key==K_LEFT:
                     a-=30
                 if event.key==K_RIGHT:
                     a+=30
                 if event.key==ord('a'):
                     pigger=0

        thunge=pygame.Rect(a, b, 120, 10)
        ball=pygame.Rect(ball1.x, ball1.y, 10, 10)
        windowSurface.blit(img,(0,0))
        windowSurface.blit(thung,thunge)
        ball1.drawball(windowSurface)
        ball1.movex()
        ball1.movey()
        ball1.trig=1
        ball1.drawblock(windowSurface)
        windowSurface.blit(mas,(-20,410))
        if thunge.colliderect(ball):
            print("collision detecte")
            ball1.rev()
            soundObj.play()

        for blok in ball1.block:
            if ball.colliderect(blok):
                ball1.block.remove(blok)

        pygame.display.update()

play()


texts: Creating default object from empty value in PHP?

texts:
Consider the following code.

$car = (object)[
   'general' => [
        'interior' => [
            'seats' => 'destroyed'
        ]
    ]
];

$exteriorProperties = [
    'hood' => 'shiny',
    'windows' => 'dirty'
];

foreach($exteriorProperties as $key => $prop){
    $car->{'other'}->{'exterior'}->{$key} = $prop;
}

This is a scenario where I'd like to add properties to an object, a few layers deep at a time, while iterating through some other data. If it doesn't exist, it will just create it, if it does it will override. PERFECT!

Unfortunately, this will throw the warning:

  Creating default object from empty value

I could resolve the issue by checking first if the property exists like so:

foreach($exteriorProperties as $key => $prop){
    if(!isset($car->other))
        $car->other = (object)[];
    if(!isset($car->other->exterior))
        $car->other->exterior = (object)[];
    $car->other->exterior->{$key} = $prop;
}

This is not my ideal solution. I'm wondering if there's a more elegant solution. Currently, I'm using this:

@$car->{'other'}->{'exterior'}->{$key} = $prop;

to suppress the warnings but I'm worried about compatibility in the future.

Does anyone have a more elegant solution to this scenario?


texts:
I am hoping that someone can take a look at my implementation of a lock-free ring buffer and critique the implementation.  I'm hoping that the focus can be of the correctness of the atomic operations and thread safety.
The buffer is implemented as a single producer/single consumer ring buffer, and owes a lot of boost's SPSC queue (unfortunately simply using boost::spsc_queue is not an option for my use case.  Therefore I rolled my own.
Usage details are as follows:

Only 1 thread (producer) may call Push()
Only 1 thread (consumer) may call Pop()
Either the producer and consumer thread may call Read/WriteAvailable()

The main concern is that the atomic operations in ReadAvailable and WriteAvailable are correct for this use case.  Secondary concerns would be any performance gains that I can achieve to make operations on the buffer faster, as well as code style critique in general.
Many Thanks.
 * LockfreeBuffer.h
 *
 * Defines a lock free, single producer/single consumer queue
 * based around a ring buffer.  Only a single thread may call
 * Push, and likewise a single thread may call Pop.  Push/Pop
 * will fail with a false return value if the queue is full (push)
 * or empty (pop).
 * ReadAvailable and WriteAvailable may be called from either the
 * producer or consumer thread.
 */

#ifndef LOCKFREE_BUFFER_H
#define LOCKFREE_BUFFER_H

#include <atomic>
#include <memory>

template<class T>
class LockfreeBuffer
{
 private:
    typedef std::size_t size_t;

    const size_t m_size;
    std::atomic<size_t> m_readIdx;
    // For Intel/AMD64, force m_readIdx and m_writeIdx onto
    // different cache lines with 64 bytes of padding
    // https://news.ycombinator.com/item?id=13186232
    unsigned char padding[64];
    std::atomic<size_t> m_writeIdx;

    std::unique_ptr<T[]> m_storage;

    static size_t ReadAvailable(
          size_t readIdx, size_t writeIdx, size_t size)
    {
       if(writeIdx >= readIdx)
          return writeIdx - readIdx;

       return writeIdx + size - readIdx;
    }

    static size_t WriteAvailable(
          size_t readIdx, size_t writeIdx, size_t size)
    {
       size_t ret = readIdx - writeIdx -1;
       if(writeIdx >= readIdx)
          ret += size;

       return ret;
    }

 public:
    LockfreeBuffer()                                   = delete;
    LockfreeBuffer(const LockfreeBuffer&)              = delete;
    LockfreeBuffer& operator=(const LockfreeBuffer&)   = delete;

    LockfreeBuffer(size_t size)
       : m_readIdx(0)
       , m_writeIdx(0)
       , m_size(size)
       , m_storage(std::unique_ptr<T[]>(new T[size]))
    { }

    bool Push(const T& obj)
    {
       const size_t nextWriteIdx =
          (m_writeIdx.load(std::memory_order_relaxed) + 1) % m_size;

       if(nextWriteIdx == m_readIdx.load(std::memory_order_acquire))
            return false; // Buffer is full

       m_storage[nextWriteIdx] = obj;

       m_writeIdx.store(nextWriteIdx, std::memory_order_release);

       return true;
    }

    bool Pop(T& obj)
    {
       const size_t writeIdx = m_writeIdx.load(std::memory_order_acquire);
       const size_t readIdx = m_readIdx.load(std::memory_order_relaxed);

       if(ReadAvailable(readIdx, writeIdx, m_size) == 0)
          // Buffer is empty
          return false;

       obj = m_storage[readIdx];

       m_readIdx.store((readIdx + 1) % m_size, std::memory_order_release);

       return true;
    }

    size_t Size()
    {
       // Const, no need to acquire
       return m_size;
    }

    size_t ReadAvailable()
    {
       const size_t readIdx = m_readIdx.load(std::memory_order_acquire);
       const size_t writeIdx = m_writeIdx.load(std::memory_order_acquire);

       return ReadAvailable(readIdx, writeIdx, m_size);
    }

    size_t WriteAvailable()
    {
       const size_t readIdx = m_readIdx.load(std::memory_order_acquire);
       const size_t writeIdx = m_writeIdx.load(std::memory_order_acquire);

       return WriteAvailable(readIdx, writeIdx, m_size);
    }
};

#endif


texts: Inject content into html served by nodejs expressjs

texts:
I have an Express server. It serves a static HTML file that uses Vue.
I don't want to render the HTML in NodeJS (e.g., using Pug), Vue already renders it on the client side and spares my server's resources. But it requires some dynamic data. Instead of polling the server for this data after the DOM is loaded, I'm injecting it into the HTML file in NodeJS:
const htmlFile = await fs.promises.readFile('htmlFile', 'utf8'),
    myData = [object1, object2, object3, etc],
    // Try to sanitize my data only by replacing <>
    myDataLazilySanitized = (JSON.stringify(myData)).replace(/[<>]/g, (char) => char === '<' ? '&lt;' : '&gt;');

// I now add myData to a custom element, right after the <body> tag
res.send(htmlFile.replace(/<body>/i, '<body><x-server-data id="x-server-data" class="hidden">' + myDataLazilySanitized + '</x-server-data>'));

Nothing in myData has < or >, so I can safely replace them for HTML entities.
The browser then parses this data:
myData = JSON.parse(document.getElementById('x-server-data').innerHTML);

I have 2 questions:

Is it safe what I'm doing? (i.e., is this lazy sanitizing enough)
Is there an easier way to do this?

Realted:
https://stackoverflow.com/questions/58264703/nodejs-how-to-insert-an-element-in-a-html-document-using-javascript


texts: Minimum difference between numbers in a file

texts:
I'm learning Java and I created a simple solution for the following problem:

  Given a file [filename].txt such that each line has the format string, double, find the minimum possible difference between any two values and identify if it is less than an arbitrary value mindDist

package com.company;

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) { try {
        Scanner sc = new Scanner(System.in);
        System.out.print("Please enter the name of the input file: ");
        Scanner inFile = new Scanner(new File(sc.nextLine()));
        sc.close();

        List<Double> l = new ArrayList<>();
        while (inFile.hasNextLine()) {
            String[] parts = inFile.nextLine().split(",");
            l.add(Double.parseDouble(parts[1]));
        }

        Collections.sort(l);
        double minDist = 5;
        double diff;
        double minDiff = Double.MAX_VALUE;

        for (int i = 1; i < l.size(); i++) {
            diff = l.get(i) - l.get(i - 1);
            if (diff < minDiff) minDiff = diff;
        }

        if (minDiff < minDist) System.out.println("The satellites are not in safe orbits.");
        else System.out.println("The satellites are in safe orbits.");
        if (l.size()!=1) System.out.println("The minimum distance between orbits (km): " + minDiff);
        inFile.close();

        } catch (NumberFormatException | FileNotFoundException | ArrayIndexOutOfBoundsException e) {
            System.err.println(e);
        }
    }
}

I am looking on advice on if there are any other possible errors / exceptions I may have missed, in addition to any way of increasing the efficiency / simplicity of my code.


texts: .NET - Get a DateTime from a pointer to an OLE Date

texts:
So I have this SDK I'm working with, which lives in unmanaged land, and when it wants to tell me something in particular it sends me a particular Windows API message and passes a pointer to a Date in the LParam of that message. I figured out that the date is OA-compatible (a double representing a fractional number of days since the epoch), and so after some playing around I came up with this:

Dereference the pointer by marshalling the raw bits at the address into an Int64.
Perform a bitwise conversion of the Int64 into a Double.
Treat that double as an OA Date and pass it to the static methods on DateTime to get the answer.

It totally works, but conceptually it sounds really kludgy; pointer, to long, to double (bitwise to boot), to DateTime. Other than inlining these three lines with only the final result being stored, is there any more direct way in .NET to turn an IntPtr to an OLE Date into a DateTime?

private void GetDateFromWinMsg(Message message)
    {
        ...
        var dateAsULong = Marshal.ReadInt64(message.LParam);
        var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong);
        var dateTime = DateTime.FromOADate(dateAsDouble);
        ...
    }


texts: Dynamic Programming with Project Euler problem 67

texts:
I am a beginner with python and programming in general. I started teaching myself about 2 months ago.

I've been working my way through Project Euler and a few similar sites to build my chops, and because I find it fun/rewarding. Below is my first attempt at some simple dynamic programming to come up with the solution to problem 67.

I would appreciate any criticism or advice. One thing in particular that I struggle with is readability (naming variables, comments, etc.). Also, I am largely ignorant when it comes to convention/best practices, so guidance here would be helpful.

pyr = []
with open('problem_67.txt') as f:
    for line in f:
        pyr.append(map(int, line.split()))
f.closed

def best_path(li):
    """Find the max total from top to bottom in a triangular array."""
    saver = {}
    n = len(li)

    # Set values for all points to 0
    for y in xrange(2, n+1):
        for x in xrange(len(li[n-y])):
            saver[(n-y, x)] = 0

    # Establish the max values for the bottom row
    for x in xrange(len(li[n-2])):
        a, b, c = li[n-2][x], li[n-1][x], li[n-1][x+1]
        saver[(n-2, x)] += max(a+b, a+c)

    # Add the highest dict of the two lower options for each other row
    for y in xrange(3, n+1):
        for x in xrange(len(li[n-y])):
            a, b, c = li[n-y][x], saver[(n-(y-1), x)], saver[(n-(y-1), x+1)]
            saver[(n-y, x)] += a + max(b, c)

    return saver[0, 0]

def main():
    print best_path(pyr)

if __name__ == "__main__":
    main()


texts:
I would like to get opinion if I am doing this right. I am creating a helper class that is globally accessible to my whole project. I want it to be easily called like Facebook.loginUser()

My code is like this:

class Facebook: NSObject {
  class func LoginUser() {
    println("Login user...")
  }
}

And on usage just call the class name and method:

Facebook.loginUser()

instead of:

var FB: Facebook = Facebook()
FB.loginUser()


texts: Produce the nth lexicographic permutation of a string consisting of letters H and V

texts:
I have tried many possible methods here but I am still not able to reduce the time complexity of below algorithm.

//This function returns the next lexicographical permutation of the StringBuilder s
static StringBuilder getKRankString(StringBuilder s)
{
    char ch[] = (s.toString()).toCharArray();
    int i = 0, j=0;
    //This loop gets the highest i for which ch[i]<ch[i+1]
    for(int k=0;k<s.length()-2;k++){
        if(ch[s.length()-2-k]<ch[s.length()-1-k]){
            i = s.length()-2-k;
            break;
        }

    }
    //System.out.println(i);
    //This loop gets the highest j for which ch[j]>ch[i]
    for(int k=s.length()-1;k>i;k--){
        if(ch[k]>ch[i]){
            j = k;
            break;
        }

    }
    //System.out.println(j);
    //swap characters at i and j
    char temp = ch[i];
    ch[i] = ch[j];
    ch[j] = temp;
    //Append the original string till i to reversed string from i till end
    StringBuilder swapped = new StringBuilder(new String(ch));
    //System.out.println(swapped);
    String sb1 = swapped.substring(0, i+1);
    String sb2 = (new StringBuilder(swapped.substring(i+1, s.length())).reverse()).toString();
    StringBuilder str = new StringBuilder(sb1+sb2);
    return str;
}

static String[] gridLand(String[] inp) {
    String[] outputArr = new String[inp.length];
    for(int i=0;i<inp.length;i++){
    //get the first line of input and get integer x and y
        int x = Integer.valueOf(inp[i].split(" ")[0]);
        int y = Integer.valueOf(inp[i].split(" ")[1]);
        int k = Integer.valueOf(inp[i].split(" ")[2]);
        StringBuilder sb = new StringBuilder();
    //form the original string using x H's and y V's.
    //This will be the first String of this order
        for(int j = 0; j < x; j++)
            sb = sb.append("H");
        for(int j = 0; j < y; j++)
            sb = sb.append("V");
        //String s1 = sb.toString();
    //run the below functoin K times to get Kth lexicographical string
        for(int m = 0; m < k; m++)
            sb = getKRankString(sb);
        outputArr[i] = sb.toString();
    }
    return outputArr;

}

The basic layout of my problem is as follows:
I have a string that is composed of only H's and V's. There can be not more than 10 H's and 10 V's possible. I need to find the Kth lexicographical order of such pattern. Also, inp[] array contains input is format:

2 2 3
4 5 4

which means that total H = 2, total V = 2 and I need to print 3rd lexicographical permutation of HHVV.
Similarly for 4 5 4, I need to print 4th lexicographical permutation of HHHHVVVVV.


texts:
I am trying to create stacked inputs using flexbox, with the additional ability to also set rows. Here is the code:

.stacked-inputs,
.stacked-inputs .row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    -ms-flex-align: center;
    align-items: center;
}
.stacked-inputs .row {
    width: 100%;
    margin-bottom: 10px;
}
.stacked-inputs > input,
.stacked-inputs .row > input {
    position: relative;
    -ms-flex: 1 1 0%;
    flex: 1 1 0%;
    min-width: 0;
}

  <input type="text" placeholder="First name">
  <input type="text" placeholder="Last name">

    <input type="text" placeholder="First name">
    <input type="text" placeholder="Last name">

    <input type="text" placeholder="Job title">
    <input type="text" placeholder="Year started">

When inputs are stacked without using rows, they will all be stacked horizontally. However, if a row is used, then obviously the rows of stacked inputs can be divided up nicely. Would love a review of this code from someone. Thanks in advance.


texts: Statement checker c# using forms and frontend

texts:
I'm just here for suggestions and code optimisations, what i could've done better, are there any better coding practices...
There's github repo link if you're interested in the code with a form too https://github.com/throtz/Operators
You basically have 2 textboxes in which you enter numbers and choose with a combobox what you want to do with those two numbers.
using System;
using System.Windows.Forms;

namespace Operators
{
    public partial class Operators : Form
    {
        public Operators()
        {
            InitializeComponent();
        }
        private void Form1_Load_1(object sender, EventArgs e)
        {
            comboBox.Items.AddRange(new string[] { "+", "-", "*", "/", "%", ">", "<", "=", ">=", "<=" });
        }
        private void ButtonCheck_Click_1(object sender, EventArgs e)
        {
            if (sender is null)
            {
                throw new ArgumentNullException(nameof(sender));
            }

            int a = Convert.ToInt32(textBox1.Text);
            int b = Convert.ToInt32(textBox2.Text);

            Nah(a, b);
        }
        private void Nah(int a, int b)
        {
            switch (comboBox.SelectedItem.ToString())
            {
                case "+":
                    MessageBox.Show("Sum of thenumbers entered is: " + (a + b));
                    break;
                case "-":
                    MessageBox.Show("Subtraction of the numbers entered is: " + (a - b));
                    break;
                case "*":
                    MessageBox.Show("Multiplication of the numbers entered is: " + (a * b));
                    break;
                case "/":
                    MessageBox.Show("Division of the numbers entered is: " + (a / b));
                    break;
                case "%":
                    MessageBox.Show("Modulo the two numbers is: " + (a % b));
                    break;
                case ">":
                    MessageBox.Show("First number is bigger than the secound one " + (a > b));
                    break;
                case "<":
                    MessageBox.Show("First number is smaller than the secound one " + (a < b));
                    break;
                case "=":
                    MessageBox.Show("Numbers are equal: " + (a == b));
                    break;
                case ">=":
                    MessageBox.Show("First number is bigger or equal to number two " + (a >= b));
                    break;
                case "<=":
                    MessageBox.Show("First number is smaller or equal to number two " + (a <= b));
                    break;
                default:
                    MessageBox.Show("Illegal operation.");
                    break;
            }
        }
    }
}


texts: Implementation of std::atomic> for C++20

texts:
As you may know, C++20 has added std::atomic<std::shared_ptr<T>> specialization to the standard, but sadly, most compilers have not implemented it yet. So I decided to implement it myself.
I want to know if I can improve this code or not. In addition, I'm not sure if my implementations of wait(), notify_one() and notify_all() are correct using condition variable.
#include <atomic>
#include <memory>
#include <condition_variable>
#include <thread>
#include <version>

#if !defined(__cpp_lib_atomic_shared_ptr) || (__cpp_lib_atomic_shared_ptr == 0)

namespace std {

template<typename T>
struct atomic<shared_ptr<T>> {

    using value_type = shared_ptr<T>;

    static constexpr bool is_always_lock_free = false;
    bool is_lock_free() const noexcept {
        return false;
    }

    constexpr atomic() noexcept {};
    atomic(shared_ptr<T> desired) noexcept : ptr_(std::move(desired)) {};
    atomic(const atomic&) = delete;
    void operator=(const atomic&) = delete;

    void store(shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept {
        std::lock_guard<std::mutex> lk(cv_m_);
        atomic_store_explicit(&ptr_, std::move(desired), order);
    }
    void operator=(shared_ptr<T> desired) noexcept {
        store(std::move(desired));
    }

    shared_ptr<T> load(memory_order order = memory_order::seq_cst) const noexcept {
        return atomic_load_explicit(&ptr_, order);
    }
    operator shared_ptr<T>() const noexcept {
        return load();
    }

    shared_ptr<T> exchange(shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept {
        return atomic_exchange_explicit(&ptr_, std::move(desired), order);
    }

    bool compare_exchange_weak(shared_ptr<T>& expected, shared_ptr<T> desired,
                                memory_order success, memory_order failure) noexcept {
        return atomic_compare_exchange_weak_explicit(&ptr_, &expected, std::move(desired), success, failure);
    }
    bool compare_exchange_strong(shared_ptr<T>& expected, shared_ptr<T> desired,
                                    memory_order success, memory_order failure) noexcept {
        return atomic_compare_exchange_strong_explicit(&ptr_, &expected, std::move(desired), success, failure);
    }
    bool compare_exchange_weak(shared_ptr<T>& expected, shared_ptr<T> desired,
                                memory_order order = memory_order::seq_cst) noexcept {
        return compare_exchange_weak(expected, std::move(desired), order, convert_order(order));
    }
    bool compare_exchange_strong(shared_ptr<T>& expected, shared_ptr<T> desired,
                                    memory_order order = memory_order::seq_cst) noexcept {
        return compare_exchange_strong(expected, std::move(desired), order, convert_order(order));
    }

    void wait(shared_ptr<T> old, memory_order order = memory_order::seq_cst) const noexcept {
        std::unique_lock<std::mutex> lk(cv_m_);
        cv_.wait(lk, [&]{ return !(load(order) == old); });
    }
    void notify_one() noexcept {
        cv_.notify_one();
    }
    void notify_all() noexcept {
        cv_.notify_all();
    }

private:
    shared_ptr<T> ptr_;
    mutable std::condition_variable cv_;
    mutable std::mutex cv_m_;

    constexpr memory_order convert_order(memory_order order) {
        switch(order) {
        case std::memory_order_acq_rel:
            return std::memory_order_acquire;

        case  std::memory_order_release:
            return std::memory_order_relaxed;

        default:
            return order;
        }
    }
};

}

#endif

int main() {
    std::atomic<std::shared_ptr<int>> a;
}

I will be happy about your suggestions. Thanks in advance.


texts:
I'm using customized Apache host files for my Digitalocean websites. Please review the code, whether it's following the good standards or not, and please mention if I'm missing something important. Here is the host file template that I'm using for all my websites (on Ubuntu 16.04):

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com

    SSLEngine on
    SSLCertificateFile /home/username/certs/example.com.pem
    SSLCertificateKeyFile /home/username/certs/example.com.key

    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/example.com/public_html

    SSLEngine on
    SSLCertificateFile /home/username/certs/example.com.pem
    SSLCertificateKeyFile /home/username/certs/example.com.key
</VirtualHost>

<Directory /var/www/example.com/public_html/>
    Options +ExecCGI
            Options FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
</Directory>


texts: Sandboxing untrusted JavaScript execution by redeclaring variables

texts:
Suppose, via AJAX, I downloaded a string jsCode containing JavaScript code from a (potentially malicious) third-party website. I want to allow the code to implement some basic Turing-complete logic, but I don't want to allow it to touch other APIs, especially cookies, localStorage, etc.

If I redeclare all variables that the script can access, ~~can I assume that I have prevented the danger of XSS?~~ please read along to see the actual question

function evalFunction(jsCode) {
    const vars = ["jsCode", "name", "fx", "ex"] // these may not be in window
    for(const name in window) vars.push(name) // regardless of hasOwnProperty()

    const fx = new Function(`var ${vars.join()}; ${jsCode}`)
    try{
       return [true, fx()]
    }catch(ex){
       return [false, ex]
    }
}

In case I want to expose some libraries such as Math, I can redeclare and clone them. (But DOM access is not possible, because they have reference to window) If implemented carefully, this will not expose extra danger not in the code above. Let's ignore this part for this question.

This seems to work: https://jsfiddle.net/16rb8cxe/6/

I am mostly confident that this will fail, but just academically discussing, how can this kind of protection be exploited?

  Scenario for those interested: I am making a static webpage that connects to some third-party server as specified by the user (assume it's like Google Translate or archive.org, but its main purpose is something that does not necessarily require DOM rendering or script loading).


texts:
Question is short. Assuming that I don't need reference itself, would this cast

((TextView) findViewById(R.id.someTextView)).setText("lala");

be better (or at least not worse) than:

TextView tv=(TextView) findViewById(R.id.someTextView);
tv.setText("lala");


texts: Validating a file input whose value is reset to empty string ("") after selection

texts:
My form comprises of a mandatory file input.

The form is validated according to the jQuery validate plugin.

The file input has attribute required so that the validator recognises it as a mandatory field.

Problem statement:
Each time the user selects a file, the value of the file input is immediately reset to "". This is done to allow the same file to be uploaded again (see here) and cannot be changed by me.
Since the file input is mandatory, its value must be non-empty to be marked as valid. However, the file input is validated after the value has been reset to "", so the input is always marked as invalid, even if the user has selected a file.
See demo here

Solution:
Step 1: Each time the user selects a file, store the value of the selected file(s) in a data- attribute of the file input:
$('input[type=file]').change(function() {

  $(this).data('files', $(this).val());

});

Step 2: Change the way the validator accesses the value of the file input. To do this I modify the elementValue function (line 718 of the plugin source) to use $element.data('files') instead of using $element.val() for file inputs:
$.extend( $.validator.prototype, {

    elementValue: function( element ) {
            ...
            ...

            if ( isContentEditable ) {
                val = $element.text();
            } else if (type === "file") {
                val = $element.data("files") === undefined ? "" : $element.data("files");
            } else {
                val = $element.val();
            }

            ...
            ...
  });

***See demo here***

Concerns:
I am wary of overwriting 'elementValue' in this way as it is an internal function of the plugin.
It doesn't seem too dangerous since the return value of the modified 'elementValue' function is the same as that of the original, so any modifications I have made are restricted to that single function and won't spill over to the rest of the plugin. But I'm not sure of this and would be grateful for any guidance as I am new to jQuery/JS and don't have any collaborators to think this through with.
Another drawback I can think of is that I will always have to check the solution's compatibility with future releases of the plugin.


texts:
I have written a Manchester Encoding encoder / decoder based on my misconception of how it works (whoops). My encoder accepts an array of ones and zeroes, and returns the 'manchester encoded' data (pretending there is a constant clock to overlay onto the data). I am reasonably new to C++, and would like to advance my knowledge and coding skill in it, hence why I coded this small application. I am looking for ways to improve my code, as well as ways to increase its efficiency.

Main.cpp

#include <iostream>
#include "Manchester.h"

int main()
{
    int data[] = { 1, 1, 0, 0 }; // Some unencoded data
    int* encoded = Manchester::encode(data, 4);
    int* decoded = Manchester::decode(encoded, 8);
    return 0;
}

Manchester.cpp

#include "Manchester.h"
#include <stdexcept>
#include <sstream>
#include <cstring>
#include <cstdlib>

#ifdef DEBUG
    #include <iostream>
#endif

int *Manchester::encode(int *data, int length)
{
    int *output = new int[length * 2];

    for (int i = 0; i < length; i++)
    {

        // Work out the array indexes to use
        int bid = i * 2;
        int nbid = bid + 1;

        // Get the data
        int real = data[i];

        int bit = 0;
        int nbit = 0;

        // Work out what it is
        switch (real)
        {
        case 0:
            bit = MANCHESTER_ZERO[0] - '0'; // Subtract 48 to work out the real value
            nbit = MANCHESTER_ZERO[1] - '0';
            break;
        case 1:
            bit = MANCHESTER_ONE[0] - '0'; // Subtract 48 to work out the real value
            nbit = MANCHESTER_ONE[1] - '0';
            break;
        }

        #ifdef DEBUG
            std::cout << "[encode] " << real << " [" << bit << nbit << "]" << std::endl;
        #endif

        output[bid] = bit;
        output[nbid] = nbit;
    }

    return output;
}

int *Manchester::decode(int *data, int length)
{
    if ((length % 2) != 0)
    {
        throw std::range_error("length is not a multiple of 2");
    }

    int *output = new int[length / 2];

    for (int i = 0; i < (length / 2); i++)
    {
        // Work out the array indexes to use
        int bid = i * 2;
        int nbid = bid + 1;

        // Get the data
        int bit = data[bid];
        int nbit = data[nbid];

        // Put the data into a stringstream for comparison
        std::stringstream con;
        con << bit << nbit;
        const char* sbit = con.str().c_str();

        int real = 0;

        // Compare the data and work out the value
        if (strcmp(sbit, MANCHESTER_ONE) == 0)
        {
            real = 1;
        } else if (strcmp(sbit, MANCHESTER_ZERO) == 0) {
            real = 0;
        }

        #ifdef DEBUG
            std::cout << "[decode] bit: " << bit << nbit << " [" << real << "]" << std::endl;
        #endif

        output[i] = real;
    }

    return output;
}

Manchester.h

#ifndef MANCHESTER_H
#define MANCHESTER_H

#define DEBUG

#define MANCHESTER_ONE "01"
#define MANCHESTER_ZERO "10"

class Manchester
{
public:
    static int *encode(int *data, int length);
    static int *decode(int *data, int length);
};

#endif


texts:
I am using a way of making error messages, and it works fine. It is just starting to get a little annoying as my project gets larger.

I was wondering if there was a way to do with with out having to rename every part of the error, and make a code so it would pick up the function it occurred in.

Private Sub tsbEditNeighbour_Click(sender As Object, e As EventArgs) Handles tsbEditNeighbour.Click
    ' Error Checking

    On Error GoTo Err_tsbEditNeighbour_Click

    Dim CurrentRow As DataRowView = TryCast(PropertyNeighboursLoadRecordsBindingSource.Current, DataRowView)

    ' Load Warranty
    Dim uNeighbours As New frmNeighbours
    With uNeighbours
        .PropertyID = Val(lblPropertyIDValue.Text)
        .NeighbourID = Val(CurrentRow("NeighbourID"))
        .LoadNeighbours()
        .ShowDialog()
        Me.Show()
    End With

Err_tsbEditNeighbour_Click:
    If Err.Number <> 0 Then
        sErrDescription = Err.Description
        WriteAuditLogRecord(Me.Name, "tsbEditNeighbour_Click", "Error", sErrDescription)
        MsgBox("System Error occurred" & Chr(13) & "tsbEditNeighbour_Click" & Chr(13) & sErrDescription, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "AztecCRM - Error Reporting")
    End If
End Sub


texts:
I am getting List ids and by using those ids I am creating a Map by fetching related data of id from database, here I am checking prevId with currId if these are not equal then I am putting them into oCMap.

Can this code be optimized?  Or are there any improvements (like is there any better algorithm)?  Please offer suggestions.

  public void populateMap(List<Number> ids)
  {
    Object oName, cName, startDate, endDate;
    String header = "
";
    String footer = "
";
    String rowStart = "
";
    String rowEnd = "
";
    String columnStart = "&nbsp;";
    String columnEnd = "	";
    SimpleDateFormat displayDateFormat = new SimpleDateFormat ("dd/MM/yyyy");
    String convertedDateString;
    Number prevId = null;
    Number currId = null;
    StringBuilder sBuild = new StringBuilder();
    StringBuilder sbLoop = new StringBuilder();

    for(int j = 0; j < ids.length; j++)
    {

      Row row = getRow(ids[j]);
      currId  = (Number)row.getAttribute("OwnerId");
      oName   = row.getAttribute("oName");
      cName = row.getAttribute("ContracttypeName");
      startDate    = row.getAttribute("StartDate");
      endDate      = row.getAttribute("EndDate");

      if(prevId != null && !currId.equals(prevId))
      {
        if(sbLoop.length() > 0)
        {
          sBuild.append(header);
          sBuild.append(sbLoop);
          sBuild.append(footer);
        }
        _oCMap.put(prevId, sBuild); //HashMap declared at class level

        sBuild = new StringBuilder();
        sbLoop = new StringBuilder();
      }

      sbLoop.append(rowStart);
      if(oName != null)
      {
        sbLoop.append(columnStart + oName + columnEnd);
      }
      else
      {
        sbLoop.append(columnStart + columnEnd);
      }
      sbLoop.append(columnStart + cName + columnEnd);
      if(startDate != null)
      {
        convertedDateString = displayDateFormat.format(((Date)startDate).dateValue());
        sbLoop.append(columnStart + convertedDateString + columnEnd);
      }
      else
      {
        sbLoop.append(columnStart + columnEnd);
      }
      if(startDate != null && endDate != null)
      {
        sbLoop.append(columnStart + " t/m" + columnEnd);
      }
      else
      {
        sbLoop.append(columnStart + columnEnd);
      }
      if(endDate != null)
      {
        convertedDateString = displayDateFormat.format(((Date)endDate).dateValue());
        sbLoop.append(columnStart + convertedDateString + columnEnd);
      }
      else
      {
        sbLoop.append(columnStart + columnEnd);
      }
      sbLoop.append(rowEnd);
      prevId = currId;

      if(j ==  ownerContract.length - 1)  //code for putting into map for last id.
      {
        if(sbLoop.length() > 0)
        {
          sBuild.append(header);
          sBuild.append(sbLoop);
          sBuild.append(footer);
        }
        _oCMap.put(prevId, sBuild); //HashMap declared at class level
      }
    }
  }


texts: Uses of barriers for one main thread controlling n threads

texts:
Referring to this post, my problem (summarized):

One main thread waits for connections, on accept() spawns a new thread for each connection. After we received n connections, the main thread dictates all threads what command to run, and must wait for all threads to finish, until issuing a new command later on.

I would love to know if this solves my problem efficiently and is correct.

static int mCommandToExecute = 0;
static int mNumberConnectedClients = 0;
static pthread_barrier_t mWaitForAllDone;
static pthread_barrier_t mWaitForCommand;

void* handleRequest(void* arg) {

    ...

    while (1) {
        // Wait for a command here
        pthread_barrier_wait(&mWaitForCommand);

        printf("\nSending to client: %s\n", commands[mCommandToExecute]);
        n = write(sockfd, commands[mCommandToExecute], length[mCommandToExecute]);
        ...

        // Wait for all threads to finish here
        pthread_barrier_wait(&mWaitForAllDone);
    }
}

void* startServer(void* arg) {
    pthread_barrier_init(&mWaitForCommand, NULL, maxConnections + 1);
    pthread_barrier_init(&mWaitForAllDone, NULL, maxConnections + 1);

    for (mNumberConnectedClients = 0; mNumberConnectedClients < maxConnections; ++mNumberConnectedClients) {
        clientSocket = accept(sockfd, (struct sockaddr *) &client_addr, &clientLength);
        pthread_create(&mThread_pool[mNumberConnectedClients], NULL, handleRequest, (void*) &clientSocket);
    }

    // Wait for all threads to have booted up and ready to execute a command
    mCommandToExecute = 0;
    for (int i = 0; i < 4; ++i) { // Run through 4 commands as an example
        pthread_barrier_wait(&mWaitForCommand);
        // At least one thread is still executing here
        pthread_barrier_wait(&mWaitForAllDone);
        // All commands are done here
        mCommandToExecute = i + 1; // No mutex is used here, so set variable before every threads reads it
    }

    // Wait for all threads to finish
    for (int i = 0; i < maxConnections; ++i) {
        pthread_join(mThread_pool[i], NULL);
    }
}


texts:
While I'm aware of various different means of checking if a variable is a Window object in JavaScript, I'm interested in writing a function that is more accurate and resilient.

For example, jQuery uses:

isWindow: function( obj ) {
    return obj != null && obj == obj.window;
}

which will return an incorrect result for:

var o = {};
o.window = o;
$.isWindow(o); //returns `true`, even though `o` is not a window object

For purposes of this question, assume that the browser's native functions and objects have not been modified at the time of initialization.

Currently my code is:

(function (w) {
    "use strict";
    var wStr;
    wStr = Object.prototype.toString.call(w);
    if (!w.isWindow) {
        w.isWindow = function (arg) {
            var e,
                str,
                self,
                hasSelf;

            //Safari returns `DOMWindow`
            //Chrome returns `global`
            //Firefox, Opera & IE9 return `Window`
            str = Object.prototype.toString.call(arg);
            switch (wStr) {
            case '[object DOMWindow]':
            case '[object Window]':
            case '[object global]':
                return str === wStr;
            }
            if ('self' in arg) {
                //`'self' in arg` is true if `'self'` is in `arg` or a prototype of `arg`
                hasSelf = arg.hasOwnProperty('self');
                //`hasSelf` is true only if `'self'` is in `arg`
                try {
                    if (hasSelf) {
                        self = arg.self;
                    }
                    delete arg.self;
                    if (hasSelf) {
                        arg.self = self;
                    }
                } catch (e) {
                    //IE 7&8 throw an error when `window.self` is deleted
                    return true;
                }
            }
            return false;
        };
    }
}(window));

A few assertions:

console.assert(isWindow(window), '"window" is a window');

var o = {};
o.self = o;
o.window = o;
console.assert(!isWindow(o), '"o" is not a window');

var w = window.open('about:blank');
console.assert(isWindow(w), '"w" is a window');

var x = window.open('http://www.example.com');
console.assert(isWindow(x), '"x" is a window');


texts: Integer Power C++ Function with base and exponent parameters

texts:
I would like to know if this is a good solution for a function that has to computer the power of integers given base and exponent.
The solution must include solution for negative numbers.
I'm trying to learn C++ trough a Deitel book and I'm doing several exercises.
#include <iostream>
using namespace std;

double integerPower(int base, int exponent){
    double result = 1;
    if(exponent >=0){
    for (int i = 0; i < exponent; i ++){
        result *= base;
        }
    } else {
        exponent *= -1;
        for (int i = 0; i < exponent; i ++){
                result /= base;
                }
    }
    return result;
}

int main() {
    int base, exponent;
    double result;
    cout << "Insert the base: " << endl;
    cin >> base;
    cout << "Insert the exponent: " << endl;
    cin >> exponent;
    result = integerPower(base, exponent);
    cout <<"The result is: " << result << endl;
    return 0;
}


texts: C++ template type traits for class members

texts:
I have written type traits for checking, if given class T has_member, then if it either has_non_static_function_member, has_static_function_member or has_non_function_member. These type traits don't take function arguments of the member nor return type to check signature validity (I will provide other type traits for this matter).

I want to know if it can be done somehow simpler, and if the current code doesn't have some logical errors. Personally, I think I might have overcomplicated the implementation.

Here is initial version:

#include <iostream>
#include <type_traits>

template<class, class = void>
struct has_member_xxx : std::false_type
{ };

template<class T>
struct has_member_xxx<
    T,
    std::void_t<
        decltype(&T::xxx)
        >
    > : std::true_type
{ };

template<class, class = void>
struct has_non_static_member_function_xxx : std::false_type
{ };

template<class T>
struct has_non_static_member_function_xxx<
    T,
    std::enable_if_t<
        std::is_member_function_pointer<
            decltype(&T::xxx)
        >::value>
    > : std::true_type
{ };

template<class, class = void>
struct has_static_member_function_xxx : std::false_type
{ };

template<class T>
struct has_static_member_function_xxx<
    T,
    std::enable_if_t<
        (!has_non_static_member_function_xxx<T>::value) &&
        std::is_function<typename std::remove_pointer<decltype(&T::xxx)>::type>::value
        >
    > : std::true_type
{ };

template<class, class = void>
struct has_non_function_member_xxx : std::false_type
{ };

template<class T>
struct has_non_function_member_xxx<
    T,
    std::enable_if_t<
        has_member_xxx<T>::value &&
        (!has_non_static_member_function_xxx<T>::value) &&
        (!has_static_member_function_xxx<T>::value)
        >
    > : std::true_type
{ };

struct A
{
    int xxx;
};

struct B
{
    int xxx();
};

struct C
{
    static int xxx();
};

int main()
{
    std::cout << std::boolalpha;
    std::cout << "has member xxx: " << std::endl;
    std::cout << "A: " << has_member_xxx<A>::value << std::endl;
    std::cout << "B: " << has_member_xxx<B>::value << std::endl;
    std::cout << "C: " << has_member_xxx<C>::value << std::endl << std::endl;

    std::cout << "has non-static member function xxx" << std::endl;
    std::cout << "A: " << has_non_static_member_function_xxx<A>::value << std::endl;
    std::cout << "B: " << has_non_static_member_function_xxx<B>::value << std::endl;
    std::cout << "C: " << has_non_static_member_function_xxx<C>::value << std::endl << std::endl;

    std::cout << "has static member function xxx" << std::endl;
    std::cout << "A: " << has_static_member_function_xxx<A>::value << std::endl;
    std::cout << "B: " << has_static_member_function_xxx<B>::value << std::endl;
    std::cout << "C: " << has_static_member_function_xxx<C>::value << std::endl << std::endl;

    std::cout << "has non-function member xxx" << std::endl;
    std::cout << "A: " << has_non_function_member_xxx<A>::value << std::endl;
    std::cout << "B: " << has_non_function_member_xxx<B>::value << std::endl;
    std::cout << "C: " << has_non_function_member_xxx<C>::value << std::endl << std::endl;
}

Code is also on Coliru for convenience.


texts: Python code to run a C program that calculates whether points are in the mandelbrot set

texts:
This is part of a project to explore the Mandelbrot set. The code to graphically navigate the complex plane and allow the user to adjust the colormap and number of iterations is all written in Python, because that sort of user interface work is easiest in a scripting language. However, Python is not very good at inner loops that run hundreds of times for each pixel, so I wrote a C program that does the actual computation. The python function runs the C executable in a separate process that passes the result back from C to python as a human-readable string. Parsing the string back to integers is slow. What is a more pythonic way of creating the interface between C and python? Also, any general tips for writing faster, better C are appreciated, I'm new to the language.

Python code:

import numpy as np
from subprocess import Popen
import subprocess

def getcounts(xmin, xmax, ymin, ymax, dim, depth):
    """render a view of the mandelbrot set on the given rectangle of the
    complex plane, by calling a C script and interpreting stdout as a
    series of integers
    output is a numpy array reshaped into a dim*dim square"""

    p = Popen(["./a.out", repr(xmin), repr(xmax), repr(ymin),
    repr(ymax), str(dim), str(depth)], stdout=subprocess.PIPE)

    counts = np.fromstring(p.stdout.readline()[:-1], dtype = np.int, sep = ' ')

    return counts.reshape([dim, dim]).transpose()

C code:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
  int dim = 100;        /*defaults produce a nice overview of the mandelbrot set*/
  int depth = 300;
  double minx = -2;
  double maxx = 2;
  double miny = -1.5;
  double maxy = 1.5;

  if(argc > 6){
      minx = atof(argv[1]);
      maxx = atof(argv[2]);
      miny = atof(argv[3]);
      maxy = atof(argv[4]);
      dim = atoi(argv[5]);
      depth = atoi(argv[6]);
  }

  double xstep = (maxx - minx)/dim;
  double ystep = (maxy - miny)/dim;

  int i, j;
  for(i = 0; i < dim; i++){
    double c_real = minx + i * xstep;
    for(j = 0; j < dim; j++){
      double c_imag = miny + j * ystep;
      int count = 0;
      double z_real = 0;
      double z_imag = 0;
      double zreal_temp;
      while((z_real * z_real + z_imag * z_imag < 4) && count < depth){
          count ++;
          zreal_temp = z_real * z_real - z_imag * z_imag + c_real;
          z_imag = z_real * z_imag * 2 + c_imag;
          z_real = zreal_temp;
      }
      printf("%d ", count);
    }
  }
}

Finally, here's a python script to test the above function: I've cut out all the bits for moving around and adjusting settings since this question is about the C - Python interface

import numpy as np
import matplotlib.pyplot as plt
xmin = -2
xmax = 2
ymin = -2
ymax = 2
depth = 60
dim = 600
counts = getcounts(xmin, xmax, ymin, ymax, dim, depth)
plt.imshow(counts, extent = [xmin, xmax, ymax, ymin], interpolation = 'nearest')
plt.show()


texts: Read line and combine duplicate entries based on one of the fields

texts:
The following Java code reads lines from an input text file and will output the entry that has the highest number in field-2 to an output file:

INPUT:

  William J. Clinton 6 Q1124
  42nd President of the United States 6 Q1124
  Bill Clinton,6,Q1124
  Bill Clinton,14,Q9890
  Bill Clinton,5,Q9880
  William Jefferson Clinton,6,Q1124

OUTPUT:

  William J. Clinton,Q1124  42nd President of the United
  States,Q1124  Bill Clinton,Q9890 (this Q-ID selected because
  field-2 was highest number "14")
  William Jefferson Clinton,Q1124

Could you offer suggestions on making this more elegant?

/*
 * This class uses a method to combine duplicate Wiki keys into one and
 * selecting the Qid of the one with largest link count
 */

public static void main(String[] args) {

    if (args.length < 2) {
        usage();
        System.exit(0);
    }

    //
    try {
        // Create output file
        BufferedWriter out = Files.newBufferedWriter(Paths.get(args[1]),
                StandardCharsets.UTF_8);

        // read input file
        BufferedReader br = Files.newBufferedReader(Paths.get(args[0]),
                StandardCharsets.UTF_8);
        String key = "";
        int links = 0;
        String qID = "";

        String next, line = br.readLine();
        for (boolean first = true, last = (line == null); !last; first = false, line = next) {
            last = ((next = br.readLine()) == null);

            String[] entry = line.split(",");

            if (first) {
                // only assign current values
                key = entry[0];
                links = new Integer(entry[1]);
                qID = entry[2];

            } else if (last) {

                //check if key is a duplicate
                if(key.equals(entry[0])){
                    //use the Qid from the highest links
                    int temp = new Integer(entry[1]);
                    if(links < temp){
                        //write entry to output higher links
                        out.write(key + "," + entry[2] + "\n");
                    }else{
                        //write entry to output using current
                        out.write(key + "," + qID + "\n");
                    }

                }else{
                    //write last entry to output
                    out.write(key + "," + qID + "\n");
                    out.write(entry[0] + "," + entry[2] + "\n");
                }

            } else {

                //check if key is a duplicate
                if(key.equalsIgnoreCase(entry[0])){
                    //use the Qid from the highest links
                    int temp = new Integer(entry[1]);
                    if(links < temp){
                        links = temp;
                        qID = entry[2];
                    }

                }else{
                    //write entry to output
                    out.write(key + "," + qID + "\n");

                    //reassign current values
                    key = entry[0];
                    links = new Integer(entry[1]);
                    qID = entry[2];
                }

            }

        }

        // Close the output stream
        out.close();

    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

}

private static void usage() {
    System.err.println("Usage: CombineKeys InputFile OutputFile");
}


texts: Optimized list filtering on implementation of Project Euler 23

texts:
I'm new to Haskell, the part of my code I'm concerned with is the isSumAbundant function. Surely there must be a better way, in an imperative language I might use a for loop and break out of the loop if i got greater than n, but it seems like having to filter the list for every single function call is not optimal.

The problem is Problem 23 from project-euler.net.

projectEuler23 =
  let a = abundantNums 28124 in
  sum [x | x <- [1..28124], not $ isSumAbundant x a]

isSumAbundant n a =
  any (\x -> (n - x) `elem` a) (takeWhile (<n) a)

abundantNums n =
  [x | x <- [1..n], (>x) $ sum $ properDivisors x]

properDivisors n =
  let  limit = (floor.sqrt.fromIntegral) n in
  [limit | limit^2 == n]
  ++ ((1:) $ concat [ [x, div n x] | x <- [2..limit - 1], rem n x == 0])


texts: What changes can I make to simply this function that groups parameter key value pairs

texts:
I am writing a function that can be used in a ruby script that will match the parameter and values together so the script can use them in an intelligent way. The idea is if you were to run a script with this function it would output the key value pairs of the parameters passed to the script.
For example
my_script.rb -user Jeff -key /path/to/key -config /path/to/config

The expected output would be an array with the key value pairs like
[ {:arg => 'user', :val => 'Jeff'}, {:arg => 'key', :val => '/path/to/key'}, {:arg => 'config', :val => '/path/to/config'} ]

This then could be used in any Ruby script that takes command line arguments and organizes it for them in a consistent way. Then the script can decide what to do with the output and act on those key value pairs passed.
My Question:
Are there are enhancements that can be made for this script and / or is there simpler ways to do this in Ruby? The function is below:
#!/usr/bin/env ruby

class Script_Helper
  def self.get_params (ary)
    args = Array.new
    unless ARGV.empty?
      for i in 0..ARGV.size-1
        if ARGV[i].start_with?('-') and i < ARGV.size + 1
          args.push ({:arg => ARGV[i], :val => ARGV[i+1]})
        end
      end
    end
    return args
  end
end


texts: Better understanding of unit testing in VBA from non-returning functions

texts:
I have always wanted to start unit testing my code, and ending last week I downloaded Rubberduck again (first time there was just too little information how to do it to get me going) but after watching this video unit testing, I decided that it looks easy enough.

So the whole weekend I read up more and watched more videos and got more excited - because Monday I am going to go through my latest project and start incorporating unit tests!!

Or maybe not... I got to this first class of mine, and I really do not see a lot of places that I can do unit testing - meaning not a lot of return functions with a value to test.

The long and short of this class is that I inherited a worksheet with a lot of data all over the place, so much so that I can not even add or delete a line without breaking a lot of formulas (true story). Anyway, I made a new sheet, loaded information from a DB into that sheet, and from there on I am doing a data transfer to the infected patient (as mentioned above) every time I need to update the information.

My class with methods is below and I am wondering if there is anyway to run a test to check if data are transferred correctly, or to re-write the code to make it less brittle. Please feel free to tear the code apart and give any other advice you deem necessary.

Option Explicit
Private firstTruckColm As Long
Private truckRow As Long
Private numberOfShops As Long
Private numberOfProducts As Long
Private wb As Workbook
Private laailys As Worksheet
Private bloem As Worksheet
Private bloemShopNamesStartRow As Long
Private bloemShopNamesStartColm As Long

Public Sub loadTrucksInit()

    Call initValues
    Call insertShopNamesAndProd

End Sub

Private Sub initValues() 'Loads values from a "settings" module. (Any thoughts on this)'

    firstTruckColm = mdl_settings.returnLaailysFirstTruckColm
    truckRow = mdl_settings.returnLaailysTruckRow
    numberOfShops = mdl_settings.returnNumberOfBloemShops
    numberOfProducts = mdl_settings.returnNumberOfBloemProducts
    Set wb = ThisWorkbook
    Set laailys = wb.Sheets("Laailys")
    Set bloem = wb.Sheets("Bloem")
    bloemShopNamesStartRow = mdl_settings.returnBloemShopNamesStartRow
    bloemShopNamesStartColm = mdl_settings.returnBloemShopNamesStartColm

End Sub

Private Sub insertShopNamesAndProd()
    Dim a As Long
    For a = 1 To numberOfShops
        With laailys
            .Cells(truckRow, firstTruckColm + a - 1).Value = bloem.Cells(bloemShopNamesStartRow, bloemShopNamesStartColm + a).Value
        End With
        Call goThroughProducts(bloemShopNamesStartColm + a, firstTruckColm + a - 1)
    Next a
End Sub

Private Sub goThroughProducts(colmToUseBloem As Long, colmToUseLaailys As Long)
    Dim a As Long
    For a = bloemShopNamesStartRow + 1 To numberOfProducts + bloemShopNamesStartRow
        If bloem.Cells(a, colmToUseBloem).Value <> vbNullString Then
            Call insertProducts(bloem.Cells(a, 1).Value, bloem.Cells(a, colmToUseBloem).Value, colmToUseLaailys)
        End If
    Next a
End Sub

Private Sub insertProducts(productCode, prodAmount, colmToUseLaailys)
    Dim a As Long
    Dim checker As Boolean
    checker = False
    For a = 1 To 200
        If laailys.Cells(a, 4).Value = productCode Then
            laailys.Cells(a, colmToUseLaailys).Value = prodAmount
            checker = True
            Exit Sub
        End If
    Next a
    If checker = False Then
        MsgBox productCode & " did not read in correctly, make sure the product code in 'Laailys' is the same as in 'Bloem'"
    End If
End Sub

A few other questions that I also want to know if possible:

I like to have a initValues method that loads all the properties that I am going to use in my class all at once in one neat place if I need to change any. Is this an acceptable practice?
I point to colm values like firstTruckColm + a - 1, should I first declare another variable and give this value to that variable, just so that my arguments for other procedures look better?
Should I rather change my Subs to Functions with a return value as most I can?


texts: Do I have too many regexes in my validation logic?

texts:
The below function uses Javascript to validate a Belgian telephone number and format it according to the guidelines for phone number formatting.

function acm_mscrm2011_psa_FormatPhoneNumber(executioncontext) {
    //get the phone number from the field that starts the validation
    var telefoonnummer = executioncontext.getEventSource().getValue();
    //check if not empty
    if (telefoonnummer) {
        telefoonnummer = telefoonnummer.replace(/(\s|-|\/|\.)+/g, "");
        //check if it's a Belgian number
        //Optional country code of +32 or 0032, followed by optional 0, followed by a local part of either (an 8 digit number) OR (a 4 followed by 8 digits)
        var telefoonRegex = /^(?:\+32|0032)?0?([1-9][0-9]{7}|4[0-9]{8})$/;
        if (telefoonRegex.test(telefoonnummer)) {
            var telefoonMetFormaat;
            //get the first captured group of the previous test, i.e. the local part
            var localpart = RegExp.$1;
            if (localpart.length == 8) {
                //landline or fax
                //group in format # ### ## ##
                telefoonMetFormaat = localpart.replace(/(\d)(\d\d\d)(\d\d)(\d\d)/, "+32 $1 $2 $3 $4");
            } else {
                //cellphone number
                //group in format ### ## ## ##
                telefoonMetFormaat = localpart.replace(/(\d\d\d)(\d\d)(\d\d)(\d\d)/, "+32 $1 $2 $3 $4");
            }
            //put the validated and formatted number back into the system
            executioncontext.getEventSource().setValue(telefoonMetFormaat);
        }
    }
}

As you can see, I first use a Regex to strip any excess delimiters from the code, then I use another Regex to check if the number is valid, then I use another Regex to format the number in a way that's more easily readable.Now, it works, most of it is readable (the validation regex is tricky but has a comment to explain it), but I'm not sure if using Regex everywhere is a good idea.

However, I don't immediately see a different solution that doesn't involve a large amount of nested ifs, fors and substrings that ultimately would be just as tricky to read and maintain as these 3 regexes.

Is there an alternative to these regexes?


texts: Remove useless whitespace from styled string

texts:
I have a big string resource (basically the "about" text of the application) which contains styles (such as <b>, <a> etc.). The string resource is written on multiple lines, like this:

<string name="about_text"><big><b>About</b></big>\n
Lorem ipsum dolor sit amet and all that stuff...\n
\n
More stuff.</string>

Now, just like in HTML, Android treats actual new lines (not the special \n) as spaces, so the text ends up looking something like this:

About
  Lorem ipsum dolor sit
amet and all that
stuff...

  More stuff.

Which looks pretty stupid. Now, I have two options:

Write the whole thing on one line. I did not go with this because:

It would be a pretty big line.
The text needs to be translated, and putting it all on one line would give the translators a great headache.

Remove the unneeded whitespace programatically.

I went with the second solution, but I'm not sure my implementation is optimal:

CharSequence aboutText = getText(R.string.about_text);

SpannableStringBuilder ssb = new SpannableStringBuilder(aboutText);
for (int i=0; i < ssb.length()-1; i++) {
    if (ssb.charAt(i) == '\n' && ssb.charAt(i+1) == ' ') {
        ssb.replace(i+1, i+2, "");
    }
}

this.aboutText = (TextView) findViewById(R.id.about_text);

this.aboutText.setText(ssb);

It seems very hackish, but I could not find a better way. Is there a better way?


texts:
I occasional write simple yet long Python scripts using Sqlite3 (I'm not proficient with functional or object oriented programming... yet)

Usually my Sqlite3 is blazing fast.  I'm used to looping through lists of SELECT statements with each SELECT taking a split second, and writing tables to text files in HTML markup. But, this is the first time I've done a LEFT JOIN in Sqlite3, and its taking much longer to complete the script than I had thought. I figured a couple of minutes perhaps, but it's taking several hours to run though all the queries.

I added print statements to narrow down that this LEFT JOIN, within a loop, is where the script hangs up for several minutes, instead taking a split second to perform. It's definitely between the SELECT and the .fetchall.

I have a couple of questions:

Is it normal for Sqlite3 to hang on LEFT JOIN (or any other JOIN)?
Did I code something the wrong way?

I need the code to work fast. If the code appears professional that's definitely a bonus.

print "selecting...",
cur.execute("SELECT \"b\".\"Disposals\" AS \"Disposals\", \
                    \"a\".\"ASSET NUMBER\" AS \"Record\", \
                    \"a\".\"DESCRIPTION\" AS \"DESCRIPTION\", \
                    \"a\".\"NAME_2012\" AS \"GIS_NAME_2012\", \
                    \"a\".\"Notes\" AS \"GIS_Notes\", \
                    \"a\".\"Other\" AS \"GIS_Other\", \
                    \"a\".\"QC_place\" AS \"GIS_place\", \
                    \"a\".\"QC_county\" AS \"GIS_county\", \
                    \"a\".\"lon_\" AS \"Longitude\", \
                    \"a\".\"lat_\" AS \"Latitude\" \
FROM \"resultsPoints\" AS \"a\" \
LEFT JOIN \"html_Tables\" AS \"b\" \
  ON (\"a\".\"ASSET NUMBER\" = \"b\".\"Assetnum\") \
WHERE \"a\".\"DEPARTMENT NUMBER\" LIKE ? \
  OR \"a\".\"AGENCY_BoB\" LIKE ? \
GROUP BY \"a\".\"ASSET NUMBER\" \
ORDER BY \"a\".\"ASSET NUMBER\"",(sqlHunt, sqlHuntBoB))

tableData = cur.fetchall()
print "fetching..",

for r, row in enumerate(tableData):
print " - ",
   for c, column in enumerate(row):
       print ".",
       mysheets[bobAgency].write (r+2, c, str(column))


texts:
I am working on a program to decode MMS PDU files.  They are binary files and I am reading them byte by byte and decoding each header value as I come to it.

One header value is the Date, and it's represented as follows (in hex):

85 04 57 E2 A2 49

0x85 is the "Date" header, 0x04 is the data length (4 bytes) and the 4 following bytes represent the date (timestamp).

I have code to read those 4 bytes and return it to me as a bytearray:

bytearray(b'W\xe2\xa2I')

Apparently \x57 is a W and \x49 is an I.

In order to parse this as a date, I need to convert it to an int.  These bytes represent the timestamp 1474470473 (or 0x57E2A249).

I have code to convert this byte array into an int, but there has got be a better way to do it than the way I came up with.

timestamp = int(''.join(map(hex, byte_range)).replace('0x', ''), 16)
value = datetime.fromtimestamp(timestamp)

That is, I am converting every byte to a string (like "0x57"), joining them together, removing the "0x"s, then reading that string as a base 16 value.  This works, but it seems a little too convoluted.

I then realized that I could replace the join/map with binascii.hexlify, so now my code is:

timestamp = int(binascii.hexlify(byte_range), 16)
value = datetime.fromtimestamp(timestamp)

Like I said, this code works, but I just feel there's a better way to do this than to convert the bytearray into a string and then parse that string back as a base-16 int.


texts:
Following my answer to Unique type ID in C++, I have worked towards a "safer" version that I am posting here.

This is a lightweight type that can store a unique (also across compilation units) ID per type for use at runtime, without RTTI.

Instead of using a built-in type for ID representation that is also accessible to the end user, a specific class type_id_t provides the external representation of the ID and encapsulates the actual storage type (a function pointer) that is not accessible.

A helper function template call type_id<T>() returns a type_id_t containing the ID of type T.

Hence, the following operations are only provided:

construction only by calling type_id function.
copy/move construction, as implicitly defined
copy/move assignment, as implicitly defined
comparison operators == and != between two type_id_t's

There is no default constructor for type_id_t.

Here is the implementation:

class type_id_t
{
    using sig = type_id_t();

    sig* id;
    type_id_t(sig* id) : id{id} {}

public:
    template<typename T>
    friend type_id_t type_id();

    bool operator==(type_id_t o) const { return id == o.id; }
    bool operator!=(type_id_t o) const { return id != o.id; }
};

template<typename T>
type_id_t type_id() { return &type_id<T>; }

It is interesting that function type_id returns a (function) pointer to itself, encapsulated into a type_id_t. No nasty type casting is necessary.

This is not a mechanism that provides runtime identification of a (polymorphic) object's type, but can be used as a low-level tool to build such functionality. I actually made this for the needs of my recent any, and then improved it.

Just for demonstration, we can store the ID of a number of types e.g. in a vector:

template<typename... T>
std::vector<type_id_t>
make_ids() { return {type_id<T>()...}; }

Later, we can compare the stored IDs to the ID of a given type:

template<typename T, typename A>
void comp_ids(const A& a)
{
    for (auto i : a)
        std::cout << (type_id<T>() == i) << " ";
    std::cout << std::endl;
}

and get the following:

auto ids = make_ids<
    int, bool, double const&, int&&, char(&)[8],
    int, void(int), unsigned char**, std::vector<void(*)()>, double[4][8]
>();

comp_ids<int>(ids);  // output: 1 0 0 0 0 1 0 0 0 0

Here is a live example.

Any comments are welcome.


texts: Comparing columns values and change their places by condition

texts:
There are three simple tables. Actor, Film, Film_actor.

Film_Actor table:

 actor_id     | film_id
--------------+---------------------------
     1        |  3
     2        |  4

Actor table:

 actor_id   | first_name                  | last_name
------------+-----------------------------+----------
     1      | Daniel                      |  Craig
     2      | Eva                         |  Green

Film table:

 film_id     | title
-------------+---------------------------------------
    3        | Casino Royale
    4        | Colombo

I would like to find two actors who cast together the most and list the titles
of those movies. Moreover, actor_id of the first_actor should be lower than actor_id of the second_actor.

So the desired result should look like this:

first_actor     | second_actor  | title
----------------+---------------+---------------
Daniel Craig    | Eva Green     | Casino Royale

I've written the following code:

SELECT
        ac1.actor_id first_actor_id
        , ac1.first_name + ' ' + ac1.last_name   first_actor
        , ac2.actor_id second_actor_id
        , ac2.first_name + ' ' + ac2.last_name second_actor
        ,count(*) FilmCount
    FROM
        Actor as ac1
        INNER JOIN Film_Actor as fa1 ON fa1.actor_id = ac1.actor_id
        INNER JOIN Film_Actor as fa2 ON fa1.film_id = fa2.film_id
        INNER JOIN Actor as ac2 ON fa2.actor_id = ac2.actor_id
            and fa1.actor_id < ac2.actor_id
        INNER JOIN Film as fi ON fa1.film_id = fi.film_id
    GROUP BY
        ac1.actor_id
        , ac1.first_name
        , ac1.last_name
        , ac2.actor_id
        , ac2.first_name
        , ac2.last_name

In my view, the above code is a little bit clumsy as the code makes checking of this condition  actor_id of the first_actor should be lower than actor_id of the second_actor*` just for second actor.

Is it possible to improve comparing actor_id of the first_actor with actor_id of the second_actor`?


texts: Photogallery First project in OOP review

texts:
Please take it easy on my as this is my first OOP web application I plan on converting it to some deeper degree but not sure yet.

The basic functionality is there I think, but I'm looking for some feedback on how I can improve this in terms of OOP and simplicity. Sorry for any simple mistakes only been doing php for a few months and its my first language :)

Many Thanks

<?php

class Image{

/*
*list of properties
*image filepath gets pasted in $imageFilepath
*/
public $imageFilepath = "";
public $imageTitle;
public $imageSize;

/*
*list of properties
*image filepath gets pasted in $imageFilepath
*/
public function __construct() {
     echo 'Welcome to Dannys awesome Gallery';
}

/*
*function to get the image filepath, runs through the files the outputs then in an array
*
*/

public function getimage_Filepath() {
    $image_files = get_files($imageFilepath);
    if (count($image_files)) {
        $index = 0;
        foreach($image_files as $index=>$file)
        $index++;
    }
    return;
}

/*
*Outputs the file images found
*
*/

public function setimage_Filepath() {
    echo $this->getimage_Filepath();
}

/*
*Generates the image name, from the actual filename
*
*/

public function getimage_title($imageTitle) {
//gets the image title using basename
    $imageTitle = $this->imageFilepath;
    basename($imageTitle);
    return $imageTitle;
}

/*
*Outputs the image name
*
*/

public function setimage_title($imageTitle) {
    //displays the image title
    echo $this->imageTitle;
}

}
$image = new Image;
?>


texts: HTML Templates with Substitutable Areas - PHP

texts:
In order to separate my views (markup) and code, I elected to write my views like this:

    <!DOCTYPE HTML>

        <title>%PAGE_TITLE%</title>
        <meta charset="UTF-8">
        <link href='PotatoDocs/views/stylesheets/docs2013.css' type='text/css' rel='stylesheet'>
        <link rel="shortcut icon" href="favicon.ico" />

        <link rel="stylesheet" href="highlight.js/styles/default.css">

%PAGE_TITLE%

                %CONTENT%

                %SIDEBAR%

&nbsp;

            Potato Seed 2013

A method then replaces the substitution area with parts of the website, like so:

    private function generatePageSource($page_title)
    {
        $page_template = file_get_contents(REGISTRY_CODE_PATH . "views/templates/" .
            $this->template_dir . "/main.html");

        $page_content = str_replace("%PAGE_TITLE%", pdisplay($page_title), $page_template);
        $page_content = str_replace("%CONTENT%", $this->pagecontent_content, $page_content);
        $page_content = str_replace("%SIDEBAR%", $this->sidebar_content, $page_content);

        $this->page_content = $page_content;
    }

The $this->page_content is later echoed.

Not too relevant to my question, but for the sake of completion, this is the pdisplay() function.

function pdisplay($pdisplay)
{
    $pdisplay = htmlentities(stripslashes($pdisplay), ENT_QUOTES);
    return $pdisplay;
}

My question is this (though I accept any code criticism at all): is this a sensible way to render pages?

I used to implant php tags with echoes onto a page -- but this meant that code (even a little bit) was on the views, so I thought this would be a better solution.


texts: ConcurrentThrottledList - Will this implementation be thread safe?

texts:
I want a thread safe list with a max item count, will the following implementation correctly provide this?

public class ConcurrentThrottledList<T>
{
    private readonly List<T>  items = new List<T>();
    private readonly int maxItems;
    private object _lock = new object();

    public ConcurrentThrottledList(int maxItems)
    {
        this.maxItems = maxItems;
    }

    public bool TryAdd(T item)
    {
        lock (_lock)
        {
            if (items.Count < maxItems)
            {
                items.Add(item);
                return true;
            }
            return false;
        }
    }

    public bool TryRemove(T item)
    {
        lock (_lock)
        {
            return items.Remove(item);
        }
    }

    public bool IsFull { get { lock (_lock) { return items.Count >= maxItems; } } }

    public T[] Items { get { lock(_lock) { return items.ToArray(); } } }
}


texts:
I'm working on an A* pathfinding algorithm to solve a programming problem, and part of the constraint is the runtime. I need to find a path in a 2D grid with blocked or non-blocked tiles. You can't move diagonally.

I have succeeded to make a working prototype of the function which can and will solve the problems encountered, but it lacks optimisation.

I think that I need to optimise my heuristic function. For now, I calculate candidly: the distance between the current tile and the goal if no tile were blocked, plus the current cost.

n.distGoal = abs(n.x - nTargetX) + abs(n.y - nTargetY) + n.cost;

Interestingly, I've found an answer that does not include the cost when calculating its heuristic. When trying it out, my algorithm doesn't work anymore.

Have you any clues on how I could make the function more optimised?

Here are a few more snippets of my code, to help understand and maybe spot an error that causes long runtime:

Finding the neighbours:

set<tile> neighbours;
    for(int k=-1;k<2;k+=2){
        if(!(cur.x+k < 0|| cur.x+k>=nMapWidth)){ //if we're out of bonds, there's nowhere to go
            struct tile neigh;
            neigh.x = cur.x+k;
            neigh.y = cur.y; //yum
            neigh.mapWidth = nMapWidth;
            int positionInMap = neigh.x + (neigh.y*nMapWidth);
            if(!(pMap[positionInMap] == 0)){ //if we can walk there
                neigh.cost = cur.cost + 1;
                neighbours.insert(neigh);
            }
        }

        if(!(cur.y+k < 0 || cur.y+k>=nMapHeight)){ //if we're out of bonds, there's nowhere to go
            struct tile neigh;
            neigh.x = cur.x;
            neigh.y = cur.y+k;
            neigh.mapWidth = nMapWidth;
            int positionInMap = neigh.x + (neigh.y*nMapWidth);
            if(!(pMap[positionInMap] == 0)){ //if we can walk there
                neigh.cost = cur.cost + 1;
                neighbours.insert(neigh);
            }
        }
    }

Reconstructing the path when we reached the end:

void buildPath(map<tile,tile> cameFrom, tile cur, int* pOutBuffer){ //Reconstructs the path
    int i = cur.distGoal - 1;
    pOutBuffer[i] = cur.x + cur.y*cur.mapWidth;
    map<tile,tile>::iterator it = cameFrom.find(cur);
    while (it != cameFrom.end()){
        i--;
        if(i<0){
            break;
        }
        cur = it->second;
        pOutBuffer[i] = cur.x + cur.y*cur.mapWidth;
        it = cameFrom.find(cur);
    }
}