texts: TaskScheduler that uses a dedicated thread

texts:
I'm trying to implement a TaskScheduler that runs all tasks in the order they are submitted, on a single dedicated thread. Here's my implementation, using a BlockingCollection:

class SequentialScheduler : TaskScheduler, IDisposable {
    readonly BlockingCollection<Task> m_taskQueue = new BlockingCollection<Task>();
    readonly Thread m_thread;
    bool m_disposed;

    public SequentialScheduler() {
        m_thread = new Thread(Run);
        m_thread.Start();
    }

    public void Dispose() {
        m_disposed = true;
    }

    void Run() {
        while (!m_disposed) {
            var task = m_taskQueue.Take();
            Debug.Assert(TryExecuteTask(task));
        }
    }

    protected override IEnumerable<Task> GetScheduledTasks() {
        return m_taskQueue;
    }

    protected override void QueueTask(Task task) {
        m_taskQueue.Add(task);
    }

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) {
        if (Thread.CurrentThread == m_thread) {
            return TryExecuteTask(task);
        }
        return false;
    }
}

I've played with it a bit and it seems to work well. I have some lingering questions however:

As you can tell by the Debug.Assert, I'm not sure how TryExecuteTask could return false and I'm just assuming that given my current implementation, it won't. Can that actually happen and what I should I do if it does?
I'm not sure my implementation of TryExecuteTaskInline makes sense as it doesn't get called in my tests. If I understand correctly, this method should run the task synchronously if possible; hence why I'm checking if the current thread is the scheduler's dedicated thread.
Also, my implementation of Dispose doesn't wait for the current task to complete, and will cause the rest of the tasks in the queue to just wait there forever, but short of making it blocking and wait for the queue to empty, I don't see how to do that any differently. I just need a way to release the thread.


texts: Login and create username and password program

texts:
I'm trying to make a password program that you can login to or make a new user.
I want to make this better, so any help would be appreciated, also any suggestions to make this better would be good

import time
LOGIN = ("Login", "login", "L", "l", "LOGIN")
CREATE = ("Create", "create", "C", "c", "CREATE", "Create Account", "Create account", "create Account", "create account", "CREATE ACCOUNT")
x = 0
newPass = "X"
newUser = "X"

validEntry = {
    "Liam" : "liampass",
    "Bob" : "bobpass"
}  #All current usernames and passwords stored in this dictionary

print("--==Welcome==--")
time.sleep(1)
def choice():
    print("Login or Create Account?")
    choice = input(":>>>")
    if choice in LOGIN:
        login()
    elif choice in CREATE:
        create()           #Choice to login or create

def login():
    print("""
Please login. Case sensitive.""")
    time.sleep(0.5)
    print("Username.")
    entry = input(":>>>")
    if entry in validEntry:
        x = 0
        while x < 3:
            print("Input Password.")
            passentry = input(":>>>")
            passright = validEntry.get(entry)  #Checks dictionary to find password associated with username entered
            if passentry == passright:
                print("Successful Login!")
                x += 5  #Correct password, addition code could be added here
            else:
                print("""Incorrect password, try again
                      """)
                x += 1     #Incorrect password, allows three attempts
    else:
        print("Username not recognised!")
        login()

def create():
    print("Please choose a username")
    newUser = str(input(":>>>"))
    print("Please choose a password for", newUser)
    newPass = str(input(":>>>"))
    global newUser, newPass  #Globalizes both new password and username for entry to dictionary

choice()

validEntry[newUser] = newPass #Adds new username and password to dictionary

choice()  #You can only make one new account then login


texts:
Please take a look at this Fiddle.

Is there a better way of building a table with titles in the first cell of each row, like this:

    A
    B
     C

   Germany
   Yes
   No
   Yes

  .........

In building a string of HTML, I use an each(function) for each returned object and then at the end set the div #area with the content. I can't think of a better way of doing this, but would like to know if there is a way to simplify the code. My actual JSON Data is way bigger than the example below, so the code would be very long and use far more each function in the buildup of the string.

JSON:

[{"title":"A","nation":"Germany,Japan","city":"Hamburg,Toyko","Name":"John,Peter,Tom"},{"title":"B","nation":"Japan,Italy","city":"Toyko","Name":"Adam,Tom"},{"title":"C","nation":"Germany","city":"Berlin,Hamburg","Name":"Mary,Tom"}]

Code:

   $.ajax({
        url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FRgDyl4%22&format=json&diagnostics=true&callback=",
        success: function (data) {
            var item_html="";

            item_html += "

	";

            $(data.query.results.json.json).each(function (index, item) {
                var title = item.title;
                item_html += ''+title+'	';
            });

            item_html += "

Germany	";

            $(data.query.results.json.json).each(function (index, item) {
                var nations = item.nation.replace(/ /g,'').split(",");
                console.log(nations);
                if ($.inArray('Germany', nations) < 0)
                {
                  item_html += "No	";
                }else{
                  item_html += "Yes	";
                }
                 });

             item_html += "
Berlin	";

             $(data.query.results.json.json).each(function (index, item) {
                var  citys = item.city.replace(/ /g,'').split(",");
                if ($.inArray('Berlin', citys) < 0)
                {
                  item_html += "No	";
                }else
                {
                  item_html += "Yes	";
                }

             });

              item_html += "
Peter	";

             $(data.query.results.json.json).each(function (index, item) {
                var  names = item.Name.replace(/ /g,'').split(",");
                if ($.inArray('Peter', names) < 0)
                {
                  item_html += "No	";
                }else
                {
                  item_html += "Yes	";
                }

             });

           item_html += "

";

           $('#tablearea').append(item_html);

        }
    });


texts:
I was asked this question in an interview, and didn't go through. I know, it needs some improvements, but probably I am missing something big? I would highly appreciate if someone can review it for me, so that I can get to know what I need to work on.

The problem is to complete this skeleton class to implement a circular buffer. I could have done the C++ and header in a different source, but they insisted on doing it all here, assuming it is not part of a big project.

class CircularBuffer {
public:
    CircularBuffer(int size)
        : data_(size, 0)
        , next_(0)
        , head_(-1)
    {
    }

    ~CircularBuffer()
    {
    }

    bool empty()
    {
        return size() == 0;
    }

    int size()
    {
        // TODO: check if head is valid.
        // TODO: check emptiness properly.
        int sz = 0;
        if (head_ >= 0)
        {
            if (next_ > head_)
                sz = next_ - head_;
            else
                sz = next_ + (data_.size() - head_);
        }
        return sz;
    }

    void push(char val)
    {
        // TODO: check if circularbuffer is full.
        if( size() == data_.size())
        {
            std::cout<<"Buffer is full, can't push anything"<< std::endl;
            return;
        }
        data_[next_++] = val;
        if(head_ < 0)
            head_ = 0;
        if (next_ == data_.size())
            next_ = 0;

        displayBuffer();
    }

    char pop()
    {
        // TODO: check if head_ is valid.
        if (head_ < 0)
        {
            std::cout<<"Empty Buffer, nothing to pop" << std::endl;
            return -1;
        }

        // TODO: adjust head_ after pop.
        char popVal = data_[head_];
        data_[head_++] = 0; // Clean the popped memory- display   purpose

        //Wrap around head_ move
        if (head_ == data_.size())
            head_ = 0;

        // Check if the buffer is empty now?
        if (head_ == next_)
        {
            head_ = -1; //Buffer is empty now
            next_ = 0;
        }

        return popVal;
    }

    void displayBuffer()
    {
        std::cout << std::endl;
        for (auto c: data_)
        {
            std::cout << c << ' ';
        }
        std::cout << "  |   HEAD = " << head_ << "  NEXT = " << next_ << std::endl;
    }
private:
    std::vector<char> data_;
    int next_;
    int head_;
};


texts:
pancake sorting is implemented below. Algorithm is below:

Find the largest out of order pancake and flip it to the bottom (you may need to flip it to the top of the stack first).Repeat step one until the stack is ordered.

from random import randint

def pancake_sort(cakes):
  if not cakes or len(cakes) == 1:
        return cakes
  cake_index = 0
  while cake_index < len(cakes)-1:
    prev_cake_size, current_cake_size = cakes[cake_index], cakes[cake_index+1]
    if prev_cake_size > current_cake_size:
      '''move the highest element to the beginning by reversing
      the cakes from 0 to highest element(including) and then move
      the highest element to the end by reversing the subarray'''
      cakes[0:cake_index+2] = (cakes[0:cake_index+1][::-1] + [cakes[cake_index+1]])[::-1]
      cake_index = 0
      continue
    cake_index += 1
  return cakes

for i in range(randint(0, 5)):
  data = [randint(0, 100) for _ in range(randint(0, 40))]
  if pancake_sort(data[:]) != sorted(data[:]):
    print("failed for", data[:])


texts:
I am creating a site that is very heavily relying on Ajax. To stop major spamming on my site, I decided to implement a PHP system that checks how many actions have been made in the last 5 minutes. I wrote this fairly quickly and I was wondering if there are any major issues with my code. Read the footnote as to why I can't test this. If you see any major errors here, please let me know. Also, spelling errors would be the fault of auto-correct.

<?php
    session_start();
    require_once(".conf.php");
    //Main config
    $verification = $_GET['verification_token'];
    $requestactions = $_GET['request_actions'];
    $username = $_SESSION['username'];
    $login = $_SESSION['login'];
    $ip = $_SERVER['SERVER_ADDR'];
    //Set up config
    $maxactions = 40;
    $maxactionserror = 'Hmm, it seems you exceded the max actions allowed here. Try again in a few, Thank you!';
    $actiontable = 'actions'
    $currentactions = 0;
    $timeout = 1;
    $cookieexpire = 600 //Time in MS
    $blockreason = 'exceeded action requests';
    //Query config
    $firstquery = mysql_query("SELECT * FROM '$actiontable' WHERE username = '$username'");
    $rows = mysql_num_rows($firstquery);

    function check() {
        if ($rows) {
            if ($rows >= $maxactions) {
                setcookie['reasonblocked', $blockreason, time() + $cookieexpire);
                setcookie['ipblocked', $ip, time() + $cookieexpire);
                setcookie['blockfinished', 'timestamp', time() + $cookieexpire);
                $blockquery = mysql_query("INSERT INTO '$actiontable'('eligible') VALUES ('0') WHERE 'username' = '$username'");
                echo $maxactionserror;
                unset($login);
                unset($username);
                session_destroy();
            } else {
                while ($get = mysql_fetch_array($firstquery)) {
                    $currentactions = $get['cactions'];
                    $newactions = $currentactions++;
                    $secondquery = mysql_query("INSERT INTO '$actiontable'('username', 'auth_token', 'cactions', 'userip') VALUES ('$username', '$verification', '$newactions', '$ip')");
                    echo 'success';
                    check();
                }
            }
        } else {
            $secondquery = mysql_query("INSERT INTO '$actiontable'('username', 'auth_token', 'cactions') VALUES ('$username', '$verification', '1')");
            echo 'success';
        }
    }
?>

PS. I am on vacation so I am unable to test this. That is why I posted on here.


texts:
I wrote a fizz buzz variation method in Python which prints "fizz", "bang", and "buzz" for 3, 7, and 11 respectively.

def FizzBang():
    string = ''
    for n in range(1,101):
        msg = ""
        if not n % 3:
            msg += "Fizz"
        if not n % 7:
            msg += "Bang"
        if not n % 11:
            msg += "Buzz"
        print msg or str(n)

What can I do to increase the speed of this program? I know the modulus is quite expensive. Also maybe concatenating strings might not be needed as well.


texts:
I would like to know please if there is an efficient way to re-write the code I did. Basically it calculates the SumIfs from another tab depending on the tab the user pointed to, in row number 3, so each time something changed in row number 3 it should recalculate all again.

Private Sub Worksheet_Change(ByVal Target As Range)

On Error Resume Next

Dim Amount As Range 'the range i want to sum
Dim ID As Range 'criteria range
Dim Arg3 As Variant 'the criteria
Dim TabToTake As String
Dim countAllActiveCell As Long
Dim CellsCnt As Range

Dim ActiveCol

If Not Intersect(Target, Range("A1:XFD3")) Is Nothing Then

ActiveCol = Left(ActiveCell.EntireColumn.Address(False, False), InStr(1, ActiveCell.EntireColumn.Address(False, False), ":") - 1)

TabToTake = ActiveCell.Value

Application.ScreenUpdating = False

  Set ID = Sheets(TabToTake).Range("A:A")
  Set Amount = Sheets(TabToTake).Range("Q:Q")

For Each CellsCnt In Range("E4:E2500").Cells
    If Not IsEmpty(CellsCnt) Then

        Cells(CellsCnt.Row, ActiveCol).Value = Application.WorksheetFunction.SumIfs(Amount, ID, Cells(CellsCnt.Row, "E").Value)

    End If
Next CellsCnt

Application.ScreenUpdating = True

    End If
End Sub


texts: Optimising a LinkedList data structure - Part 1

texts:
I have implemented a linked list.  I feel I overdid it with pointers, used old standards and C++11, and I ended with too many lines of code. I will make my quotations into two parts: one for the Node and iterator struct and the other for rest of the class.

For node and iterator, how can I optimize for C++11?  Can you review it?

#include <vector>
#include <cassert>
template <typename T_>
class LinkedList
{
private:
    struct Node
    {
        T_ data;
        Node* prev;
        Node* next;
        /*Node(T_ D, Node* p = nullptr, Node* n = nullptr) : data(d), prev(p), next(n) {}*/

        Node( const T_ & d = Object{ }, Node * p = nullptr, Node * n = nullptr )
          : data(d), prev(p), next(n) { }

        Node( T_ && d, Node * p = nullptr, Node * n = nullptr )
          : data( std::move(d)), prev(p), next(n) { }

        Node( Node && n ) {        // Rvalue move ctor
            data = std::move(n.data);
            prev = std::move(n.prev);
            next = std::move(n.next);
        }
        Node& operator = ( Node && n ) { // Rvalue = operator
            data = std::move(n.data);
            prev = std::move(n.prev);
            next = std::move(n.next);
            return *this;
        }
        void swap(Node& rhs) throw ()
        {
            std::swap(prev, rhs.prev); std::swap(next, rhs.next);
        }
    };

public:
    struct LinkedListIterator : public std::iterator<std::forward_iterator_tag, T_, int>
    {
        Node*  _pNode;

        LinkedListIterator(Node* p = nullptr) : _pNode(p) {}

        Node* getNode() { return _pNode; }

        T_ operator * () { return _pNode->data; }
        LinkedListIterator & operator ++ () { _pNode = _pNode->next; return *this; } // pre
        LinkedListIterator operator ++ (int) { LinkedListIterator retval = *this; ++*this; return retval; } // post
        bool operator < ( LinkedListIterator const& rhs ) const { return _pNode < rhs._pNode; }
        bool operator != ( LinkedListIterator const& rhs ) const { return _pNode != rhs._pNode; }
        bool operator == ( LinkedListIterator const& rhs ) const { return _pNode == rhs._pNode; }
    };


texts: Is checking for null redundant while using Contract Annotator from JetBrains?

texts:
I'm curious whether checking for null is redundant in this concrete example.

 public LoginJob(@NotNull String login, @NotNull String password) {
        super(new Params(Priority.NORMAL).requireNetwork().persist());
        Preconditions.checkNotNull(login, "login is null or empty");
        Preconditions.checkNotNull(password, "password is null or empty");

        this.login = login;
        this.password = password;
    }

Please notice I'm using Contract Annotator from JetBrains, so the User of a Class warned the LoginJob constructor can't take null values, it can't prevent him/her of doing so though.


texts: Simple pool of threads which calculate the sum of a given number from the main process

texts:
I have to make a program which creates a number of threads that are waiting at the beginning, then the main process creates a doubly linked list where random numbers are put and then a signal tells the threads that a number has been put in the list, then the threads should "process" these numbers (is simply calculate the sum from 0 to the given number), graphically it looks like this:

And here is the code, I wonder if I'm doing what I'm doing fine...

Note: I'm working with 4 threads and the sleep(1) was to see the output...

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <semaphore.h>

#include "double_linked_list.h"

void *sum(void *ptr);

sem_t semaphore;
pthread_mutex_t mutex;

int main() {
    sem_init(&semaphore, 0, 0);

    int threads = 4;
    int number, i;

    pthread_t *threads_tab;
    int *thread_args;

    threads_tab = malloc(threads * sizeof(pthread_t));
    thread_args = malloc(threads * sizeof(int));

    srand(time(NULL));

    head = NULL;
    tail = NULL;

    for (i = 0; i < threads; i++) {
        thread_args[i] = i;
        pthread_create(&threads_tab[i], NULL, sum, (void*) &thread_args[i]);
    }

    while (1) {
        number = rand() % 100;

        printf("Insertando: %d\n", number);
        InsertAtHead(number);

        sem_post(&semaphore);

        sleep(1);
    }

    return 0;
}

void *sum(void *ptr) {
    int i, acumulator, number;

    while (1) {
        sem_wait(&semaphore);

        acumulator = 0;

        pthread_mutex_lock(&mutex);
        number = tail->data;
        PopTail();
        pthread_mutex_unlock(&mutex);

        for (i = 0; i < number + 1; i++)
            acumulator += i;

        printf("The number is: %d and the result is: %d from thread: %d\n", number, acumulator, *(int *)ptr);
    }
}

Apparently it's working well, it doesn't generate any errors and the outputs are the expected ones, but I would like to hear more opinions, because I am new in this, perhaps I'm making some mistakes without realizing...


texts: Pairwise combinations of an array in Javascript

texts:
I wrote a Javascript function that seems to successfully generate the unique pairwise combinations of a list:

function pairwise(list) {
  var pairs = [];
  list
    .slice(0, list.length - 1)
    .forEach(function (first, n) {
      var tail = list.slice(n + 1, list.length);
      tail.forEach(function (item) {
        pairs.push([first, item])
      });
    })
  return pairs;
}

pairwise('abcd'.split(''))
// [["a","b"],["a","c"],["a","d"],["b","c"],["b","d"],["c","d"]]

I checked it by using the combinatorics formula:

$$
combinations = \frac{n(n-1)}{2}
$$

var alpha = [ "a", "b", "c", "d", "e", "f", "h", "i", "j" ];

for(var n=1;n<7;n++){
  console.log(
    n,                                 // number of items
    pairwise(alpha.slice(0,n)).length, // how many pairs from function?
    n*(n-1)/2                          // double check with formula above
  );
}

// 1 0 0
// 2 1 1
// 3 3 3
// 4 6 6
// 5 10 10
// 6 15 15

Which looks right: there are 6 ways to chose pairs from 4 items, and so on.

It works, but I find it hard to read, and I'm not sure how to make it more readable. I'd welcome suggestions.


texts:
I just wrote this decimal to Roman numeral converter, inspired by Kevlin Henney's talk "Get Kata".
I have been reading the Rust docs little by little and this is one of my first attempts at some code.
I'd like to get feedback on style, general rust idioms and how I could have implemented this algorithm in a more succinct manner.
Code also available here.
use std::env;
use std::io;
use std::io::BufWriter;
use std::io::Write;

static BASE10_NUMERALS: [&str; 7] = ["I", "X", "C", "M", "X̄", "C̄", "M̄"];

static CENTRE_NUMERALS: [&str; 6] = ["V", "L", "D", "V̄", "L̄", "D̄"];

struct Bases {
    base: usize
}

impl Iterator for Bases {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.base = self.base - 1;
        Some(self.base)
    }
}

fn iter_bases(largest_base: usize) -> Bases {
    Bases { base: largest_base }
}

fn encode((decimal_number, base, ): (char, usize, )) -> String {
    let digit = decimal_number.to_digit(10).unwrap();
    let max_base = CENTRE_NUMERALS.len();

    if base >= max_base {
        BASE10_NUMERALS[BASE10_NUMERALS.len() - 1]
            //This pow function is the main limiter for decimal size
            .repeat((10_u32.pow((base - max_base) as u32) * digit) as usize)
    } else {
        if digit == 9 {
            format!("{}{}"
                    , if base == 3 { "Ī"} else { BASE10_NUMERALS[base] }
                    , BASE10_NUMERALS[base + 1]
            )
        } else if digit >= 5 {
            format!("{}{}", CENTRE_NUMERALS[
                base], BASE10_NUMERALS[base]
                        .repeat((digit - 5) as usize))
        } else if digit == 4 {
            format!("{}{}", BASE10_NUMERALS[base], CENTRE_NUMERALS[base])
        } else {
            // Less than 4
            BASE10_NUMERALS[base].repeat(digit as usize)
        }
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut writer = BufWriter::new(io::stdout());
    let input = &args[1];
    for roman_numeral in input
        .chars()
        .zip(iter_bases(input.len()))
        .map(encode) {
        writer.write(roman_numeral.as_bytes())
            .expect("Unable to write to stdout");
    }
}


texts:
I'm using C# for a project and thought I would get a feel for the language by making some simple programs.  My current program is a simple file recurser that prints the names of files and directories.  Any suggestions would be greatly appreciated.

using System;
using System.IO;

namespace FileRecurser
{
    class Program
    {
        private static int indent = -2; // Start off at -2 so first indent
                                        // starts at 0.

        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: recurser <directory>");
                return;
            }

            // Check if directory exists.
            string directory = args[0];
            if (!Directory.Exists(directory))
            {
                Console.WriteLine("Error: {0} doesn't exist!", directory);
                return;
            }

            Console.WriteLine("Printing files for {0}\n", directory);
            PrintDirectoryFiles(directory);
        }

        private static void PrintDirectoryFiles(string directory)
        {
            indent += 2;

            // If any subdirectories.
            string[] subdirectories = Directory.GetDirectories(directory);

            if (subdirectories.Length != 0)
            {
                foreach (var subdirectory in subdirectories)
                {
                    // Change color to reflect directory.
                    Console.ForegroundColor = ConsoleColor.Cyan;

                    Console.WriteLine(
                        "{0}{1}:",
                        new String(' ', indent),
                        Path.GetFileName(subdirectory)
                    );

                    Console.ResetColor();

                    PrintDirectoryFiles(subdirectory);
                    Console.WriteLine();
                }
            }

            // Print file names.
            string[] files = Directory.GetFiles(directory);

            if (files.Length != 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine(
                        "{0}{1}",
                        new String(' ', indent),
                        Path.GetFileName(file)
                    );
                }
            }

            indent -= 2;
        }
    }
}


texts: Matasano Cryptopals Challenge 1: convert hex to base64

texts:
Cryptopals challenge 1

Using binary strings to convert from hex to binary felt kinda hacky. I'd like to hear if there are better ways to do that.

I used memcpy() and pointer to the end of the string instead of strcat() to avoid the Shlemiel the Painter problem.

EDIT: follow up question

#include <stdio.h>
#include <assert.h>

char* hex_2_base64(char *_hex)
{
  char *hex_2_bin[16] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };
  char *dec_2_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  //allocating memory for binary string
  int bin_size = strlen(_hex) * 4;
  while (bin_size % 6 != 0) //add space for zero padding
    bin_size += 8;
  char *bin = malloc(bin_size + 1);
  memset(bin, 0, bin_size + 1);

  //these are for strtol, its arguments need the zero terminator
  char buf[2] = { 0 };
  char b64buf[6 + 1] = { 0 };

  //converting hex input to binary
  char *bin_end = bin;
  for (int i = 0; i < strlen(_hex); i++)
  {
    buf[0] = _hex[i];
    memcpy(bin_end, hex_2_bin[strtol(buf, NULL, 16)], 4);
    bin_end += 4;
  }

  //pad binary string w/ zeroes
  while (strlen(bin) < bin_size)
    strcat(bin, "00000000");

  //allocating memory for b64 output
  int b64size = (strlen(bin) / 6) + 1;
  char *out = malloc(b64size);
  memset(out, 0, b64size);

  //walk through binary string, converting chunks of 6 bytes into base64 chars
  char *bin_ptr = bin;
  char *out_end = out;
  int index_b64;
  while (*bin_ptr)
  {
    strncpy(b64buf, bin_ptr, 6);
    index_b64 = strtol(b64buf, NULL, 2);
    if (index_b64 == 0)
      buf[0] = '=';
    else
      buf[0] = dec_2_base64[index_b64];
    memcpy(out_end, buf, 1);
    out_end += 1;
    bin_ptr += 6;
  }

  free(bin);
  return out;
}

int main(void) {
  char *out = NULL;

  out = hex_2_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
  assert(strcmp(out, "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t") == 0);
  free(out);

  //Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.
  out = hex_2_base64("4d616e2069732064697374696e677569736865642c206e6f74206f6e6c792062792068697320726561736f6e2c2062757420627920746869732073696e67756c61722070617373696f6e2066726f6d206f7468657220616e696d616c732c2077686963682069732061206c757374206f6620746865206d696e642c20746861742062792061207065727365766572616e6365206f662064656c6967687420696e2074686520636f6e74696e75656420616e6420696e6465666174696761626c652067656e65726174696f6e206f66206b6e6f776c656467652c2065786365656473207468652073686f727420766568656d656e6365206f6620616e79206361726e616c20706c6561737572652e");
  assert(strcmp(out, "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=") == 0);
  free(out);

  //f
  out = hex_2_base64("66");
  assert(strcmp(out, "Zg==") == 0);
  free(out);

  //fo
  out = hex_2_base64("666f");
  assert(strcmp(out, "Zm8=") == 0);
  free(out);

  //foo
  out = hex_2_base64("666f6f");
  assert(strcmp(out, "Zm9v") == 0);
  free(out);

  //foob
  out = hex_2_base64("666f6f62");
  assert(strcmp(out, "Zm9vYg==") == 0);
  free(out);

  //fooba
  out = hex_2_base64("666f6f6261");
  assert(strcmp(out, "Zm9vYmE=") == 0);
  free(out);

  //foobar
  out = hex_2_base64("666f6f626172");
  assert(strcmp(out, "Zm9vYmFy") == 0);
  free(out);

  printf("OK!");

  return 0;
}


texts: Mock/Stub out filesystem in F# for unit testing

texts:
I'm looking to do some basic verification testing on my functions that write to the filesystem.

I took a hint from here on how to mock out the filesystem using an interface, but I'm kinda bummed on how the FileSystemOperations type needs to be passed along through every function. Any ideas how to improve this, or where I went wrong?

I'm rather new to FP, so any feedback on other design issues are welcome as well.

module FileSystem =

    open System.IO

    type IFileSystemOperations =
        abstract member copy: string -> string -> bool -> unit
        abstract member delete: string -> unit
        abstract member readAllBytes: string -> byte[]
        abstract member createDirectory: string -> DirectoryInfo
        abstract member directoryExists: string -> bool

    type FileSystemOperations () =
        interface IFileSystemOperations with
            member this.copy source destination overwrite =
                File.Copy(source, destination, overwrite)

            member this.delete path =
                File.Delete path

            member this.readAllBytes path =
                File.ReadAllBytes path

            member this.createDirectory path =
                Directory.CreateDirectory path

            member this.directoryExists path =
                let fileInfo = FileInfo path
                fileInfo.Directory.Exists

module FileMover =

    open FileSystem

    let private ensureDirectoryExists (fileSystemsOperations:IFileSystemOperations) destination =
        let directoryExists = fileSystemsOperations.directoryExists destination
        if not (directoryExists) then
            fileSystemsOperations.createDirectory destination |> ignore

    let private compareFiles (fileSystemsOperations:IFileSystemOperations) moveRequest =
        let sourceStream = fileSystemsOperations.readAllBytes moveRequest.Source
        let destinationStream = fileSystemsOperations.readAllBytes moveRequest.Destination
        sourceStream = destinationStream

    let private copyToDestination (fileSystemsOperations:IFileSystemOperations) (moveRequest:MoveRequest) =
        ensureDirectoryExists fileSystemsOperations moveRequest.Destination
        fileSystemsOperations.copy moveRequest.Source moveRequest.Destination true

    let private deleteSource (fileSystemsOperations:IFileSystemOperations) (move:Move) =
        fileSystemsOperations.delete move.Request.Source

    let private moveFile (fileSystemsOperations:IFileSystemOperations) moveRequest =
        copyToDestination fileSystemsOperations moveRequest
        let filesMatch = compareFiles fileSystemsOperations moveRequest
        let move = match filesMatch with
                   | true -> {Request = moveRequest; Result = Success}
                   | false -> {Request = moveRequest; Result = Failure BytesDidNotMatch}

        deleteSource fileSystemsOperations move

    let move (fileSystemsOperations:IFileSystemOperations) targetPath pictures =
        let moveFile = moveFile fileSystemsOperations

        pictures
        |> getMoveRequests targetPath
        |> Seq.map moveFile

Update (for reference & anyone interested)

Based on the answers below, here is how I currently refactored the code. It's a work in progress, but it's already more easily testable (main goal) and the responsibilities seem to fit better as well (eg: injecting ensureDirectoryExists into copyToDestination instead of into moveFile).

Thanks for your answers!


texts: Permutation of a string eliminating duplicates

texts:
This code lists the permutations of the string, and eliminates duplicates if any. I'm looking for code review, best practices, optimizations etc.

I'm also verifying complexity: \$O(n! * n)\$ as time complexity and \$O(n * n)\$ as space complexity, where \$n\$ is length of the input string.

public final class Permutation {

    private Permutation() {
    };

    /**
     * Return permutation of a given string.
     * But, if the string contains duplicate characters, it
     * takes care to eradicate duplicate permutations.
     *
     * @param string    the string whose permutation needs to be found out.
     * @return  a list with permuted values.
     */
    public static List<String> permutation(String string) {
        final List<String> stringPermutations = new ArrayList<String>();
        permute(string, 0, stringPermutations);
        return stringPermutations;
    }

    private static void permute(String s, int currIndex, List<String> stringPermutations) {
        if (currIndex == s.length() - 1) {
            stringPermutations.add(s);
            return;
        }

        // prints the string without permuting characters from currIndex onwards.
        permute(s, currIndex + 1, stringPermutations);

        // prints the strings on permuting the characters from currIndex onwards.
        for (int i = currIndex + 1; i < s.length(); i++) {
            if (s.charAt(currIndex) == s.charAt(i)) continue;
            s = swap(s, currIndex, i);
            permute(s, currIndex + 1, stringPermutations);
        }
    }

    private static String swap(String s, int i, int j) {
        char[] ch = s.toCharArray();
        char tmp = ch[i];
        ch[i] = ch[j];
        ch[j] = tmp;
        return new String(ch);
    }

    public static void main(String[] args) {
        for (String str : permutation("abc")) {
            System.out.println(str);
        }

        System.out.println("------------");

        for (String str : permutation("aabb")) {
            System.out.println(str);
        }
    }
}


texts:
I am trying a very simple method of getting the theme information via a theme.xml within each theme folder.

What it should do:

Scan the theme directory ../themes
Return the names of all the theme folders (array)
Use the name of the theme folder returned to create a link to search in file_exists()
Find the theme.xml in every folder
Parse every theme.xml with simplexml_load_file()
Return an array ready for output in a foreach()
If !file_exists(), output "theme.xml Not Found in (themename)"

I tried to make this in 2 functions but it would always output the first or last themes info, so this is what I'm doing now, can anyone suggest a way to help separate the function from the output.

Get available theme folder names function

 public function getAvailableThemes() {
    $path = '../themes';
    $themeDir = glob($path . '/*' , GLOB_ONLYDIR);
    return $themeDir;
}

Output in wcx_themes.php file

    <?php
    $themeDir = $backend->getAvailableThemes();
    foreach($themeDir as $themeDir) {
        $preview = $backend->getThemePreview($themeDir);
        $xmlfile = $themeDir.'/theme.xml';
    if(file_exists($xmlfile)) {
        $xml = simplexml_load_file($xmlfile);
        $themename = $xml->themename;
        $themedescription = $xml->themedescription;
        $themeversion = $xml->themeversion;
        $themeauthor = $xml->themeauthor;

    echo '

Name:&nbsp;'.$themename.'

Description:&nbsp;'.$themedescription.'

Version:&nbsp;'.$themeversion.'

Author:&nbsp;'.$themeauthor.'

'.$themename.'

    INSTALL

';
    }
    else {
    echo '

    getThemePreview($themeDir).'"/>

THEME.XML DOES NOT EXIST

';
    }
    }
    ?>

Get theme preview image

    public function getThemePreview($theme) {
    $ext = '.png';
    $preview = '../themes/'.$theme.'/preview'.$ext;
    if(file_exists($preview)) {
       return $preview;
    }
    else {
      $preview = 'images/nopreview'.$ext;
    return $preview;
   }
   }

Theme.xml

<?xml version="1.0" encoding="utf-8"?>
 <theme>
  <themename>Default</themename>
  <themedescription>This is the Default Theme</themedescription>
  <themeversion>1.0</themeversion>
  <themeauthor>WCX</themeauthor>
 </theme>


texts: Is there a better way to preview the addition of a new element?

texts:
I am to preview where a new element will be added on button click. I thought about just creating the element and showing that in the preview, but I have several buttons and some of the elements they create require input (via window.prompt) so I decided to just make a placeholder div and use that instead
Javascript:
var addTempDiv = function (e) {
  ...
}

buttons.on('mouseenter', addTempDiv).on('mouseleave', function() {$("#NewElemPlaceholder").remove();});

CSS:
#NewElemPlaceholder {
  background: blue;
  opacity: 50%;
  height: 3em;
}

body.editMode-dontlist #editDiv {
  display: block !important;
  position: sticky;
}

The buttons are in #editDiv, div above the main content with position: sticky (as shown)
The placeholder is removed on mouseleave on the button, or on button click.
Internally, I am storing the placeholder div in a global variable so that it can be reused.
I haven't included the code in addTempDiv, as it's rather convoluted. But it does add the tempDiv in the right place.

-- Edit --
What makes addTempDiv convoluted is that I maintain a "lastFocused" element in the main content, and new content elements are added relative to the lastFocused element. It is also complicated because of html hierarchy: With some elements (like P's and H1's) the new element is appended after the element. With others (like TD) the new element should be added as a child of the TD.
The whole reason for adding the "preview" feature is that if someone is editing an ol/ul list, and then they hit "P", it will create a new paragraph under the list item (if that is the lastFocused element). But if the last focused element is an ol/ul, then the new paragraph is added after the list (in the editDiv there is a toolbar to set lastFocused to parent elements in the DOM hierarchy)
I created this technology, and even I get tripped up with exactly the case above (adding a paragraph after a list). So my idea was to add this preview/temp div so that I (and hopefully others going forward) could see where the new element would be placed before adding it.
Maybe this information should have be right at the start of my question, but then I have to get into the sticky issues of lastFocused and addTempDiv right away which I worry could confuse people looking at my question. Anyway, I've put it here.
-- End Edit --
This is currently working with all bugs fixed.
Is there a better way to preview / indicate where a new element will appear on button click? Has anyone else done this differently and can tell me about how they designed such a feature? Is this implementation going to come back and bite me?


texts: Prime number sieve using ranges::view::ints

texts:
I wrote a simple prime number generator in C++17.  The function generate_primes(max) generates all prime numbers up to max.  I aimed for maximum portability.  Here's the code:

#include <cstdint>
#include <iostream>
#include <set>
#include <range/v3/view/iota.hpp>

namespace view = ranges::view;

using number_t = std::uint_fast32_t;
using numbers_t = std::set<number_t>;

numbers_t generate_primes(number_t max)
{
    if (max < 2)
        return {};

    numbers_t primes{view::ints(number_t(2), max)};
    for (number_t n = 2; n * n <= max; ++n) {
        if (primes.find(n) != primes.end()) {
            for (number_t m = 2; m <= max / n; ++m)
                primes.erase(n * m);
        }
    }
    return primes;
}

I used the ints utility from the Ranges library to populate primes.  view::ints(number_t(2), max) lazily generates all the integers of type number_t that is greater or equal to 2 and that is less than or equal to max in ascending order.  In C++20, the Ranges library is standardized.

Example usage:

void print(std::ostream& os, const numbers_t& nums)
{
    // convert to unsigned long so that it can be portability printed
    for (unsigned long n : nums)
        os << n << "\n";
}

int main()
{
    print(std::cout, generate_primes(100));
}

Output:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97


texts: Speeding up my Python code for reading from Excel, performing geospatial analysis and writing to Excel files

texts:
I have written a Python snippet that reads lat and long stored in an Excel file. Converts them to a point which is then used to perform multiple geospatial analysis including buffer, intersection, and searching within a shapefile's attribute table (finding count of a specific attribute occurrence and a single row can have multiple attributes in the same column). This code snippet is very slow. I need to traverse around 2000 records and search for around 179 attributes (count) against 10 different radii. It takes around 2.45 minutes to traverse against 1 point for 10 radii and search for the count of only 10 attribute occurrences. Is there any way to speed up this process?
I am attaching the code below.
# importing libraries
from openpyxl import load_workbook
from shapely.geometry import Point
import pandas as pd
import geopandas as gpd
#import matplotlib.pyplot as plt
import csv

#loading input excel
book = load_workbook(r'File path of input file.xlsx')
sheet = book.active
bookOut = r'outputfile.csv'
#outputSheet = bookOut.active
#searching for a specific category and returning its count
def bSearch(lst, cat):
     c = 0
     for index, row in lst[0:len(lst)].iterrows():
        if cat in row['Category_t']:
            c = c+1
     return (c)

# creates buffer
def createbuf(p,r):
    bufp = p['geometry'].buffer(distance = r)
    buf = gpd.GeoDataFrame(geometry = bufp, crs = ucs.crs)
    return (buf)

# calculates intersection
def calint(b,u):
    areaoi = gpd.overlay(u, b, how= "intersection")
    return (areaoi)

# shapefiles Input
ucs = gpd.read_file(r'Boundary.shp')
ucs = ucs.to_crs(epsg=32643)

#Business List
business = gpd.read_file(r'List of Categories.shp')
business = business.to_crs(epsg=32643)
businessArray = [
'Cat1','Cat2','Cat3','Cat4','Cat5','Cat6','Cat7','Cat8','Cat9','Cat10'
]
radiusVals=[0.5, 1, 1.5, 2, 2.5, 3.000, 4.000, 5.000, 7.000, 10.000]
# lat long
latlng = []
i = 0
otp = []
for row in range(143, sheet.max_row+1):
    detStore = []
    ind = 0
    for column in "AB":
        cell_name = "{}{}".format(column, row)
        latlng.append(sheet[cell_name].value)
        detStore.append(sheet[cell_name].value)
    for column in "CD":
        cell_name = "{}{}".format(column, row)
        detStore.append(sheet[cell_name].value)
    # PCS SRID
    p1 = Point((latlng[i],latlng[i+1]))
    df = pd.DataFrame({'a':[latlng[i+1],latlng[i]]})
    po = gpd.GeoDataFrame(geometry = [p1], crs = ucs.crs)
    po['geometry'] = po['geometry'].to_crs(epsg = 32643)
    print(i,  "--", latlng[i+1], latlng[i])
    i = i+2
    # calling functions
    for r in range (0, len(radiusVals)):
        outputStore = []
        for d in range (0, len(detStore)):
            outputStore.append(detStore[d])
        outputStore.append(radiusVals[r])
        bufo = createbuf(po,(radiusVals[r]/111))
        aoi = calint(bufo ,ucs)
        busList = calint(bufo, business)
        for b in range (0, len(businessArray)):
            buSearch = bSearch (busList,businessArray[b])
            outputStore.append(buSearch)
        otp.append(outputStore)
print (otp)
fields = ['Location X', 'Location Y', 'Type', 'Name', 'Radius', 'Cat1','Cat2','Cat3','Cat4','Cat5','Cat6','Cat7','Cat8','Cat9','Cat10']
with open(bookOut, 'w',  newline='') as f:
    write = csv.writer (f)
    write.writerow(fields)
    write.writerows(otp)


texts: How to do a proper quaternion transformation?

texts:
I have some code which transforms a transformation on quaternions and works. But it is written pretty badly, does someone know how to write this better/shorter and does someone knows, if this entire transformation is a transformation 90 degrees on y in euler angles?

Edit: I get a quaternion (orix, oriy, oriz, oriw), then I use this transformation, which should be -pi/2 around y (but I am not sure), then I got the output quaternion. There is no code missing, this code functions as it is here. (of course with the right imports, tf2.

            tf2::Quaternion quat(orix, -oriy, oriz, oriw);
            tf2::Quaternion q_rot;
            tf2::Vector3 rotation_vector(0.7071068, 0, 0.7071068);
            q_rot.setRotation(rotation_vector, M_PI);
            quat = q_rot*quat;
            quat.normalize();
            tf2::Matrix3x3 matrix(quat);
            tf2::Matrix3x3 change_y(1,0, 0, 0, -1,0 ,0 ,0, 1);
            matrix = change_y * matrix;

            double roll, pitch, yaw;
            matrix.getRPY(roll, pitch, yaw);
            quat.setRPY(roll,pitch,yaw);`


texts:
I have a project in embedded systems and I have to write the code in C, and make it simple.

This is my first time, and it's only a simulation of how it should work.

#include<iostream.h>
#include<stdio.h>

void manualMode();
 void defaultMode();

int temp, timeToWash, operation;

int main() {
     int mode =0, part=3, waterLevel;
     int doorSensor=0, timer = 3,waterLevelSensor = 0, tempSensor = 25;
     char startPause;
     cout<<"Washing Machine CE224"<<endl;
 do{
      cout<<"Choose Mode: (1)Default, (2)Manual \n";
      cin>>mode;
      if (mode == 1)
                 defaultMode();
      if (mode == 2)
                 manualMode();
 }while(mode == 0);

 cout<<"Choose Parts to wash: (1)Upper Only, (2)Lower Only, (3)Upper and Lower \n";
 cin>>part;
 switch(part){
            case 1:
            case 2:
                 waterLevel= 0.5;
                 break;
            case 3:
                 waterLevel = 1;
                 break;
 }
 if (doorSensor == 0){
      do{
                 cout<<"Press (S) to Start,and close the Door."<<endl;
                 cin>>startPause;
                 cout<<"LED is On\n";
                 while(waterLevelSensor != waterLevel){
                             waterLevelSensor++;
                 }
                 while(tempSensor != temp){
                             tempSensor++;
                 }
                 cout<<"Washing Operation Started!               Time Left:"<<timeToWash<<endl;
                 cout<<"Washing with Soap Operation Started!\n";
                 timeToWash = timeToWash / 2 ;
                 cout<<"Rinsing Operation Started!               Time Left:"<<timeToWash<<endl;
                 timeToWash = timeToWash / 2 ;
                 cout<<"Drying Operation Started!               Time Left:"<<timeToWash<<endl;
                 timeToWash = 0 ;
                 startPause = 'P';
      }while((startPause == 's') || (startPause =='S'));
 }
 cout<<"End!\nLED is Off";
 return 0;
}

void manualMode(){
     cout<<"Enter Temperature: \n";
     cin>>temp;
     cout<<"Enter Time to wash: \n";
     cin>>timeToWash;
     cout<<"Choose Operation: (1)Water Only, (2)Water and Soap, (3)Rinse, (4)Dry, (5)All\n";
     cin>>operation;
}
void defaultMode(){
     int whatToWash;
     cout<<"Choose what to Wash: (1)Cups, (2)Plates, (3)Pots";
     cin>>whatToWash;
     switch(whatToWash){
          case 1:
                temp = 30;
                timeToWash = 3;
                break;
          case 2:
                temp = 40;
                timeToWash = 3;
                break;
          case 3:
                temp = 60;
                timeToWash = 3;
                break;
     }
 }


texts:
So I am working on an x86 Assembly program for Linux using NASM. This program basically asks the user for their name and their favorite color. After doing this and storing the two strings in variables declared in the .bss section, the program prints "No way name of user, favorite color is my favorite color, too!

The problem I am having is that there are enormous spaces in the output because I do not know how long the string was that the user entered, only the length that I declared the buffer to be.

section .data
    greet:       db 'Hello!', 0Ah, 'What is your name?', 0Ah  ;simple greeting
    greetL:      equ $-greet                                  ;greet length
    colorQ:      db 'What is your favorite color?'            ;color question
    colorL:      equ $-colorQ                                 ;colorQ length
    suprise1:    db 'No way '
    suprise1L    equ $-suprise1
    suprise3:    db ' is my favorite color, too!', 0Ah

section .bss
    name:        resb 20                                      ;user's name
    color:       resb 15                                      ;user's color

section .text
    global _start
_start:

    greeting:
         mov eax, 4
         mov ebx, 1
         mov ecx, greet
         mov edx, greetL
         int 80                                               ;print greet

    getname:
         mov eax, 3
         mov ebx, 0
         mov ecx, name
         mov edx, 20
         int 80                                               ;get name

    askcolor:
         ;asks the user's favorite color using colorQ

    getcolor:
         mov eax, 3
         mov ebx, 0
         mov ecx, name
         mov edx, 20
         int 80

    thesuprise:
         mov eax, 4
         mov ebx, 1
         mov ecx, suprise1
         mov edx, suprise1L
         int 80

         mov eax, 4
         mov ebx, 1
         mov ecx, name
         mov edx, 20
         int 80

         ;write the color

         ;write the "suprise" 3

         mov eax, 1
         mov ebx, 0
         int 80

The code for what I am doing is above. Does anyone have a good method for finding the length of the entered string, or of taking in a character at a time to find out the length of the string?


texts:
The task:

  Given a real number n, find the square root of n. For example, given n
  = 9, return 3.

My solution:

const findRoot = n => n >=  0 ? n ** .5 : void 0;

console.log(findRoot(9));

Is this some kind of trick question? What's there to solve? Did I miss something?


texts: Calculating the Collatz conjecture of a number

texts:
I've made a Collatz Conjecture sequence calculator and I would like some feedback on what I can do better in regards to the code I've implemented, i.e. bad practices you see, improvements that can be made to make it faster, errors that might arise from this code that I am not managing, etc.

public static void CollatzConjecture()
{
    Console.WriteLine("Enter an integer number into the program to calculate its Collatz Conjecture sequence:");
    var consoleReading = string.Empty;
    var collatzConjectureNumber = 0;
    while (true)
    {
        consoleReading = Console.ReadLine();
        if (int.TryParse(consoleReading, out collatzConjectureNumber))
            break;
        else
        {
            Console.WriteLine("Please insert an integer number:");
        }
    }
    var collatzNumberCollection = new List<int>();

    Console.WriteLine("The entered number is {0}, calculating Collatz's sequence:", collatzConjectureNumber);

    collatzNumberCollection.Add(collatzConjectureNumber);

    int collatzStepCounter = 0;
    while (collatzConjectureNumber > 1)
    {
        collatzConjectureNumber = (collatzConjectureNumber%2).Equals(0)
            ? collatzConjectureNumber / 2
            : collatzConjectureNumber * 3 + 1;

        collatzNumberCollection.Add(collatzConjectureNumber);

        Console.WriteLine("Element {0} of the {1}'s collatz sequence is: {2}", ++collatzStepCounter, collatzNumberCollection[0], collatzConjectureNumber);
        Thread.Sleep(100);
    }

    Console.WriteLine("The Collatz Conjecture sequence for the number {0} contains {1} numbers", collatzNumberCollection[0], collatzNumberCollection.Count);

    Console.WriteLine("The Collatz Conjecture sequence has been calculated, press enter key to exit");
    Console.ReadLine();
}

The code works as intended but, as said, I would like feedback on what I can improve in this code. That explains why I post this question even though there exist duplicates of this one, I just want feedback on my code, that's all.

Thanks in advance for your responses.


texts:
So I started this question, I believe i have synchronized the methods correctly, need some insight on whats wrong and what should be done. I have to modify ths class Purse  so that the method AddCoin is synchronized and  implement a synchronized RemoveCoin method with a Coin argument, I believe that is done just fine. Where im really having trouble is implementing thread that adds pennies, another thread that adds quarters, and another thread that removes and prints randomly selected coins, pennies, quarters, any one. Then finally synchronize the threads to wait for each other when necessary. Here is what I have so far:
Purse.cs
using System;
using System.Collections;
using System.Threading;

namespace TestingProject
{
    /// <summary>
    /// A purse holds a collection of coins.
    /// </summary>
public class Purse
{
    ///  Constructs an empty purse.
    public Purse()
    {
        coins = new ArrayList();

    }

    ///   Add a coin to the purse.
    ///   @param aCoin the coin to add
    public void Add(Coin aCoin)
    {
        Monitor.Enter(coins);
        coins.Add(aCoin);

        Monitor.Exit(coins);
    }
    public void RemoveCoin(Coin aCoin)
    {
        Monitor.Enter(coins);
        coins.Remove(aCoin);

        Monitor.Exit(coins);
    }

    ///  Get the total value of the coins in the purse.
    ///  @return the sum of all coin values
    public double GetTotal()
    {
        double total = 0;
        for (int i = 0; i < coins.Count; i++)
        {
            Coin aCoin = (Coin)coins[i];
            total = total + aCoin.GetValue();
        }
        return total;
    }

    private ArrayList coins;
}

}

Coin.cs
using System;
using System.Collections;

namespace TestingProject
{
    /// <summary>
    /// A coin with a monetary value.
    /// </summary>
public class Coin   {

    /// Constructs a coin.
    /// @param aValue the monetary value of the coin
    /// @param aName the name of the coin
    public Coin(double aValue, String aName)
    {
        value = aValue;
        name = aName;
    }

    public Coin()
    {
    }

    /// Gets the coin value.
    /// @return the value
    public double GetValue()
    {
        return value;
    }

    /// Gets the coin name.
    /// @return the name
    public String GetName()
    {
        return name;
    }

    public override bool Equals(Object otherObject)
    {
        Coin other = (Coin)otherObject;
        return name==other.name
            && value == other.value;
    }

    // C# requirement:
    // since we override Equals, MUST also override GetHashCode ( !! )
    public override int GetHashCode()
    {
        return base.GetHashCode ();
    }

    private double value;
    private string name;
}
}

pursetest.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualBasic;

namespace TestingProject
{

class PurseTest
{
    public static void Main(string[] args)
    {

        // Random object used by each thread
        Random random = new Random();

        Purse purse =new Purse();

        Coin coin = new Coin();

        // output column heads and initial buffer state
        Console.WriteLine("{0,-35}{1,-9}{2}\n",
           "Operation", "Buffer", "Occupied Count");

        Thread purseThread =
           new Thread(new ThreadStart(purse.Add))
           {
               Name = "Purse"
           };

        Thread coinThread =
           new Thread(new ThreadStart(coin.GetValue));
        coinThread.Name = "coin";

        // start each thread
        purseThread.Start();
        coinThread.Start();

    }
}
}


texts: Scraping Forum Tables w/ Links Using Beautiful Soup

texts:
This code scrapes post links (among other information) from a table on a forum. While the current code works, I would like to know if there is a better/simpler way of writing it (maybe not as many for-loops?) and with the assumption that additional functionality will be added, such as:

Currently only scrapes page 1, but eventually scrape pages 2-134 too.
Scrape each individual post (e.g., each text post, which user posted it, date/time it was posted, etc.)
Store data to dataframe/csv instead of printing it

Here is the current code:

import requests
from bs4 import BeautifulSoup

# Set Soup
url = 'http://www.cornerofberkshireandfairfax.ca/forum/investment-ideas'
headers = {'User-Agent': 'Mozilla/5.0'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')

# Set table and rows
table = soup.find_all("table")[0]
rows = table.find_all("tr")

# Scrape each row of the table
for row in rows:

    # Set table columns and classes
    subject_column = row.find_all("td", class_="subject windowbg2")
    stats_column = row.find_all("td", class_="stats windowbg")
    last_post_column = row.find_all("td", class_="lastpost windowbg2")

    # Scrape company name and first page
    for company in subject_column:
        company = company.find_all("a")[0]
        page_one = company['href']
        print("Company: " + company.text)
        print("- Page One: " + page_one)

    # Scrape username and profile link
    for started_by_user in subject_column:
        started_by_user = started_by_user.find_all("a")[1]
        user_profile = started_by_user['href']
        print("- Started by User: " + started_by_user.text)
        print("- User profile:" + user_profile)

    # Scrape number of views and replies
    for stats in stats_column:
        stats = stats.get_text().split()
        replies = stats[0]
        views = stats[2]
        print("- Replies: " + replies)
        print("- Views: " + views)

    # Scrape link for last post
    for last_post in last_post_column:
        last_post = last_post.find_all("a")[0]
        last_post = last_post['href']
        print("- Last Post: " + last_post)
        print("\n")


texts: Generating lists populated with random objects

texts:
For the purposes of unit-testing in Python, I've written a very simple function for generating variable-length lists populated with random objects:

constructors = [
    object,
    dict,
    lambda: bool(randint(0, 1)),
    lambda: randint(1, 1000),
    lambda: ''.join(choice(digits) for _ in range(randint(1, 10)))
]

choices = (
    lambda _: choice(constructors)(),
    lambda off: fake_list(off),
    lambda off: tuple(fake_list(off))
)

def fake_list(off = None):
    '''Creates a list populated with random objects.'''
    off = (off or 0) + 1
    return [choice(choices)(off) for _ in range(max(randint(1, 10) - off, 0))]

List generated with this function typically look something like this:

[(269, '6'), [{}, 990, 347, <object object at 0x7f51b230b130>, {}, [{}, '91921063', 302, '0047953', {}, ()], True], '70262', True]

Do you see any problems with it? Is there a more efficient/elegant way of doing this that you could suggest?

Quality of the generated primitives (strings, integers) is not of priority (i.e. string.digits should be enough).


texts:
I made a little Python3 script to grab video clips from a website for viewing off-line later and would like your critique, advice, tips & tricks and/or learning resources to create better code. (Project on GitHub)

#!/usr/bin/env python3
''' phgrab.py: clip downloader. '''

import os
import sys
import argparse
import urllib.request
import bs4

def reporthook(blocknum, blocksize, totalsize):
    ''' Define the reporthook for url-retrieval
    (displays info while grabbing). '''
    readsofar = blocknum * blocksize
    if totalsize > 0:
        percent = readsofar * 1e2 / totalsize
        display = "\r%*d / %d %5.0f%%" % (
            len(str(totalsize)), readsofar, totalsize, percent)
        sys.stdout.write(display)
        if readsofar >= totalsize:
            sys.stdout.write("\n")
    else:   # total size unknown
        sys.stderr.write("read %d\n" % (readsofar,))

PARSER = argparse.ArgumentParser(
    description="a commandline clip downloader.")
PARSER.add_argument('clipcode', nargs='+',
                    help="a ten-digit clipcode.")
PARSER.add_argument('-p', '--proxy',
                    help="A http proxy to use; e.g. http://localhost:8000")

PROXY = PARSER.parse_args().proxy
CLIPCODES = PARSER.parse_args().clipcode

if PROXY:
    print("Grabbing through http proxy: %s\n" % PROXY)
    os.environ['http_proxy'] = PROXY

for i in CLIPCODES:
    if not i.isdigit() or not len(i) == 10:
        sys.exit(
            "'\033[1m%s\033[0m' is not a valid ten-digit clipcode," % i,
            "please check your input and try again.")

for i in CLIPCODES:
    soup = bs4.BeautifulSoup(
        urllib.request.urlopen("http://somesite.com/%s" % i))
    title = soup.find("h1", class_="video-title").string
    href = soup.find("a", class_="download button")['href']
    print("Grabbing \033[1m%s\033[0m:" % i)
    local_filename, headers = urllib.request.urlretrieve(
        href, '%s - %s.mp4' % (i, title), reporthook)
    print("\033[1m", local_filename, "Done\033[0m")


texts: UITableView, auto locate back at indexPath when user drags it

texts:
I have a tableView, which auto locates back at indexPath after user has dragged it.

In other words, bouncing the tableView back into its bounds, after user dragged it out.

Here is the code:

// ...

var tracking = false
var currentPath = 0

@objc func updateRecorder(_ timer: Timer){
     currentPath = somethingCalculated
}

// ...

extension ViewController: UITableViewDelegate{

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
            // when the scene is in a special state
            tracking = true
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // when the scene is in the same special state
        if tracking == true{
            tracking = false
            scrollToRow(at: IndexPath(row: currentPath, section: 0), at: UITableView.ScrollPosition.middle, animated: true)
        }
    }
}

In fact, it is a music tracking app. People sing a song, the lyric tableView tracks the voice, and it auto scrolls to current line.

When tracking, and people scrolls by hand, the lyric tableView should bounces back to it ought to be.

The code above works.

Any other ideas?


texts:
This will be my third post of this program, I have received a lot of great feedback and have learned a lot from the community. I have edited this program a lot, and am here for another review to see if I got it correctly. I had a hard time implementing one minor fix with output stream delimiter which was suggested in an earlier answer, but I believe I fixed the inheritance issues. Any other fixes would be very appreciated:

Person.h

#ifndef PERSON
#define PERSON
#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class Person
{
    friend std::istream& operator>>(std::istream&,Person&);
    friend std::ostream& operator<<(std::ostream&, const Person&);
public:
    //comparison operator
    bool operator<(const Person&) const;
private:
    std::string name;
    std::string address;
};

#endif // !PERSON

Person.cpp

#include "Person.h"

bool Person::operator<(const Person& other) const {
    return name < other.name;
}

std::istream& operator>>(std::istream &in, Person &p){
    in >> p.name;
    getline(in, p.address);
    return in;
}

std::ostream& operator<<(std::ostream& os, const Person &p) {
    os << "Name: " << p.name << "\nAddress: " << p.address;
    return os;
}

Address_book.h

#ifndef ADDRESS_BOOK
#define ADDRESS_BOOK
#pragma once

#include "Person.h"

class Address_book
{
    friend std::istream& operator>>(std::istream&, Address_book&);
    friend std::ostream& operator<<(std::ostream&, Address_book&);
public:
    //set vector size to match appropriate number of entries
    void Address_book::resize(size_t entries);
    void Address_book::sort();

private:
    std::vector<Person> add_book;
};

#endif

Address_book.cpp

#include "Address_book.h"

//fills address book
std::istream& operator>>(std::istream& in, Address_book& abook) {
    for (int i = 0; i < abook.add_book.size(); ++i) {
        std::cin >> abook.add_book[i];
    }
    return in;
}

//sort address book
void Address_book::sort() {
    std::sort(this->add_book.begin(), this->add_book.end());
}
//prints contents of address book
std::ostream& operator<<(std::ostream& os, Address_book& abook) {
    for (int i = 0; i < abook.add_book.size(); ++i) {
        std::cout << abook.add_book[i] << "\n";
    }
    return os;
}

void Address_book::resize(size_t entries) {
    add_book.resize(entries);
}

main.cpp

#include <iostream>
#include <vector>
#include <string>
#include "Address_book.h"
#include "Person.h"

void pause();

int main() {

    size_t entries = 0;

    std::cout << "Enter number of entries to go in addressbook: ";
    std::cin >> entries;

    Address_book abook1;
    abook1.resize(entries);

    //input into addressbook
    std::cout << "Enter the name, followed by the address:\n";
    std::cin >> abook1;
    //sort addressbook
    abook1.sort();

    //output addressbook
    std::cout << "\n";
    std::cout << abook1;

    pause();
}

void pause() {
    std::string pause;
    std::cout << "Press any key followed by enter to continue...";
    std::cin >> pause;
}


texts:
Here's a function that sorts an array of objects with a dateProp by the date. First it uses moment to convert the Date object to a unix timestamp.

var _ = require('lodash')
var moment = require('moment')

util.orderByDate = function (arr, dateProp) {
  if (!dateProp) return arr
  return _.chain(arr)
  .map(function (item) {
    item[dateProp] = moment(item[dateProp]).format('x')
    return item
  })
  .sortBy(dateProp)
  .value()
}


texts:
I've created some methods to help me convert PDF to text and then text to a JSON object. I've never done this before and I'm using this exercise as a way to improve my knowledge of Ruby.

The following code does what I want, it works. It just returns a very ugly object. Right now I'm trying to craft some regular expressions to help produce cleaner objects. In the meantime, I'd love some feedback on how to improve what I've got so far.

require "pdf_outliner/version"
# Regexes
# words: /\A[\w{*}]+[\s]/
# sentences: /^[A-Z]+[\S\s]+[.?!]/
# paragraphs:
# outline headings (I., A.,, etc): /^[A-Za-z1-9]+\./

module PdfOutliner

  def pdf_to_text(pdf, file)
    File.open(file, 'w') do |f|
      pdf.pages.each do |p|
        f.write(p)
      end
    end
  end

  def create_json(obj, file = 'policy.json')
    data = JSON.generate(obj)
    File.open(file, 'w') { |d| d.write(data)}
  end

  # Outline the text document to create JSON object
  def outline(doc)
    json     = {}
    i        = 0
    document = File.open(doc, 'a+')

    document.each_line do |f|
      # Get rid of extra whitespace
      line = f.strip
      next if line.empty?
      next if line == ""

      # Find the headings for each section by counting words
      # and checking them.
      words = line.split(" ")

      # Document headings are all caps and short. Lines that are capitalized
      # are the start of a paragraph. Lines not capitalized are
      # part of previous data sentence, so append them.
      if is_upper?(line)
        json["title#{i}"] = line
      else
        json["data#{i}"] = line unless is_lower?(line[0])
        if is_lower?(line[0])
          json.values.last.concat(line)
        end
      end
      i+= 1
    end

    # Create JSON file from this object and write to file.
    create_json(json)
  end

end

EDIT:

Appended missing code unless is_lower?(line[0]) to the if statement
next to json['data#{i}']
Link to the object returned with this
code:  http://www.jsonmate.com/permalink/54ed43e78622dbdf0c4232b6


texts:
I was recently playing around with some code, and someone mentioned that my code uses too many classes. I didn't realize I've been doing ES6 incorrectly for so long.

I'm having a hard time finding a way to organize my code in a way that reads nicely. I say this coming from a C# background.

Thanks for your time, everyone.

class Producer {
    constructor(starterString) {
        this.rules = [];
        this.createRules();
        this.producedString = starterString;
    }
    createRules() {
        this.rules.add(new RuleAddE());
        this.rules.add(new RuleAddNumberOne());
    }
    produce() {
        for(var i = 0, len = this.rules.length; i < len; i++) {
            this.producedString = this.rules[i].run(this.producedString);
        }

        return this.producedString;
    }
}

class Rule {
    constructor() {
        this.applied = false;
    }
    run() {
    }
}

class RuleAddE extends Rule {
    constructor() {
        super();
    }

    run(stringToChange) {
        this.applied = true;
        return stringToChange + "e";
    }
}

class RuleAddNumberOne extends Rule {
    constructor() {
        super();
    }

    run(stringToChange) {
        this.applied = true;
        return stringToChange + "1";
    }
}

var producer = new Producer("aa 1hdheb");

console.log(producer.produce());

How could I improve this code with more proper structure?


texts: Dynamically convert property to different data type

texts:
The code finds marked attributes and parses them according to the attribute type.

Is it possible to simplify this logic? Is there generic way to do it? Please suggest some way to optimise this code. All the data type of Product class will be string. I'm getting product input as XML directly converting serialized data to a class with decimal, int, float will not give proper error message.

If there is list of items it will throw error in XMl and we won't know which row has caused the error.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TestSolution
{
    public interface ICustomParser
    {
        bool Parse(string input);
    }

    public class DecimalParserAttribute : Attribute, ICustomParser
    {
        public bool Parse(string input)
        {
            if (input == null) return false;

            decimal decimalValue;

            return decimal.TryParse(input, out decimalValue);
        }
    }

    public class intParserAttribute : Attribute, ICustomParser
    {
        public bool Parse(string input)
        {
            if (input == null) return false;

            int intValue;

            return int.TryParse(input, out intValue);
        }
    }

    public class Product
    {
        [DecimalParser]
        public string Weight { get; set; }

        [intParser]
        public string NoOfItems { get; set; }

        [intParser]
        public string GRodes { get; set; }

        [intParser]
        public string WRodes { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {

            var sb = Validate(new Product() { NoOfItems = "1", GRodes = "4", Weight = "5", WRodes = "23" });

            Console.WriteLine(sb);
            sb = Validate(new Product() { NoOfItems = "1", GRodes = "4w", Weight = "5", WRodes = "23" });

            Console.WriteLine(sb);
            Console.ReadKey();
        }

        private static string Validate(Product product)
        {
            var sb = new StringBuilder();

            foreach (var property in product.GetType().GetProperties())
            {
                var value = Convert.ToString(property.GetValue(product, null));

                var sel = property.GetAttribute<ICustomParser>();

                if (sel == null) continue;

                var parserinstance = (ICustomParser)sel;

                if (parserinstance.Parse(value)) continue;

                sb.AppendLine(string.Format("{0} Has invalid value", property.Name));
            }
            return sb.ToString();
        }
    }

    public static class Extensions
    {
        public static T GetAttribute<T>(this PropertyInfo property)
        {
            return (T)property.GetCustomAttributes(false).Where(s => s is T).FirstOrDefault();
        }
    }
}


texts:
I have learned a bit of C in university and I'm now learning C++ independently. I'm trying to print out std::vector<std::string> char by char. I know, that in C, strings are arrays and are terminated by '\0' terminator. Can I assume the same thing in c++? I use C++14.

This works, but I'm unsure if it's the correct way to do this. I know, I can use getline(std::cin, line) to read from stream as well. Which one is more preferred? How would you make my code better?

using namespace std;

int main()
{
    cout << "Enter text\n";

    // Get input
    vector<string> str;
    for (string temp; cin >> temp; ) {
        str.push_back(temp);
        // If input ends with enter, break loop
        if (cin.peek() == '\n') break;
    }
    cout << "\n\n";

    // Output vector string by string
    vector<string>::iterator it;
    for (it = str.begin(); it != str.end(); ++it) {
        cout << *it << '\n';
    }
    cout << "\n\n";

    // Output vector char by char
    it = str.begin();
    while (it != str.end()) {
        /* Is this (*it)[i] != '\0' correct? Are strings '\0' terminated in
         * c++ as well, and are they in vector<string> '\0 terminated? */
        for (size_t i = 0; (*it)[i] != '\0' ; ++i) {
            cout << (*it)[i];
        }
    cout << ' ';
    ++it;
    }
    cout << "\n\n";
}


texts:
Today I had an interview, where I was asked to solve this question:

Design Tic tac toe game

Game rules:

  Design a simple tic tac game with 2 modes for 3*3 matrix. At the
  beginning, ask if single player or two player mode has to be played
  (more details on the mode below).

  The players input position on matrix by inputting 2 integers, like:

0,0    0,1    0,2

1,0    1,1    1,2

2,0    2,1    2,2

  If anywhere player gives incorrect input, he has to be prompted to
  give the right value again.

  Print the updated matrix after every input. Example: after 3 moves,
  one game might look like

1    1    _

2    _    _

_     _    _

  Single player mode

  In this mode, player plays against the computer.
  You’ve to first assign 0’s or  X’s to the Player. X’s play first. The
  computer can randomly place its assigned symbol at any available
  position within the matrix.

  Two player mode

  In this mode, two players play against each other.

  The game ends when either player wins, or there are no moves left
  (draw). At the end of game, print the final result Ask if the player
  wants to play another game, and start a new game/end the game
  accordingly.

I got the feedback that complexity could be improved, How to improve it?
and how to make it more readable

Code goes below:

def get_input(mat, player):
    input_value = map(int, raw_input().split(','))
    while(validate_input(mat, input_value) == False):
        print "not correct input"
        input_value = map(int,raw_input().split(','))
    mat[input_value[0]][input_value[1]] = player
    return input_value

def validate_input(mat, input_value):
    x = input_value[0]
    y = input_value[1]
    if x not in [0,1,2] or y not in [0,1,2]:
        return False
    if mat[x][y]:
        return False
    return True

def switch_play(player):
    player = 2 if player==1 else 1
    return player

def print_game(mat):
    print mat

def get_random(mat):
    input_value = [random.randint(0,2)] *2
    while(validate_input(mat, input_value) == False):
        print "not correct input"
        input_value = [random.randint(0,2)] *2

    mat[input_value[0]][input_value[1]] = 2
    return input_value

def game_completed(mat):
    if not game_won(mat):
        for i in xrange(3):
            for j in xrange(3):
                if not mat[i][j]:
                    return False

    return True

def game_won(mat):
    for i in xrange(3):
        row = mat[i]
        if len(set(mat[i])) == 1 and set(mat[i]) != {0}:
            print 'won the game:player', mat[i][0]
            return True
    for i in xrange(3):
        col = [row[i] for row in mat]
        if len(set(col)) == 1 and set(col)!={0}:
            print 'won the game:player', mat[0][i]
            return True
        dia1 = [mat[i][i] for i in xrange(3)]
        dia2 = [mat[2-i][i] for i in xrange(3)]
        if (len(set(dia1)) == 1 and set(dia1)!={0}):
                print 'won game: player', mat[0][0]
                return True
        if (len(set(dia2)) == 1 and set(dia2)!={0}):
                print 'won game: player', mat[2][2]
                return True
        return False

print "hoose player 1 your type, X or O?"
p1 = raw_input()
p2 = 'O' if p1=='X' else 'X'
player = 1
mat = [[0,0,0], [0,0,0], [0,0,0]]
computer_playing = False
while True:
    if computer_playing and player==2:
        get_random(mat, player)
    else:
        get_input(mat, player)
    print_game(mat)
    if game_completed(mat):
        print "game is completed"
        break
    player = switch_play(player)


texts: Asking for a name and showing the initials

texts:
I've seen code that basically does the same thing, but i'd like some input on this. Basically what i did wrong or not good enough heh :).

#include <stdio.h>
#include <String.h>
#include <stdlib.h>
#include <ctype.h>
char *getName() {
    char name[100];
    int length;
    char *holder;
    printf("Tell me your name!\n");
    fgets(name,100,stdin);

    length = strlen(name)+1;

    holder = (char*)malloc(length*sizeof(char));
    strcpy(holder, name);

    printf("The name is: %s", holder);

    return holder;

}
char getInitials(char *name) {
    int length,i,j = 0;

    char *initials;

    length = strlen(name);

    initials = (char*)malloc(length*sizeof(char));

    for(i = 0;i < length;i++){
        if(i == 0)    {
            initials[j] = toupper(name[i]);
            j++;
      }
        else if(name[i] == ' '){
            initials[j] = toupper(name[i+1]);
            j++;

        }
    }
    initials[j] = '\0';
    printf("The initials are: %s",initials);
    free(initials);

}
int main() {
    char *name = getName();
    getInitials(name);
}


texts:
During Winter Bash 2014, the Naruto hat was awarded to users who gave an answer that got accepted but hasn't received votes for 12 hours.
It was a weird thing, really:
why would someone ever accept a question but not upvote it?
I haven't yet experienced a situation where this would be reasonable.

Accepted answers without upvotes seem to be an anomaly:
it happens when the OP doesn't have enough reputation to upvote,
and the post gets overlooked by other users in the community.
The community might actually want to clean these up.

To find eligible posts I put together this simple SEDE query (latest version, NOT for review):

DECLARE @username as NVarchar(60) = RTRIM(LTRIM(##DisplayName:string? ##));
DECLARE @userId as int = ##UserId:int?-1##;

SELECT TOP 100
  u.id as [User Link],
  p.Id as [Post Link],
  p.CreationDate
FROM Posts p
  JOIN Users u ON p.OwnerUserId = u.Id
  JOIN Posts q ON p.ParentId = q.Id
WHERE
  (@username = '' OR u.DisplayName = @username)
  AND (@userId = -1 OR u.Id = @userId)
  AND p.Score = 0
  AND p.Id = q.AcceptedAnswerId
ORDER BY p.CreationDate DESC

The query accepts two parameters:

Optional display name, to filter by username
Optional user id, to filter by user id
With default values it will show all eligible posts of the given site
It won't make sense to set both display name and user id, but such misuse would be  the user's fault

Something I don't like about this is the username parameter.
I would have wanted NULL or empty string as default value but couldn't figure out how to do that.
Using space does work, but it's not exactly pretty,
I'm wondering if there's a better way I'm missing.

I'm interested in any other suggestions to improve this query.


texts: Saves files and attachments regardless of errors in the model

texts:
I have a long form with dozens of fields, and users can upload photos and attachments in the form. It's super annoying when there is a simple field missing, the record doesn't save, and the user has to go and pick & choose all the files again. So I save the photos and attachments even upon validation errors. I would have liked to use asynchronous Javascript uploading, but that requires a separate form, and forms cannot be embedded in other forms.

This works, but it doesn't feel very DRY or very Rails. Is there a way to improve it?

class User < ApplicationRecord
  belongs_to :image, optional: true, dependent: :destroy
  belongs_to :company, optional: true, dependent: :destroy
  accepts_nested_attributes_for :company, :image

class Company < ApplicationRecord
  belongs_to :image, optional: true, dependent: :destroy
  has_and_belongs_to_many :attachments, dependent: :destroy
  accepts_nested_attributes_for :image, :attachments, :principals, reject_if: :all_blank, allow_destroy: true

class UsersController < ApplicationController
  def update
    @user = User.find(params[:id])
    @user.assign_attributes user_params # has to come before update_* or else it will create company twice for new users
    update_image
    update_company_image
    update_company_attachments
    if @user.save

  def update_image
    if image_params.has_key? :file
      if @user.image
        @user.image.update image_params
      else
        @user.create_image image_params
        @user.save(validate: false)
      end
    end
  end

  def update_company_image
    if company_image_params.has_key? :file
      if @user.company && @user.company.image # company & image exists
        @user.company.image.update company_image_params
      elsif @user.company # company exists
        @user.company.create_image company_image_params
        @user.company.save(validate: false)
      else
        @user.build_company
        @user.company.create_image company_image_params
        @user.company.save(validate: false)
        @user.save(validate: false)
      end
    end
  end

  def update_company_attachments
    company_attachments_params.each do |cap|
      if cap.has_key? :file
        if @user.company
          @user.company.attachments.create cap
        else
          @user.build_company
          @user.company.attachments.create cap
          @user.company.save(validate: false)
          @user.save(validate: false)
        end
      end
    end
  end

  def user_params
    params.require(:user).permit :name, ...,
      company_attributes: [:id, :name, ...,
        attachments_attributes: [:id, :_destroy]]
        # image_attributes: [:id, :file],
        # attachments_attributes: [:id, :file, :_destroy]]
      #image_attributes: [:id, :file]
  end

  def image_params
    params.require(:user).fetch(:image_attributes, {}).permit :id, :file
  end

  def company_image_params
    params.require(:user).fetch(:company_attributes, {}).fetch(:image_attributes, {}).permit :id, :file
  end

  def company_attachments_params
    params.require(:user).fetch(:company_attributes, {}).permit(:attachments_attributes, attachments_attributes: [:id, :file, :_destroy]).fetch(:attachments_attributes, {}).values
  end


texts: Next Bigger Number with the same digits Solution

texts:
Please review my code. I would love to know what improvements I can make in terms of efficiency as well as readability. Thank you!

using System;
using System.Linq;
public class Bojo
{
      public static long NextBiggerNumber(long n)
        {
            //check if bigger number is even a possibility
            if (NoBiggerNumber(n))
                return -1;
            var results = FindPivot(n.ToString());
            //Console.WriteLine(results.FirstPart + "," + results.PivotIndex + "," + results.SecondPart);
            string newSecondPart = ReorganizeSecondPart(results.SecondPart);
            return Convert.ToInt64(results.FirstPart + newSecondPart);
        }

        private static string ReorganizeSecondPart(string secondPart)
        {
            string newSecondPart = "";
            var secondPartNumbers = secondPart.Select(c => c - '0').ToList();
            //Step 1 - Find second largest digit for pivot index i.e. 0
            var sortedAsc = secondPartNumbers.OrderBy(n => n).ToList();
            var duplicatesRemoved = sortedAsc.Distinct().ToList();
            var nextPivotIndex = duplicatesRemoved.IndexOf(secondPartNumbers[0]) + 1;
            newSecondPart += duplicatesRemoved[nextPivotIndex].ToString();
            //Step 2 - Rearrange the rest of the second part excluding the new pivot
            sortedAsc.Remove(duplicatesRemoved[nextPivotIndex]);
            newSecondPart += String.Concat(sortedAsc.Select(n => n.ToString()));
            return newSecondPart;
        }

        private static (string FirstPart, int PivotIndex, string SecondPart) FindPivot(string strNumber)
        {
            var numbers = strNumber.Select(c => c - '0').ToArray();
            for (int i = numbers.Count() - 1; i >= 1; i--)
            {
                if (numbers[i] > numbers[i - 1])
                {
                    int pivot = i - 1;
                    string left = strNumber.Substring(0, i - 1);
                    string right = strNumber.Substring(i - 1);
                    return (left, pivot, right);
                }
            }
            return ("",-1, "");
        }
        public static bool NoBiggerNumber(long n)
        {
            string strN = n.ToString();
            if (strN.Length == 1)
                return true;
            if (strN.Distinct().Count() == 1)
                return true;
            for (int i = 1; i < strN.Length; i++)
            {
                if (strN[i] > strN[i - 1])
                    return false;
            }

            return true;
        }
}


texts:
Fishstacks is a deadfish derivative based on a stack the stack can only hold four elements when a fifth element is pushed the bottom element is kicked out and eventually printed out to the screen.

I've come up with an interpreter in TI-BASIC for my calculator. However, I fell slightly guilty about using all four variables ABCD. I wonder if there could be a better way? Maybe with lists (arrays). I've just started learning about them, so I don't feel confident switching over yet. Any guidance would be appreciated.

Also, in order not to push anything to the screen until something falls off the stack, I've had to initialize variables to -2. This is the main reason I have not converted to arrays yet; I don't see how they could address this issue. (maybe even throw a DOMAIN error).

:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:0->I
:-2->A
:A->B
:B->C
:C->D
:Input Str1
:While I<length(Str1)
:I+1->I
:sub(Str1,I,1)->Str2
:If Str2="I"
:A+1->A
:If Str2="D"
:A-1->A
:If Str2="S"
:A^2->A
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:B->C
:A->B
:0->A
:End
:If A=256 or A=-1
:0->A
:If A=-2
:Stop
:End

By convention, I've represented the STO→ character, → with ->


texts: Provide binding event mechanism in revealing module pattern

texts:
Goal: provide binding event mechanism which can use default or custom settings in a most proper, organised and readable way.

var module = (function () {
    var settingsDefault = {
        clickObject: 'body'
    };
    var s = settingsDefault;

    var init = function (settingsCustom) {
        s = settingsCustom;
        console.log(s);
    };

    var _click = function(clickObject){
        console.log('click occured on: ' + clickObject);
    };

    var bindEvent = (function () {

        var click = function () {
            $(s.clickObject).unbind('click').click(function() {
                _click(s.clickObject);
            });

            return this;
        };

        return {
            click: click
        }
    })();

    return {
        init: init,
        bindEvent: bindEvent
    }
})();

My concerns

Did I use a good naming convention? Particularly: If I added the underscore for private _click method should I use the underscore for all private methods then?
Is this a proper way to handle default and custom settings in revealing module pattern?
Is it a good idea to keep all binding events in a separate method of my main module, or should I rather move them one level up or move them to a new module?
If I use init method should I resign from IIFE and use module.init() method to initialize the module, or can I leave it as it is?
Other suggestions unrelated to above concerns would be also appreciated.


texts:
I have created an application with Angular 4. I set up the Angular application with Angular CLI. Can anybody check this and suggest some improvements?

Following is the folder structure I used:

In AppModule I have the following code:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA, Injector, APP_INITIALIZER } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { NgBootstrapFormValidationModule } from 'ng-bootstrap-form-validation';
import { AppRoutingModule } from './app.routing';
import { SharedModule } from './shared/shared.module';
import { AuthenticationService, DashboardService, NotificationService, AlertService, KnowledgeBaseService, AssetService } from './shared/services/index';
import { AuthGuard } from './shared/guards/auth.guard';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { MainComponent } from './main/main.component';

import { AppPreBootstrap } from '../AppPreBootstrap';

export function appInitializerFactory(injector: Injector) {
    return () => {
        return new Promise<boolean>((resolve, reject) => {
            resolve(AppPreBootstrap.getApplicationConfig());
        });
    }
}

@NgModule({
    declarations: [
        AppComponent

    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,
        NgBootstrapFormValidationModule.forRoot(),
        SharedModule,
        RouterModule,
        AppRoutingModule
    ],
    providers: [
        AuthenticationService,
        DashboardService,
        NotificationService,
        AlertService,
        KnowledgeBaseService,
        AssetService,
        AuthGuard,
         {
            provide: APP_INITIALIZER,
            useFactory: appInitializerFactory,
            deps: [Injector],
            multi: true
        }
    ],
    bootstrap: [AppComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }


texts: Query performance of this Select Where each Column is a Select

texts:
I would like to know how to improve the performance of the following query:

SELECT          Kunde.Nachname,
                Kunde.Vorname,
                Kunde.Debitorennummer,
                sum(Abmeldestatus) AS Abmeldestatus,
                Ab1.Fruehstuck,
                Best1.Menu1,
                Best2.Menu2,
                Ab2.Vesper,
                Ab3.Abendbrot

FROM            Kunde
LEFT OUTER JOIN
                (   SELECT      EssenTyp AS Fruehstuck,
                                RefKundeId
                     FROM       Abbestellungen
                     WHERE      ([date] =@Datum)
                     AND        (EssenTyp = 0)
                ) AS Ab1 ON Ab1.RefKundeId = Kunde.KundeId

LEFT OUTER JOIN
                (   SELECT      BestellDetails.Anzahl AS Menu1,
                                Bestellung.RefKundeId
                    FROM        Bestellung
                    INNER JOIN  BestellDetails ON Bestellung.BestellId = BestellDetails.RefBestellId
                    WHERE       (BestellDetails.Datum = @Datum)
                    AND         (BestellDetails.SpaltenNr = 0)
                ) AS Best1 ON Best1.RefKundeId = Kunde.KundeId

LEFT OUTER JOIN
                (   SELECT      BestellDetails.Anzahl AS Menu2, Bestellung.RefKundeId
                    FROM        Bestellung
                    INNER JOIN  BestellDetails ON Bestellung.BestellId = BestellDetails.RefBestellId
                    WHERE       (BestellDetails.Datum = @Datum)
                    AND         (BestellDetails.SpaltenNr = 1)
                ) AS Best2 ON Best2.RefKundeId = Kunde.KundeId

LEFT OUTER JOIN
                (   SELECT      EssenTyp AS Vesper,
                                RefKundeId
                    FROM        Abbestellungen
                     WHERE      ([date] =@Datum)
                    AND         (EssenTyp = 1)
                ) AS Ab2 ON Ab2.RefKundeId = Kunde.KundeId

LEFT OUTER JOIN
                (   SELECT      EssenTyp AS Abendbrot,
                                RefKundeId
                    FROM        Abbestellungen
                     WHERE      ([date] =@Datum)
                    AND         (EssenTyp = 2)
                ) AS Ab3 ON Ab3.RefKundeId = Kunde.KundeId

LEFT OUTER JOIN
                (   SELECT      AbmeldeId AS Abmeldestatus,
                                RefKundenId
                    FROM        Abmelden
                     WHERE      (StartDate <= @Datum)
                    AND         (EndDate IS NULL OR EndDate >= @Datum)
                ) AS Abm ON Abm.RefKundenId  = Kunde.KundeId

INNER JOIN  dbo.iter_intlist_to_tbl(@Kunden) AS i ON Kunde.KundeId = i.number

GROUP BY    Kunde.Nachname,
            Kunde.Vorname,
            Kunde.Debitorennummer,
            Ab1.Fruehstuck,
            Best1.Menu1,
            Best2.Menu2,
            Ab2.Vesper,
            Ab3.Abendbrot

The query above takes 13sec to execute for 100 Kunden which is not acceptable.

My function iter_intlist_to_tbl takes a list of numbers (IDs) and creates a table with them.

I build my SELECT based on multiple SELECTs which are OUTER JOIN to return what I expect.

The result looks like:

Nachname | Vormane | Debitorennummer | Fruehstuck | Menu1 | Menu2 | Vesper | Abendbrot
--------------------------------------------------------------------------------------
Schmiedt | Lee     | 123456789       | NULL        |   1  |  NULL |   1    |    1
Müller   | Marie   | 123456700       |     1       | NULL |  NULL |  NULL  |    NULL

Execution plan:


texts:
I wrote a little function which formats a ms timestamp in a human readable way. I know there are lots of scripts out there, but I needed a very simple one, which only outputs minutes and hours.

I was wondering if there is any way to shorten or improve this code snippet, because to me it seems to be very long for the few things it actually does.

function prettyTime(ms) {
      var sec = ms / 1000,
          time,
          timeUnit;

      if(sec > 3600) {
          // Hours
          time = Math.round(sec / 3600);
          timeUnit = ' hr';
      } else if(sec > 60) {
          // Minutes
          time = Math.round(sec / 60);
          timeUnit = ' min';
      } else {
          return 'less than 1 min';
      }

      if(time > 1) {
          timeUnit += 's';
      }

      return 'about ' + time + timeUnit + 'ago';
}

alert(prettyTime(7600001));


texts: The quest for a succint, readable expression of Next in a sequence

texts:
I have a need to express something like this:

while(bytesToWrite > 0)
{
    // get the NEXT location to write from a Key/Value collection of locations

    // read a packet from a file at the specified location

    // write some bytes to the packet

    bytesToWrite -= bytesWritten
}

This was my first attempt:

var dictionary = new Dictionary<long, long>() { .. }
...

while(bytesToWrite > 0)
{
    var pin = dictionary.Take(1).First();
    Debug.Print(pin.Key.ToString() + ", " + pin.Value.ToString());

   // Write the bytes using Key and Value for location information.

    dictionary = dictionary.Skip(1)
    bytesToWrite -= bytesWritten;
}

But it doesn't look terribly efficient to me.  It looks like I'm making a new collection each time through the loop, just to peel off a single item, and the Take(1).First() and dictionary = dictionary.Skip(1) syntax is a bit awkward.

If I put my original collection in a LinkedList, I can do this:

var map = new LinkedList<KeyValuePair<long, long>>(dictionary);
...
var pin = map.First;
while (pin != null && bytesToWrite > 0)
{
    // Value.Key and Value.Value??
    Debug.Print(pin.Value.Key.ToString() + ", " + pin.Value.Value.ToString());

    // Write the bytes

    pin = pin.Next;
    bytesToWrite -= bytesWritten;
}

Eww.  Value.Key and Value.Value is not exactly intuitive.

I can write a couple of wrapper classes, like so:

public class StateList<T>
{
    LinkedList<T> list;
    LinkedListNode<T> currentNode;

    public StateList(IEnumerable<T> source)
    {
        list = new LinkedList<T>(source);
    }

    public StateList<T> Create<T>(IEnumerable<T> source)
    {
        return new StateList<T>(source);
    }

    public T First
    {
        get
        {
            var node = list.First;
            return Value(node);
        }
    }

    public T Last
    {
        get
        {
            var node = list.Last;
            return Value(node);
        }
    }

    public T Next
    {
        get
        {
            var node = currentNode.Next;
            return Value(node);
        }
    }

    public T Previous
    {
        get
        {
            var node = currentNode.Previous;
            return Value(node);
        }
    }

    public T Value(LinkedListNode<T> node)
    {
        if (node != null)
        {
            var value = node.Value;
            currentNode = node;
            return value;
        }
        return default(T);
    }
}

public static class StateList
{
    public static StateList<T> Create<T>(IEnumerable<T> source)
    {
        return new StateList<T>(source);
    }
}

and get the code look like this:

var map = StateList.Create(dictionary);
...
var pin = map.First;
while (bytesToWrite > 0)
{
    // Ah, that's better.
    Debug.Print(pin.Key.ToString() + ", " + pin.Value.ToString());

    // Write the bytes

    // Pin is taken from the map, not from the previous pin.
    pin = map.Next;
    bytesToWrite -= bytesWritten;
}

Ah, that's much better.  The question is, is all that ceremony really worth it?  I feel like I'm missing something simple and obvious.

I'd also like comments on the relative merit of the StateList class, whether it is a satisfactory approach from a good practices viewpoint, or a terrible abomination.