texts: MVC controller and action that handles favorite items in a session-based list

texts:
I've written a Controller and a corresponding Action for a Symfony 2.8 project, that does the following:

handles a list of favorite items of a user
the ids of the favorites are stored in the session
multiple entites can be favorized
possible actions on the favorite list are [add|remove]
the controller's action is called via AJAX and returns a JSON object

My questions are:

Can the PHP Code be optimized?
Is this code DRY?
Is this code safe?
Is this too much logic for one action?
Is it too much or not enough or even wrongly documented?

A few notes:

$this->getRepositoryName() is a custom function from the AbstracController base class that returns the correct repository name for a given entity
the returned JSON object is more then just the state of success, so the JavaScript can see, what exactly failed, if one ore more properties come back empty
I only need the favorites in the session for a filter later, they are not going to be stored or tracked using a database

class FavoritesController extends AbstractController
{
    private $validEntites = ['entityA', 'entityB'];
    private $validActions = ['add', 'remove'];

    /**
     * Can add or remove favorites to/from the list in the session.
     *
     * @Route("/handle-favorites", name="handle_favorites")
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function handleFavoritesAction(Request $request)
    {
        // initiate return value, will be send as JSON
        $result = [
            'success' => true,
            'entity' => null,
            'count' => null,
            'id' => null,
            'action' => null,
        ];

        // test for XHR request
        if(!$request->isXmlHttpRequest()) {
            $result['success'] = false;
            return new JsonResponse($result);
        }

        // retrieve values from session and create favorites array if necessary
        $session = $request->getSession();
        $favorites = $session->get('favorites');

        if (!$favorites) {
            $favorites = [];

            foreach ($this->validEntites as $value) {
                $favorites[$value] = [];
            }
        }

        // get and test request parameters
        $entity = $request->get('entity');
        $id = $request->get('id');
        $action = $request->get('action');

        if (in_array($entity, $this->validEntites)) {
            $result['entity'] = $entity;
        } else {
            $result['success'] = false;
        }

        if (in_array($action, $this->validActions)) {
            $result['action'] = $action;
        } else {
            $result['success'] = false;
        }

        if (false !== filter_var($id, FILTER_VALIDATE_INT, array('options' => array('min_range'=> 1)))) {
            $result['id'] = $id;
        } else {
            $result['success'] = false;
        }

        // add or remove item
        if ($result['success']) {
            if ('remove' === $action) {
                $favorites[$entity] = array_diff($favorites[$entity], [$id]);
            }

            if ('add' === $action && !in_array($id, $favorites[$entity])) {
                $repository = $this->getDoctrine()->getRepository($this->getRepositoryName(ucfirst($entity)));
                $object = $repository->find($id);

                if ($object) {
                    $favorites[$entity][] = $id;
                } else {
                    $result['success'] = false;
                    $id = null;
                    $result['id'] = $id;
                }
            }

            // update session
            $session->set('favorites', $favorites);
        }

        // update count
        $result['count'] = count($favorites[$entity]);

        return new JsonResponse($result);
    }
}


texts:
For the first time I've worked in Excel VBA to find rows in my dataset that contain the same adress as another entry in a cluster. These entries have to be merged and the row then is deleted. I've come up with the following, which works (As far as I can tell from the testing I did on small samples of the set):

Sub Merge_Orders()

Application.ScreenUpdating = False

Application.DisplayStatusBar = False

Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Dim y As Long
Dim x As Long
Dim j As Long
Dim k As Long

For i = 2 To lastrow //for each row, starting below header row
j = 1

y = (Cells(i, 9)) //this is the clusternumber
Do While y = (Cells(i + j, 9)) //while the next row is in the same cluster
 x = (Cells(i, 12)) //this is the adresscode
 k = 1
    Do While x = (Cells(i + k, 12)) //while the current adresscode is the same as the next, iterating until another adresscode is hit
     Cells(i, 16) = Val(Cells(i, 16)) + Val(Cells(i + k, 16)) //update cell value
     Cells(i, 18) = Cells(i, 18) + Cells(i + k, 18)  //update cell value
     Cells(i, 19) = Cells(i, 19) + Cells(i + k, 19)  //update cell value
     If Cells(i, 20) > Cells(i + k, 20) Then
     Cells(i, 20) = Cells(i + k, 20)  //update cell value
    End If
    If Cells(i, 21) > Cells(i + k, 21) Then
     Cells(i, 21) = Cells(i + k, 21)  //update cell value
    End If
    Cells(i, 22) = Cells(i, 22) + Cells(i + k, 22)  //update cell value
    Cells(i, 23) = Cells(i, 23) + Cells(i + k, 23)  //update cell value

    Rows(i + 1).EntireRow.Delete //Delete the row from which data was pulled
    k = k + 1
    Loop
 j = j + 1
Loop

Next i

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
End Sub

The problem I'm facing is time. Testing this on a small sample of ~50 rows took over 5 minutes. My entries total over 100K rows. I would expect it has to run for close to 10 days. It's been running for over a day with no end in sight.

Is there a way to optimize this so I don't have to wait until I'm grey?

Note: I've added //comments just for CR/SO, they are not in VBA.


texts:
I have implemented insertion sort using C++. Is there any way to improve my code and is it CppCoreGuideline compliant? As I passed the vector as const in print method, do I need to specify const in range for loop?

/*
 *  Insertion Sort
 */

#include <iostream>
#include <vector>

void insertionSort(std::vector<int> &v);
void print(const std::vector<int> &v);

int main()
{
    std::ios_base::sync_with_stdio(false);

    std::vector<int> v {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

    // Print the vector before sorting.
    print(v);
    // Sort
    insertionSort(v);
    // Print the vector after sorting.
    print(v);

    return 0;
}

void insertionSort(std::vector<int> &v) {
    for (auto i = v.begin() + 1; i != v.end(); ++i) {
        int key = *i;

        auto j = i - 1;
        while (j >= v.begin() && *j > key) {
            *(j+1) = *j;
            --j;
        }
        *(j+1) = key;
    }
    return;
}

void print(const std::vector<int> &v) {
    for (const auto &i : v) {
        std::cout << i << " ";
    }
    std::cout << "\n";
}


texts: Script to create a customized, efficient adblocking hosts file

texts:
I am writing a Python script that creates a customized, efficient adblocking hosts file.  Basically it checks the user's DNS cache and sees if any entries there are listed in the popular hosts files.  If so, it adds those entries to the user's hosts file.  The purpose is to keep the hosts file small and avoid adverse effects on browsing speed.  I was looking for any input on my overall approach, any ways to make it faster, and any stylistic revisions/suggestions.

import os
import urllib.request
import subprocess
import re
import datetime

# Create a list of ad domains from hosts files found online
def get_ad_dmns(src_urls):
    dmns = set()
    for src in src_urls:
        entries = [line.decode('utf-8') for line in list(urllib.request.urlopen(src))]
        for entry in entries:
            # If hosts file entry is a valid block rule, add domain to list
            if entry.startswith(('0.0.0.0', '127.0.0.1')):
                dmns.add(entry.split()[1])
    return dmns

# Create a list of domains found in the user's DNS cache
def get_dns_dmns():
    dns_cache = subprocess.check_output('ipconfig /displaydns').decode('utf-8')
    # Regex pattern to match domains in the DNS cache
    pattern = '\n\s+(\S+)\r\n\s+-'
    dmns = re.findall(pattern, dns_cache)
    return dmns

# Create a list of domains currently in the user's hosts file
def get_cur_dmns(hosts_dir):
    os.chdir(hosts_dir)
    dmns = set()
    hosts_file = open('hosts', 'r')
    for entry in hosts_file:
        if entry.startswith(('0.0.0.0', '127.0.0.1')):
            dmns.add(entry.split()[1])
    hosts_file.close()
    return dmns

# Write new domains to the hosts file
def write_hosts_file(dmns, hosts_dir):
    os.chdir(hosts_dir)
    hosts_file = open('hosts', 'a')
    hosts_file.write('\n# Updated: {}\n'.format(datetime.datetime.now()))
    for dmn in dmns:
        hosts_file.write('0.0.0.0 {}\n'.format(dmn))
    hosts_file.close()

def main():
    hosts_dir = 'C:/Windows/System32/drivers/etc'
    srcs = ['http://winhelp2002.mvps.org/hosts.txt',
            'http://someonewhocares.org/hosts/zero/hosts']
    ad_dmns = get_ad_dmns(srcs)
    dns_dmns = get_dns_dmns()
    cur_dmns = get_cur_dmns(hosts_dir)
    dmns_to_add = [dmn for dmn in dns_dmns if dmn in ad_dmns and dmn not in cur_dmns]
    if dmns_to_add:
        print ('Adding {} domain(s)...'.format(len(dmns_to_add)))
        write_hosts_file(dmns_to_add, hosts_dir)

if __name__ == '__main__':
    main()


texts: Is there a better way to insert an enum into a set without macros?

texts:
I created an enum for a class and in the constructor I inserted all the enum values into a set.  I am wondering if there is a better way anyone can recommend.  I feel like there should be, but have been unable to think of one or find one online.  I wrote the code in C++ and am using the Boost libraries.

Here is the enum:

class CreateAndUseIniFile {

    std::set<CreateAndUseIniFile::iniFileValues> m_modules;
    enum iniFileValues {
        FIXED_VOLTAGE1,
        FIXED_VOLTAGE2,
        FIXED_VOLTAGE3,
        FIXED_VOLTAGE4
    }
}

and this is the constructor where I add the values

CreateAndUseIniFile::CreateAndUseIniFile() {
    m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE1);
    m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE2);
    m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE3);
    m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE4);
}


texts: Analysis of the most common and salient words in a text

texts:
I've been trying to get more understanding and experience in the Natural Language Processing space and, to get some more practice, decided to attempt to make a simple high-level analysis of the "Industrial Society and its Future" (aka "Unabomber Manifesto").

Here is what I am trying to do:

download the text of the Manifesto from the Washington Post website
preprocess it using nltk:

tokenize into words
remove the non-alpha words
remove English stop words
lemmatize the tokens

count most commonly used words
use the TF-IDF model from gensim library to compute the most popular and most rarely used / important words

The code:

from bs4 import BeautifulSoup

from gensim.models.tfidfmodel import TfidfModel
from gensim.corpora.dictionary import Dictionary

from nltk import word_tokenize, Counter, sent_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords

import requests

ENGLISH_STOPS = set(stopwords.words('english'))

def retrieve_text(url):
    """Downloads HTML content from a URL, parses with an HTML parser and returns text only."""
    response = requests.get(url)

    soup = BeautifulSoup(response.content, "html.parser")
    return soup.get_text()

def preprocess(text):
    """Pre-processes the text, splits into tokens that are lower-cased, filtered and lemmatized."""
    tokens = word_tokenize(text)

    # lowering
    lower_tokens = [token.lower() for token in tokens]

    # Retain alphabetic words: alpha_only
    alpha_only = [t for t in lower_tokens if t.isalpha()]

    # Remove all stop words: no_stops
    no_stops = [t for t in alpha_only if t not in ENGLISH_STOPS]

    # Lemmatize all tokens into a new list: lemmatized
    wordnet_lemmatizer = WordNetLemmatizer()
    lemmatized = [wordnet_lemmatizer.lemmatize(t) for t in no_stops]

    return lemmatized

def tf_idf(text):
    """
    Computes the TF-IDF of a text - using every sentence as a separate "document".
    Returns a list of tuples with words and weights.
    """
    texts = [preprocess(sentence) for sentence in sent_tokenize(text)]

    dictionary = Dictionary(texts)
    corpus = [dictionary.doc2bow(text) for text in texts]

    tfidf = TfidfModel(corpus)
    corpus_tfidf = tfidf[corpus]

    tfidf_weights = {dictionary.get(id): value
                     for doc in corpus_tfidf
                     for id, value in doc}
    sorted_tfidf_weights = sorted(tfidf_weights.items(), key=lambda w: w[1])

    return sorted_tfidf_weights

if __name__ == '__main__':
    content = retrieve_text("http://www.washingtonpost.com/wp-srv/national/longterm/unabomber/manifesto.text.htm")

    tokens = preprocess(content)
    token_counter = Counter(tokens)

    most_common = token_counter.most_common(10)
    tf_idf_results = tf_idf(content)
    popular_terms, rare_terms = tf_idf_results[:10], tf_idf_results[-10:]

    # print out words only (without counts and weights)
    keys = lambda x: next(zip(*x))
    print(f"Most common words: {keys(most_common)}")
    print(f"Most popular terms: {keys(popular_terms)}")
    print(f"Most unique/important terms: {keys(rare_terms)}")

Prints:

Most common words: ('society', 'system', 'people', 'power', 'would', 'one', 'human', 'technology', 'leftist', 'need')
Most popular terms: ('society', 'people', 'freedom', 'whole', 'human', 'lead', 'system', 'necessity', 'process', 'use')
Most unique/important terms: ('license', 'simplification', 'personnel', 'carried', 'crossroad', 'eminent', 'exactly', 'paramount', 'danger', 'virtue')

I am still learning and would like my code to be reviewed. Would appreciate any feedback about the code quality, performance or any other possible improvements.

Also, I am not 100% sure the TF-IDF model is applied in the most appropriate way. Currently, I am treating each sentence as a separate document. Is this a good approach to detect the most "important"/"valuable" terms/words, or should I use other articles/posts as documents for the corpus?


texts:
Is using a static variable in a lambda function ok, or considered a bad practice? The code below works as intended (fills a vector with consecutive numbers).

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

using namespace std;

int main()
{
    vector<int> vec(100);

    generate(vec.begin(), vec.end(), [] () { static int i = 0; return i++; });
}


texts: Script to calculate width, and either resize, show, or hide HTML menu

texts:
I have created a script that handles the responsive liabilities of my HTML menu. The menu will have a variable amount of <li class="menu-item">, resulting in a variable total width. I have 3 functions.

This function is responsible for looping through each li element and calculating the greatest width of the set of elements.

function resize_menu() {

    var maxWidth = -1;

    $(".menu-item").each(function() {
        maxWidth = maxWidth > $(this).width() ? maxWidth : $(this).width();
    });

    $(".menu-item").each(function() {
        $(this).width(maxWidth);
    });
}

This function is responsible for displaying the mobile menu, and hiding the standard menu.

function mobile_menu() {
    $("#mobile-menu").css("display", "block");

    $(".menu-primary-menu-container").css("display", "none");
}

This function is responsible for showing the standard menu, and hiding the mobile menu, invert of the above.

function show_menu() {
    $("#mobile-menu").css("display", "none");

    $(".menu-primary-menu-container").css("display", "initial");
}

Now to execute functions above, I have created instances in which they need to be fired.

$( window ).load(function() {
    //declare variables
    var resizeTimer;
    var maxWidth = -1;
    var count = $(".menu-item").length;

    // Loop menu items, and retrieve greatest width, to be multiplied by count
    $(".menu-item").each(function() {
        maxWidth = maxWidth > $(this).width() ? maxWidth : $(this).width();
    });

    // Only resize li elements if screen width is greater than menu width
    if ($(window).width() > maxWidth * count) {
        resize_menu();
    } else {
    // or else show the mobile menu
        mobile_menu();
    };

    // On a resize (delayed for performance)
    $(window).on('resize', function(e) {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
            // again, if window is less than menu, show mobile
            if ($(window).width() < maxWidth * count) {
                mobile_menu();
            } else {
            // or else, show regular menu
            // Note: resize, incase screen was loaded smaller than menu
                resize_menu();
                show_menu();
            };
        }, 50);
    });

    // if the mobile menu icon is clicked, show menu
    $("#mobile-menu").click(function() {
        show_menu();
    });
});

This code does work, however there are some performance issues. When I resize the window, some times the hiding of the regular menu, and showing of the mobile is delayed, caused probably by the timeout I set, is it worth getting rid of? Also, I know this code is wet, lots of repetition. I could use advice on that. Finally, how can I store my selectors in variables and use them throughout the script?


texts:
If you need to kill the same process that you're in (for testing purposes or whatever) this code will do it.

A definitive, quick, unmerciful dead of the current Java program/app.
Not a System.exit(0) or a graceful dead.

A headshot to the running JVM

public class KillMe {

  private static final String CMD_WINDOWS = "taskkill /F /PID %d";
  private static final String CMD_LINUX = "kill -9 %d";

  public static void tryNow()  {
    Thread t = new Thread( () -> {
        try {
            now();
        } catch (CantKillMeException e) {
            //TODO whatever
            e.printStackTrace();
        }
    });
    t.setName("killmethread");
    t.setDaemon(true);
    t.start();
  }

public static void now() throws CantKillMeException {
    int pid = obtainPid();
    String command = getCommand(pid);
    executeCommand(command);
}

static int obtainPid() throws CantKillMeException {
    try {
        java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
        java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);
        sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
        java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);
        int pid = (Integer) pid_method.invoke(mgmt);
        return pid;
    } catch (IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | NoSuchFieldException e) {
        throw new CantKillMeException("Cant obtain pid", e);
    }
}

// https://stackoverflow.com/questions/9573696/kill-a-process-based-on-pid-in-java
static String getCommand(int pid) {
    String command =  isWindows() ? CMD_WINDOWS : CMD_LINUX;
    return String.format(command,pid);
}

// https://stackoverflow.com/questions/14288185/detecting-windows-or-linux
static boolean isWindows() {
    String osname = System.getProperty("os.name").toLowerCase();
    return osname.contains("win");
}

static void executeCommand(String command) throws CantKillMeException {
    try {
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();
    } catch (java.io.IOException | InterruptedException e) {
        throw new CantKillMeException("Cant execute command " + command, e);
    }
}

  public static class CantKillMeException extends Exception {

      CantKillMeException(String message, Throwable cause) {
          super(message, cause);
      }
  }

  }

Will work on Linux. Windows should work (not tested). There's room for improvement, for sure.


texts: Utilisation of multi-threading while reading a file and want to find the top 20 most frequently used words

texts:
The purpose of this code per the title is to utilise the multi-threading (even though the improvement might be minor or even have negative impact, although comments on how to improve efficiency are appreciated). As part of the work, we are expected to read a file and print the 20 most frequently used words.

#include <iostream>
#include <iterator>
#include <set>
#include <vector>
#include <algorithm>
#include <map>
#include <mutex>
#include <fstream>
#include <pthread.h>
#include <queue>
#include "mingw-std-threads-master/mingw-std-threads-master/mingw.thread.h"
#include "mingw-std-threads-master/mingw-std-threads-master/mingw.mutex.h"

//bad practise but convenient for this code example
using namespace std;

//File to read so that we can find the most frequent used words.
#define FILENAME "mobydick.txt"

//The amount of words to find which are most used.
#define WORDS_TO_FIND 20

map<string,int> word_count;
queue<string> word_queue;
std::mutex m;

//Not great approach but condition_variable is not available in my environment.
bool keep_running = true;

//Ignore punctuations coming from the stream, and to read only valid "english" letters from the input stream.
//This is an improvement but it still doesn't cover all cases.
struct letter_only: ctype<char>
{
    letter_only(): ctype<char>(get_table()) {}

    static ctype_base::mask const* get_table()
    {
        static vector<ctype_base::mask> rc(ctype<char>::table_size,ctype_base::space);

        fill(&rc['a'], &rc['z'+1], ctype_base::alpha);
        return &rc[0];
    }
};

void insert()
{
    string word;

    while(keep_running || (!keep_running && !word_queue.empty()))
    {
        if(!word_queue.empty())
        {
            m.lock();
            word = word_queue.front();
            word_queue.pop();

            if (word_count.find(word) == word_count.end())
            {
                word_count.insert(pair<string, int>(word, 1));
            }
            else
            {
                word_count.find(word).operator*().second++;
            }
            m.unlock();
        }
    }
}

void read_file()
{
    ifstream file;

    file.imbue(locale(locale(), new letter_only()));

    file.open(FILENAME);

    if (!file.is_open())
    {
        exit(-1);
    }

    string word;
    while (file >> word)
    {
        m.lock();
        word_queue.push(word);
        m.unlock();
    }

    file.close();
    keep_running = false;
}

void print_results()
{
    int biggestNum = 0;
    string word;

    for(int i = 0; i < WORDS_TO_FIND; i++)
    {
        for(auto it = word_count.begin(); it != word_count.end(); ++it )
        {
            if (it->second > biggestNum)
            {
                biggestNum = it->second;
                word = it->first;
            }
        }

        if(word.length() > 0)
        {
            word_count.erase(word);
            cout << word + ": " << biggestNum << endl;
        }

        biggestNum = 0;
    }
}

int main()
{
    /** Thoughts...
    * The only ways I know to improve disk read performance are:
     * 1) read the data from a compressed source.
     * 2) use faster disks, or RAID array. or
     * 3) split the data onto separate disks and read 1 thread per disk. Usually, if a single thread can't keep up
     * with your disk read time, you have big problems.
    **/

    //An option to consider is task-based parallelism.. std::async which lets the platform decide when to spawn a thread.

    thread first(read_file);
    first.detach();

    thread second(insert);
    second.join(); //wait for read_file and insert to finish before printing the results

    print_results();

    return 0;
}


texts: Image placed with username in recent post of WordPress

texts:
I am using this code to display the recent post from my subdomain to my main domain. I got it after spending 6-7 hours. Now I need to show the avatar image and username of the user of has posted the questions on questions.admissiontimes.com. Right now, it's coming in green and black.

function print_requested_template_part() {
    // Respond only to requests from the same address...
    if ( $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
        $part = $_GET['load_part'];
        $func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
        if ( function_exists($func) ) {
            // Allow for passing parameters to the function
            if ( isset($_GET['params']) ) {
                $params = $_GET['params'];
                $params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
                call_user_func_array($func, $params);
            } else {
                call_user_func($func);
            }
        }
        exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
    }
}
add_action('init', 'print_requested_template_part', 1);

function render_my_recent_posts( $numberposts = 5 ) { ?>

    <?php
        $args = array( 'numberposts' => '5' );
        $recent_posts = wp_get_recent_posts( $args );
        foreach( $recent_posts as $recent ) {
            echo '
' .   $recent["post_title"].'
 ';
        }
    ?>

<?php
}


texts: getRandom() - Randomize array and get result

texts:
I've written a function that allows you to pass an array of values, which is then shuffled and returned based on a parameter $preserveArray.

This is the code:

function getRandom($arr, $preserveArray = false, $shuffles = 1) {
    if(empty($arr)) return false;
    if($preserveArray) {
        $tmp = array();
        foreach($arr as $key => $value) {
            $tmp[] = array('key' => $key, 'value' => $value);
        }
        $arr = $tmp;
    }
    for($x = 1; $x <= $shuffles; $x++) {
        if(!shuffle($arr)) {
            return false;
        }
    }
    if($preserveArray) {
        $tmp = array();
        foreach($arr as $value) {
            $tmp[$value['key']] = $value['value'];
        }
        $arr = $tmp;
        return $arr;
    }
    return $arr[0];
}

So you can pass any array as the first parameter that you want randomized, then the 2nd parameter determines how the data is returned, then the 3rd parameter tells the function how many times to shuffle the array.

I've written this because I think it will be useful for people on StackOverflow, I see a lot of questions trying to figure out how to get a random value from an array.

The $preserveArray parameter tells the function to either only return a single array element if false, or return the whole array (with keys in-tact) if true.

As you can see in my code, I have to check for the 2nd parameter twice to do actions before and after the actual array shuffle. I wanted to see if anyone had any advice or knows of any ways I can improve my code.

I've been posting a lot of my code here lately, and I really enjoy how much I'm able to learn from answers. Thanks in advance!


texts:
I have come up with the following solution to find the maximum product for a contiguous sub-array:
def maxProduct(nums):

    max_prod = [0]*len(nums)
    min_prod = [0]*len(nums)
    for i in range(0, len(nums)):
        min_prod[i] = min(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i])
        max_prod[i] = max(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i])

    return max(max_prod)

Current solution is O(n) in space, trying to find O(1) solution for space, but I keep seem to missing it. Ideas?


texts:
I've implemented an updateable priority queue as a part of implementing some single-source-shortest-path algorithms (Dijkstra, BF). I'm relatively new to Python.

class UpdateableQueue:
    def __init__(self,iterable=None):
        self._heap = []
        self._entry_finder = {}
        if iterable:
            for item in iterable:
                self._entry_finder[item[0]] = item[1]
                heapq.heappush(self._heap,(item[1],item[0]))

    def __getitem__(self, key):
        if key in self._entry_finder:
            return self._entry_finder[key]
        else:
            raise KeyError('Item not found in the priority queue')

    def __len__(self):
        return len(self._entry_finder)

    def __contains__(self, key):
        return key in self._entry_finder

    def push(self, key,priority):
        self._entry_finder[key] = priority
        heapq.heappush(self._heap, (priority, key))

    def pop(self):
        if not self._heap:
            raise IndexError("The heap is empty")

        value,key = self._heap[0]
        while key not in self or self._entry_finder[key] != value:
            heapq.heappop(self._heap)
            if not self._heap:
                raise IndexError("The heap is empty")
            value,key = self._heap[0]

        value, key = heapq.heappop(self._heap)
        del self._entry_finder[key]
        return key,value

Edit: a simple test case example of the UpdateableQueue

from UpdateableQueue.UpdateableQueue import UpdateableQueue

if __name__ == "__main__":
    # Initalizing empty queue
    queue = UpdateableQueue()
    # Inserting key=1,priority=4 element to the queue the heap is now of size 1, and the dict size 1
    queue.push(1,4)
    # editing key=1,priority=1 element to the queue the heap is now of size 2, and the dict size 1
    queue.push(1,1)
    # editing key=1,priority=2 element to the queue the heap is now of size 3, and the dict size 1
    queue.push(1,2)
    assert len(queue) == 1 # True
    assert 1 in queue # True
    # on pop we remove (key=1,value=1) from the heap and then pop out that value of (1,2), followed by
    # removing that key from the dict
    key, value = queue.pop()
    assert 1 not in queue #True
    assert key == 1 # True
    assert value == 2 # True
    # Inserting key=2,priority=5 element to the queue the heap is now of size 2, and the dict size 1
    queue.push(2,5)
    assert len(queue) == 1
    # We "clean" the remaining (1,4) element from the heap and return pop (2,5) as expected.
    key, value = queue.pop()
    assert key == 2  # True
    assert value == 5  # True


texts: Using TryXXX pattern to avoid exceptions

texts:
I have been using the TryXXX and GetXXX pattern lately to give clients a choice whether to trap an exception or to read a boolean. An example of this concept would be System.Integer.TryParse and System.Integer.Parse.

It is my understanding that you should get two benefits from this:

using an if statement in calling code instead of try-catch
a performance benefit from not causing an exception.

In this class, I am attempting to do this, but I think I am getting only benefit 1, not benefit 2. I am drawing a blank as how to not throw any exception without code duplication.

       Public Function ConvertFractionToDecimal(ByVal fraction As String) As Decimal

        If String.IsNullOrWhiteSpace(fraction) Then Throw BuildBadFractionException(fraction)

        'will accept fractions of the form:
        'X-Y/Z
        'X Y/Z
        'Y/Z
        'will not accept negative signs in numerator, denominator, or whole number

        Dim whole As String
        Dim numen As String
        Dim denom As String

        Dim loc1 As Integer
        Dim loc2 As Integer

        fraction = fraction.Trim
        If fraction Like "*?-*?/?*" Then
            loc1 = InStr(fraction, "-")
            loc2 = InStr(fraction, "/")
        ElseIf fraction Like "*? *?/?*" Then
            loc1 = InStr(fraction, " ")
            loc2 = InStr(fraction, "/")
        ElseIf fraction Like "*?/?*" Then
            loc2 = InStr(fraction, "/")
        Else
            Throw BuildBadFractionException(fraction)
        End If

        If loc1 > 0 Then
            whole = Mid(fraction, 1, loc1 - 1).Trim
        Else
            whole = "0"
        End If
        numen = Mid(fraction, loc1 + 1, loc2 - loc1 - 1).Trim
        denom = Mid(fraction, loc2 + 1).Trim

        Dim Uwhole As UInt32
        Dim Unumen As UInt32
        Dim Udenom As UInt32
        If Not UInt32.TryParse(whole, Uwhole) Then Throw BuildBadFractionException(fraction)
        If Not UInt32.TryParse(numen, Unumen) Then Throw BuildBadFractionException(fraction)
        If Not UInt32.TryParse(denom, Udenom) Then Throw BuildBadFractionException(fraction)

        Return CDec(Uwhole + Unumen / Udenom)

    End Function

    Public Function TryConvertFractionToDecimal(ByVal fraction As String, ByRef result As Decimal) As Boolean
        Try
            result = ConvertFractionToDecimal(fraction)
            Return True
        Catch ex As Exception
            result = 0
            Return False
        End Try
    End Function

    Private Function BuildBadFractionException(ByVal fraction As String) As InvalidOperationException
        Return New InvalidOperationException(String.Format("'{0}' is not a recognisable fraction.", fraction))
    End Function


texts: Creating change with the smallest number of coins

texts:
This is a basic algorithm that creates change with the smallest number of coins. How can this be better written? It works perfectly, but I just imagine there is a cleaner and shorter version of this.

const generateCoinChange = cents => {
    let quarter = 0;
    let dime = 0;
    let nickel = 0;
    let penny = 0;
    let remainingChange = cents;

    while (remainingChange >= 25) {
        remainingChange -= 25;
        quarter++;
    }
    while (remainingChange >= 10) {
        remainingChange -= 10;
        dime++;
    }
    while (remainingChange >= 5) {
        remainingChange -= 5;
        nickel++;
    }
    while (remainingChange > 0) {
        remainingChange -= 1;
        penny++;
    }
    console.log(`Quarters: ${quarter}, Dimes: ${dime}, Nickels: ${nickel}, Pennies: ${penny}`)
};
generateCoinChange(94);
generateCoinChange(100);
generateCoinChange(23);


texts:
I am currently processing some large time-series data with pandas, and I have a function that is intolerably slow, and I'm sure it could be done faster.

The problem is: I'm studying a factory that produces things. It runs continuously throughout the week, but on weekends it shuts down. Before the end of the week, and at the start of a new one, the factory behaves differently, which interferes with the analysis that I'm doing, and so I want to filter out a time window around these weekends.

I have a large dataframe, call it df, whose rows are the articles produced and the columns are their various attributes, one of which is the time at which it was produced, df['timeProduced']. These articles are produced at irregularly-spaced points in time.I want to discard the rows in the table whose timeProduced entry was near one of these shutdown periods. The actual data is confidential, but it looks similar to this:

index   partId        colour   timeProduced  \ ...
1       '026531|352'  Red    2017-02-01 00:00:02
2       '026531|353'  Blue   2017-02-01 00:00:03
3       '026531|354'  Blue   2017-02-01 00:00:05
4       '026531|355'  Green  2017-02-01 00:00:09

This  takes tens of minutes to crunch through a million entries. I know it's slow because it isn't at all vectorized, but I'm not sure how to do a pure vectorized numpy/pandas implementation. Any ideas?

def dropIrregularGaps(series, gapLength, runIn):
    '''
    Designed for time-series data where there is points sampled at irregular time intervals.
    Detects adjacent points that are sampled too far apart, and then removes points on either
    side of the gap which are within a defined runIn period.
    Assumes timeseries data is already sorted. If not, will deliver garbage.
    series is a pandas series object, with values as pandas DateTime objects.
    gapLength is the amount of time that is considered to be a shutdown
    runIn is the length of time to remove on either side of the gap.
    returns a list of indices that are valid
    '''
    samples = list(series)
    indices = list(series.index)

    prev = samples[0]
    ind = indices[0]
    allGoodIndices = []
    currentGoodIndices = [ind]
    currentGoodTimes = [prev]
    skipPoint = None

    for new, ind in zip(samples[1:], indices[1:]):
        if skipPoint:
            if new - skipPoint >= runIn:
                # if a gap has been detected, skip over all points until the current
                # point is past the run-in period.
                skipPoint = None
                currentGoodIndices = [ind]
                currentGoodTimes = [new]

        elif new - prev > gapLength:
            # if a gap is detected. cut out the cooldown period from the list,
            # and add what remains to the list of goodIndices.
            endPoint = currentGoodTimes[-1]
            while currentGoodTimes and (endPoint - currentGoodTimes[-1] < runIn):
                del (currentGoodTimes[-1])
                del (currentGoodIndices[-1])

            allGoodIndices += currentGoodIndices
            currentGoodIndices = []
            currentGoodTimes = []
            skipPoint = new
        else:
            currentGoodIndices += [ind]
            currentGoodTimes += [new]

        prev = new

    allGoodIndices += currentGoodIndices

    return allGoodIndices

I operate this function by taking my dataframe, and running:

result = dropIrregularGaps(df['timeProduced'],pd.Timedelta('4 hours'), pd.Timedelta('8 hours 0 minutes'))

I then use the result to index into the dataframe, giving me the dataframe without the startup/cooldown periods.

df = df.loc[result]


texts:
I often write something like this in my code:

try {
    obj.doSomething();
} catch (Throwable exception) {
    // there is no need to interrupt application
    String exceptionMessage = String.valueOf(exception.getMessage());
    Log.e("Name of my app", exceptionMessage, exception);
    // and may be something else
}

So I wrote this simple class:

public class TryHelper {

    public static final TryHelper LOGGER = new TryHelper(new Handler<Throwable>() {
        @Override
        public void handle(Throwable exception) {
            LogUtils.exception(exception);
        }
    });

    private final Handler<Throwable> exceptionHandler;

    public TryHelper(Handler<Throwable> exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    public void tryDoIt(Runnable runnable) {
        try {
            runnable.run();
        } catch (Throwable exception) {
            exceptionHandler.handle(exception);
        }
    }

    public void tryDoIt(RunnableAbleToThrowCheckedException runnable) {
        try {
            runnable.run();
        } catch (Throwable exception) {
            exceptionHandler.handle(exception);
        }
    }

}

And interfaces from my own util package:

public interface RunnableAbleToThrowCheckedException {
    void run() throws Exception;
}

public interface Handler<T> {
    void handle(T obj);
}

Using:

TryHelper.LOGGER.tryDoIt(new Runnable() {
    @Override
    public void run() {
        obj.doSomething();
    }
});

But I'm pretty bad at English. So I need your help in choosing proper names (instead of TryHelper, RunnableAbleToThrowCheckedException, tryDoIt(), etc.).

I'm a fan of Uncle Bob and his book "Clean Code":

  We want the code to read like a top-down narrative.

And what do you think about the need for this class? Maybe it was a bad idea?


texts:
I am designing a basic in-memory cache storage with a thin CRUD (actually CRD) interface. The design is inspired by backend solutions such as Parse and StackMob.

Main characteristics:

Cache consists of tables(schemas) storing hashes.
The keys(fields) in a table are fixed(enforced).
Maximum memory efficiency for storing large data.

Here is the design I came up with, which is tested and fully functional.

There are too many Exceptions for my taste, but somehow I need to enforce things that "should not happen". Another thought was to log errors silently and then ignore them. However, that means my code using this API will have to account for those errors, increasing the complexity.

The basic methods are create, readOne, read, and delete.
CRUD usually includes update but I find it useless as it can be accessed by combining 'read', 'delete', 'create' and requires additional decision how to handle concurrency.

I'm curious to get feedback and thankful for any critiques or remarks regarding what can be improved.

/** Local In-Memory Cache: Tables referred by their string names
 * Storing hashes:
 *    all hashes must have 'id' as key
 *    all hashes must have keys other than 'id'
 *    and hashes in the same table must have the same key structure (enforced)
 * Basic CRUD interface + 'readOne' for the first entry + 'realDelete'
 * optimized to save memory: arrays packed into |-separated strings and gz(de/in)flated
 */
class LocStore {
   // ass. array 'table' => string of keys
   private $_keys = array();
   // assoc. array of strings indexed by table and id
   private $_values = array();

   /** create entry, enforce the same keys and new id
    * @param string $table
    * @param ass. array $hash, must have 'id' not null
    */
   public function create ($table, array $hash) {
      $id = $hash['id'];
      if (! $id) throw new Exception('Id is null');
      unset($hash['id']);
      if (! $hash) throw new Exception('Empty hash beside id');
      // sort by keys alphabetically
      ksort($hash);
      $keyString = $this->_toString(array_keys($hash));
      if ( empty($this->_keys[$table]) ) {
         $this->_keys[$table] = $keyString;
      } elseif ($this->_keys[$table] != $keyString) {
         throw new Exception('Array keys mismatch');
      }
      if ( isset($this->_values[$table]) && ! empty($this->_values[$table][$id]) ) {
         throw new Exception("Id '$id' already exists");
      }
      $this->_values[$table][$id] = $this->_toString(array_values($hash));
      // for chaining
      return $this;
   }

   // read one entry, empty array if nothing is there
   public function readOne ($table) {
      if ( empty($this->_values[$table]) ) return array();
      reset($this->_values[$table]);
      $id = key($this->_values[$table]);
      return $this->read($table, $id);
   }

   // read by id, empty array if not found
   public function read ($table, $id) {
      if ( empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) return array();
      $keys = $this->_toArray($this->_keys[$table]);
      $values = $this->_toArray($this->_values[$table][$id]);
      $result = array_combine($keys, $values);
      $result['id'] = $id;
      return $result;
   }

   // delete by id, exception if not found
   public function delete ($table, $id) {
      if ( empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) {
         throw new Exception('Deleting non-existant entry');
      }
      unset($this->_values[$table][$id]);
      return $this;
   }

   public function readDelete($table, $id) {
      $hash = $this->read($table, $id);
      if ($hash) $this->delete($table, $id);
      return $hash;
   }

   private function _toString (array $array) {
      $json = json_encode($array);
      return gzdeflate($json);
   }

   private function _toArray ($string) {
      $string = gzinflate($string);
      return json_decode($string);
   }

}


texts: Lazy loading generator for training a Keras network

texts:
A common use for Keras LSTM layers is to generate text. There are
many examples showing you how to do it.

The usual method is to convert the text into a sequence of tokens and
then slice up the sequence into overlapping windows which is used as
inputs and the windows following tokens are the outputs.

So if your token sequence is of length i and the length of each window
is j, the input data would have the dimensions (i, j). The output data
would have the dimensions (i). But then you also have to one hot
encode the data. So if the number of unique tokens is k, the input
gets the dimensions (i, j, k) and the output (i, k).

This is way to much data to fit in memory. So you have to load it
iteratively, using a generator. Here is my generator that does that:

class OneHotGenerator(Sequence):
    def __init__(self, seq, batch_size, win_size, vocab_size):
        self.seq = seq
        self.batch_size = batch_size
        self.win_size = win_size
        self.vocab_size = vocab_size

    def __len__(self):
        n_windows = len(self.seq) - self.win_size
        return int(np.ceil(n_windows / self.batch_size))

    def __getitem__(self, i):
        base = i * self.batch_size

        # Fix running over the dge.
        n_windows = len(self.seq) - self.win_size
        batch_size = min(n_windows - base, self.batch_size)

        X = np.zeros((batch_size, self.win_size, self.vocab_size),
                     dtype = np.bool)
        Y = np.zeros((batch_size, self.vocab_size),
                     dtype = np.bool)
        for i in range(batch_size):
            for j in range(self.win_size):
                X[i, j, self.seq[base + i + j]] = 1
            Y[i, self.seq[base + i + self.win_size]] = 1
        return X, Y

Meant to be used like this:

gen = OneHotGenerator(seq, batch_size, win_size, vocab_size)
model.fit_generator(generator = gen,
                    steps_per_epoch = len(seq) // batch_size,
                    ...)

where seq is the sequence of tokens. The code works (I think), but
I'm not happy with it for a few reasons:

Windowing a sequence and converting it to one hot vectors seem like
a very common use case. There should be something in Keras that can
do what I want so I don't have to write the code myself.
I haven't double-checked all indexing operations. There may be some
unhandled edge cases.
My __getitem__ code doesn't seem to be very efficient. It seem to
slow down training quite a bit.
The code doesn't handle different step sizes (the amount of overlap
between windows) or any edge cases.

So what I want to know is if there is a better way to do what I want?
If it isn't can my code be improved?


texts: Check whether array is sorted recursively

texts:
I'm trying to implement isSorted method checking whether given array is sorted recursively. I've written two types, one is similar to merge sort logic, the another is like loop. Can they be made more efficient? Is there any thing I overlooked?

class SortedRecursive {
    public static void main(String[] args) {
        List<Integer> test = new ArrayList<>(Arrays.asList(9, 9, 9));
        List<Integer> test2 = new ArrayList<>(Arrays.asList(9, 10, 11));
        List<Integer> test3 = new ArrayList<>(Arrays.asList(5, 5, 3, 7));
        List<Integer> test4 = new ArrayList<>(Arrays.asList(1,2,2,3,3,4));

        System.out.println("test(nlogn) -> " + isSorted(test));
        System.out.println("test(n) -> " + isSortedAnotherVersion(test, 0));
        System.out.println("test2(nlogn) -> " + isSorted(test2));
        System.out.println("test2(n) -> " + isSortedAnotherVersion(test2, 0));
        System.out.println("input(nlogn) -> " + isSorted(test3));
        System.out.println("input(n) -> " + isSortedAnotherVersion(test3, 0));
        System.out.println("output(nlogn) -> " + isSorted(test4));
        System.out.println("output(n) -> " + isSortedAnotherVersion(test4, 0));
    }

    public static boolean isSorted(List<Integer> arr) {
        if (arr == null || arr.size() == 0) {
            return false;
        }

        if (arr.size() == 1) {
            return true;
        }

        int middleIndex = arr.size() / 2 ;
        List<Integer> left = new ArrayList<>();
        List<Integer> right = new ArrayList<>();

        for (int i = 0; i < middleIndex; i++) {
            left.add(arr.get(i));
        }

        for (int i = middleIndex; i < arr.size(); i++) {
            right.add(arr.get(i));
        }

        //System.out.println("left -> " + left + " right -> " + right);

        boolean result = left.get(middleIndex - 1) <= right.get(0);

        return isSorted(left) && result && isSorted(right);

    }

    public static boolean isSortedAnotherVersion(List<Integer> arr, int index) {
        if (arr.size() == 1 || index == arr.size() - 1)
            return true;
        if (arr.get(index) > arr.get(index + 1)) return false;
        return isSortedAnotherVersion(arr, index + 1);
    }

}


texts:
I want to write a search that raises an error if the list supplied is not sorted.

class BinarySearch

  attr_accessor :list

  def initialize(orig)
    raise ArgumentError unless sorted? orig
    self.list = orig
  end

  def search_for(n)
    s_list = self.list
    offset = 0
    loop do
      mid = s_list.length/2
      left = s_list[0..mid-1]
      right = s_list[mid+1..s_list.length-1]
      mid_val = s_list[mid]
      if n == mid_val
        return offset+mid
      elsif n > mid_val
        offset += mid+1
        s_list = right
      else
        s_list = left
      end
      raise RuntimeError if s_list.empty?
    end
  end

  def middle
   self.list.length/2
  end

  private

  def sorted?(orig)
    for i in 1..orig.length-1
        return false if orig[i] < orig[i-1]
    end
    return true
  end

end


texts: Async Check for Domain Fullname With WPF and Caliburn.Micro

texts:
I have a small WPF program built using Caliburn.Micro which checks Active Directory for a user with the current username of the logged-on user. I have a Bootstrapper method:

protected async override void OnStartup(object sender, StartupEventArgs e)
{
    await ShellViewModel.CollectFullnameAsync();
    DisplayRootViewFor<ShellViewModel>();
}

This starts the ShellViewModel and kicks off an async method to start looking for the currently logged on user on the domain

My ShellViewModel looks like this:

public ShellViewModel()
{
    Computername = EnvironmentHelpers.ComputerName;
    Fullname = _fullnameplaceholder;
}

public static async Task CollectFullnameAsync()
{
    _fullnameplaceholder = ADHelpers.GetFullADName();

    while(_fullnameplaceholder == "Failed" && _attemptsToCollectFullName < 5)
    {
        _attemptsToCollectFullName++;
        await Task.Delay(2000);
        _fullnameplaceholder = ADHelpers.GetFullADName();
    }
}

So my code is meant to:

Look for the user on the domain
Check 5 times for the user, waiting 2 seconds between each attempt.
Display the ShellView with either "Failed" or the Fullname returned from the domain

Can I please get some insight into how I am performing this task? Is this the correct way to do this or am I barking up the wrong tree?


texts: Grouping and summing values for food takeout

texts:
I have 4 properties which I calculate using LINQ:

public decimal TotalEatin { get; set; }
public int EatinAmount { get; set; }

public decimal TotalTakeout { get; set; }
public int TakeoutAmount { get; set; }

The way I generate the values are done correctly this way, but I think the code is a bit cumbersome because of the repeated iteration that is needed.

Because I need to generate the values from different DataTables, I have no idea how I can improve this using one "large" query. My knowledge of LINQ / SQL-like syntax is simply way too low.

Is it somehow possible to put these properties in a separate class, and use proper LINQ to generate one instance of this class with the right property values?

TotalEatin = Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
    .SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && !d.Field<bool>("takeout")))
    .Sum(x => x.Field<decimal>("price"));

TotalEatin += Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
    .SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && !d.Field<bool>("takeout")))
    .SelectMany(x => Data.MenuDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("orderid")))
    .Sum(x => x.Field<decimal>("prijs"));

EatinAmount = Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
    .SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && !d.Field<bool>("takeout")))
    .GroupBy(x => new { takeout = x.Field<bool>("takeout"), orderid = x.Field<int>("orderid") }).Distinct().Count();

TotalTakeout = Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
    .SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && d.Field<bool>("takeout")))
    .Sum(x => x.Field<decimal>("price"));

TotalTakeout += Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
    .SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && d.Field<bool>("takeout")))
    .SelectMany(x => Data.MenuDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("orderid")))
    .Sum(x => x.Field<decimal>("prijs"));

TakeoutAmount = Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
    .SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && d.Field<bool>("takeout")))
    .GroupBy(x => new { takeout = x.Field<bool>("takeout"), orderid = x.Field<int>("orderid") }).Distinct().Count();


texts:
I wrote this to pull one column of data from a csv file, divide each of the results in 2, and then format it as JSON so I can do stuff with it in a web app.  It works, but it feels wonky and weird.  Is there a better way to do this?

$fname = "subjects.csv";

$half = array();
$otherkeys = array();
$records = array();

if (($handle = fopen($fname, "r")) === FALSE) {
    exit;
}

/* First line is header with keys */
$keys = fgetcsv($handle);

echo '[';  //added the '['. here to get a propoerly formatted JSON response, not sure why I needed to but I did
while (($data = fgetcsv($handle)) !== FALSE) {
    $half[] = ''.$data[0]/2;    //added the ''. here to get a propoerly formatted JSON response, not sure why I needed to but I did
    $otherkeys[] = $keys[0];
    $records = array_combine($otherkeys, $half);
    $response = json_encode($records);
    echo $response;
}
fclose($handle);
echo ']';  //added the ']'. here to get a properly formatted JSON response, not sure why I needed to but I did

Any thoughts are much appreciated.


texts: Sorting a set of numbers in a file using Java BitSet

texts:
I have implemented a program to sort a file consisting of numbers. The program generates a different output file with all numbers sorted in it. I have implemented this program using BitSet and want to understand BitSet.

public class Application {
    public static void main(String[] args) throws Exception {

        String inputFile = "c:\\temp\\numbers.txt";
        NumberFileSorter.sort(inputFile, 100);
    }
}

class NumberFileSorter {

    private NumberFileSorter() {
    }

    public static void sort(String inputFile, int maxValue) throws Exception {

        final BitSet bitSet = createBitSet(inputFile, maxValue);
        final String outputFile = deriveOutputFile(inputFile);
        writeBitSet(bitSet, outputFile);
    }

    private static BitSet createBitSet(String inputFile, int maxValue)
            throws Exception {

        final FileInputStream stream = new FileInputStream(inputFile);
        final InputStreamReader streamReader = new InputStreamReader(stream);
        final BufferedReader buffReader = new BufferedReader(streamReader);

        String line = null;
        int totalBits = maxValue + 1;
        BitSet bitSet = new BitSet(totalBits);

        try {
            while ((line = buffReader.readLine()) != null) {
                int number = Integer.parseInt(line);
                bitSet.set(number, true);
            }
        } finally {
            buffReader.close();
            streamReader.close();
            stream.close();
        }

        return bitSet;
    }

    private static String deriveOutputFile(String inputFile) {
        String outputFileName = Paths.get(inputFile).getParent().toString()
                + "/output.txt";
        return outputFileName;
    }

    private static void writeBitSet(BitSet bitSet, String outputFile)
            throws Exception {

        final File file = new File(outputFile);
        file.createNewFile();

        final FileOutputStream outputStream = new FileOutputStream(file);
        final OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        final BufferedWriter buffWriter = new BufferedWriter(writer);

        try {
            for (int bitIndex = 0; bitIndex < bitSet.length(); bitIndex++) {
                if (bitSet.get(bitIndex)) {
                    buffWriter.write(Integer.toString(bitIndex));
                    buffWriter.newLine();
                }
            }
        } finally {
            buffWriter.close();
            writer.close();
            outputStream.close();
        }
    }
}

I request reviewers to provide feedback on the following:

Is existing code readable? What are changes required to make it more readable?
Is it advisable to unit test sorting logic by decoupling it from the file-system by introducing appropriate interfaces and using dependency injection?
Can this program be made more reliable and robust?
Can this code be structured differently for the better?
Would you integration test it or unit test it?  Could you explain the reason?


texts: Parallel quicksort algorithm taking way too long

texts:
Below is a Python implementation of the quicksort algorithm using parallelism. It takes about 1 second per every 10 items in the list, which is hilariously unacceptable. Why is it so slow?

from multiprocessing import *

def quicksort(lyst, connection=None):
    if len(lyst) > 1:
        pivot = lyst.pop(len(lyst)-1)
        wall = 0
        for i in range(len(lyst)):
            if lyst[i] <= pivot:
                lyst[wall], lyst[i] = lyst[i], lyst[wall]
                wall += 1
        receiveLeft, sendLeft = Pipe()
        receiveRight, sendRight = Pipe()
        Process(target=quicksort, args=(lyst[:wall], sendLeft)).start()
        Process(target=quicksort, args=(lyst[wall:], sendRight)).start()
        lyst = receiveLeft.recv() + [pivot] + receiveRight.recv()
    if connection:
        connection.send(lyst)
        connection.close()
    return lyst

if __name__ == '__main__':
    quicksort([8,4,6,9,1,3,10,2,7,5])

EDIT
Thanks for the responses. As it turns out, switching to Threads and limiting the number of them I was spawning sped things up. However, my linear version of the algorithm still performed better.


texts:
I want you to pick my code apart and give me some feedback on how I could make it better or more simple. In my opinion this is the best code I have written, being that I'm new to programming. The program is a basic "converter" that has the user input his/her age and it tells how many days, hours, and minutes the user has been alive. Let me know what you think!

import time
import sys

def name():
    name = input("What is your name? ")
    while name.isdigit():
        print("Make sure to enter an actual name.")
        name = input("What is your name? ")
    return name

def user_input():
    while True:
        age = input("What is your age? ")
        try:
            return int(age)
            break
        except ValueError:
            try:
                return float(age)
                break
            except ValueError:
                print("Make sure to enter a real age.")

def again():
    while True:
        again = input("Play again? Yes/No ").lower()
        if again == "no":
            sys.exit(0)
        elif again == "yes":
            break
        else:
            print("That was not an option.")

while True:
    the_name = name()
    age = user_input()
    Days = age * 365
    Hours = Days * 24
    Minutes = Hours * 60
    print("Ok {}, I have your results.".format(the_name))
    time.sleep(2)
    print("If you are {} years of age....".format(age))
    time.sleep(2)
    print("You are {} days old.".format(Days))
    time.sleep(2)
    print("You are {} hours old.".format(Hours))
    time.sleep(2)
    print("You are {} minutes old!".format(Minutes))

    again()

NOTE: If you make a change, please explain to me why and how it works in the most simple way you can, so I understand it better.


texts: Validator and Sanitizer for HTML 5 attribute regex according to current HTML living standard

texts:
According to https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 an HTML 5 attribute name is defined like this:

Attribute names must consist of one or more characters other than
controls, U+0020 SPACE, U+0022 ("), U+0027 ('), U+003E (>), U+002F
(/), U+003D (=), and noncharacters. In the HTML syntax, attribute
names, even those for foreign elements, may be written with any mix of
ASCII lower and ASCII upper alphas.

Creating a class which can handle or sanitize HTML 5 attribute names I have ended up with the following code - especially the following regex:
class AttributeNameValidator
{
    public const ATTRIBUTE_NAME_MATCHER = "/[\s\x{0000}\x{0020}\x{0022}\x{0027}\x{003E}\x{002F}\x{003D}\x{200B}-\x{200D}\x{FDD0}-\x{FDEF}\x{FEFF}[:cntrl:]]+/u";

    /**
     * Checks if a given string is a valid HTML attribute name.
     * @param string $attributeName
     * @return bool: True if the given attribute name is a valid HTML attribute name.
     */
    public static function isAttributeNameValid(string $attributeName): bool
    {
        return (bool)preg_match(self::ATTRIBUTE_NAME_MATCHER, $attributeName);
    }

    /**
     * Sanitizes a string to be a valid HTML5 attribute name.
     * @param string $attributeName
     * @return string
     * @throws NonSanitizeableException
     */
    public static function sanitizeAttributeName(string $attributeName): string
    {
        $sanitizedAttributeName = preg_replace(self::ATTRIBUTE_NAME_MATCHER, '', $attributeName);
        if(!$sanitizedAttributeName) {
            throw new NonSanitizeableException("Failed to sanitize attribute name");
        }
        return $sanitizedAttributeName;
    }
}

My manual tests seem to work well still I am not sure if the regex exactly matches the standard or if I have forgotten something. Is there still something to improve?


texts: Multithreading to allow multiple clients on to a server and client requests handling

texts:
I have to create a client-server JavaFX application using MVC which does many operations consisting mainly in messages exchange.
I'd like to know if this way to handle client acceptance and client requests is good or not.

public class ServerOperations {

// other code

public void serverConnection() {
    Runnable runnable = new AcceptingClients();
    Thread thread = new Thread(runnable);
    thread.setDaemon(true);
    thread.start();
}

public class AcceptingClients extends Thread {

    static final int PORT = 9090;
    private Socket socket = null;

    ServerSocket serverSocket = null;
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            System.out.println("I/O error: " + e);
        }
        while (true) {

            try {
                socket = serverSocket.accept();

                // other code

                Runnable runnable = new ClientRequests(socket, inputStream, outputStream);
                Thread thread = new Thread(runnable);
                thread.setDaemon(true);
                thread.start();

            } catch (IOException e) {
                System.out.println("I/O error: " + e);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ServerRequests.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

public class ClientRequest extends Thread {
  // other code
  public ClientRequest(Socket socket) throws ClassNotFoundException {
         // other code
  }

@Override
public void run() {
       // handling client requests
 }
// other code
}

I want to focus on few parts of this class ServerOperations:

1) Is good to put all those thread in one class for accepting clients and handling requests or is it bad coding (if not, what a good alternative would be)? Using this way may give me problems if I have a lot of clients connected?

2) If i don't extend the class AcceptingClients with Thread I have problem with JavaFX UI thread, I can't add text in TextArea for example etc. I can't understand from where this interference come from, not even using Platform.runLater() makes me append text or interact with my controller's components.

3) To let everything run I have a method in my model where this method serverConnection() is called. When the Server class starts, the first thing it does is to open the server UI and run this method called from the model. Good or not?!
Note: Server class is different from ServerOperations. ServerOperations is a separate classe which just handle client acceptance and requests.


texts: Producer consumer with threads and using boost ring buffer

texts:
I have two threads, one is the producer and other is consumer. My consumer is always late (due to some costly function call, simulated in below code using sleeps) so I have used ring buffer as I can afford to loose some events.

I am looking to see if my locking looks alright and general c++ review comments.

#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <atomic>
#include <boost/circular_buffer.hpp>
#include <condition_variable>
#include <functional>

std::atomic<bool> mRunning;
std::mutex m_mutex;
std::condition_variable m_condVar;

class VecBuf {
    private:
    std::vector<int8_t> vec;

    public:
    VecBuf() = default;
    VecBuf(std::vector<int8_t> v)
    {
        vec = v;
    }
};

std::vector<int8_t> data{ 10, 20, 30 };

class Detacher {
    public:
    template<typename Function, typename ... Args>
    void createTask(Function &&func, Args&& ... args) {
        m_threads.emplace_back(std::forward<Function>(func), std::forward<Args>(args)...);
    }

    Detacher() = default;
    Detacher(const Detacher&) = delete;
    Detacher & operator=(const Detacher&) = delete;
    Detacher(Detacher&&) = default;
    Detacher& operator=(Detacher&&) = default;

    ~Detacher() {
        for (auto& thread : m_threads) {
            thread.join();
        }
    }

    private:
    std::vector<std::thread> m_threads;
};

void foo_1(boost::circular_buffer<VecBuf> *cb)
{
    while (mRunning) {
        std::unique_lock<std::mutex> mlock(m_mutex);

        m_condVar.wait(mlock, [=]() { return !cb->empty(); });

        VecBuf local_data(cb->front());
        cb->pop_front();
        mlock.unlock();
        if (!mRunning) {
            break;
        }
        //simulate time consuming function call and consume local_data here
        std::this_thread::sleep_for(std::chrono::milliseconds(16));
    }

    while (cb->size()) {
        VecBuf local_data(cb->front());
        cb->pop_front();
        if (!mRunning) {
            break;
        }
    }
}

void foo_2(boost::circular_buffer<VecBuf> *cb)
{
    while (mRunning) {
        std::unique_lock<std::mutex> mlock(m_mutex);

        while (cb->full()) {
            mlock.unlock();
            /* can we do better than this? */
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            mlock.lock();
        }
        cb->push_back(VecBuf(data));
        m_condVar.notify_one();
    }
}

int main()
{
    mRunning = true;
    boost::circular_buffer<VecBuf> cb(100);
    Detacher thread_1;
    thread_1.createTask(foo_1, &cb);
    Detacher thread_2;
    thread_2.createTask(foo_2, &cb);
    std::this_thread::sleep_for(std::chrono::milliseconds(20000));
    mRunning = false;
}


texts: Faster way of converting a 1-d table to predefined userdata in Lua

texts:
I have defined a userdata in Lua (Lua version is 5.1) as shown below-

#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>

typedef struct FloatArray {
  int size;
  float values[1];
} FloatArray;

static int new_array(lua_State *L) {
  int n = luaL_checkint(L, 1);
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  a->size = n;
  return 1;
}

I can create a new array of given size by using following Lua code-

a = array.new(10)

Now, I am extending the above function for converting any given 1-d table to array. Please see the code snippet below-

static int new_array_from_table(lua_State *L) {
  luaL_argcheck(L, lua_type(L, -1) == LUA_TTABLE, 1, "'1-d array' expected");

  // get the length of input table
  int n = lua_objlen(L, -1);
  int index;
  float values[n];

  // fetch data and use it to fill the array
  for (index = 1; index <= n; index++) {
    lua_rawgeti(L, -1, index);
    values[index - 1] = (float)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }

  // create new userdata
  size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
  FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
  a->size = n;

  // fill the userdata
  for (index = 0; index < n; index++)
    a->values[index] = values[index];

  return 1;
}

The above code works. However, as you can notice that fetching the table data and filling the userdata are done separately.

I wish to have a better implementation, in which we first create new userdata and then we fill the userdata from fetched data at one step.

In other words, I am looking for a way to do the following-

// get the length of input table
int n = lua_objlen(L, -1);

// create new userdata
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;

// fetch data and use it to fill the array
int index;
for (index = 1; index <= n; index++) {
  lua_rawgeti(L, -1, index);
  a->values[index] = (float)lua_tonumber(L, -1);
  lua_pop(L, 1);
}

I noticed that after creating new userdata, the data is being converted to 0. Any workaround, please?


texts:
I wrote a library that implements LZW compression and decompression. A goal of this project was to help me acquaint myself with modern C++ development practices (I primarily come from a Java background and have a smattering of C experience).
I want to use this library to compress data and stream it over TCP sockets to be decompressed by the recipient, all without storing a compressed version of the full data on either the sender or the recipient's machine (for hobby/non-production purposes).
lzw.hpp
#pragma once

#include <iostream>
#include <optional>
#include <unordered_map>
#include <vector>

namespace lzw {

class lzw_encoder {
public:
  lzw_encoder(std::istream &is, std::ostream &os);

  void encode();

private:
  uint32_t current_code = 0;
  std::string current;

  std::unordered_map<std::string, uint32_t> codebook;
  std::istream &is;
  std::ostream &os;
};

class lzw_decoder {
public:
  lzw_decoder(std::istream &is, std::ostream &os);

  void decode();

private:
  std::vector<std::string> codebook;
  std::optional<uint32_t> prev;
  std::istream &is;
  std::ostream &os;
};
} // namespace lzw

lzw.cpp
#include "lzw.hpp"

namespace lzw {

static constexpr size_t ENCODER_BUFFER_SIZE = 256;

static constexpr size_t DECODER_BUFFER_SIZE = 64;

lzw_encoder::lzw_encoder(std::istream &is, std::ostream &os)
    : is(is), os(os), current_code(0) {
  for (current_code = 0; current_code < 256; ++current_code) {
    codebook[std::string(1, static_cast<char>(current_code))] = current_code;
  }
}

void lzw_encoder::encode() {
  char buffer[ENCODER_BUFFER_SIZE];

  while (true) {
    is.read(buffer, ENCODER_BUFFER_SIZE);
    auto read_length = is.gcount();
    if (read_length == 0)
      break;

    for (size_t i = 0; i < read_length; ++i) {
      current.push_back(buffer[i]);

      auto iter = codebook.find(current);
      if (iter == codebook.end()) {
        codebook[current] = current_code++;

        current.pop_back();
        auto code_val = codebook[current];
        os.write(reinterpret_cast<char *>(&code_val), sizeof(code_val));

        current.clear();
        current.push_back(buffer[i]);
      }
    }
  }
  if (current.size()) {
    auto code_val = codebook[current];
    os.write(reinterpret_cast<char *>(&code_val), sizeof(code_val));
  }
}

lzw_decoder::lzw_decoder(std::istream &is, std::ostream &os)
    : is(is), os(os), prev{} {
  for (int i = 0; i < 256; ++i) {
    codebook.emplace_back(1, static_cast<char>(i));
  }
}

void lzw_decoder::decode() {
  uint32_t buffer[DECODER_BUFFER_SIZE];
  while (true) {
    is.read(reinterpret_cast<char *>(buffer),
            DECODER_BUFFER_SIZE * sizeof(uint32_t));
    auto read_length = is.gcount() / sizeof(uint32_t);
    if (read_length == 0)
      break;

    for (size_t i = 0; i < read_length; ++i) {
      if (buffer[i] < codebook.size()) {
        os << codebook[buffer[i]];
        if (prev) {
          codebook.push_back(codebook[*prev] + codebook[buffer[i]].front());
        }
      } else {
        codebook.push_back(codebook[*prev] + codebook[*prev].front());
        os << codebook.back();
      }
      prev = buffer[i];
    }
  }
}
} // namespace lzw

I plan on replacing the unordered_map in the lzw_encoder with a dictionary trie in a future edit.
Does my code exhibit a reasonable way to use io streams?
I feel that my usage of read and write did not have a feeling of modern C++, and I'm wondering if I am unaware of some standard library tools to help me with binary io. In particular, I don't like that I used
while(true) instead of some condition related to the input streams. Also, I was wondering if there was a way to do binary io without using reinterpret_cast to cast numeric/binary data pointers to char *.


texts: Find a value in a comma delimited String

texts:
Here is a simple WPF converter method designed, where the object is a string, and the parameters are a string, which contain a set of comma separated values. The program return true if the list has the value in and false otherwise.

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            string temp = parameter as string;
            List<String> list = temp.Split(',').ToList();
            string x = value as string;

            return list.Contains(x);
        }
        catch (Exception)
        {

            throw;
        }
    }

Why I am doing this

I was making a WPF Tab Controller, that looks at the type of objects that it can load and opens up different views based on that information. I cannot change the types of stations that are being supplied to me. Several of these stations share a view between all of them even though their type is different, I am using this converter in a Data Trigger in order to show the same view for this list of stations.

            <DataTrigger Binding="{Binding StationState.StationType, Converter={StaticResource BindingInListConvertor}, ConverterParameter={StaticResource FinishingString}}" Value="True">
                <Setter Property="ContentTemplate" Value="{StaticResource FinishingTemplate}" />
            </DataTrigger>

The only other ways I could think of to do this are a multibinding data-trigger, or just a whole lot of them, and figured this would be best because the the possibility of future functionality.

This is my solution for it, is their a better/simpler/cooler way to acomplish this, thanks.


texts: Return values from array A in the order they are in array B

texts:
So my question is the cleanest way to do #product_panels_for below:

class ProductPanel < Struct.new(:product)
end

class ProductPresenter
  def product_panels_for(selected_products)
    selected_products.map do |product|
      product_panels.find { |panel| panel.product.to_s == product }
    end.
      compact
  end

  def product_panels
    [ProductPanel.new(:iphone), ProductPanel.new(:ipad), ProductPanel.new(:ibidet)]
  end
end

ProductPresenter.new.product_panels_for(['ipad', 'iphone']) # => [<ProductPanel product=:ipad>, <ProductPanel product=:iphone>]

This is obviously simplified, but the point is #product_panels_for should return values from product_panels but in the order given in selected_panels. Maybe this is fine is just feels a bit gangly for something that seems conceptually simpler than that.

To be clear the order is defined by the business, it won't be alphabetical or anything nice.

In case anyone's thinking it, yes, I know in Ruby 2.7 I could replace .map...compact with .filter_map, but I'm not on 2.7 yet.

My previous implementation was:

def product_panels_for(selected_products)
  product_panels.select { |pp| selected_products.include?(pp) }
end

which was nice and clean but didn't preserve the order of selected_products.

If the implementation at the top can't be improved on, is there a nice way to use this previous implementation but chain something after the select that sorts the result so the order matches selected_products? I'm just generally curious about a good way to cleanly sort A so its order matches B where B is a list of values for an attributes of A.


texts: Selection Sort implementation using modern C++

texts:
I have written this code for Selection sort. I want to use more C++11, C++14 or C++17. Please sugest some better alternatives.

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

template <typename InputItr>
void selectionSort(InputItr first, InputItr last)
{
  while(first != last)
  {
    InputItr min = std::min_element(first, last);
    if(*min < *first)
    {
      std::swap(*min, *first);
    }
    ++first;
  }
}

template <typename Itr>
void print(Itr first, Itr last)
{
  while(first != last)
  {
    std::cout << *first <<" ";
    ++first;
  }
  std::cout << "\n";
}

int main()
{
  std::vector<int> v({5, 3, 12, 2, 8});
  std::cout << "Original Array :";
  print(v.begin(), v.end());
  selectionSort(v.begin(), v.end());
  std::cout <<"Sorted Array :";
  print(v.begin(), v.end());
  std::cout << '\n';

  std::vector<char> c({'t', 'q', 'a', 'r', 'p'});
  std::cout << "Original Array :";
  print(c.begin(), c.end());
  selectionSort(c.begin(), c.end());
  std::cout <<"Sorted Array :";
  print(c.begin(), c.end());
  std::cout << '\n';

  std::vector<std::string> str({"code", "live", "love", "sing", "create"});
  std::cout << "Original Array :";
  print(str.begin(), str.end());
  selectionSort(str.begin(), str.end());
  std::cout <<"Sorted Array :";
  print(str.begin(), str.end());
  std::cout << '\n';

}


texts: Validating the presence of properties in a document

texts:
How can I reduce cyclomatic complexity of validation and refactor it better way?

Class Document
  def initialize(opts)
    @opts = opts
    return ArgumentError unless valid?
  end

  def valid?
    return false if @opts.nil?
    return false if @opts[:property_1].nil?
    return false if @opts[:property_2].nil?
    return false if !@opts[:property_4].nil? && @opts[:property_3].nil?
    # etc. 12 times more, otherwise valid will return true
    true
  end

  def usage_example
   if @opts[:property_3]
      "#{@opts[:property_3]} #{@opts[:property_1]}"
   else
      "#{@opts[:property_4]} #{@opts[:property_2]}"
   end
  end
end

I am trying to avoid duplication of return false if and somehow perhaps list parameters that I want to verify

Possible interpretation of what I trying to reach is "verify set of rules before processing file"


texts: MVC Controller in Java Swing Apps - Singleton or public static

texts:
This article has left me a little confused.

In explaining a method on how to design MVC into Java Swing apps the author defines the controller class as Singleton and relays a series of calls to the Controller for each operation.

In a view object:

...
Controller.getInstance().setOwner(this);
Controller.getInstance().setNameTextField(this.nameTextField);
Controller.getInstance().setEmailTextField(this.emailTextField);
Controller.getInstance().processForm();
...

And inside the controller class:

public void processForm() {
    result1 = doSomethingWithName(this.nameTextField.getText());
    result2 = doSomethingWithEmail(this.emailTextField.getText());
    this.owner.setResult(result1, result2);
}

I don't understand why this has been made so complex! Wouldn't it be simpler, less error prone and more modular to simply:

Controller.processForm(this, this.nameTextField.getText(), this.emailTextField.getText());

and

public static void processForm(OwnerClass owner, String name, String email) {
    result1 = doSomethingWithName(name);
    result2 = doSomethingWithEmail(email);
    this.owner.setResult(result1, result2);
}

Is anyone familiar with this design pattern? Is there reason to this method?


texts:
As per the instructions are given in MaxCounters-Codility,

  You are given N counters, initially set to 0, and you have two possible operations on them:

  increase(X) − counter X is increased by 1,
  max counter − all counters are set to the maximum value of any counter.

  A non-empty array A of M integers is given. This array represents consecutive operations:

  if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
  if A[K] = N + 1 then operation K is max counter.

I have written this code

public int[] maxCount(int[]A,int N) {
    int[] I = new int[N];
    for (int i = 0; i < A.length; i++) {
        try {
            I[A[i] - 1]++;
        } catch (Exception e) {
            Arrays.sort(I);
            Arrays.fill(I, I[I.length - 1]);
        }
    }
    return I;
}

It gives correct answers for all test cases. Any Idea to do this with time complexity O(N). Its currently on O(N*M).


texts:
I needed a simple and efficient way to use events in my JavaScript code, so I came up with a small event library.

Currently, I'm doing it like this:

// eva.js - The lightweight es6 event library.
var eva = (() => {
  // Prepare local globals
  var eva = {};
  var receivers = [];
  var gid = 0;
  /**
   * Verify the type of a parameter.
   * Throw if the type does not match the expected type.
   * @param {object} item - The argument itself
   * @param {string} name - The name of the argument
   * @param {string} expected - The expected type
   */
  var verifyType = (item, name, expected) => {
    if (typeof (item) !== expected) {
      throw "Argument '" + name + "' has to be of type '" + expected + "'.";
    }
  }
  /**
   * Subscribe to an event.
   * @param {string} name - The name of the event
   * @param {function} action - The event action
   * @returns {number} - The subscription identifier
   */
  var subscribe = (name, action) => {
    verifyType(name, 'name', 'string');
    verifyType(action, 'action', 'function');
    receivers.push({name: name, action: action, id: gid});
    return gid++;
  }
  /**
   * Unsubscribe from an event.
   * @param {number} id - The subscription identifier
   * @returns {boolean} - Whether the subscription has been removed
   */
  var unsubscribe = id => {
    verifyType(id, 'id', 'number');
    var result = false;
    receivers.every((item, index, arr) => {
      if (item['id'] === id) {
        arr.splice(index, 1);
        result = true;
      }
      return !result;
    });
    return result;
  }
  /**
   * Dispatch an event.
   * @param {string} name - The name of the event
   * @param {object} e - The event data
   */
  var dispatch = (name, e) => {
    verifyType(name, 'name', 'string');
    receivers
      .filter(item => name === item['name'])
      .forEach(item => item['action']({event: name, data: e}));
  };
  /**
   * List all receivers.
   * @returns {array} - The receivers
   */
  var list = () => receivers;
  /**
   * Clear all receivers.
   */
  var clear = () => {
    receivers.length = 0;
  };
  // Make functions accessible
  eva.subscribe = subscribe;
  eva.unsubscribe = unsubscribe;
  eva.dispatch = dispatch;
  eva.clear = clear;
  eva.list = list;
  // Return eva object
  return eva;
}());
module.exports = eva;

Since I usually don't write JavaScript code and don't know any best practices and quirks of that language, constructive criticism would be greatly appreciated.


texts:
My program gets some input values and outputs Fibonacci values.

Generally, I'm adding single numbers from the right to left, and I'm saving it in the sum value and get rest of it and add to string. (The value of "second" will always be larger than "first").

Is there some way to speed up my code?

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

string addition(string &first, string &second);

int main()
{
      unsigned int value;
      cin>>value;
      string first="1";
      string second="1";
      string helper;

      if(value==1)
          cout<<"1"<<endl;
      else if(value==2)
          cout<<"1"<<endl;

      for(int i=2; i<value;i++)
      {
            helper=addition(first,second);
            first=second;
            second=helper;
      }
      cout<<helper<<endl;
      return 0;
 }

string addition(string &first, string &second)
{
      string finalValue;
      short moveValue=0;
      unsigned int maximum=0, minimum=0;
      short sum;
      char app;

      maximum=second.length();
      minimum=first.length();

      for(int i=maximum-1;i>=0;i--)
      {
             if(minimum)
             {
                  minimum--;
                  sum=first[minimum]-48+second[i]-48+moveValue;
                  moveValue=sum/10;
                  app=sum%10+48;
                  finalValue=app+finalValue;
             }
             else
             {
                  sum=second[i]-48+moveValue;
                  moveValue=sum/10;
                  app=sum%10+48;
                  finalValue=app+finalValue;
             }
      }

      if(moveValue==1)
      {
           app=moveValue+48;
           finalValue=app+finalValue;
      }
      return finalValue;
}


texts:
I have the following piece of code in my project, and that a few times:

$this->uniqueSessionKey = $settings->get('uniqueSessionKey') ? $settings->get('uniqueSessionKey') : $_SERVER['HTTP_USER_AGENT'] . time();

I was wondering if there's a better way of writing this, especially the part where it checks if $settings->get(...) is not false and then uses the previously checked value. As it uses a database connection it's probably not very efficient checking for the same thing twice.

Is there a better way of writing this? I'm already using the shortest if-else that I'm aware of.
If it's not possible, I will put the $settings->get(...) in a variable anyway, and then check if it's false. I've tried using || but that returned false (?) so I probably did that wrong.

Note that I don't want to check it for multiple values, so I don't need to use for etc.


texts: Optimizing location updates when adding a new object

texts:
I'm trying to keep a bunch of Objects called Machine in their proper order. I was wondering if it'd be possible to further optimize the function HandleLocationCount for performance.
Any general feedback is of course also welcome. The function HandleLocationCount is only executed when a new Machine object is added.
The Machine object is below, it references a Section object, which acts as a container for the various machines.
public class Machine
{
    [Key]
    public int ID { get; set; }

    public string OrderNo { get; set; }

    public Section Section { get; set; }

    public int LocationInSection { get; set; }

    public ForcedLocation ForcedLocation { get; set; } = ForcedLocation.Blank;
}

Section object & enum for completeness; it's an enum instead of a boolean for future proofing:
public class Section
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public string OrderNo { get; set; }

    public IEnumerable<Machine> MachinesInSection { get; set; }
}

public enum ForcedLocation
{
    /// <summary>
    /// Does nothing for the location.
    /// </summary>
    Blank,

    /// <summary>
    /// This entity is always last in the location.
    /// </summary>
    Keep_Last,
}

The function that calls the HandleLocationCount function looks like this; a user is able to manually set the location if needed.
    public Machine Add(Machine entity)
    {
        if (entity.LocationInSection == 0)
        {
            IEnumerable<Machine> AmountMachines = GetMachinesByOrderNoAndSection(entity.OrderNo, entity.Section);
            entity.LocationInSection = handleLocationCount(AmountMachines);
        }

        _machineRepository.Add(entity);

        return entity;
    }

The function that returns the index just searches every machine for their order number & name, the repository itself is just an interface that has a generic index function
public IEnumerable<Machine> GetMachinesByOrderNoAndSection(string orderno, Section section)
    {
        return _machineRepository.Index()
         .Where(m => m.OrderNo == orderno && m.Section == section);
    }

And the code for the location looks like this, it updates older machines if this is needed; else just passes the new location for the machine
    private int HandleLocationCount(IEnumerable<Machine> AmountOfMachines)
    {
        int newLocation = AmountOfMachines.Count() + 1;

        foreach (var Machine in AmountOfMachines)
        {
            int oldLocation = Machine.LocationInSection;
            switch (Machine.ForcedLocation)
            {
                case ForcedLocation.Blank:
                    break;
                case ForcedLocation.Keep_Last:
                    Machine.LocationInSection = AmountOfMachines.Count() + 1;
                    break;
                default:
                    break;
            }

            if (Machine.LocationInSection != oldLocation)
            {
                newLocation = oldLocation;
                Update(Machine);
            }
        }

        return newLocation;
    }


texts: Delete each character in one string that matches any character in another

texts:
I am trying to solve an exercise in which I am given the following function:

/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
 int i, j;

 for (i = j = 0; s[i] != '\0'; i++)
     if (s[i] != c)
       s[j++] = s[i];
 s[j] = '\0';
}

the exercise is:

  Write an alternative version of squeeze(s1,s2) that deletes each
  character in s1 that matches any character in the string s2.

I have came up with this:

#define COPY   1
#define NOCOPY 0

void multisqueeze(char s[], char f[])
{
int i, j,k, state;
i = j = k = 0;
state = COPY;
while (s[i] != '\0')
{
    state = COPY;
    while (f[k] != '\0' && state == COPY)
    {

        printf("s is %c, f is %c\n", s[i], f[k]);
        if (tolower(f[k]) == tolower(s[i]))
        {
            state = NOCOPY;
            printf("Nocopy set \n");
        }
        k++;
    }
    k=0;

    if (state == COPY)
    {
        printf("Copying a character, %c\n", s[i]);
        s[j++] = s[i];
    }
    i++;
}
printf("Loop ended, s is %c\n", s[i]);
s[j] = '\0';
}

This seems to be a valid solution for the problem and outputs the correct answer.  But I have been told that the implementation is messy and not readable because of the use of the state variable and that there are more elegant ways of doing it. I have been trying to wrap my head around it for some time and I simply can't see a way to not use the state variable at all. I think this exercise is from The C programming Language by Brian Kernighan and Dennis Ritchie.


texts:
I'm fairly new to JavaScript. I would like some feedback on the naming and grouping of the following code. Is there any change that will make it more readable?

Template.documentPage.events({
  'click .hint-text': function(e) {
    e.preventDefault()

    var currentHintId = $(e.target).attr('id')
    Session.set('currentHintId', currentHintId)

    $('.hint-popup').show()
  },

  'click .hint-submit': function(e) {
    e.preventDefault()

    var currentHintId = Session.get('currentHintId')
    var popupInput = $('.hint-popup input').val()

    $('#' + currentHintId).text(popupInput)
    Documents.update(this._id, {$set: {content: $('.content').html()}}, function() {
      console.log('Saved.')
    })

    $('.hint-popup').hide()
    $('.hint-popup input').val('Enter text')
  }
})


texts:
I'm trying to recreate strstr in c, my code works but I think it is too long, and it needs some improvement.

#include <stdlib.h>

static int      find_str_indx(char *str, int index, char *str_to_find)
{
    int i;
    int temp;
    int found_index;

    while (str[index] != '\0')
    {
        if (str[index] == *str_to_find)
        {
            temp = index;
            i = 0;
            found_index = index;
            while (str_to_find[i] != '\0' && str[index] != '\0')
            {
                if(str_to_find[i] != str[index])
                    found_index = -1;
                i++;
                index++;
            }
            if (found_index == -1)
                index = temp;
        }
        index++;
    }
    return (found_index);
}

char    *my_strstr(char *str, char *to_find)
{
    char    *found_str;
    int     found_index;
    int     i;

    found_str = (char*)malloc(sizeof(found_str));
    found_index = find_str_indx(str, 0, to_find);
    if (found_index != -1)
    {
        i = 0;
        while (str[found_index] != '\0')
        {
            found_str[i] = str[found_index];
            found_index++;
            i++;
        }
    }
    else
        found_str = NULL;
    return (found_str);
}

UPDATE

I have rewritten the code to get rid of allocating memory inside strstr, as advised by ratchet freak and Jerry Coffin.

char    *my_strstr(const char *haystack, const char *needle)
{
    size_t  needle_len;

    needle_len = strlen(needle);
    while (*haystack)
    {
        if (*haystack == *needle)
        {
            if (!strncmp(haystack, needle, needle_len))
                    return ((char *)haystack);
        }
        haystack++;
    }
    return (NULL);
}


texts: Creating an Enum with a Custom Type in Swift 4.x

texts:
I was in a code review today and someone said, "Why don't you do an enum on that?" I had started to, but conforming to a bunch of protocols seemed like a gigantic PITA and it seemed more error prone than just writing something simple, readable, and maintainable.

That said, I started to fiddle around with it this evening and I can't figure it out.

This is what I've started with:

typealias PolicyType = (filename: String, text: String)

struct Policy {
  static let first = PolicyType(filename: "firstFile.txt", text: "text in first file")
  static let second = PolicyType(filename: "secondFile.txt", text: "text in second file")
  static let third = PolicyType(filename: "thirdFile.txt", text: "text in third file")
}

let thirdPolicyText = Policy.third.text

Is there a more memory efficient, maintainable way to do this with an enum? My primary objective is maintainability.

Below is what I've come up with. It feels hacky and looks like...well, you know:

public struct PolicyType : Equatable, ExpressibleByStringLiteral {
  var filename: String
  var text: String

  //MARK:- Equatable Methods
  public static func == (lhs: PolicyType, rhs: PolicyType) -> Bool {
    return (lhs.filename == rhs.filename && lhs.text == rhs.text)
  }

  //MARK:- ExpressibleByStringLiteral Methods
  public init(stringLiteral value: String) {
    let components = value.components(separatedBy: "|")
    self.filename = components[0]
    self.text = components[1]
  }

  public init(unicodeScalarLiteral value: String) {
    self.init(stringLiteral: value)
  }
  public init(extendedGraphemeClusterLiteral value: String) {
    self.init(stringLiteral: value)
  }
}

enum Policy: PolicyType {
  case first = "testFile1.txt|This is sample text"
  case second = "testFile2.txt|This is more sample text"
  case third = "testFile3.txt|This is more sample text"
}

Policy.third.rawValue.text