texts:
Longtime lurker here. I'm making a pun generator in JavaScript, and I was looking for some feedback/guidance. I don't have much experience building applications with Node, and so a lot of my code feels a bit like rambling. This class is meant to be used like so:

let p = new Phrase("The dog likes cheese.")
p.generatePun().then((response) => {
    console.log(response)
})

Specifically, I think the web api call could be structured better, but I don't quite know how. I'd appreciate any feedback!

Phrase.js

const util = require("./util.js");
const wordsApi = require("./rhymeApi.js");

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

class Phrase {
    constructor(string, badwords = ["the", "on"]) {
        this.tokens = string.split(" ");
        this.badwords = badwords;
    }

    generatePun() {

        let nonBadWordsIndices = [];
        for (let i = 0; i < this.tokens.length; i++) {
            if (!this.badwords.includes(this.tokens[i].toLowerCase())) {
                nonBadWordsIndices.push(i)
            }
        }

        let replaceIndex = util.getRandomElement(nonBadWordsIndices);
        let wordToBePunned = this.tokens[replaceIndex];

        const isCapitalized = wordToBePunned[0] === wordToBePunned[0].toUpperCase();
        const isAllCaps = wordToBePunned === wordToBePunned.toUpperCase();
        const punctuation= wordToBePunned[wordToBePunned.length - 1];
        const isPunctuated = !letters.includes(punctuation);

        if (isPunctuated) {
            wordToBePunned = wordToBePunned.slice(0, wordToBePunned.length - 1)
        }

        return wordsApi.getRhyme(wordToBePunned).then((rhymes) => {
            let rhyme = util.getRandomElement(rhymes).word;
            if (isCapitalized) {
                rhyme = rhyme.replace(/\b\w/g, l => l.toUpperCase())
            }
            if (isAllCaps) {
                rhyme = rhyme.toUpperCase();
            }
            if (isPunctuated) {

                rhyme = rhyme + punctuation
            }

            let punnedPhrase = this.tokens.slice();
            punnedPhrase.splice(replaceIndex, 1, rhyme);
            return punnedPhrase.join(" ")

        }).catch((err) => {
            return "Error in generating pun: " + err;
        });

    }

    toString() {
        return this.tokens.join(" ");
    }
}

module.exports = Phrase;

util.js

let getRandomElement = (array) => {
    return array[Math.floor(Math.random()*array.length)];
}

//returns random int in [0, stop)
let getRandomIntInRange = (stop) => {
    return Math.floor(Math.random()*stop)
}

module.exports = {
    getRandomElement,
    getRandomIntInRange
}

rhymeApi.js

const rp = require('request-promise');

const options = {
    method: 'GET',
    uri: 'https://api.datamuse.com',
    json: true
}

let getRhyme = (word) => {
    let rhymeOptions = Object.assign({}, options);
    rhymeOptions.uri += '/words?rel_rhy=' + word;
    return rp(rhymeOptions)
}

module.exports = {
    getRhyme
}


texts: Compare length of iterator with as few `next` calls as possible. How can I deduplicate this code?

texts:
I'm writing a few simple functions that compare the length of an iterator to an integer, returning as early as possible. Right now I have:

class ILengthComparator:
    def __init__(self, iterator: Iterator):
        self.iterator = iterator

    def has_more(self) -> bool:
        try:
            next(self.iterator)
        except StopIteration:
            return False

        return True

    def __eq__(self, length: int) -> bool:
        if length < 0:
            return False

        if not self.has_more():
            return length == 0

        return self == length-1

    def __gt__(self, length: int) -> bool:
        if length < 1:
            return False

        if not self.has_more():
            return True

        return self > length-1

    def __lt__(self, length: int) -> bool:
        if length < 0:
            return True

        if not self.has_more():
            return False

        return self < length - 1

Clearly this class isn't finished (__neq__, __gte__, __lte__), and anything after the first comparison isn't guaranteed to work (as the iterator may be consumed), but I'm wondering: is it is possible to logically simplify this into a single function with an operator function as an argument (ie operator.eq, operator.lt), or at least just reduce the semi-duplicate parts (ie, every function has a comparison with length against a number, and a case for checking if the iterator is empty - each with a rather ad-hoc return value).

(any suggestions don't need to be recursive or use the has_more method, those were just the first thing I reached for when trying to solve this problem)

Pastebin with the above some quick and dirty unit tests: https://pastebin.com/N65Q2qcJ


texts: Finding the smallest positive number evenly divisible by a range of numbers

texts:
This method finds the smallest positive number that is evenly divisible by all numbers from 1 to 20.

I am wondering if there is a better way to test if all iterations of a for loop completed successfully. When I put the found boolean outside the for loop, it was terminating my while loop prematurely since the break in the for loop goes to the end and executes whatever is below the for loop inside the while loop. It also seems a bit sloppy to subtract the number that is given and then add 1 to it inside the while loop. But if I put the number++ below the for loop after found is set true and I don't need to increment the number anymore. It increments one last time.

For example, for the number 20, the answer is 232792560. But due to the last increment it would return 232792561, which is an incorrect answer.

public int getLowestDiv(int n) {
    //initialize found variable, as we havent found the number yet
    boolean found = false;
    /* initilize the number as what was passed to this method minus 1, since we will increment below*/
    int number = n - 1;

    while (found != true) {
        number++;

        for (int i = 1; i <= n; i++) {
            //for 1 to int that was passed divide the current number and see if its divisible
            if (number % i != 0) {
                break;
            } else if (i == n)
                found = true;
        }
    }
    return number;
}

I have looked through the specs for Java's loops and didn't find anything about handling these type of situations. Specifically, I will loop for a certain number of iterations, testing if something is true, and if not, break, but only execute a particular statement if the for loop passed the condition on all iterations. I would like to see what the status-quo is when it comes to this as I've run into it before.


texts: Create an isolated dependency scope with "overrides" in Asp.Net Core

texts:
Some of the classes in my multi-tenant Asp.Net Core application depend on database repositories which in turn depend on a delegate called GetCurrentTenantKey.

In the normal request pipeline, the GetCurrentTenantKey delegate will be resolved to a Func that returns the tenant key found in the current users auth token.

But then I have a few background tasks that also need access to repositories, and in those cases, the tenant key doesn't come from any "current user", rather I'd like to provide it then and there. I thought the best solution would be to manually bind GetCurrentTenantKey to a local Func, but I don't want to affect the "normal" dependency tree in any way.

This is the class you'll use to create a scope:

public class IsolatedServiceScopeFactory : IServiceScopeFactory
{
    private readonly IServiceCollection _services;

    public IsolatedServiceScopeFactory(IServiceCollection services)
    {
        _services = services;
    }

    public IServiceScope CreateScopeWithOverrides(Func<IServiceCollection, IServiceCollection> overrides)
    {
        var detachedCollection = new ImmutableServiceCollection(_services);

        var collectionWithOverrides = overrides(detachedCollection);

        return collectionWithOverrides.BuildServiceProvider().CreateScope();
    }

    public IServiceScope CreateScope() => _services.BuildServiceProvider().CreateScope();
}

It's intended to be used like this:

using (var serviceScope = _serviceScopeFactory.CreateScopeWithOverrides(x => x
    .AddScoped<GetCurrentTenantKey>(y => () => "any string")
    .AddSingleton<SomeOtherOverride>()
))
{
    // This will be resolved using my "overridden" version of GetCurrentTenantKey
    var myRepository = serviceScope.ServiceProvider.GetRequiredService<IRepository<SomeType>>();
}

The ImmutableServiceCollection class is quite simple:

public class ImmutableServiceCollection : IServiceCollection
{
    private ImmutableList<ServiceDescriptor> _services;

    public ImmutableServiceCollection(IEnumerable<ServiceDescriptor> services)
    {
        _services = services.ToImmutableList();
    }

    public IEnumerator<ServiceDescriptor> GetEnumerator()
    {
        return _services.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Add(ServiceDescriptor item)
    {
        _services = _services.Add(item);
    }

    public void Clear()
    {
        _services = _services.Clear();
    }

    public bool Contains(ServiceDescriptor item)
    {
        return _services.Contains(item);
    }

    public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
    {
        _services.CopyTo(array, arrayIndex);
    }

    public bool Remove(ServiceDescriptor item)
    {
        var removed = _services.Contains(item);
        _services = _services.Remove(item);

        return removed;
    }

    public int Count => _services.Count;

    public bool IsReadOnly { get; } = true;

    public int IndexOf(ServiceDescriptor item)
    {
        return _services.IndexOf(item);
    }

    public void Insert(int index, ServiceDescriptor item)
    {
        _services = _services.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _services = _services.RemoveAt(index);
    }

    public ServiceDescriptor this[int index]
    {
        get => _services[index];
        set => _services = _services.SetItem(index, value);
    }
}

It seems to work, but I'm not sure if I've maybe went about this the wrong way somehow?


texts: Macro enabling Python style 'with' in C++

texts:
I am developing a simple macro that enables Python style 'with' in C++.
I have shamelessly prefixed the macro name with BOOST_ - primarily because there's a similarity to BOOST_FOREACH, and because I didn't want to call it plain WITH.

The motivation are familiar bugs like these:

void bug1() {
    std::unique_lock<std::mutex>(my_mutex);
    // oooops, forgot to give the lock a name
    function_call();
}

void bug2() {
    std::unique_lock<std::mutex> waldo(my_mutex);
    function_call();
    // oooops, forgot to unlock
    other_function_call();
}

void ugly() {
    {
        // intent of explicit scope not as obvious as could be
        std::unique_lock<std::mutex> waldo(my_mutex);
        function_call();
    }
    other_function_call();
}

So here are the questions:

Is this useful to anyone but me?
Is this a bad idea for whatever reason?
Have I overlooked a possibility to implement this in C++03?
Can it be implemented without the is_move_constructible type requirement?
Do you have suggestions for improvement?
(With a twinkle) Should I apply for some speaking time during the C++Now 2015 Lightning Talks and present this?

And here's my implementation:

NOTE: I have considered an alternative signature such as...

BOOST_WITH(type, ...)

...where ... would be the arguments to the constructor. I have decided to stick to this:

#ifndef BOOST_WITH_HPP_INCLUDED
#define BOOST_WITH_HPP_INCLUDED

#include <utility>
#include <type_traits>

// This macro expands to code that can be used in the same way as the standard
// control structures can. Whatever 'exp' returns lives as long as a loop
// variable would in similar context.
//
// Example:
// BOOST_WITH(std::unique_lock<std::mutex>(my_mutex))
//     do_something();
//
// Example:
// BOOST_WITH(Pushed_matrix()) {
//     draw_something();
//     draw_something_else();
// }
#define BOOST_WITH(exp)                                                        \
    if (auto BOOST_WITH_always_true = boost::with_detail::make_true(exp))

namespace boost {
namespace with_detail {

// wraps an object of movable type
// and provides conversion to bool (always true)
template <class T>
struct always_true {
    explicit always_true(T what) : x{std::move(what)} {}
    constexpr operator bool() const { return true; }
    T x;
};

// always_true<T> construction helper
template <class T>
always_true<T> make_true(T&& what) {
    static_assert(std::is_move_constructible<T>::value,
                  "BOOST_WITH requires the scoped object's type to be move "
                  "constructible");
    return always_true<T>{std::forward<T>(what)};
}

}} // namepace boost::with_detail

#endif // BOOST_WITH_HPP_INCLUDED

Finally, a minimal example:

#include "with.hpp"
#include <cassert>
#include <mutex>

// nothing serious, just a prove of concept
struct Lockable {
    Lockable() : locked(false) {}
    void lock() { locked = true; }
    void unlock() { locked = false; }
    bool locked;
};

int main() {
    Lockable the_lock;
    assert(!the_lock.locked);
    BOOST_WITH(std::unique_lock<Lockable>(the_lock))
        assert(the_lock.locked);
    assert(!the_lock.locked);
}


texts: Project Euler #4 in C++: largest palindrome product of two 3-digit numbers

texts:
Project Euler #4

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

Any reviews are accepted.

#include <iostream>
#include <algorithm>
#include <string>
bool isPalindrome(std::string num);
int findLargestProduct();
int main(){
        std::cout << findLargestProduct() << std::endl;
        return 0;
}

bool isPalindrome(std::string  num){
        std::string oldnum = num;
        reverse(oldnum.begin(),oldnum.end());
        if(oldnum == num)
                return true;
        else
                return false;

}

int findLargestProduct(){
        int largest,prod =0;
        for(int i =100;i<=999;i++){
                for(int j =100; j<=999;j++){
                        prod = i*j;
                        if(isPalindrome(std::to_string(prod)) && prod > largest){
                                largest = prod;
                        }
                }

        }
        return largest;
}


texts:
I have a catalogue of activities that are marked based on the age group that they are relevant to. There are 14 checkboxes for checking what grades. K, 1 - 12, and Adult. I have a switch statement to change the K and Adult to a numeric representation.

The following PHP code grabs the grades checked and displays them in consecutive groups.
Aka. K, 1, 2, 3, 5, 6, 7, 10, 11, Adult will display as K - 3, 5 - 7, 10 - Adult.

What I would like to ask is, is this a clumsy solution for my problem? Can I learn to make this more efficient or less prone to issues?

// generated through database, but set manually here for testing
$new_grades_array = array(K, 1, 2, 3, 5, 6, 7, 10, 11, Adult)

// grades related variables
$last = ""; // records previous grade in loop for checking consecutiveness
$display = ""; // concatenated display of results
$conseq = FALSE; // records if previous grade was consecutive

for ($i = 0; $i < count($new_grades_array); $i++):

     // set grade digit for K and Adult
     switch ($new_grades_array[$i]):
           case "K":
               $currentgrade_dig = 0;
               break;
           case "Adult":
               $currentgrade_dig = 13;
               break;
           default:
               $currentgrade_dig = $new_grades_array[$i];
     endswitch;

     // concatenates string to display variable based on situation
     if ($i == 0): // if the first grade listed

          $display = $new_grades_array[$i];

     elseif ($i +1 == count($new_grades_array)): //if the last grade listed

          if ($conseq != FALSE):
               $display .= " - " . $last . ", " . $new_grades_array[$i];
          else:
               $display .= ", " . $new_grades_array[$i];
          endif;

         $conseq = FALSE;

     elseif ($currentgrade_dig - $last ==1): // if consecutive number from previous
          $conseq = TRUE;

     else: // if not a consecutive number

          if ($conseq != FALSE):
               $display .= " - " . $last . ", " . $new_grades_array[$i];
               $conseq = FALSE;
          else:
               $display .= ", " . $new_grades_array[$i];
          endif;
     endif;

     $last = $new_grades_array[$i];

endfor;

print $display;


texts:
Playing with a simple Java Point class where I would like to constrain the X and Y values to be doubles that must be in the range -10 to 10, inclusive. I've written some code, but it's been years since I've written java and I would like to know if this is how it would be written in modern Java:

public class Point {
    private double x;
    private double y;

    public Point(double x, double y) {
        constrain("x", x);
        constrain("y", y);
        this.x = x;
        this.y = y;
    }

    // is there a cleaner/shorter way of handling this, such as a direct way of declaring a
    // subtype of double that I could use in method signatures?
    protected static void constrain(String name, double val) {
        if ( val < -10 || val > 10 ) {
            throw new IllegalArgumentException(name + " must be between -10 and 10");
        }
    }

    public double getX() { return x; }

    public void setX(double x) {
        constrain("x", x);
        this.x = x;
    }

    public double getY() { return y; }

    public void setY(double y) {
        constrain("y", y);
        this.y = y;
    }

    @Override
    public String toString() {
        return ("[" + x + "," + y + "]");
    }
}


texts:
I want to parse a command line using boost.program_options. Most of my command line arguments will be intervals, which I could implement as something like --x-min=2000 and --x-max=2500.

However, I thought about adding a class that can be written to/read from streams that allows me to handle an option of that reads --x=2000:2500. The following code seems to work fine, but I'm not sure if this "range" approach is advisable at all:

#include <iostream>

template<typename T>
struct Interval
{
  /** sep should not be specific to each template instantiation, should it? **/
  static const char sep = ':';
  T lowest;
  T highest;
};

template<typename T>
std::ostream& operator<<(std::ostream& o, const Interval<T>& t)
{
  o << t.lowest << Interval<T>::sep << t.highest;
  return o;
}

template<typename T>
std::istream& operator>>(std::istream& i, Interval<T>& t)
{
  // don't read from failed stream
  if(i.fail())
  {
    return i;
  }

  // read value left of separator
  T l;
  i >> l;

  // read separator
  char c;
  i >> c;
  if (c != Interval<T>::sep)
  {
    i.setstate(std::ios::failbit);
    return i;
  }

  // read value right of separator
  T r;
  i >> r;

  // prefer less-than comparison over >=
  if (r < l)
  {
    i.setstate(std::ios::failbit);
    return i;
  }

  // set given Interval's members
  t.lowest = l;
  t.highest = r;

  return i;
}

using namespace std;

int main()
{
  Interval<double> i;
  i.lowest = 0;
  i.highest = 10;
  cout << "range is " << i << endl << "enter new range: ";
  cin >> i;
  cout << "new range is " << i << endl;
  return 0;
}

This code uses available stream operators for T, which simplifies things, and it looks clean enough so that I think it can't be too wrong.

One potential problem I see is that I cannot constrain one end of x, which would work with individual --x-min and --x-max options. Such an implementation of Interval would need to accept --x=:2500 and --x=2000:. I'd have to add handling of optional values, which could get messy.

Are there any serious pitfalls in my current implementation?
Would you advise to use such a command line format at all?

A possible extension of this could be used to create regularly spaced lists of values, like Matlab's linspace and logspace functions do: --x=0:100:101 and --x=10:1000:20,log.


texts:
I've been working on a safe inserting method for a while, and I think I've found a pretty secure way to do this. Would you CRitters mind taking a look at it and maybe give me some tips to improve my script?

function dbRowInsert($table, $data) {
   require_once('../config.inc.php');

     $buildData = null;
     $countLoop = 1;

     foreach($data as $field) {
          $sep = ($countLoop!=count($data) ? ',' : '') ;
      if((int)$field == $field) {
        $buildData .= (int)$field . $sep;
      } else {
        $buildData .= '"' .mysqli_real_escape_string($conn, (string)$field) . '"' . $sep;
      }
      $countLoop++;
     }

   $fields = array_keys($data);

   mysqli_query($conn, "INSERT INTO" . $table . "(`" . implode('`, `', $fields) . "`)
                        VALUES('" . $buildData . "')");
}


texts:
Reversing an array in Python without using a built-in function:

def reverse(alist):
    end = len(alist)-1
    limit = int(end/2) + 1
    for i in range(limit):
        alist[i],alist[end] = alist[end],alist[i]
        end = end - 1
    return alist

print reverse([1,2,3,4,5,6])


texts: My solution to a competitive programming problem (UVA 10189, Minesweeper)

texts:
This is one of my first competitive programming solutions. The problem it solves is described here; basically, you get a series of grids ("fields"), where . means "no mine" and * means "mine"; you have to compute how many mines are adjacent (8 adjacent squares) to each non-mine square. My solution is correct, but seems pretty complicated for such a simple problem. What could I have done better, taking into account that my only concern is to write the program as quickly and correctly as possible (readability/proper practices don't count here)? You may also separately critique readability/proper practices.

import sys
from itertools import *

data = sys.stdin.read().splitlines()

fields = []
import re
for i in range(0,len(data)):
    match = re.match('(\d+) (\d+)', data[i])
    if match:
        r = int(match.group(1))
        if r != 0:
            fields.append(data[i+1 : i+1+r])

for field in fields:
    for (x,y) in product(range(len(field)), range(len(field[0]))):

        if field[x][y] == '*':
            continue

        count = 0
        for (x_offset, y_offset) in product(range(-1,2), repeat=2):

            if x_offset == y_offset == 0 or x+x_offset < 0 or y_offset+y < 0:
                continue

            try:
                if field[x+x_offset][y+y_offset] == '*':
                    count += 1
            except IndexError:
                pass

        row = list(field[x])
        row[y] = str(count)
        field[x] = ''.join(row)

for i in range(0,len(fields)):
    print("Field #%i:" % (i+1))
    for row in fields[i]:
        print(row)

    if i < len(fields)-1:
        print()


texts:
Can someone tell me how I can improve this code? It works ok, but I feel that I'm using too many pointers.

#include <iostream>
using namespace std;
struct link{
    int data;
    link *next;
};
class link_list{
private:
    int boundaries = 0;
    link *tail;
    link *temp;
    link *head = NULL;
public:

    void add_node(int data){

        temp = new link;
        temp->data = data;
        temp->next = NULL;
        if (head == NULL){
            head = temp;
            boundaries++;
        }
        else{
            link *tail = head;
            while (tail->next != NULL){
                tail = tail->next;
            }
            tail->next = temp;
            boundaries++;
        }
    }
    void delete_b(){
        link *end = head;
        link *next_to_end = NULL;
        while (end->next != NULL){
            next_to_end = end;
            end = end->next;
        }
        next_to_end->next = NULL;
        end = NULL;
        boundaries--;
    }
    void add_front(int data){
        link *ptr = new link;
        ptr->next = head;
        ptr->data = data;
        head = ptr;
        boundaries++;

    }
    void delete_front(){
        link *new_head = head;
        new_head = head->next;
        head = NULL;
        head = new_head;
        boundaries--;

    }

    void add_by_position(int data, int pos){
        link *node = new link;
        link *linker = head;
        node->data = data;
        for (int i = 0; i < pos; i++){
            linker = linker->next;
        }
        node->next = linker;
        linker = head;
        for (int i = 0; i < pos - 1; i++){
            linker = linker->next;
        }
        linker->next = node;
        boundaries++;

    }

    void show(){
        link *sh = head;
        while (sh){ cout << sh->data << endl; sh = sh->next; }

    }

};

int main()
{
    link_list obj;
    obj.add_node(7);
    obj.add_node(5);

    obj.add_node(8);

    obj.show();
}


texts:
I am making a simple counter in assembly. It counts to a billion and exits. However, the performance of this is really horrible. A Java application (that does the same) outperforms it by around 10x. How can I optimize this code?

include 'include/win32ax.inc'

section '.data' Data readable writeable
  outhandle  DD ?
    inhandle   DD ?
    incr DD 0
    numwritten DD ?
    inchar     DB ?
    numread DD ?
section '.text' code readable executable
  start:
     invoke  AllocConsole
      invoke  GetStdHandle,STD_OUTPUT_HANDLE
         mov [outhandle],eax
       invoke  GetStdHandle,STD_INPUT_HANDLE
        mov [inhandle],eax
        invoke  WriteConsole,[outhandle],"Starting...",11,numwritten,0

        jmp loopcount
       loopcount:
       inc [incr]
       cmp [incr], 1000000000;1 billion. ;]
       jne loopcount
       invoke  WriteConsole,[outhandle],"   Done count",13,numwritten,0
       invoke  ReadConsole,[inhandle],inchar,2,numread,0
       invoke ExitProcess,0
.end start


texts: Repeating use of "v." annoys me. Do you see a nicer way?

texts:
This code smells to me, but I don't see the way to clean it up. I see v. mentioned over and over. Any hints would be appreciated!

  #
  # Create a new Value if it doesn't already exist, and initialize the attributes per
  # the parameters of the call.
  #
  def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil)
    prog = Program.find(prog_id)
    attrs = {participant_id: part_id, round_id: round_id, question_id: quest_id}
    v = prog.values.where(attrs).first
    if v.nil?
      v = prog.values.build
      v.assign_attributes(attrs, without_protection: true)
    end
    v.value = new_value
    v.save
    v
  end
end


texts:
Was just wanting some general feedback on the below code regarding
1. Readability
2. Structure
3. Efficiency

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 * Created on 5/27/2016.
 *
 * Simple functions used to reverse either a sentence or a word.
 */

public class Reverse {

    /**
     * The main function is used to retrieve user input and apply it to one of the
     * two reverse functions.
     * @param args Not used in this application.
     */
    public static void main(String[] args){

        Scanner userInput = new Scanner(System.in);

        // Gets user input.
        System.out.print(">>> ");
        String input = userInput.nextLine();

        if(input.contains(" ")) // If contains space its a sentence
            System.out.println(reverse(Arrays.asList(input.split(" "))));
        else
            System.out.println(reverse(input));
    }

    /**
     * Used to reverse the order of given list.
     * @param words The list of words that will be reversed then returned.
     * @return The result of the reversed parameter.
     */
    private static String reverse(List<String> words){
        Collections.reverse(words); // Reverses order of words.
        return String.join(" ", words);
    }

    /**
     * Used to reverse the order of a single word.
     * @param word The string word that will be loaded into a list one character at a time.
     * @return The result of the reversed parameter.
     */
    private static String reverse(String word){
        List<String> letters = Arrays.asList(word.split("")); // Stores each letter of word into list.
        Collections.reverse(letters); // Reverses the order of the list.
        return String.join("", letters);
    }
}


texts:
I wanted to know if the useMemo function extracted like this is valid at all. This is a whole component (Sorry for the imports) that uses useMemo to get a data that is grabbed from the server using GraphQL and react-apollo-hooks.

I extracted the useMemo to prevent bloat in the actual component.

/**
 * The list of grades that the teacher needs to choose first.
 */

import React, { useMemo, memo } from 'react';
import {
  Paper,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  Button,
} from '@material-ui/core';
import { useQuery } from 'react-apollo-hooks';

import Container from '../../../components/Container';
import { GET_ALL_GRADES, Grades } from '../../../graphql/grades';
import { useAuth } from '../../../auth/index';
import { RouteComponentProps, NavigateFn } from '@reach/router';

function useGradesData(data: Grades[], navigate: NavigateFn) {
  return useMemo(() => {
    if (!data) {
      return '';
    }
    return data.map(grade => {
      return {
        async listSubjectFromGrades() {
          await navigate(`/list/${grade.gradeId}`);
        },
        ...grade,
      };
    });
  }, [data, navigate]);
}

function Grade(props: RouteComponentProps) {
  const tenantId =
    useAuth().tenantIds[0] || 'c96bcd70-70bc-4e66-b47d-88a066912a77';
  const { data, loading } = useQuery(GET_ALL_GRADES, {
    variables: {
      tenantId,
    },
  }) as { data: Grades[]; loading: boolean };

  const mappedData = useGradesData(data, props.navigate!);

  if (loading) {
    return
Loading
;
  }

  return (
    <Container>
      <Paper style={{ width: '100%' }}>

          <TableHead>
            <TableRow>
              <TableCell>#</TableCell>
              <TableCell>Nombre del Grado</TableCell>
              <TableCell>Acción</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {!!mappedData &&
              mappedData.map((grade, index) => (
                <TableRow key={grade.gradeId}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>{grade.name}</TableCell>
                  <TableCell>
                    <Button onClick={grade.listSubjectFromGrades}>Ver</Button>
                  </TableCell>
                </TableRow>
              ))}
          </TableBody>

      </Paper>
    </Container>
  );
}

export default memo(Grade);

In addition, you are more than welcome to spot any other improvements in the whole code.


texts: Division without multiplication, addition or division

texts:
In context of preparing for a coding interview, I gave the division problem a go using Java. This is what I came up with. It's a little bit different to other solutions I've come across the interweb.

  Implement integer division without using multiplication or repeated subtraction (i.e. to divide n by d, you man not repeatedly subtract off d from n).

public static int division(int a, int b) {

    // For the basic cases
    if (b == 1) { return  a; }
    if (a == 1) { return  b; }
    if (a == 0 || b== 0) { return  0; }
    if (b > a)  { return  0; }
    if (a == b) { return  1; }

    int result = 0;
    int size = size(a) - 1;
    for (int i = size(a) - size(b); i >= 0; i--) {
        if((a - (b << i) >= 0)) {
            a = a - (b << i);
            result = result + (1 << i);
        }
    }

    return result;
}

public static int size(int a) {
    // The index of the most left 1 in the binary structure
    int temp = new Integer(a);
    int depth = 0;
    while (a > 0) {
        a >>= 1;
        depth++;
    }
    return depth;
}


texts: A defined macro to copy selected values of std::vector to an array using std::copy

texts:
Thought I share this piece of code to the world. But be aware, I am not sure if this piece of code is safe and efficient. Feel free to improve it or give some feedback and suggestions.

#pragma region DOCUMENTATION ON: STD_COPY_VECTOR_TO_ARRAY
//////////////////////////////////////////////////////////////////////////////
// MACRO: STD_COPY_VECTOR_TO_ARRAY( Vector, Position, Length, Array )       //
//                                                                          //
// DESCRIPTION:                                                             //
// A defined macro that is created to copy selected values of std::vector   //
// an array. This defined macro takes 4 arguments.                          //
//                                                                          //
// ARGUMENTS:                                                               //
// Vector - The std::vector that contains the values that will be copied.   //
// Position - Position of the first value from Vector to be copied.         //
// Note: The first value of Position is marked by the value of 0 and not 1. //
// Length - Amount of values to be copied from Vector.                      //
// Array - The Array that the values will be copied to.                     //
//                                                                          //
// TIPS:                                                                    //
// #1 - To copy all values within Vector, set the value of Position to 0    //
// and set the value of Length to the size of Vector (std::vector::size).   //
//////////////////////////////////////////////////////////////////////////////
#pragma endregion
#define STD_COPY_VECTOR_TO_ARRAY( Vector, Position, Length, Array )         \
                                  std::copy( Vector.begin( ) + Position,    \
                                  Vector.begin( ) + Position + Length ,     \
                                  Array )


texts:
I'm using Ed scripts to track changes in a web app I'm developing. Ed scripts are probably the easiest kind of patch file for a computer to parse: detailed explanation of Ed scripts.

I quickly put together the Ruby code below with extremely little thought. I'd like to know what kind of high-level patterns I could use for a problem like this. I'm aware of state machines in an electrical engineering sense, but I'm not aware of the generally-accepted way to apply them in Ruby.

def self.apply_patch(old_text, patch)
  new_text_array = old_text.split("\n")
  patch_array = patch.split("\n")
  i=0
  current_line = 0
  while i < patch_array.length
    #grab the command
    patch_array[i].match(/(\d*),?(\d*)(\w)/)
    first_line = $1.to_i
    last_line = $2.to_i
    command = $3
    if first_line == 0
      first_line = current_line
    end
    if last_line == 0
      last_line = first_line
    end
    case command
    when "a"
      current_line = first_line
      i+=1
      while patch_array[i] != "."
        if patch_array[i] == ".."
          if patch_array[i+2] == "s/.//"
            new_text_array.insert(current_line, ".")
          else
            new_text_array.insert(current_line, "..")
          end
        else
          new_text_array.insert(current_line, patch_array[i])
        end
        current_line+=1
        i+=1
      end
    when "d"
      length = last_line - first_line
      for ii in 0..length
        new_text_array.delete_at(first_line-1)
      end
    when "c"
      length = last_line - first_line
      for ii in 0..length
        new_text_array.delete_at(first_line-1)
      end
      current_line = first_line-1
      i+=1
      while patch_array[i] != "."
        if patch_array[i] == ".."
          if patch_array[i+2] == "s/.//"
            new_text_array.insert(current_line, ".")
          else
            new_text_array.insert(current_line, "..")
          end
        else
          new_text_array.insert(current_line, patch_array[i])
        end
        current_line+=1
        i+=1
      end
    else
      if patch_array[i] == "s/.//"
      else
        raise "invalid ed command"
      end
    end
    i+=1
  end
  new_text = new_text_array.join("\n")
end


texts: Is there a more efficient way of loading views within my java app?

texts:
I'm building a web application in Java.  I'm new to Java, so before I get too far into this... I'm hoping to take advantage of all the experience here and learn the problems with this setup.

My Servlet

package cms.content;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Ben
 */
@WebServlet(name = "EditServlet", urlPatterns = {"/content/edit"})
public class EditServlet extends library.Controller {
    @Override
    public void doGet (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.loadView(request, response, "/content/edit");

        response.getWriter().write("Hi");
        System.out.println("EditServlet loaded");
    }
}

My Controller

package library;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Ben
 */
public class Controller extends HttpServlet {
    public final library.MySQL db;

    public Controller() {
        this.db = new MySQL();
    }

    public void loadView (HttpServletRequest request, HttpServletResponse response, String view)
            throws ServletException, IOException {
        RequestDispatcher dispatcher = request.getRequestDispatcher(view+".jsp");

        response.setContentType("text/html;charset=UTF-8");

        System.out.println("MyServlet::LoadView() success");

        dispatcher.forward(request, response);
    }
}

My View

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

This is edit.jsp

I haven't tried to pass any parameters to this view or anything like that.  But are there any obvious problems or improvements that need to be made?


texts:
I am writing a Tetris game while learning Haskell and I'm trying to make the following code more concise and easier to read. How can I improve it?

Note that the function is not finished yet (There is no check for complete lines, for instance); I currently want to improve its readability.

updateGame :: IORef InputsData -> IORef GameState -> IO()
updateGame keysIORef gameIORef = do
    game <- readIORef gameIORef
    keys <- readIORef keysIORef
    newTime <- getCurrentTime
    elapsed <- getMilliseconds $ diffUTCTime newTime (time game)

    -- Updating current time
    modifyIORef gameIORef (\g -> g {time = newTime})
    game <- readIORef gameIORef

    -- Updating keys cooldown
    modifyIORef gameIORef (\g -> g {keyCooldowns = updateCooldowns (keyCooldowns game) elapsed})
    game <- readIORef gameIORef

    -- Processing side movements
    when (not $ isOnCooldown (keyCooldowns game) (SpecialKey KeyRight)) $ do
        if right keys
          then when (canTetrominoMove (currentTetromino game) (Helpers.R) (tank game)) $ do
            modifyIORef gameIORef (\g -> g {currentTetromino = (currentTetromino g) {x = x (currentTetromino g) + 1}})
            modifyIORef gameIORef (\g -> g {keyCooldowns = addCooldown (keyCooldowns game) (SpecialKey KeyRight) 100})
          else if left keys
            then when (canTetrominoMove (currentTetromino game) (Helpers.L) (tank game)) $ do
              modifyIORef gameIORef (\g -> g {currentTetromino = (currentTetromino g) {x = x (currentTetromino g) - 1}})
              modifyIORef gameIORef (\g -> g {keyCooldowns = addCooldown (keyCooldowns game) (SpecialKey KeyRight) 100})
            else return ()
    game <- readIORef gameIORef

    -- Processing tetromino rotations
    when (not $ isOnCooldown (keyCooldowns game) (Char 'z')) $ do
        if xKey keys
          then when (canTetrominoRotate (currentTetromino game) (Helpers.R) (tank game)) $ do
            modifyIORef gameIORef (\g -> g {currentTetromino = rotateTetromino (currentTetromino g) Helpers.R})
            modifyIORef gameIORef (\g -> g {keyCooldowns = addCooldown (keyCooldowns game) (Char 'z') 200})
          else if zKey keys
            then when (canTetrominoRotate (currentTetromino game) (Helpers.L) (tank game)) $ do
              modifyIORef gameIORef (\g -> g {currentTetromino = rotateTetromino (currentTetromino g) Helpers.L})
              modifyIORef gameIORef (\g -> g {keyCooldowns = addCooldown (keyCooldowns game) (Char 'z') 200})
            else return ()
    game <- readIORef gameIORef

    -- Updating current tetromino falling time
    modifyIORef gameIORef (\g -> g {tetrominoFallingTime = (tetrominoFallingTime g) - elapsed})
    game <- readIORef gameIORef

    -- Making current tetromino fall & restarting current tetromino falling time
    when (tetrominoFallingTime game < 0) $ do
        modifyIORef gameIORef (\g -> g {tetrominoFallingTime = (tetrominoFallingTime g) + getTetrominoFallingSpeed (difficultyLevel g)})
        if canTetrominoFall (currentTetromino game) (tank game)
            then do
                modifyIORef gameIORef (\g -> g {currentTetromino = (currentTetromino g) {y = y (currentTetromino g) - 1}})
            else do
                modifyIORef gameIORef (\g -> g {tank = addTetrominoToTank (currentTetromino game) (tank game)})
                let (currentTetromino', tetrominoBag', rndGen') = drawTetrominoFromBag (rndGen game) (tetrominoBag game)
                modifyIORef gameIORef (\g -> g {currentTetromino = currentTetromino', rndGen = rndGen', tetrominoBag = tetrominoBag'})

    addTimerCallback 1 $ updateGame keysIORef gameIORef
    postRedisplay Nothing


texts: Implementing Ajax deferred/promise patterns

texts:
I have a test case where I want to send a request to the server every time a form field change event occurs.  The implementation below works as expected until I submit the form and check for any empty values (this is the only front-end validation carried out, the rest is done via ajax). If a field is empty I trigger a change event so validation can be carried out on the server side.

In the example below I had to set async=>false so each trigger would work as expected.  I realize this is not ideal and there is a better way around this using deferred/promise patterns.

I am already using somewhat of the pattern .promise and .then however I think I need to use the .when method but I am unsure how to work it into my partially working example.

I am also a little unsure of the amount of request being sent to the server. Is it viable to send this many, i.e.: each time an event occurs?

Please ignore the block comments, I just use them for code separation.

(function($){
var Registration= {};

/**
 *
 * @type type
**/
Registration.fields = {};
/**
 *
 * @type type
**/
Registration.options = {
    cache       : false,
    type        : 'POST',
    dataType    : 'json',
    url         : SITE_URL + '/members/validateFieldOnChange',
    context     : undefined,
    data        : undefined,
    async       : false    // TODO
};
/**
 *
 * @returns {undefined}
**/
Registration.init = function(){

    //caching
    this.Form = $('form#form-register');

    this.fields = {
        username    : this.Form.find('#username'),
        email       : this.Form.find('#email'),
        password    : this.Form.find('#password'),
    };

    // register event handlers
    this.Form.on('change', 'input', $.proxy(this.handleEvents, this));
    this.Form.on('submit', $.proxy(this.handleEvents, this));
};
/**
 *
 * @param {type} event
 * @returns {undefined}
**/
Registration.handleEvents = function(event){
    var type, target

    event.preventDefault();

    type   = event.type;
    target = event.target;

    if(type == 'change'){
        return this.handleChangeEvent(event.target);
    }

    return this.handleSubmitEvent();
};

/**
 *
 * @param {type} target
 * @returns {undefined}
**/
Registration.handleChangeEvent = function(target){

    this.options.context = target;

    this.options.data = { field : target.name, value : target.value}

    return this.validate();
};

/**
 *
 * @returns {undefined}
**/
Registration.handleSubmitEvent = function(){

    // Ugly testcase if values are empty
    // TODO
    if($('#username').val() == ''){
        $('#username').trigger('change');
    }

    if($('#email').val() == ''){
        $('#email').trigger('change');
    }

    if($('#password').val() == ''){
        $('#password').trigger('change');
    }

};
/**
 *
 * @returns {_L2.Registration@call;doAjax@call;then}
**/
Registration.validate = function(){
    return this.doAjax().then(
        $.proxy(this.handleResponse, this),
        $.proxy(this.handleError, this)
    );
};

/**
 *
 * @param {type} response
 * @returns {undefined}
**/
Registration.handleResponse = function(response){

    var field = $(this.options.context);

    if(response.msg == 'success')
    {
        field.addClass('valid');
    }
    else
    {
        field.val('');
        field.attr('placeholder', response.responseError);
        field.addClass('invalid');
    }

    return;
};
/**
 *
 * @param {type} error
 * @returns {undefined}
**/
Registration.handleError = function(error){
    switch(error.code)
    {
        case 404:
            return console.error('Not found');
        break;
        case 401:
            return console.error('un-authorized access!');
        break;
        case 500:
            return console.error('system error!');
        break;
    }
};

/**
 *
 * @returns {unresolved}
**/
Registration.doAjax = function(){
    return $.ajax(this.options).promise();
}

Registration.init();
})(jQuery);


texts:
I have here a program created for pset5 of the CS50 course. The program compiles correctly and does as it should. However, is there any way to improve the run time of this program? Are there any pieces of code that are redundant and can be omitted? And is there anything that can be improved on in general?

/*
 * Implements a dictionary's functionality.
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "dictionary.h"

typedef struct trie
{
    bool word;
    struct trie* children[27];
}trie;

trie* root;

unsigned int wordCount;

// Function that frees a node from the heap.
void freenode(trie* node)
{
    for (int i = 0; i < 27; i++)
    {
        if (node->children[i] != NULL)
        {
            freenode(node->children[i]);
        }
    }

    free(node);
}

/**
 * Returns true if word is in dictionary else false.
 */
bool check(const char* word)
{
    int n = strlen(word);

    trie* node = root;

    for (int i=0; i < n; i++)
    {
        char c = tolower(word[i]);

        if (c == '\'')
        {
            // ASCII a (97) + 26
            c = 123;
        }

        struct trie* current = node->children[c-97];

        if (current == NULL)
        {
            return false;
        }
        else
        {
            node = current;
        }
    }

    if (node->word == true)
    {
        return true;
    }

    return false;
}

/**
 * Loads dictionary into memory.  Returns true if successful else false.
 */
bool load(const char* dictionary)
{
    // Open the dictionary file
    FILE* d = fopen(dictionary, "r");
    if (d == NULL)
    {
        return false;
    }

    root = calloc(1, sizeof(trie));

    trie* node = root;

    for (char c = tolower(fgetc(d)); c != EOF; c = fgetc(d))
    {
        if (c == '\n')
        {
            if (node != root)
            {
                wordCount++;

                node->word = true;

                node = root;
            }
        }
        else
        {
            if (c == '\'')
            {
                c = 123;
            }

            struct trie* current = node->children[c-97];
            if (current == NULL)
            {
                node->children[c-97] = calloc(1, sizeof(trie));

                node = node->children[c-97];
            }
            else
            {
                node = current;
            }

        }
    }

    fclose(d);

    return true;
}

/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
    return wordCount;
}

/**
 * Unloads dictionary from memory.  Returns true if successful else false.
 */
bool unload(void)
{
    freenode(root);
    return true;
}


texts: Read numeric data from a text file using C++

texts:
I need to read Numeric Data from a text file that looks like this:

2
cell X-cord Y-cord
1    1.1    2.2
2    2.1    2.0

The first line indicates the dimension (2 or 3), the second line is just trash. The file can be comma separated, so it may look like this:

3
cell X-cord Y-Cord Z-Cord
1,   1.1,  2.2,    3.2

Of course this is just a short example, the real file has hundreds of thousands of cells, so I want to improve the performance.

When I have a comma separated file I use this code:

std::istringstream iss;     //used iterate over the elements in line
while (std::getline(myfile,line))
{
    replace(line.begin(),line.end(),',',' ');  //this replaces commas for spaces
    iss.str(line);          //this will let us iterate over the elements of line
    if (dim==2)             // if it is a 2d problem
    {
        iss>>cell>>x>>y;
        cell_vector.push_back(cell);
        x_vector.push_back(x);
        y_vector.push_back(y);
    }
    else
    {
        iss>>cell>>x>>y>>z;
        cell_vector.push_back(cell);
        x_vector.push_back(x);
        y_vector.push_back(y);
        z_vector.push_back(z);
    }
iss.clear();  //so that we can assing a new line to it
}

When the file is not comma separated I use this code:

int i=0;      //used to know where to save a
while (my_file>>a)
{
    if (dim==2)
    {
        switch(i%3)
        {
            case 0:
                cell_vector.push_back(a);
                break;
            case 1:
                x_vector.push_back(a);
                break;
            case 2:
                y_vector.push_back(a);
                break;
        }
        i++l;
    }
    else
    {
        //similar but for 3 dimensions
    }
}

I have tested both codes independently and they work fine. However, I don't know beforehand if the file is comma separated or not, so I thought of doing something like this:

int dim;
input_v>>dim;  //to get the information regarding dimension

std::getline(input_v,line);
std::getline(input_v,line);
std::getline(input_v,line);   //3 times to skip the "cell X-cord...." part

bool flag_comma=false;   //used to later determine if file is comma separated
for (int i=0;i<=line.length();i++)
{
    if (line[i]==',')
    {
        flag_comma=true;
        break;
    }
}

if (flag_comma)
{
    //code for comma separated file
}
else
{
    //code for space separated file
}

Everything works fine except that the program only starts to save everything starting from cell 2 onwards... I can't save the data from cell 1.

The only way I found around it is to add this:

    replace(line.begin(),line.end(),',',' ');  //this replaces commas for spaces
    iss.str(line);          //this will let us iterate over the elements of line
    if (dim==2)             // if it is a 2d problem
    {
        iss>>cell>>x>>y;
    }
    else
    {
        iss>>cell>>x>>y>>z;
    }
iss.clear();  //so that we can assing a new line to it

Before the if (flag_comma) part, regardless of the case (comma or space). It is the same piece of code used inside the while loop for the comma separated part.

It is also worth noting that the "comma separated code" works just as well when the file has no commas (i.e. it is space separated). The reason I made the space separated part is because I want to improve performance. I don't really know how complex is the replace function.

So my questions are:

A) Do I really improve performance this way? Instead of just keeping the comma separated version of the code?

B) How can I improve my code (in general)?

C) Is there a better way to get the data from cell 1?

D) Can I improve something memory-wise?


texts:
my shoppingcart is working but i used to many var and functions and i think it looks sloppy. i dont know how to set it right.

here is the Jsfiddle link:

https://jsfiddle.net/z0c1ja37/

can someone help me to put things right in this code?

look at my jsfiddle link there is the full code

$('.productprijzen').hide();
var $select = $('<select>').addClass('keuzes');
$select.append('<option>Kies je optie</option>');
$select.append('<option value="volvo">Volvo</option>');
$select.append('<option value="saab">saab</option>');
$select.append('<option value="peugeot">peugeot</option>');
$select.append('<option value="mazda">mazda</option>');

$select.on('change', function () {
    $parent = $(this).closest(".row");
    $('.productprijzen', $parent).slideDown();

    // prijs en btw laten zien
    var merk = $(this).val();
    var productInfo = oProducten[merk];
    $parent.find('.prijs').html("€" + productInfo.prijs);
    $parent.find('.btw').html(productInfo.btw + "%");

    // berekening van aantal x prijs
    var $aantalKeuze = $parent.find('input.aantal');
    var $subtotaal = $parent.find('.sub');

    $aantalKeuze.bind('keyup mouseup', function () {
        var $subtotaalUiteindelijk = productInfo.prijs * $aantalKeuze.val();
        $subtotaal.html($subtotaalUiteindelijk);

        var totaalBtw6 = 0;
        var totaalBtw21 = 0;
        var $totaal = 0;
        var $subtotaalVeld = $(".sub");
        $subtotaalVeld.each(function () {
            if ($(this).text() !== "") {
                $totaal = $totaal + Number($(this).text());
            }
        });


texts:
I have been trying to code something simple where I call a class with different functions to different paths,
if I call etc:
from lib.utils import GetAllPaths

path = GetAllPaths()
path.test()

with following code:
class GetAllPaths:
    """
    Return file and paths directions
    """

    if platform == "win32":

        def test(self):
            return "C:\\Users\\test.py"

        def test2(self):
            return "C:\\Users\\test2.py"

        def test_flag(self):
            # new_manual_url.flag
            return "C:\\Users\\*test.flag"

        def kill_flag(self):
            # kill_*.txt
            return "C:\\Users\\*kill_*.flag"

        def restart(self):
            # start_*.txt
            return "C:\\Users\\*start_*.flag"

    elif platform == "linux" or platform == "linux2":

        def test(self):
            return "/home/test.py"

        def test2(self):
            return "/home/test2.py"

        def test_flag(self):
            return "/home/*test.flag"

        def kill_flag(self):
            return "/home/*kill_*.flag"

        def restart(self):
            return "/home/*start_*.flag"

My problem here is that I run sometimes my code through Linux and sometimes through Windows, so I have created a if else statement if the script is ran through Linux or Windows,
however I do see huge potential to short this code by alot but I don't know how to apply it where I can choose etc if its linux then use the correct path of "test" for linux or if its windows then use the correct path of "test" for windows


texts:
I've seen many implementations of Sieve of Eratosthenes in Scheme, but I thought I'd try to write one that is both space- and time-efficient:

Space-efficient: I use R7RS bytevectors as a bitset, which encodes odd numbers starting with 3 (so bit 0 = 3, bit 1 = 5, bit 2 = 7, etc.).
Time-efficient: Many implementations scan the table looking for the next viable prime. I instead use first-set-bit (analogous to Integer.numberOfTrailingZeros in Java) to avoid scanning each bit individually.

This code generates prime numbers up to at least n, and usually a handful more. It depends on SRFI 60 for the bitwise operations.

(define (primes-up-to-about n)
  (define table
    (make-bytevector (+ (arithmetic-shift n -4) 1) 255))
  (define len (bytevector-length table))
  (define bitlen (arithmetic-shift len 3))

  (define (clear! i)
    (define q (arithmetic-shift i -3))
    (bytevector-u8-set! table q
                        (copy-bit (bitwise-and i 7) (bytevector-u8-ref table q) #f)))
  (define (next-marked-from i)
    (let loop ((q (arithmetic-shift i -3))
               (m (arithmetic-shift -1 (bitwise-and i 7))))
      (and (< q len)
           (let ((v (bitwise-and (bytevector-u8-ref table q) m)))
             (cond ((zero? v) (loop (+ q 1) -1))
                   (else (+ (arithmetic-shift q 3) (first-set-bit v))))))))
  (define (index->value i)
    (+ i i 3))

  (let loop ((rv '(2)) (i 0))
    (define next (next-marked-from i))
    (if (not next)
        (reverse rv)
        (let ((nextval (index->value next)))
          (do ((j next (+ j nextval)))
              ((>= j bitlen))
            (clear! j))
          (loop (cons nextval rv) next)))))

I'm looking for ways to make the code more compact and/or elegant without sacrificing the space or time efficiency.

In particular, if you can make a SRFI 42 :bitset generator that actually does the equivalent of my next-marked-from, I can just turn the whole function into a list-ec comprehension. What's not to like? :-)

For people who want to test this program in Racket (since there aren't very many R7RS implementations currently around), add the following lines before the function definition:

(require srfi/60)
(define bytevector-length bytes-length)
(define bytevector-u8-ref bytes-ref)
(define bytevector-u8-set! bytes-set!)
(define make-bytevector make-bytes)


texts: Hash calculation for array of long values in C#

texts:
Can the following function be improved in terms of performance?

I am calculating millions of such hashes.
The long array represents a record from data table where all values are encoded as long values. Usually in one calculation stream all arrays are of the same length but in some rare cases this rule does not apply.
Typical length of the array vary from 300 to 1 elements.

I was wondering whether using SIMD (SSE / AVX) instructions in System.Numerics.Vectors library of .NET 4.6 could help?

public static int GetHashCode(long[] array)
{
    if (array == null) return 0;
    unchecked
    {
        int hash = 17;
        for(int i = 0; i < array.Length; i++)
            hash = 31 * hash + array[i].GetHashCode();
        return hash;
    }
}


texts:
This is my program code for comparing if 2 images are the same. It basically uses the open dialog and opens 1 image at a time and puts it in 1 picture box.

I heard that GetPixel() method may be slow. Is there a more efficient and faster way to compare 2 if 2 images are the same?

Bitmap image1 = null;
Bitmap image2 = null;

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e) //first image open
{
    OpenFileDialog openDialog = new OpenFileDialog();
    if (openDialog.ShowDialog() == DialogResult.OK)
    {
        image1 = new Bitmap(openDialog.FileName);
        pictureBox1.Image = image1;
    }
}

private void button2_Click(object sender, EventArgs e) //second image open
{

    OpenFileDialog openDialog = new OpenFileDialog();
    if (openDialog.ShowDialog() == DialogResult.OK)
    {
        image2 = new Bitmap(openDialog.FileName);
        pictureBox2.Image = image2;
    }
}

private void button3_Click(object sender, EventArgs e) //compare button
{
    if (compare(image1, image2))
    {
        MessageBox.Show("Same Image.");
    }

    else
    {
        MessageBox.Show("Different Image.");
    }
}

private bool compare(Bitmap bmp1, Bitmap bmp2)
{
    bool equals = true;
    bool flag = true;  //Inner loop isn't broken

    //Test to see if we have the same size of image
    if (bmp1.Size == bmp2.Size)
    {
        for (int x = 0; x < bmp1.Width; ++x)
        {
            for (int y = 0; y < bmp1.Height; ++y)
            {
                if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
                {
                    equals = false;
                    flag = false;
                    break;
                }
            }
            if (!flag)
            {
                break;
            }
        }
    }
    else
    {
        equals = false;
    }
    return equals;
}


texts:
I am using the book "Realm of Racket" which was written by the people behind the Racket and Dr. Racket projects. It is a great book based on games, similar to the famous "Land of Lisp".

The first game we are supposed to code is the classic "Guess My Number". Following the instructions on the book you end up with this code:

(define lower 1)

(define upper 100)

(define (computer-guess)
  (round (/ (+ lower upper) 2)))

(define (smaller)
  (set! upper (max lower (sub1 (computer-guess))))
  (computer-guess))

(define (bigger)
  (set! lower (min upper (add1 (computer-guess))))
  (computer-guess))

(define (start n m)
  (set! lower (min n m))
  (set! upper (max n m)))

As a matter of practice I decided to try something different. On the previous code, you need to keep using the interactive panel to make new guesses until you reach the number.

As you can see, the algorithm uses binary search.

I am trying the best I can to practice the concept of a recursive definition which generates an iterative procedure.

Hence, I tried to create a code which would keep making new guesses until reaching the determined number. I also tried to create a code that would count the number of tries.

I ended up with the following code which works!

Despite providing the expected output and working fine, I think I could do some refactoring.

I am repeating my self but I do not see how to avoid this:

#lang racket

(define (guess lower-boundary upper-boundary)
  (round (/ (+ lower-boundary upper-boundary) 2)))

(require racket/trace)

(define (game-iter number)
  (define (iter number count lower-boundary  upper-boundary accu)
    (cond ((= (guess lower-boundary upper-boundary) number) (values count (guess lower-boundary upper-boundary)))
          ((> (guess lower-boundary upper-boundary) number)
           (iter  number
                  (add1 count)
                  lower-boundary
                  (sub1 (guess lower-boundary upper-boundary))
                  (guess lower-boundary upper-boundary)))
          (else (iter number (add1 count) (add1 (guess lower-boundary upper-boundary)) upper-boundary (guess lower-boundary upper-boundary)))))
  (trace iter)
  (iter number 0 1 100 (guess 1 100)))

(game-iter 10)


texts:
I have this code that fetches data from a 3rd party api and sends it to my backend to be processed. The 3rd party api needs to target the user's localhost address so it has to come from the front end. I have the code below which works perfectly fine but it looks messy, I'm sure there is a better way to write it. Any suggestions?
I am using fetch for the original request because if I use axios to the 3rd party api I get a cors error.
  getLogs = () => {
    const { user } = this.props.auth;
    fetch(`http://127.0.0.1:60000/onexagent/api/registerclient?name=${user.id}`)
      .then((res) => res.text())
      .then((result) => {
        const regxml = new XMLParser().parseFromString(result);
        if (regxml.attributes.ResponseCode === "0") {
          axios.post(`/api/avaya/register/${user.id}`, regxml);
        }
        console.log(regxml);
      });

    fetch(`/api/avaya/getid/${user.id}`)
      .then((res) => res.text())
      .then((result) => {
        fetch(
          `http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=${result}`
        )
          .then((res) => res.text())
          .then((result) => {
            const xml = new XMLParser().parseFromString(result);
            axios.post(`/api/avaya/getlogs/${user.id}`, xml);
          });
      });
  };

  timer = (time) => {
    const date = new Date(time);
    return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  };

  componentDidMount() {
    this.getLogs();
    this.interval = setInterval(this.getLogs, 5000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }


texts: Gradient Boosting Class/Module using sklearn. (My first Python Module)

texts:
This is a follow-up question to My last question. From then on, I think that I have improved quite a lot thanks to a large amount of feedback I received from my last post. This will be the last time I ask for feedback based on this code. I am looking for any feedback on best practices or coding style but to be honest any kind of tip, information or feedback is greatly accepted. This is my first real python module so I can imagine there is quite a bit of strange or simply wrong stuff.

import os.path
import math
from typing import (Tuple, List)

import pandas as pd
import numpy as np

from sklearn import ensemble
from sklearn.externals import joblib
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

def prepare_dataset(path: str) -> List[pd.DataFrame]:
    df = pd.read_csv(path)
    features = df.drop('days_remaning', axis=1)
    output = df['days_remaning']
    return train_test_split(features, output, test_size=0.3)

class Model():
    def __init__(self, product: str) -> None:
        self.product = product
        self.save_path = f'models/trained_{product}_classifier_model.pkl'
        (self.x_train, self.x_test, self.y_train, self.y_test) = prepare_dataset(
            f'datasets/{product}_dataset.csv')
        if os.path.isfile(self.save_path):
            print(f'Loading Local Model, product: {product}.')
            self.model = joblib.load(self.save_path)
        else:
            print(f'Creating New Model, product: {product}.')
            self.model = self.create_model()

    def create_model(self) -> ensemble.GradientBoostingRegressor:
        '''Create & fit a GB model using GridSearch optimised parameters.'''
        params = dict(
            learning_rate=0.01,
            loss='ls',
            max_depth=4,
            max_features=0.3,
            min_samples_leaf=9,
            n_estimators=500
        )
        model = ensemble.GradientBoostingRegressor(**params)
        model.fit(self.x_train, self.y_train)
        return model

    def use_model(self, data: List[List[int]]) -> np.ndarray:
        return self.model.predict(data)

    def print_model_output(self, data: List[List[int]]) -> None:
        for output in self.use_model(data):
            print('In about {} to {} days you will need to buy new {}.'.format(
                math.floor(output), math.ceil(output), self.product))

    def save_model(self) -> None:
        joblib.dump(self.model, self.save_path)

    def calculate_error_rates(self) -> Tuple[float]:
        train_error = mean_absolute_error(
            self.y_train, self.model.predict(self.x_train))
        test_error = mean_absolute_error(
            self.y_test, self.model.predict(self.x_test))
        return train_error, test_error

    def print_error_rates(self) -> None:
        (train_error, test_error) = self.calculate_error_rates()
        print(f'Training Set Mean Absolute Error: {train_error:.4f}')
        print(f'Test Set Mean Absolute Error: {test_error:.4f}')

    def print_features_importance(self):
        features_labels = np.array(['days_after_restock', 'left_content'])
        importance = self.model.feature_importances_
        features_indexes_by_importance = importance.argsort()
        for feature in features_indexes_by_importance:
            print(
                f'{features_labels[feature]} - {importance[feature] * 100.0:.2f}%')

if __name__ == '__main__':
    EGGS = Model('eggs')
    EGGS.print_error_rates()
    EGGS.print_features_importance()
    EGGS.print_model_output([[2, 7], [7, 2]])


texts: Grouping the results in an array having same name

texts:
results is a list of dict having panel name and work type and price to do that work on that panel. There can be two dicts for same name and work type where one of them is on car model level and another is on car type level. In such cases we would give preference to car model level dict.

output is the group of panels and prices per work type (removing the prices on car type if car model price exist for same panel and work type combination).

results = sorted(results, key=lambda datum: datum['car_model'])

#removing the car type if car model exists.
d = defaultdict(dict)
for l in results:
    d[l['name']+'-'+l['work_type']] = l

results = d.values()

#grouping the results at panel level.
d = defaultdict(dict)
for l in results:
    d.setdefault(l['name'],[]).append(l)

#creating dict such that panel name is key and price_list is array of all the panel prices.
output = []
for key,value in d.iteritems():
    output.append({"name":key,"price_list":value})

Example input:

results = [
        {
            "id":1,
            "car_type":1,
            "car_model":None,
            "name":"Door",
            "work_type":"Dent",
            "price":2300,
        },
        {
            "id":2,
            "car_type":1,
            "car_model":None,
            "name":"Door",
            "work_type":"Scratch",
            "price":1200,
        },
        {
            "id":3,
            "car_type":None,
            "car_model":2,
            "name":"Door",
            "work_type":"Dent",
            "price":2500,
        },
        {
            "id":4,
            "car_type":1,
            "car_model":None,
            "name":"Fender",
            "work_type":"Dent",
            "price":2300,
        },
        {
            "id":5,
            "car_type":1,
            "car_model":None,
            "name":"Fender",
            "work_type":"Scratch",
            "price":1300,
        }
    ]

Expected output:

[{'name': 'Fender',
  'price_list': [{'car_model': None,
    'car_type': 1,
    'id': 5,
    'name': 'Fender',
    'price': 1300,
    'work_type': 'Scratch'},
   {'car_model': None,
    'car_type': 1,
    'id': 4,
    'name': 'Fender',
    'price': 2300,
    'work_type': 'Dent'}]},
 {'name': 'Door',
  'price_list': [{'car_model': 2,
    'car_type': None,
    'id': 3,
    'name': 'Door',
    'price': 2500,
    'work_type': 'Dent'},
   {'car_model': None,
    'car_type': 1,
    'id': 2,
    'name': 'Door',
    'price': 1200,
    'work_type': 'Scratch'}]}]


texts: Best way to write generic factory in Java

texts:
I need to write a factory of generic converters to produce converters from/to MongoDB objects to/from Java objects. Here is my implementation, it doesn't look good enough to me, so I would like to see your advice.

public static <T> Converter<T> getConverter(final Class<T> clazz) {
    return new Converter<T>() {
        public DBObject convert(T t) {
            if (clazz == Manager.class) {
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("age", ((Manager) t).getAge());
                dbObject.append("id", ((Manager) t).getId());
                return dbObject;
            }
            throw new IllegalArgumentException("Unsuported Object Type " + clazz);
        }

        public T convert(DBObject o) {
            if (clazz == Manager.class) {
                int age= Integer.valueOf((String) o.get("age"));
                int id= Integer.valueOf((String) o.get("id"));
                Manager t = new Manager(id, age);
                return (T) t;
            }
            throw new IllegalArgumentException("Unsuported Object Type " + clazz);
        }
    };
}


texts:
I'm trying to create a simple HTTP client. In order to make one that is standard compliant, I must be able to extract user information from a URI and convert it to base64 and send it via an authentication header to the server. I created this demo program to test my progress on this function I've made. Does this program seem sufficient? Is there any major flaws with it? You can see the demo here.

char *base64encode(char *input) {
    int len = strlen(input), padding = (len % 3)?3 - (len % 3):0, n, xlen = 0;
    size_t bitlen = len * 8;
    uint8_t *x = malloc(((int)(bitlen / 24) * 4) + ((padding)?4:0)), i, o;
    for (n = 0; n < len; n++) {
        switch (n % 3) {
            case 0:
                i = (uint8_t)(input[n] >> 2);
                x[xlen++] = i;
                break;
            case 1:
                i = (uint8_t)((input[n-1] & 3) << 4);
                o = (uint8_t)((input[n] & 240) >> 4);
                x[xlen++] = i | o;
                break;
            case 2:
                i = (uint8_t)((input[n-1] & 15) << 2);
                o = (uint8_t)((input[n] & 192) >> 6);
                x[xlen++] = i | o;
                i = (uint8_t)(input[n] & 63);
                x[xlen++] = i;
                break;
        }
        if ((len - n) == ((padding==2)?2:3) && padding > 0) {
            n++;
            break;
        }
    }
    if (padding == 2) {
        i = (uint8_t)(input[n] >> 2);
        x[xlen++] = i;
        i = (uint8_t)((input[n] & 3) << 4);
        x[xlen++] = i;
    } else if (padding == 1) {
        i = (uint8_t)(input[n] >> 2);
        x[xlen++] = i;
        i = (uint8_t)((input[n] & 3) << 4);
        o = (uint8_t)((input[n+1] & 240) >> 4);
        x[xlen++] = i | o;
        i = (uint8_t)((input[n+1] & 15) << 2);
        x[xlen++] = i;
    }
    const char *index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    char *returnString = malloc((int)((bitlen / 24) + padding) * 4 + 1);
    for (n = 0; n < ((int)(bitlen / 24) * 4) + ((padding)?4:0) - padding; n++) {
        returnString[n] = index[x[n]];
    }
    free(x);
    for (;padding > 0; padding--) {
        returnString[n++] = '=';
    }
    returnString[n] = '\0';
    return returnString;
}


texts: Merge sort and selection sort comparison taking too long

texts:
I have this python code that compares merge sort and selection sort, but it is taking "forever."

import time
import random

# Selection Sort Code #
def maxIndex(J):
    return J.index(max(J))

def swap(LCopy, i, j):
    temp = LCopy[i]
    LCopy[i] = LCopy[j]
    LCopy[j] = temp

# Implementation of selection sort
def selectionSort(L):
    for i in range(len(L)-1, 1, -1):
        j = maxIndex(L[0:i+1])
        swap(L, i, j)

# Merge Sort Code #
# Assumes that L[first:mid+1] is sorted and also
# that L[mid: last+1] is sorted. Returns L with L[first: last+1] sorted

def merge(L, first, mid, last):

    i = first # index into the first half
    j = mid + 1 # index into the second half

    tempList = []

    # This loops goes on as long as BOTH i and j stay within their
    # respective sorted blocks
    while (i <= mid) and (j <= last):
        if L[i] <= L[j]:
            tempList.append(L[i])
            #print L[i], "from the first block"
            i += 1
        else:
            tempList.append(L[j])
            #print L[j], "from the second block"
            j += 1

    # If i goes beyond the first block, there may be some elements
    # in the second block that need to be copied into tempList.
    # Similarly, if j goes beyond the second block, there may be some
    # elements in the first block that need to be copied into tempList
    if i == mid + 1:
        tempList.extend(L[j:last+1])
        #print L[j:last+1], "some elements in second block are left over"
    elif j == last+1:
        tempList.extend(L[i:mid+1])
        #print L[i:mid+1], "some elements from first block are left over"

    L[first:last+1] = tempList
    #print tempList

# The merge sort function; sorts the sublist L[first:last+1]
def generalMergeSort(L, first, last):
    # Base case: if first == last then it is already sorted

    # Recursive case: L[first:last+1] has size 2 or more
    if first < last:
        # divide step
        mid = (first + last)/2

        # conquer step
        generalMergeSort(L, first, mid)
        generalMergeSort(L, mid+1, last)

        # combine step
        merge(L, first, mid, last)

# Wrapper function
def mergeSort(L):
    generalMergeSort(L, 0, len(L)-1)

m = 10
n = 100000
n_increments = 9
baseList = [ random.randint(0,100) for r in range(n) ]

i = 0

while i < n_increments:
    j = 0
    sel_time = 0
    mer_time = 0

    while j < m:
        # Do a Selection Sort #
        x = time.clock()

        selectionSort( baseList)

        y = time.clock()

        sel_time += ( y - x )

        random.shuffle( baseList )

        # Do a Merge Sort #

        x = time.clock()

        mergeSort( baseList )

        y = time.clock()

        mer_time += ( y - x )

        random.shuffle( baseList )

        j += 1
    print "average select sort time for a list of", n, "size:", sel_time / m
    print "average merge sort time for a list of", n, "size:", mer_time / m

    j = 0
    i += 1
    n += 10000


texts: Finding the average, the five smallest, and the five largest numbers in an array

texts:
I am going though some PHP arrays exercises on w3resource. I have just completed the following:

Write a PHP script to calculate and display average temperature, five lowest and highest temperatures.

Recorded temperatures : 78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73

Here is my code:
<?php
    echo "
";

    $temperatures = array(78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73);

    function listvalues($value)
    {
        echo "$value, ";
    }

    function printAverage($array)
    {
        $total = 0;
        foreach($array as $element)
        {
            $total += $element;
        }
        echo number_format($total / count($array), 1);
    }

    echo "Recorded temperatures : ";
    array_walk($temperatures, "listvalues");
    echo "
";

    echo "Average Temperature is : ";
    printAverage($temperatures);
    echo "
";

    //sort the temperatures in ascending order for both of the following lists.
    sort($temperatures);

    //print the first 5 values
    echo "List of five lowest temperatures : ";
    for($i = 0; $i < 5; $i++)
    {
        echo "$temperatures[$i], ";
    }
    echo "
";

    //print the last 5 values
    echo "List of five highest temperatures : ";
    for($i = count($temperatures) - 5; $i <= count($temperatures) - 1; $i++)
    {
        echo "$temperatures[$i], ";
    }
    echo "
";

    echo "
";
?>

And here is its output:

Recorded temperatures : 78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73,
Average Temperature is : 69.8
List of seven lowest temperatures : 60, 62, 62, 62, 62,
List of seven highest temperatures : 76, 76, 78, 79, 85,

(I paid no attention to fixing the commas at the end of each part of the output, for now.)
My questions are:

Is this an appropriate use of array_walk()? Is it more appropriate to use a  foreach() loop?

Is ($total / count($array) the easiest way to find the average of an array, and is that the best way to format it for readability?

Can you spot parts of my code which you think could be coded better?


texts:
This is just a classic implementation of a trie using python 3.6, with types. I am a PHP developer, so these are my first attempts with Python.

I know I can improve the readability of my code, it's a bit messy, but I am struggling finding the right way of doing it. I'm sure I am missing a lot of the Pythonic ways in here :-)

from typing import Optional

class Trie:
    def __init__(self):
        self.root = Node(char=None, is_word=False)

    def add(self, word: str) -> None:
        current = self.root
        is_end_of_word = False

        for i in range(0, len(word)):
            char = word[i]
            if i == len(word) - 1:
                is_end_of_word = True

            if not current.children:
                node_to_insert = Node(char, is_end_of_word)
                current.add_child(node_to_insert)
                current = node_to_insert
                continue

            if char not in current.children:
                node_to_insert = Node(char, is_end_of_word)
                current.add_child(node_to_insert)
                current = node_to_insert
            else:
                current = current.children[char]

    def contains(self, word: str) -> bool:
        current = self.root

        for char in word:
            if not current.children:
                return False

            if char in current.children:
                current = current.children[char]
                continue
            else:
                return False

        if not current.is_word:
            return False

        return True

    def remove(self, word: str) -> None:
        current = self.root

        for i in range(0, len(word)):
            char = word[i]
            is_end_of_word = False

            if i == len(word) - 1:
                is_end_of_word = True

            if char in current.children:
                if current.children[char].is_word and is_end_of_word:
                    current.children[char].is_word = False
                    return
                current = current.children[char]
            else:
                return

    def retrieve_all_words(self) -> list:
        return self._retrieve_all_words(self.root, '', [])

    def _retrieve_all_words(self, current: 'Node', word: str, words: list) -> list:
        for child in current.children.values():
            word = word + child.char
            if child.is_word:
                words.append(word)

            if child.children:
                self._retrieve_all_words(child, word, words)
                word = word[:-1]
                continue

            word = word[:-1]

        return words

class Node:
    def __init__(self, char: Optional[str], is_word: bool):
        self.char = char
        self.is_word = is_word
        self.children = {}

    def add_child(self, node: 'Node'):
        self.children[node.char] = node


texts: Fetching categories and subcategories from database

texts:
For a small blog with a limited count of categories, I wrote this code to fetch categories and subcategories from the database.

I used a recursive function to call all categories and sub categories , my goal since I do not have a lot of results is to get them all and display them.

So here is my code. I wish to get your feedback about it.

<?php
//mysql cat table table
/*

  CREATE TABLE `cat` (
  `id` int(255) NOT NULL,
  `id_parent` int(255) DEFAULT NULL,
  `name` varchar(255) NOT NULL,
  `descr` varchar(1000) NOT NULL
  )

 */
//preparing dsn var for PDO
$dsn = 'mysql:host=localhost;dbname=dbname';

//instantiating pdo object
$pdo = new PDO($dsn, "dbuser", 'dbpass');

//make a function take sql and pdo object
function getCats($sql, $pdo) {
    //preparing sql statment
    $stmt = $pdo->prepare($sql);
    //executing our query
    $stmt->execute();
    //saving results in array
    $array = $stmt->fetchAll();
    //checking if array siez is zero we return 1;
    if ($array == []) {
        return 1;
    }
    //var_dump($array);
    //outputting html list for all our cats
    echo "
";
    for ($i = 0; $i < count($array); $i++) {
        echo "
";
        echo $array[$i]['name'];
        echo "
";
        //calling recursive function to get sub cats
        getCats("SELECT * from cat where id_parent = {$array[$i][0]}", $pdo);
    }
    echo '
';
}

//calling the function
getCats("SELECT * from cat where id_parent is NULL", $pdo);


texts: Ajax plugin that binds to click and page load

texts:
I have an app that has a number ajax requests and instead of writing them all out, I created a plugin that takes options based on the request I am making.

I would like the ajax requests to occur when page loads and when the user clicks, mouses over certain buttons.

I decided to use the jquery.bind() method to bind the ajax request to what event takes place. But I am running into a problem when the event is 'load' and the jquery selector is $('window') or document.

Currently, I put a conditional statement to make it work, but then I have write the same function twice just for the 'load' event like this:

(function($) {

    $.fn.getData = function(options) {

        var defaults = {
            eventType : "load",
            // more default options
        }

        var options = $.extend(defaults, options);

        if (options.eventType == "load")
        {
            $.ajax({
                // ajax object with options
            });
        }
        else {
            return this.bind(options.eventType, function() {

                $.ajax({
                    // ajax object with options
                });

            return false;

            });
        }
    }
})(jQuery);

So when on my view pages, I call the plugins like this:

// for click events
$('#selector').getData({
    eventType : 'click',
    // other default options
});

// need ajax when page loads
$('window').getData({
    eventType : 'load',
    // other default options
});

I don't know if there is anyway around writing the function twice and I'm also unsure that it's even good practice to bind event handler to the Window's page load event, but not sure else how to make this plugin flexible to work with browser events like page load and user events like click, mouseover.

Any help would be greatly appreciated.
Thanks


texts: Effectively calculate the result of geometric series

texts:
Given \$f(n) = 1 + x + x^2 + x^3 + \ldots + x^n\$ and the fact that computers take more time when multiplying two numbers than when adding, how can we work out the result with greater efficiency?

#include <iostream>
using namespace std;

double powerWithIntExponent(double base, int exponent)
{
    if(exponent == 0)
        return 1;
    if (exponent == 1)
        return base;

    double result = powerWithIntExponent(base, exponent >> 1);
    result *= result;
    if ((exponent & 0x1) == 1) {
        result *= base;
    }
    return result;
}

double func(double x, int n)
{
    if (x == 0) return 1;
    if (x == 1) return n+1;

    double sum = 0;
    double x_n = 0;
    x_n = powerWithIntExponent(x, n+1);// the Geometric series start from x^0
    sum = (1-x_n)/(1-x);
    return sum;

}
int main(int argc, const char * argv[])
{

    double result = func(2, 2);
    cout<<result<<endl;
    return 0;
}


texts: Enabling stack overflow protection with Y/N prompt

texts:
This asks the user if they would like to enable stack overflow protection. If they enter yes (Y or y), then a Boolean SOProtection is set to true. If they enter no (N or n), then SOProtection is set to false.

If neither Y, y, N nor n is entered, then it clears the input stream (to protect against a case where multiple characters are entered, which results in the input being run through multiple times).

How can this code be optimized (in both efficiency and performance)?

bool SOProtection;
char checkSOProtection;

while(true){
    std::cout << "Stack overflow protection? Y/N: ";
    std::cin >> checkSOProtection;

    if(checkSOProtection == 'Y' || checkSOProtection == 'y'){
        SOProtection = true;
        break;
    }

    if(checkSOProtection == 'N' || checkSOProtection == 'n'){
        std::cout << "Warning: If large values are entered, segmentation fault will occur!" << std::endl;
        SOProtection = false;
        break;
    }
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<char>::digits10);
}


texts: Generate features for future ML analysis of asset returns

texts:
I have built the following code to download stock data from Yahoo Finance. The plan is to then use the built-in pandas functions to calculate metrics from this data that will then be used as features for classification. I also try to calculate whether or not the asset performed better, worse, or equal to the median asset during the next month. I then want to shift this piece of information back to the month the metrics where calculated for. Then from this create a dataset that can be used in a classification algorithm to see if the metrics have any predictive power for whether or not the stock will outperform the median stock for the next month.

I'm new to Python and I feel my code is clunky and inefficient, so I was wondering if anyone could see any obviously better/smoother ways to do this.

My second issue is that I'm not sure if the "time" of the different metrics are preserved through my transformations. It's obvious that for a single sample in the future training set, the metrics all are calculated using the same n-datapoints back in time, and that the recording of whether or not the stock is a winner or loser actually is for that particular stock, one month ahead.

import pandas as pd
import pandas.io.data as web

names = ['AAPL','GOOG','MSFT']

# Functions
def get_px(stock, start, end):
    return web.get_data_yahoo(stock, start, end)['Close']

def getWinners(stock, medRet, retsM):
    return retsM[stock].shift(-1) >= medRet.shift(-1)

def getStd(stock, rets, period):
    return pd.rolling_std(rets[stock],period).asfreq('BM').fillna(method='pad')

pxlol = {n: get_px(n,'1/1/2006','1/1/2014') for n in names}

px = pd.DataFrame(data={n: get_px(n,'1/1/2006','1/1/2014') for n in names})

px = px.asfreq('B').fillna(method = 'pad')
rets = px.pct_change()

# Start
retsM = px.asfreq('BM').fillna(method = 'pad').pct_change()
medRet = retsM.median(axis = 1)

# Generating initial feature dataframes
winners = pd.DataFrame({n: getWinners(n,medRet,retsM) for n in names})
stds = pd.DataFrame({n: getStd(n,rets,20) for n in names})

# Concatentating feature dataframes
retsM = pd.concat(retsM[n] for n in names)
winners = pd.concat(winners[n] for n in names)
stds = pd.concat(stds[n] for n in names)

# Main DataFrame
mainDict = {'Returns':retsM, 'Std.Devs':stds, 'Winners':winners}
frame = pd.DataFrame(mainDict)


texts: Getting name from user, and handling any errors in C

texts:
The primary purpose of this program is to practice catching if the user enters data that does not correspond to expected input. Note if the user enters their name as "123", this is valid as it can be used as an identity, however if users enter only spaces (i.e. "    ") or just a newline char then their input will be rejected. Also note preceding and trailing spaces are OK as long as there is some form of symbol present in the entire name.

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define BUFFSIZE 10

/*Checks to see if name contains actual characters and not just whitespace*/
bool isThereChars(const char * name)
{
    bool charCheck = false;
    for (size_t index = 0; index < BUFFSIZE; ++index) {
        if (name[index] != ' ' && name[index] != '\0')
            charCheck = true;
    }
    return charCheck;
}

void retreiveName(char* name)
{
    for (;;) {
        if (fgets(name, BUFFSIZE, stdin) != NULL) {
            name[strcspn(name, "\n")] = '\0';
            if (name[0] == '\0' || isThereChars(name) == false) {
                printf("Invalid name entered please try again...\n");
            }
            else
                return;
        }
        else
            printf("Memory could not be allocated please try again...\n");
    }
}

int main(void)
{
    char name[BUFFSIZE];

    printf("Enter Name: ");
    retreiveName(name);

    printf("Your name is: %s\n", name);
    printf("Press enter to continue...\n");
    getchar();

    return 0;
}


texts: Generating random permutation with forced change of order (Secret Santa)

texts:
I wrote this function to generate random permutation of input vector, while making sure every element has switched place (for a Secret Santa like purpose).
std::map<std::string, std::string> getPermutation(const std::vector<std::string>& participants)
{
  auto permuted = participants;
  std::random_device rd;
  std::mt19937 g(rd());
  bool correctlyPermuted = false;
  while(!correctlyPermuted)
  {
    std::shuffle(permuted.begin(), permuted.end(), g);
    auto res = std::mismatch(participants.begin(), participants.end(), permuted.begin(), std::not_equal_to{});
    if(res.first == participants.end())
    {
      correctlyPermuted = true;
    }
  }

  std::map<std::string, std::string> result;
  for(int i = 0; i < participants.size(); ++i)
  {
    result[participants[i]] = permuted[i];
  }
  return result;
}

You can run code here. Note that's still work in progress, I'm mostly concerned about the function above.
participants is guaranteed to contain no duplicate elements.
I'm not really concerned with speed - it's supposed to be executed by humans, they are unlikely to notice any performance improvement. Of course, you are welcome to point any obvious performance issues.
However, I'm concerned with the readability of the function, particularly with the use of std::mismatch to find actually matching elements. It feels too clever, but maybe it's just good use of functional programming and I'm overthinking? It also seems too long for a good function (22 lines), but I can't think of how it could be splitted/shortened logically.


texts:
Task: I have two dimensional array of chars filled with random values [a-z] and need to find if the word ala appears vertically, horizontally or diagonally in it.

In my program, I go through all characters and try to find word in all dimensions.

I feel there is more intelligent way to do this task which will:

Work with words of different length without hard-coding.
Replace bunch of if statements so it will be easier.

Any advice?

import java.util.Random;

public class Ala {
    public static void main(String[] args) {
        Random randomGenerator = new Random();
        char[][] arr = new char[50][50];
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = (char) (randomGenerator.nextInt(26)+97);
            }
        }
        for (int i = 0; i < arr.length; i++) {
                System.out.printf("%-3d", i);
        }
        System.out.println();
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j]+"  ");
            }
            System.out.println();
        }
        boolean ala = false;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (j>1) {
                    if (arr[i][j] == 'a' && arr[i][j - 1] == 'l' && arr[i][j - 2] == 'a') {//left
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (j<arr[i].length-2) {
                    if (arr[i][j] == 'a' && arr[i][j + 1] == 'l' && arr[i][j + 2] == 'a') {//rigth
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (i<arr.length-2) {
                    if (arr[i][j] == 'a' && arr[i + 1][j] == 'l' && arr[i + 2][j] == 'a') {//bot
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (i>1) {
                    if (arr[i][j] == 'a' && arr[i-1][j] == 'l' && arr[i - 2][j] == 'a') {//top
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (i<arr.length-2 && j<arr[i].length-2) {
                    if (arr[i][j] == 'a' && arr[i + 1][j + 1] == 'l' && arr[i + 2][j + 2] == 'a') {//bot&rigth
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (i>1 && j>1) {
                    if (arr[i][j] == 'a' && arr[i - 1][j - 1] == 'l' && arr[i - 2][j - 2] == 'a') {//top&left
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (i>1 && j<arr[i].length-2) {
                    if (arr[i][j] == 'a' && arr[i - 1][j + 1] == 'l' && arr[i - 2][j + 2] == 'a') {//top&rigth
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
                if (i<arr.length-2 && j>1) {
                    if (arr[i][j] == 'a' && arr[i + 1][j - 1] == 'l' && arr[i + 2][j - 2] == 'a') {//bot&left
                        ala = true;
                        System.out.println(i + " " + j);
                    }
                }
            }
        }
        System.out.println(ala);
    }
}


texts:
I've written code in C for reading a string of any length, and printing the string. It's one of my first C programs. I posted the program as part of a Stack Overflow question, and received a comment:

... there are many things wrong with your C version.

I'd really like to know what is wrong with the function I have written. Suspects: EOF handling, calling dynamic memory allocation functions too many times.
#include <stdlib.h>
#include <stdio.h>

/* Asks the user for string input.
 * Returns a pointer to the string entered by the user.
 * The pointer must be freed.
 */
char* input()
{
    char *s = malloc(sizeof(char));  /* For the null character */
    if (s == NULL) {
        fprintf(stderr, "Error: malloc\n");
        exit(1);
    }
    s[0] = '\0';

    /* Read characters one by one */
    char ch;
    size_t s_len = 0;
    while((ch = (char) getchar()) != '\n') {
        if (ch == EOF) {
            exit(0);
        }
        s_len++;
        s = realloc(s, (s_len * sizeof(char)) + sizeof(char));
        if (s == NULL) {
            fprintf(stderr, "Error: realloc\n");
            exit(1);
        }
        s[s_len - 1] = ch;
        s[s_len] = '\0';
    }
    return s;
}

int main()
{
    printf("Name: ");
    char *s = input();
    printf("%s\n", s);
    free(s);
    return 0;
}