texts:
This program tokenizes an arithmetic expression specified in infix notation. It is one of my personal projects and I would love to receive expert advice.
After compiling, you can run the program with one command-line argument:
$ tokenize <arith_expr>

This is an example of running the program:
$ tokenize "3^2 + 4.5 * (-2 - 1)"

The tokenizer currently supports these operators + - * / ^.
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Can store an operator or an operand */
struct token {
    char operator;
    float operand;
};

/* Check if given token is an operator */
bool is_operator(char token)
{
    if (token == '+' ||
        token == '-' ||
        token == '*' ||
        token == '/' ||
        token == '^')
        return true;
    else
        return false;
}

/* Remove all spaces from string */
void rmspaces(char *str)
{
    const char *dup = str;
    do {
        while (isspace(*dup))
            ++dup;
    } while (*str++ = *dup++);
}

/* Return first token of given arithmetic expression */
struct token *tokenize(char **expr)
{
    static bool op_allowed = false;
    struct token *token = malloc(sizeof *token);
    if (!token) {
        printf("Error: memory allocation failed");
        exit(EXIT_FAILURE);
    }

    if (op_allowed && is_operator(*expr[0])) {
        token->operator = *expr[0];
        ++(*expr);
        op_allowed = false;
    } else if (!op_allowed && *expr[0] == '(') {
        token->operator = *expr[0];
        ++(*expr);
    } else if (op_allowed && *expr[0] == ')') {
        token->operator = *expr[0];
        ++(*expr);
    } else {
        char *rest;
        token->operand = strtof(*expr, &rest);
        token->operator = '\0';
        if (*expr == rest) {
            printf("Invalid expression\n");
            exit(EXIT_FAILURE);
        }
        strcpy(*expr, rest);
        op_allowed = true;
    }

    return token;
}

/* Handle command line arguments */
int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("Usage:   %s <arith_expr>\n"
            "Example: %s \"5 2 3 * +\"\n",
            argv[0], argv[0]);
        exit(EXIT_FAILURE);
    }

    char *expr = argv[1];
    rmspaces(expr);
    struct token *token;
    while (expr[0] != '\0') {
        token = tokenize(&expr);
        if (token->operator == '\0') // token is operand
            printf("%f\n", token->operand);
        else
            printf("%c\n", token->operator);
    }

    return EXIT_SUCCESS;
}


texts:
Problem Statement
In a School, Chocolate bars have to be distributed to children waiting in a queue. Each Chocolate bar is rectangular in shape. Consider its side lengths are integer values.
The distribution procedure is as follows:-
If bar is not square in shape, then the largest possible square piece of Chocolate is broken and given to the first child in queue.
If bar is square in shape, then complete bar is given to the first child in queue.
Once a child receives his share of Chocolate, he leaves the queue. The remaining portion of the Chocolate bar is dealt in same fashion and the whole or a portion of it is given to the next child in the queue.
School has got a carton of Chocolate bars to be distributed among the children all over the School. The Chocolate bars in the carton are of different sizes. A bar of length i and breadth j is considered to be different from a bar of length j and breadth i. For every i such that \$M \le i \le N\$ and every j such that \$P\le j \le Q\$ (where M, N, P and Q are integers). Each Chocolate bar in carton is unique in length (i) and breath(j).
Given the values of M, N, P and Q (where M, N values are the ranges for length of Chocolate and P, Q values are the ranges for breadth of the chocolate). Find the number of children who will receive Chocolate from the carton.
Input Specification:
M, N, P, Q are of integer type (M, N values are the ranges for length of chocolate bar. P, Q values are the ranges for breadth of chocolate bar).
Output Specification:
Number of children who will receive Cadbury bar from the carton.
M = 5, N = 6, P = 3, Q=4 Here, i can be from 5 to 6 and j can be from 3 to 4. So the four bars will be in carton of sizes 5x3, 5x4, 6x3, 6x4.
First we choose a Cadbury bar of size 5x3 → first child would receive 3x3 portion ( remaining 2x3 portion ) → next child would receive 2x2 portion ( remaining 2x1 portion ) → now the remaining portion are 2 square pieces of (1x1), which can be given to 2 more children
So the Cadbury bar with the size of 5x3 can be distributed to 4 children.
Similarly we can find out number of children for rest of the combinations (i.e. 5x4, 6x3, 6x4) in the given range as follows

Can anyone suggest improvements?
m, n, p, q = raw_input().split(":")
ll = int
bb = int
count = 0

def cadbury(m, n, p, q):
    leng = [m, n]
    brd = [p, q]
    for l in leng:
        for b in brd:
            call(l, b)

def call(l, b):
    #print l,b
    global count
    area = l * b
    if l > b:
        bb = l
        rem = bb - b
        #print rem
        rem_part1 = rem
        #print rem_part1
        rem_part2 = b
        #print rem_part2
        l = rem_part1
        #print l
        b = rem_part2
        #print b
        if l != b:
            if (l==1) or (b==1):
                count += 1
                count += (l*b)
                #print count
                return
            else:
                count += 1
                #print count
                call(l, b)
        if l==b:
            count+=2
            #print count
            return
    elif b > l:
        ll = b
        #print ll
        rem = ll - l
        #print rem
        rem_part1 = rem
        #print rem_part1
        rem_part2 = l
        #print rem_part2
        l = rem_part1
        #print l
        b = rem_part2
        #print b
        if l != b:
            if (l==1) or (b==1):
                count += 1
                count += (l*b)
                #print count
                return
            else:
                count += 1
                #print count
                call(l, b)
        if l==b:
            count+=2
            #print count
            return
cadbury(int(m), int(n), int(p), int(q))
print count


texts: Scraping StackOverflow's questions with Node.js

texts:
I'm new to node and web scraping in general but with some research I've written this working code.

My goal is to get all questions from X Stack Overflow's pages sorted by most rated and save that data locally to use on another project to plot charts and other analytical stuff.

How can I improve it in both readability and perfomance?
Any convention or language/technology nuance that I got wrong?

const CHEERIO = require('cheerio');
const REQUEST = require('request');
const JSONFRAME = require('jsonframe-cheerio');
const CORES = require('os').cpus().length;
const CLUSTER = require('cluster');
const FS = require('fs');
const LAST_PAGE_TO_SCRAPE = 10;
const QUANTITY_OF_PAGES_PER_WORKER = 1;

const BASE_URL = 'https://stackoverflow.com/questions?page=';
const URL_ORDERING = '&sort=votes';

if (CLUSTER.isMaster) {
    let nextPage = 1;
    for (let i = 0; i < CORES; i++) {
        CLUSTER.fork({ startingPoint: nextPage });
        nextPage += 1;
    }

    CLUSTER.on('online', (worker) => {
        console.log(`Worker ${worker.process.pid} is now working.`);
    });

    CLUSTER.on('exit', (worker, code, signal) => {
        if (code !== 0) {//restart
            console.log(`Worker ${worker.process.pid} died. Restarting.`);
            CLUSTER.fork({ startingPoint: worker.process.env.startingPoint });
        } else {//scrape next X pages
            console.log(`Worker ${worker.process.pid} finished it's work succesfully.`);
            if (nextPage <= LAST_PAGE_TO_SCRAPE) {
                CLUSTER.fork({ startingPoint: nextPage });
                nextPage += QUANTITY_OF_PAGES_PER_WORKER;
            }
        }
    });
} else {
    let workerStartingPoint = parseInt(process.env.startingPoint);
    for (let i = workerStartingPoint; i < workerStartingPoint + QUANTITY_OF_PAGES_PER_WORKER; i++) {
        REQUEST(BASE_URL + i + URL_ORDERING, function (error, response, html) {
            if (error) {
                process.exit(workerStartingPoint);//error code is where the worker should start again
            }
            let $ = CHEERIO.load(html);
            JSONFRAME($);
            let frame = {
                questions: {
                    _s: "#questions .question-summary",
                    _d: [{
                        "votes": ".statscontainer .stats .vote .votes .vote-count-post strong",
                        "answers": ".statscontainer .stats .status strong",
                        "views": ".statscontainer .views",
                        "title": ".summary h3 a",
                        "tags": [".summary .tags a"],
                        "url": ".question-hyperlink @ href",
                        "user": {
                            "name": ".summary .started .user-info .user-details a",
                            "profile-link": ".summary .started .user-info .user-details a @ href",
                            "reputation": ".summary .started .user-info .user-details .-flair .reputation-score"
                        },
                        "date asked": ".summary .started .user-info .user-action-time .relativetime"
                    }]
                }
            }
            let questions = $('body').scrape(frame, { string: true });
            FS.writeFile('page-' + i + '.json', questions, function (error) {
                if (error) {
                    process.exit(workerStartingPoint);
                }
                process.exit(0);
            })
        });
    }
}

If you're going to run this,don't set the LAST_PAGE_TO_SCRAPE too large because your IP is going to get temporarily blocked by SO.


texts:
I have a select case that checks against a string variable.  It's starting to get large and I am wondering if there is a better way of doing this?

Here is a sample of the Select Case statement:

Select Case Param.ToLower
    Case "dashboard_home_vm"
        Return _Locator.DashboardHome_VM
    Case "job_list_vm"
        Return _Locator.JobList_VM
    Case "job_add_vm"
        Return _Locator.JobAdd_VM
    Case "client_add_vm"
        Return _Locator.ClientAdd_VM
    Case "client_list_vm"
        Return _Locator.ClientList_VM
    Case "client_report_vm"
        Return _Locator.ClientReport_VM
    Case "employee_add_vm"
        Return _Locator.EmployeeAdd_VM
    Case "employee_certification_vm"
        Return _Locator.EmployeeCertification_VM
    Case "employee_list_vm"
        Return _Locator.EmployeeList_VM
    Case "employee_report_vm"
        Return _Locator.EmployeeReport_VM
    Case "employee_role_vm"
        Return _Locator.EmployeeRole_VM
    Case "employee_timeslip_vm"
        Return _Locator.EmployeeTimeslip_VM
    Case "product_add_vm"
        Return _Locator.ProductAdd_VM
    Case "product_category_vm"
        Return _Locator.ProductCategory_VM
    Case "product_list_vm"
        Return _Locator.ProductList_VM
    Case "product_type_vm"
        Return _Locator.ProductType_VM
    Case "product_unit_vm"
        Return _Locator.ProductUnit_VM
    Case "tracking_stock_vm"
        Return _Locator.TrackingInStock_VM
    Case "tracking_list_vm"
        Return _Locator.TrackingList_VM
    Case "tracking_site_vm"
        Return _Locator.TrackingOnSite_VM
    Case "vendor_add_vm"
        Return _Locator.VendorAdd_VM
    Case "vendor_list_vm"
        Return _Locator.VendorList_VM
    Case "vendor_report_vm"
        Return _Locator.VendorReport_VM
    Case Else
        Return Nothing
End Select

This actual list will be about 50 - 80 comparisons.  Is this the fastest way to do this or is there a better way?


texts: React.js hook to validate a form on submission

texts:
I am fooling around with hooks in React and I'm stumbling against decisions that I need to make regarding implementation. Below is the code for the custom useForm hook which can be used to hook up forms to validation using Yub schema's.

Currently you can pass a callback function to the useForm that gets called when all the values are valid but this is where I'm not 100% sure what the best approach would be. Callback pattern or a promise or something I have not thought of?

I use flow for type annotations and I would love you guys to give me some feedback. Please do bash it!

import { useState } from 'react'
import { mapYubValidationSchemaErrors } from '@domain/helpers'

type YubValidationSchema = any

function useForm(validationSchema: YubValidationSchema, callback: () => void) {
  const [values, setValues] = useState({})
  const [errors, setErrors] = useState({})

  async function handleSubmit(event: SyntheticEvent<HTMLFormElement>) {
    event.preventDefault()

    try {
      await validationSchema.validate(values, { abortEarly: false })
      callback()
    } catch (errorResult) {
      setErrors(
        mapYubValidationSchemaErrors(errorResult.inner),
      )
    }
  }

  function handleChange(event: SyntheticInputEvent<HTMLInputElement>) {
    event.persist()

    const newValues = {
      ...values,
     [event.target.name]: event.target.value,
    }

    setValues(newValues)
  }

  return {
   values,
   errors,
   handleSubmit,
   handleChange,
  }
}

export default useForm

The code to use it can be as follows

function onValidated() {
  // Do something
}

const {
  errors,
  handleChange,
  handleSubmit,
} = useForm(validationSchema, onValidated)


texts: Variant of 2-SUM Problem using Hashtable with multi-threading

texts:
I am doing a Coursera assignment on Hashtable and my solution is taking too long to run. Here is the problem as described in the assignment:

The goal of this problem is to implement a variant of the 2-SUM algorithm covered in this week's lectures.
The file contains 1 million integers, both positive and negative (there might be some repetitions!).This is your array of integers, with the ith row of the file specifying the ith entry of the array.
Your task is to compute the number of target values t in the interval [-10000,10000] (inclusive) such that there are distinct numbers x,y in the input file that satisfy x+y=t

Here is my entire Python code:
from collections import defaultdict
import threading

def hash_fn(n):
    M=1999993
    return n%M

def two_sum_present(target):
    global ans
    bool=True
    for x in nums:
        y = target-x
        if y in my_hash_table[hash_fn(y)] and y!=x:
            bool=False
            ans+=1
            return 1
    if bool == True:
        return 0
f = open('_6ec67df2804ff4b58ab21c12edcb21f8_algo1-programming_prob-2sum.txt')
nums=[]
my_hash_table = defaultdict(list)
for line in f.readlines():
    num = int(line.split('\n')[0])
    nums.append(num)
    my_hash_table[hash_fn(num)].append(num)

ans=0
for nr in range(-10000, 10001):
    thr = threading.Thread(target = two_sum_present, args=(nr,))
    thr.start()

print(ans)

Notes:

I found a page for the same problem here, but this solution uses neither hashing nor binary search, so it should take longer than my solution. This solution is essentially this:
 ans = sum(any(n-x in nums and 2*x != n for x in nums) for n in range(-10000, 10001))

The text file can be found here. if someone is interested. But think of it as a  big text file with 1M lines having 1 integer(+ve or -ve) on each line.

'distinct' as mentioned here only means that x+x=t is not a valid 2-sum pair; but two (x, y) pairs where x and y are not same constitute a valid pair


texts:
The base64 decode algorithm is taken directly from Base64 wiki page. This exercise is meant to help me learn Rust, so any pointers in that general direction are very welcome. :)

fn main() {
    println!("{}",
         hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"));
}

fn hex_to_base64(hex_string: &str) -> String {
    println!("Converting {} from hex to base64", hex_string);
    let alphabet: Vec<char> =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".chars().collect();

    // Decode the input string from hex into individual bytes
    let input_chars: Vec<char> = hex_string.chars().collect();
    let mut decoded_bytes: Vec<u8> = Vec::new();

    for i in 0..hex_string.len() {
        if i % 2 != 0 { continue }
        let first_byte = input_chars[i].to_digit(16).unwrap() as u8;
        let second_byte = input_chars[i + 1].to_digit(16).unwrap() as u8;
        println!("Decoding 0x{}{} to bytes:", input_chars[i], input_chars[i + 1]);
        let byte = (first_byte << 4) | second_byte;
        println!("    {}", byte);
        decoded_bytes.push(byte)
    }

    // Encode the decoded bytes into Base64
    let mut output = String::from("");

    let mut b: u8;
    for i in 0..decoded_bytes.len() {
        if i % 3 != 0 { continue }
        b = (decoded_bytes[i] & 0xFC) >> 2;
        output.push(alphabet[b as usize]);
        b = (decoded_bytes[i] & 0x03) << 4;
        if i + 1 < decoded_bytes.len() {
            b |= (decoded_bytes[i + 1] & 0xF0) >> 4;
            output.push(alphabet[b as usize]);
            b = (decoded_bytes[i + 1] & 0x0F) << 2;
            if i + 2 < decoded_bytes.len() {
                b |= (decoded_bytes[i + 2] & 0xC0) >> 6;
                output.push(alphabet[b as usize]);
                b = decoded_bytes[i + 2] & 0x3F;
                output.push(alphabet[b as usize]);
            } else {
                output.push(alphabet[b as usize]);
                output.push('=');
            }
        } else {
            output.push(alphabet[b as usize]);
            output.push_str("==");
        }
    }
    return output
}

#[test]
fn test_hex_to_base64() {
    assert!(hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d") == String::from("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"));
}


texts:
I'm currently working on a natural language processing project and I have two ArrayLists<String> where each ArrayList contains a verb at index 0, a noun at index 1 and a noun at index 2 (repeat). I'm trying to find any two nouns in the first list that is present consecutively in the second by using:

 for(int i = 1; i<finalKnowledgeGraph.size(); i+=3) {
      for(int j = 1; j<finalKnowledgeGraph.size(); j+=3) {
           for(int k=1; k<storeAsserions.size(); k+=3) {
               if(finalKnowledgeGraph.get(i).equals(storeAsserions.get(k)) && finalKnowledgeGraph.get(j+1).equals(storeAsserions.get(k+1))){
                   System.out.println("Found one");
               } else if(finalKnowledgeGraph.get(i+1).equals(storeAsserions.get(k)) && finalKnowledgeGraph.get(j).equals(storeAsserions.get(k+1))) {
                   System.out.println("Found another");
               }
            }
        }
    }

However, this code has cubic complexity and both ArrayLists are thousands of lines long. I'm wondering if anyone has any tips on how I could go about speeding up this process. Also, I know virtually nothing about optimization so if you do have some help please break it down relatively simply.
One of my friends recently suggested a HashMap and searching through that but in my head that's simply pushing the search problem from one data-structure to another


texts: K&R 2-7 - Invert a bitfield from a number

texts:
This is my solution to the Exercise 2-7 of K&R C book. The assignment is:

  Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

Note: It's assumed that the rigthmost bit of a number has position 0.

Example: If x = 8 (00001000 in binary), p = 2 and n = 3, the result should be 20 (00010100), because bits 2, 3 and 4 are inverted.

Code:

#include <stdio.h>

unsigned invert(unsigned x, int p, int n);

int main(void)
{
    // just a test
    printf("%u\n", invert(8, 2, 3));
    return 0;
}

unsigned invert(unsigned x, int p, int n)
{
    /* The right part makes a mask with 1's under the
       desired bits to be inverted. Then, they're inverted
       by X0Ring it and x.
    */
    return x ^ (~(~0 << n) << p);
}


texts:
I wrote cat program in x86 NASM and I would like to know if there is anything that can be improved.

This implementation of cat supports:

Reading from stdin.
Multiple arguments.

I checked few cases and program behaves exactly like original cat command.

I was thinking if I should add labels like write even if I wouldn't jmp to them, so code would be cleaner.

Code:

section .text
    global _start

_start:
    ;esi=1
    mov esi, 1

    ;if(argc==1)
    ;goto open
    cmp dword [esp], 1
    jnz open

    ;else
    ;fd=STDIN_FILENO
    mov dword [fd], 0
    jmp read

open:
    ;fd=open(path,oflag)
    mov eax, 5
    mov ebx, [esp+esi*4+4]
    mov ecx, 0
    int 0x80
    mov [fd], eax

read:
    ;bytes_read=read(fd,buf,BUFSIZE)
    mov eax, 3
    mov ebx, [fd]
    mov ecx, buf
    mov edx, BUFSIZE
    int 0x80

    ;write(STDOUT_FILENO,buf,bytes_read)
    mov edx, eax
    mov eax, 4
    mov ebx, 1
    mov ecx, buf
    int 0x80

    ;if(bytes_read!=0)
    ;goto read
    cmp edx, 0
    jnz read

    ;close(fd)
    mov eax, 6
    mov ebx, [fd]
    int 0x80

    ;esi++
    inc esi

    ;if(esi<argc)
    cmp dword esi, [esp]
    jl open

exit:
    mov eax, 1
    mov ebx, 0
    int 0x80

section .data
    BUFSIZE equ 1024

section .bss
    buf resb BUFSIZE
    fd resd 1


texts: Is this file a good starting point for accessing data inside this json file via javascript classes?

texts:
I was given a spreadsheet of data that I turned into a CSV file and then converted it into a JSON file.
I threw it into my application and I am processing it in the following manner:
const fs = require("fs");

class DataRepository {
  constructor(filename) {
    if (!filename) {
      throw new Error("Creating a repository requires a filename");
    }

    this.filename = filename;
    try {
      fs.accessSync(this.filename);
    } catch (error) {
      console.error("data does not exist");
    }
  }

  async getAll() {
    // Open the file called this.filename
    return JSON.parse(
      await fs.promises.readFile(this.filename, {
        encoding: "utf-8",
      })
    );
  }

  async getOneBy(filters) {
    const records = await this.getAll();

    for (let record of records) {
      let found = true;

      for (let key in filters) {
        if (record[key] !== filters[key]) {
          found = false;
        }
      }

      if (found) {
        return record;
      }
    }
  }
}

module.exports = new DataRepository("cales_data.json");

With this approach, will I later be able to create some JavaScript classes to access values inside of it like so:
export class Address {
    constructor() {
        this.Address = repo.Address;
    }
}


texts:
I wrote this code to remove points that create a straight line when plotted.

For instance, this has many points in a straight line:

import matplotlib.pyplot as plt
import numpy as np

pattern = np.array(
    [ 9, 10, 11, 10,  9,  8,  6,  5,  4,  3,  4,  5,  7,  6,  5,  4,  2,
      1,  2,  3,  4,  5,  7,  8,  9, 10,  8,  7,  8,  9, 10, 11, 10, 11,
     12, 13, 12, 11, 10,  8,  7,  6,  5,  4,  6,  5,  3,  2,  3,  2,  0,
      1,  2,  3,  4,  5,  6,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 19,
     21, 19, 18, 16, 15, 14, 12, 11, 12, 11, 10, 11, 12, 13, 14, 15, 13,
     12, 11, 10,  9,  8,  7,  6,  5,  6,  5,  4,  6])

plt.plot(pattern)
plt.plot(pattern, 'bo')
plt.show()

Using the degrees function I can remove any lines that create an angle of
180deg between the two neighboring points.

from numpy.lib.stride_tricks import as_strided

def moving_slice(a, k):
    a = a.ravel()
    return as_strided(a, (a.size - k + 1, k), 2 * a.strides)

def degrees(x, y):
    x_window, y_window = moving_slice(x, 3), moving_slice(y, 3)
    x_window = np.concatenate((x_window, x_window[:, None, 0]), axis=1)
    y_window = np.concatenate((y_window, y_window[:, None, 0]), axis=1)

    triangle_sides = np.sqrt(np.square(np.diff(x_window)) + np.square(np.diff(y_window)))
    squared_sides = np.square(triangle_sides)

    cos_num = np.sum(squared_sides[:, :2], axis=1) - squared_sides[:, 2]
    cos_den = 2 * np.prod(triangle_sides[:, :2], axis=1)
    return np.degrees(np.arccos(cos_num / cos_den))

This is what I'm trying to achieve:

# My review function
angles = degrees(np.arange(len(pattern)), pattern)

pattern = pattern[1:-1] # <- No angles between the end points
less_than_180 = angles < 180
plt.plot(pattern[less_than_180])
plt.plot(pattern[less_than_180], 'bo')
plt.show()

You can see that it's pretty good. Missed a few points to remove (due to decimal accuracy) but otherwise the function does what I want. I'd like to know if there is a simpler way to achieve the desired result without calculating all the angles. What do you think?


texts: Transforming an array of arrays into an array with joins

texts:
I'm transforming this:

[["Apples", "fruitgroup", "123"], ["Bananas", "fruitgroup", "012"], ["Jumbo Jet", "planegroup", "99"], ["Crop duster", "planegroup", "40"], ["Melons", "fruitgroup", "55"]]

into this:

["Apples or Bananas or Melons [x]", "Jumbo Jet or Crop duster [x]"]

Because basically I have to group the child arrays by whatever is in their second index, or [1], and then join them with " or ".

I am successful but I'm afraid this isn't really the best way to acheive this.  Isn't there a more simple way to do this?

var
  filters = [["Apples", "fruitgroup", "123"], ["Bananas", "fruitgroup", "012"], ["Jumbo Jet", "planegroup", "99"], ["Crop duster", "planegroup", "40"], ["Melons", "fruitgroup", "55"]],
  fieldnames = _.uniq(_.map(filters, function (filter) {
    return filter[1];
  })),
  groups = _.groupBy(filters, function (filter) {
    return filter[1];
  }),
  strings = _.map(groups, function (group) {
    return _.map(group, function (item) {
      return item[0];
    }).join(" or ") + " [x]";
  });
console.log(strings);


texts: WebAPI Handling fire and forget exceptions

texts:
This is a fire and forget task from within an existing WebAPI service. The code below simply sends a log event (might be that a client has connected to the service to perform some task) to another service and if it fails should not return an error to the client.

I simply want the exception logged and forgotten about, meanwhile the service will continue to carrying out the original task.

I've used ContinueWith and am wondering if this is the correct way to do it.

Task.Factory.StartNew(() =>
{
    var client = (HttpWebRequest) WebRequest.Create(_url);

    client.Method = "POST";
    client.ContentType = "application/json";

    var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(log));

    var requestStream = client.GetRequestStream();

    requestStream.Write(bytes, 0, bytes.Length);

    requestStream.Close();

    var response = client.GetResponse();

    requestStream.Close();
    response.Close();

}).ContinueWith((ca) =>
{
    if (ca.Exception != null)
    {
        _logger.LogException(LogLevel.Error, ca.Exception.Message, ca.Exception);
    }

}, TaskContinuationOptions.OnlyOnFaulted);


texts:
As part of my programming training, I was told to research metrics for programming. I went ahead and turned the metrics into code starting with the cyclomatic complexity by McCabe. It works for bash sourcecode which I was targeting in this example.

My approach relies heavily on the while read line to read the Code line by line.
I tried to use more Regex at first but I soon hit a wall and decided to do it this way. Im familiar with Regex but inexperienced in combining them with sed or awk. So I'd like to ditch the while read line if that is possible for this kind of problem, and general readability tips for bash scripting would also be nice (im using vim to write the code).

if [ "$1" == "" ]
then
    echo "Type in file name: "
    read filename
else
# $1 is the first input parameter
filename=$1
fi

counter=1
caseflag=0
casecounter=0

while read line
do

 if [ "$caseflag" == "1" ]
 then
    if [[ $line == *"#"* ]]
    then
        #takes care of the comments in the SC
        temp=${line%%#*}
        tempcounter=$(echo $temp|awk '/;;$/{counter++}END{print counter}')
        let counter=$counter+$tempcounter > /dev/null 2>&1
    else
        tempcounter=$(echo $line|awk '/;;$/{counter++}END{print counter}')
        let counter=$counter+$tempcounter > /dev/null 2>&1
    fi
 fi
#loop detection
 temp=`echo $line | cut -d ' ' -f1`
 if [ "$temp" == "until" ] || [ "$temp" == "if" ] || [ "$temp" == "else" ] || [ "$temp" == "elif" ] || [ "$temp" == "while" ] || [ "$temp" == "for" ]
 then
    let counter=$counter+1
 fi
#case detection
 if [ "$temp" == "case" ]
 then
    caseflag=1
    let casecounter=$casecounter+1

 elif [ "$temp" == "esac" ]
 then
    caseflag=0
 fi

done < $filename

let counter=$counter-$casecounter > /dev/null 2>&1
echo "Cyclomatic complexity score: $counter"


texts:
I have made a small project and I am just wondering if I could add more functionality to the project e.g more classed etc.  Is a better way of displaying my results and what error handling I could do?

I was also wondering what would be the best way to add Inheritance to the this project.I was thinking a EveningCourse class or PostGrad, UnderGrad class. What would be the best way to go about it?

The user enters student name, age, year and student number.

package david;

public class Student
{

    private String name;
    private int age;
    private int year;
    private String studentNum;

    public Student(String name, int age, int year, String studentNum)
    {

        this.name = name;
        this.age = age;
        this.year = year;
        this.studentNum = studentNum;
    }

    // Setters and getters (Name, Age, Year and Student Number)

    public String getName() // name
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge() // age
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public int getYear() // year
    {
        return year;
    }

    public void setYear(int year)
    {
        this.year = year;
    }

    public String getstudentNum() // studentNum
    {
    return studentNum;
    }

    public void setstudentNum(String studentNum)
    {
        this.studentNum = studentNum;
    }

}

package david;

// David Needham - G00263842.
// Student information program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class TestStudents
{

    public static void main(String[] args) throws IOException
    {

    System.out.println("============" + "=================");
    System.out.println("Students " + "Personal Details");
    System.out.println("============" + "=================");

    String name;
    int age;
    int year;
    String studentNum;

    List<Student> studentsList = new ArrayList<Student>();

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

    int studentNumber = (i + 1);

    System.out.println("");
    System.out.println("Please enter " + "data for student " + studentNumber);

    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);

    System.out.println("Enter Student "+ studentNumber + " Name:");
    name = in.readLine();

    System.out.println("Enter Student " + studentNumber + " Age (Integer):");
    age = Integer.valueOf(in.readLine());

    System.out.println("Enter Student " + studentNumber + " Year (Integer):");
    year = Integer.valueOf(in.readLine());

    System.out.println("Enter Student " + studentNumber + " Student Number:");
    studentNum = in.readLine();

    Student student = new Student(name, age, year, studentNum);

    studentsList.add(student); // add student
    }

    for (int j = 0; j < studentsList.size(); j++)
    {

        Student st = studentsList.get(j);

        System.out.println("Student : " + (j + 1));
        System.out.println("Name: " + st.getName() + " - Age: " + st.getAge() + " - Year: " + st.getYear() + " - Student Number: " + st.getstudentNum());
    }

    }
}


texts:
I've tried implementing merge sort in C++ just by looking at this Wikipedia graphic. Comparing my code to other merge sort code implementations, it doesn't look quite the same at first glance. Have I done it in an acceptable way? How can it be improved, particularly using modern C++?

#include <iostream>
#include <deque> // using deque for `pop_front`
#include <random>

std::deque<int> mergeChunks(std::deque<int> &a, std::deque<int> &b);

std::deque<int> mergeSort(const std::deque<int> &d) {
    std::deque<std::deque<int>> chunks; // in the end, the first element will be the sorted list
    for (const auto &a : d) {
        // add each element of `v` to `chunks` as its own chunk
        chunks.push_back({ a });
    }

    while (chunks.size() > 1) {
        std::deque<std::deque<int>> tmp; // this will be the new set of chunks at the end of this iteration
        for (auto i = 0; i < chunks.size() - 1; i += 2) {
            tmp.push_back(mergeChunks(chunks[i], chunks[i + 1]));
        }

        // if there is an odd number of elements, then add the one that was missed in the for loop to `tmp`
        if (chunks.size() % 2 == 1) {
            tmp.push_back(chunks[chunks.size() - 1]);
        }

        chunks = tmp;
    }

    return chunks[0];
}

std::deque<int> mergeChunks(std::deque<int> &a, std::deque<int> &b) {
    std::deque<int> ret;
    while (true) {
        // if all the elemnts of one chunk have been added to `ret` then add the remaining
        // elements of the other chunk to the end of `ret` (knowing that they're sorted)
        if (a.size() == 0) {
            ret.insert(ret.end(), b.begin(), b.end());
            return ret;
        }
        if (b.size() == 0) {
            ret.insert(ret.end(), a.begin(), a.end());
            return ret;
        }

        // always comparing the first elements of each chunk. After an element is added
        // to `ret`, pop it from the chunk
        if (a[0] < b[0]) {
            ret.push_back(a[0]);
            a.pop_front();
        }
        else {
            ret.push_back(b[0]);
            b.pop_front();
        }
    }
    return ret; // never reached
}

int main() {
    auto list = mergeSort({ 8, 7, 6, 5, 4, 3, 2, 1 });
}


texts: Tree-view of Active Directory group memberships using recursion

texts:
Using Powershell, I've created a script to create a tree-view of a group/s' memberships in Active Directory. I originally had layers of nested loops, but I wanted a more algorithmic solution.

The following code does the following:

Get user input for: input source, depth-level int, output location
Recursively find all the AD Groups from the input and print out in tree-style formatting to a plaintext file.

I'm concerned the following code is too complicated and has reached "spaghetti-code" status.  I've read multiple times code-readability is very important.  What improvements could be made to improve readability and make the code more professional?  Any additional comments and advice to keep me from going down the dark path of sloppy programming are appreciated.

###   -- PRIMARY FUNCTION --   ###
function getGroupMemberships (){
    ### DESCRIPTION: Main Function ###

    # -- SWITCH OPTIONS -- #
    write-host "options:`n1: Type a User/Group`n2: Type filepath of CSV file containing list of users/groups."
    $route = read-host ":"
    switch ($route)
    {
        1 {
            $group = read-host "type group or user"
            $primaryGroups = Get-ADPrincipalGroupMembership $group
        }

        2 {
            $continue = $false
            while ($continue -eq $false) {
                $csv = read-host "CSV Filepath (no quotes!)"
                if ((test-path $csv) -eq $true) {
                    $continue = $true
                }
                elseif ((test-path $csv) -eq $false) {
                    write-host "Location $csv does not exist.  Please try again..."
                }
            }
           $primaryGroups = Import-Csv $csv
        }
    }

    # -- OTHER REQUIRED OPTIONS -- "
    $maxLevelInt = read-host "# depth of levels"
    $ouputFilePath = read-host "TXT Output Filepath: (no quotes!)"
    write-host "------------------------------------"
    $level = 0
    getNextGroupMembers $level $primaryGroups
}

### -- SECONDAY FUNCTIONS -- ###
    function getNextGroupMembers ($currentLevel, $groupIn) {
        # DESCRIPTION: main loop for gathering next groups' memberships and recursively finding

        $level++
        $groupIn = ( $groupIn | sort-object name ).name

        foreach ($group in $groupIn) {
            outputFormat $level $group
            $nextLevelMemberships = Get-ADPrincipalGroupMembership $group | select name
            if ( $level -eq $maxLevelInt ) { break } # if reached maxLevelInt
            getNextGroupMembers $level $nextLevelMemberships
        }

        $level-- # subtracts level counter once the loop completes
    }

        function outputFormat ([int]$level,$groupName) {
            # DESCRIPTION: creates string for formatting tree view; adds bars and spaces to make more readable

            $spaces="    "; $bar="|"
            if ($level -eq 1) { $out = $groupName }
            elseif ($level -eq 2) { $out = ( $spaces + $groupName ) }
            elseif ($level -gt 2) { $out = ( $spaces + $bar )*( $level - 2 ) + $spaces + $groupName }
            write-host $out; writeToFile $out
        }

        function writeToFile ($writeLine) {
            ### DESCRIPTION: writes string to file location ###

            $writeLine | out-file $ouputFilePath -append
        }

    function checkFilePath ($path) {
        $filepathTest = test-path $path
        return $filepathTest
    }

### RUN ###
getGroupMemberships


texts:
I had some issues with sending huge data and receiving them with Winsock so I made some improvements on my RecvAllBytes function and the same with SendAllBytes. I would like you to review it because I made a lot of conditions and loops.  Please let me know how to improve the code below.

constexpr int maxBufferSize = 8192;

bool Server::RecvAllBytes(std::shared_ptr<Connection> connection, char * data, int totalbytes)
{
    int totalbytesreceived = 0;
    if (totalbytes > maxBufferSize)// if buffer is bigger then maximum allowed
    {
        while (totalbytesreceived < totalbytes)//while full buffer not received
        {
            int bytesrecv = 0;
            int bytesleft = totalbytes - totalbytesreceived;
            if (bytesleft >= maxBufferSize)// if there is still more left then maximum size keep recv full size
            {
                while (bytesrecv < maxBufferSize)
                {
                    int ReturnCheck = recv(connection->socket, data + totalbytesreceived, maxBufferSize - bytesrecv, NULL);
                    if (ReturnCheck == SOCKET_ERROR)
                    {
                        return false;
                    }
                    bytesrecv += ReturnCheck;
                    totalbytesreceived += ReturnCheck;
                }
            }
            else// if left less then maximum size recv last bytes left
            {
                while (bytesrecv < bytesleft)
                {
                    int ReturnCheck = recv(connection->socket, data + totalbytesreceived, bytesleft - bytesrecv, NULL);
                    if (ReturnCheck == SOCKET_ERROR)
                    {
                        return false;
                    }
                    bytesrecv += ReturnCheck;
                    totalbytesreceived += ReturnCheck;
                }
            }
        }
    }
    else // if buffer is not bigger then maximum allowed
    {
        while (totalbytesreceived < totalbytes) {
            int ReturnCheck = recv(connection->socket, data + totalbytesreceived, totalbytes - totalbytesreceived, NULL);
            if (ReturnCheck == SOCKET_ERROR) {
                return false;
            }
            totalbytesreceived += ReturnCheck;
        }
    }
    return true;
}


texts: Plotting a graph of survey answers in Laravel

texts:
I'm using PHP (Laravel) to iterate over the survey_answers table and build datasets which I can show in a graph. I'm just wondering if this is the way to go.

ChartFactory.php

public static function buildFromSurvey($survey)
{
    $chart = new Chart($survey->name);

    foreach($survey->answers as $answer) {

        if($chart->hasDataset($answer->user_id)) {
            $dataset = $chart->getDataset($answer->user_id);
        } else {
            $dataset = new Dataset();
            $dataset->setTitle($answer->user->name);
            $dataset->setColor(config('assessment.chart_colors_survey')[0]);
            $dataset->setOwner($answer->user);
            $chart->addDataSet($dataset);
        }

        // Create the category if not exists in this dataset
        if ($dataset->hasDataItem($answer->question->category->name)) {
            $category = $dataset->getDataItem($answer->question->category->name);
            $category->addScore($answer->score);
        } else {
            $category = new Category();
            $category->setName($answer->question->category->name);
            $category->addScore($answer->score);

            $dataset->addDataItem($category);
            $chart->addLabel($answer->question->category->name);
        }
    }

    return $chart;
}


texts:
The logic is like this:

All brands have 2 products (Rose and Tulip)
Each brand names their product name differently (such as Brand 1 names their rose as No. 1 Rose and Brand 2 names their rose as No. 2 Rose )
All brands don't have products from all countries (Such as Brand 1 has Roses from USA and US whereas Brand 2 has Roses from Canada and China)

This is the working prototype of this function given below (Or, the fiddle):

$(document).ready(function() {

    $(document).on("input", "#intBrand, #intProcudt", function() {

        var intBrand = $('#intBrand').val();
        var intProcudt = $('#intProcudt').val();

        if (intBrand == "bAll") {
            if (intProcudt == "rose") {
                product = 'Rose';
            } else if (intProcudt == "tulip") {
                product = 'Tulip';
            }
        } else if (intBrand == "b1") {
            if (intProcudt == "rose") {
                product = 'No. 1 Rose';
            } else if (intProcudt == "tulip") {
                product = 'No. 1 Tulip';
            }
        } else if (intBrand == "b2") {
            if (intProcudt == "rose") {
                product = 'No. 2 Rose';
            } else if (intProcudt == "tulip") {
                product = 'No. 2 Tulip';
            }
        }

        var item1 = product + ' from US(1)
';
        var item2 = product + ' form USA(2)
';
        var item3 = product + ' from Canada(3)
';
        var item4 = product + ' from China(4)
';

        if (intBrand == "bAll") {
            roseP = item1 + item2 + item3 + item4;
            tulipP = item1 + item2 + item4;
        } else if (intBrand == "b1") {
            roseP = item1 + item2;
            tulipP = item1;
        } else if (intBrand == "b2") {
            roseP = item3 + item4;
            tulipP = item3 + item4;
        }

        $('#allRoseItems').html(roseP);
        $('#allTulipItems').html(tulipP);

    });

    $("#intBrand").trigger("input");
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">

      Select Brand:

      <select id="intBrand" name="intBrand" required>
         <option value="bAll" >All items</option>
         <option value="b1" selected>Brand 1</option>
         <option value="b2" >Brand 2</option>
      </select>

      Select Product:

      <select id="intProcudt" name="intProcudt" required>
         <option value="rose" >Rose</option>
         <option value="tulip">Tulip</option>
      </select>

My question is just keeping the following section untouched, could it be built in a better way?

var item1 = product + ' from US(1)
';
var item2 = product + ' form USA(2)
';
var item3 = product + ' from Canada(3)
';
var item4 = product + ' from China(4)
';

I'd really appreciate your suggestions on how it could be written in a more efficient way with fewer lines of code.


texts: Find the minimum value that data could have had before it was rounded

texts:
I have this function in R:

Minimum <- function(data) {
    answer <- numeric(length(data))

    diference <- c(0, diff(data, lag = 1, differences = 1)) #Padded initially =0

    answer[1]=data[1]
    for (i in 2:length(diference)) {
        if (diference[i]==0) {
            answer[i]=answer[i-1]
        } else {
            answer[i]=data[i]-diference[i]/2
        }
    }
    return(answer)
}

Its purpose is to find the minimum value which "data" could had before it was rounded.

The minimum possible value is the average of the values which "data" had at the last change of value in "data"

This code works, but since for loops are inefficient in R, it is advised to vectorize the function.

The problem is that the "answer" vector depends on the former values in "answer", so I cannot use a lambda function.


texts:
I have the following Qt class:
mainwindow.h

class MainWindow : public QWidget {
Q_OBJECT
QPushButton* m_button;
public:
    explicit MainWindow();
};

mainwindow.cpp

MainWindow::MainWindow() {
    auto main_layout = new QHBoxLayout;
    m_button = new QPushButton("Press me");
    main_layout->addWidget(m_button);
    setLayout(main_layout);
    connect(m_button, &QPushButton::pressed, [this] {
        m_button->setText("Presse me again");
    });
}

It features a button which once pressed will change its text to "Press me again". I use a lambda function and I am capturing by copy this to access the button inside the lambda.

As the QPushButton is allocated on the heap, I think that making it a class member is an unnecessary step. My question: Are there any drawbacks if I instead use it as a local pointer which I would capture by copy in the connect lambda ? It would look like this:

mainwindow.h

class MainWindow : public QWidget {
Q_OBJECT
public:
    explicit MainWindow();
};

mainwindow.cpp

MainWindow::MainWindow() {
    auto main_layout = new QHBoxLayout;
    auto button = new QPushButton("Press me");
    main_layout->addWidget(button);
    setLayout(main_layout);
    connect(button, &QPushButton::pressed, [button] { // I am copying the button's address here
        button->setText("Presse me again");
    });
}

One thing to note: Qt manages the destruction of all Qt classes automatically, so no need to call the button's destructor later if I understood correctly this conversation.


texts: Simplify test for divisibility by all numbers 1…20


texts: Using datetime to obtain the time of the next lecture

texts:
Often before the lecture starts, and occasionally in the break I like to display a timer with a countdown until the lectures starts/ resumes while playing some lofi-hip hop in the background. While the university students seems to enjoy this, I am ashamed of the code running the timer.
So my lecture schedules is as follows
Monday:    10:15 -- 12:00
Wednesday: 12:15 -- 14:00
Thursday:  08:15 -- 10:00

I am interested in finding when my next lecture is in iso format. I did this using the code below and it works fine. E.g if the current time is 16:00 on a Thursday, the output should be Monday and 10:15. I commented out the actual timer, as it is not important.

Is there a better way / cleaner python code to obtain the date and time for my next lecture?

My attempt (which works, albeit a bit ugly) is as follows:
from datetime import datetime, timedelta
from subprocess import call

# Format (day, hour, minute)
Lectures = [(0, 10, 15), (), (2, 12, 15), (3, 8, 15)]

def get_next_lecture(now=datetime.now()):

    next_lecture = now.replace(minute=15, second=0, microsecond=0)

    # monday = 0, tuesday = 1, ...
    current_day = datetime.today().weekday()
    current_hour = now.hour
    lecture_day = current_day

    correct_day = False
    while not correct_day:
        # If the day is tuesday, increment to wednesday
        if current_day == 1:
            lecture_day = current_day + 1
            lecture_hour = Lectures[lecture_day][1]
            lecture_minute = Lectures[lecture_day][2]
            now += timedelta(days=1)
            correct_day = True
            # if the day is friday, increment to monday
        elif current_day == 4:
            lecture_day = 0
            lecture_hour = Lectures[lecture_day][1]
            lecture_minute = Lectures[lecture_day][2]
            now += datetime.today() + timedelta(days=3)
            correct_day = True
        else:
            # If it is not monday or friday, I have a lecture
            # checks if the lecture is in the future, if else increment day and try again
            if now.hour < Lectures[lecture_day][1]:
                if now.minute < Lectures[lecture_day][2]:
                    lecture_hour = Lectures[lecture_day][1]
                    lecture_minute = Lectures[lecture_day][2]
                    correct_day = True
                else:
                    current_day += 1
                    now += timedelta(days=1)
            else:
                current_day += 1
                now += timedelta(days=1)

    next_lecture = now.replace(
        hour=lecture_hour, minute=lecture_minute, second=0, microsecond=0
    )

    return next_lecture

def launch_timer(time):
    call(["termdown", time.isoformat()])

if __name__ == "__main__":

    next_lecture = get_next_lecture()
    print(lecture)
    # launch_timer(next_lecture)


texts:
Solved this:

  Implement atoi to convert a string to an integer.

  Requirements for atoi:

  The function first discards as many whitespace characters as necessary
  until the first non-whitespace character is found. Then, starting from
  this character, takes an optional initial plus or minus sign followed
  by as many numerical digits as possible, and interprets them as a
  numerical value.

  The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.

  If the first sequence of non-whitespace characters in str is not a
  valid integral number, or if no such sequence exists because either
  str is empty or it contains only whitespace characters, no conversion
  is performed.

  If no valid conversion could be performed, a zero value is returned.
  If the correct value is out of the range of representable values,
  INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Solution:

Check if string is null first then empty, if either is true, return 0. Keep iterating through string until we hit the first non-empty space character.

From this position, we check if the first character is '+' or '-'. If so, we move the iterator by one step and note the sign in boolean isNegative.

From the current position, as long as the character is an integer, we add it to solution while checking for overflow each time we do so. We keep iterating through the string until we hit a non-integer character and return solution:

class Solution {
    boolean isNegative = false;
    int i = 0; // string iterator position

    public int myAtoi(String str) {
        int solution = 0;

        if (str == null || str.isEmpty()) {
            return 0;
        }
        while (i < str.length() && str.charAt(i) == ' ') {
            i++; // discard leading whitespace
        }
        checkSign(str);
        for (; i < str.length(); i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                int prev = solution; // keep solution from last iter to check for overflow
                solution = solution*10; // move number left one position
                solution = solution+(str.charAt(i)-'0'); // increase solution by curr integer
                if (isOverflow(prev, solution)) {
                    if (isNegative) {
                        return Integer.MIN_VALUE;
                    }
                    return Integer.MAX_VALUE;
                }
            } else {
                return signSolution(solution); // we've reached a non-integer character before end of string
            }
        }
        return signSolution(solution); // last character of string is an integer
    }

    boolean isOverflow(int prev, int curr) {
        // prev = value at last iteration
        // curr = value after current iteration
        if (curr/10 == prev) {
            return false;
        }
        return true;
    }

    void checkSign(String str) {
        if (str.charAt(i) == '+') {
            i++;
        } else if (str.charAt(i) == '-') {
            isNegative = true;
            i++;
        }
    }

    int signSolution(int solution) {
        if (isNegative) {
            return solution*-1;
        }
        return solution;
    }
  }


texts:
I've done some tinkering about with Knockout in search for a better solution on how to bind select lists (dropdowns). I came up with a extender in combination with a binding.

Extender:

ko.extenders.selectList = function (target, params) {
                    var result = ko.computed({
                        read: target,
                        write: function (newValue) {
                            if (newValue) {
                                target(newValue);
                            } else {
                                target(undefined);
                            }
                        }
                    });

                //add some sub-observables
                result.options = $.map(params.options, function (v, k) { return { val: k, txt: v }; });
                result.caption = params.caption;

                function getInitialEnableValue(){
                    if(params.hasOwnProperty('enable')){
                        if($.isFunction(params.enable)){
                            return params.enable();
                        }
                        return params.enable;
                    }
                    return true;
                }

                var isEnabled = ko.observable(getInitialEnableValue());
                result.enable = ko.computed({
                    read: function(){
                        return isEnabled();
                    },
                    write: function(newValue){
                        if(!newValue) result(undefined);
                        isEnabled(newValue);
                    }
                });

                if(isEnabled() && result.options.length === 1){
                    result(result.options[0].val);
                }

                //return the new observable
                return result;
            };

Binding:

var selectListHTML = "<select data-bind=\"value: {0}, options: {0}.options, optionsCaption: {0}.caption, optionsText: 'txt', optionsValue: 'val', enable: {0}.enable\"></select>";
                    ko.bindingHandlers.selectList = {
                        init: function(element, vA, aBA,vm,bc){
                            $(element).html(selectListHTML.replace(/\{0\}/g,vA()));
                        }
                    };

Example fiddle

Are there any pitfalls I'm missing? Does this look like good code? Any comments welcome, thanks in advance!


texts: Creating all possible combinations of points

texts:
I want to create all possible combinations of points (0,0),(0,1)...(12345,6789) and then all segments from these points.

The code I have written is simple and with no optimization.  Is there any algorithm to generate it in less time?

public static void main(String[] args) {
    int m=12345;
    int n=6789;

    for(int x1=0;x1<=m;x1++)
    {
        for(int y1=0;y1<=n;y1++)
        {
            for(int x2=0;x2<=m;x2++)
            {
                for(int y2=0;y2<=n;y2++)
                {
                    for(int x3=0;x3<=m;x3++)
                    {
                        for(int y3=0;y3<=n;y3++)
                        {
                            for(int x4=0;x4<=m;x4++)
                            {
                                for(int y4=0;y4<=n;y4++)
                                {
                                    Point p1 = new Point(x1, y1);
                                    Point p2 = new Point(x2, y2);
                                    Point p3 = new Point(x3, y3);
                                    Point p4 = new Point(x4, y4);

                                    Segment s1 = new Segment(p1, p2);
                                    Segment s2 = new Segment(p2, p3);
                                    Segment s3 = new Segment(p3, p4);
                                    Segment s4 = new Segment(p4, p1);

                                    //operate on those segements

                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


texts:
Is there a better way to write this code? I.e. without using loop and if statement? It's about Conway's Game of Life. Is it possible to solve this using reduce, forEach or map? I'm not sure how to start this code. There are plenty of examples on internet about Conway's Game of Life but they are all pretty much with loops or if statement. Any ideas?

Any solution or hint is appreciated.

var x = 400;
var y = 400;
var g = ca(y);
for (var i = 0; i < 400; i++) {
    g[i] = [];
}
var m = ca(y);

for (var j = 0; j < x; j++) { //first loop
    for (var k = 0; k < y; k++) { //second loop
        var r = Math.random(); //generates random number
        var ra = (r * 2);
        var rb = Math.floor(ra);
        if (rb === 1) {
            g[j][k] = 1;
        } else {
            g[j][k] = 0;
        }
    }
}

//functions
function f() {
    //this is first part of function
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.clearRect(0, 0, 400, 400);
    for (var j = 1; j < x; j++) { //first loop
        for (var k = 1; k < y; k++) { //second loop
            if (g[j][k] === 1) {
                ctx.fillStyle = "#FF0000";
                ctx.fillRect(j, k, 1, 1);
            }
        }
    }
    //this is second part of the function
    f_2();
    requestAnimationFrame(f);
}

function ca(r_y) {
    var arr = [];
    for (var i = 0; i < r_y; i++) {
        arr[i] = [];
    }
    return arr;
}

function f_2() { //this is second part of the function
    for (var j = 1; j < x - 1; j++) { //first loop
        for (var k = 1; k < y - 1; k++) { //second loop
            //apply the rules to each cell
            if (g[j][k] === 0) {
                switch (g[j - 1][k - 1] + g[j - 1][k] + g[j - 1][k + 1] + g[j][k - 1] + g[j][k + 1] + g[j + 1][k - 1] + g[j + 1][k] + g[j + 1][k + 1]) {
                    case 1:
                    case 2:
                        m[j][k] = 0; //sets the value to 0
                        break;
                    case 3:
                        m[j][k] = 1; //sets the value to 1
                        break;
                    case 4:
                        m[j][k] = 1;
                    case 5:
                        m[j][k] = !(m[j][k] | !m[j][k]);
                    default:
                        m[j][k] = 0; //sets the value to 0
                }
            } else if (g[j][k] === 1) {
                switch (g[j - 1][k - 1] + g[j - 1][k] + g[j - 1][k + 1] + g[j][k - 1] + g[j][k + 1] + g[j + 1][k - 1] + g[j + 1][k] + g[j + 1][k + 1]) {
                    case 0:
                    case 1:
                        m[j][k] = (m[j][k] | !m[j][k]);
                        break;
                    case 2:
                        m[j][k] = (m[j][k] | !m[j][k]);
                    case 3:
                        m[j][k] = 1;
                        break;
                    case 4:
                    case 5:
                        m[j][k] = (m[j][k] & !m[j][k]);
                    case 6:
                    case 7:
                    case 8:
                        m[j][k] = 0;
                        break;
                    default:
                        m[j][k] = 0;

                }

            }
        }
    }

    for (var j = 0; j < x; j++) {
        for (var k = 0; k < y; k++) {
            g[j][k] = m[j][k];

        }
    }

}
<body onload="f()">
        <canvas id="myCanvas" width="400" height="400"></canvas>
    </body>


texts: Get sum of an array in 3 ways, for, while and recursive

texts:
So i was trying to find sum of an array using 3 ways in perl6

for
while
recursive

(I know there are inbuilt perl6 functions for this)

I want to know if there is a better way to do this or is this it?

sub sumFor(@list)
{
   my $sum = 0;
   for (@list)
   {
      $sum += $_;
   }
   return $sum;
}

sub sumWhile(@list)
{
   my $sum = 0;
   my $index = 0;
   while ($index < @list.elems)
   {
      $sum += @list[$index++];
   }
   return $sum;
}

sub sumRec(@list, $index = 0)
{
   my $sum = 0;
   if ($index < @list.elems)
   {
      $sum = @list[$index] + sumRec(@list,$index+1);
   }
   return $sum;
}

my @list = 1,2,3,4;

say sumFor(@list);
say sumWhile(@list);
say sumRec(@list);


texts: ReactJS component to classify a list of books

texts:
In my project, I am getting an array of objects from api, and I want to divide the array into 3 three arrays based on the value of the shelf property of each
array element which is an object. Now for doing that I am using formatBooks function inside the same component.

Later on I am passing this formatBooks function as prop to other component which calls this function.

I was hoping if there is any better by making another component and place the formatBooks inside that. I wanted to know a better and elegant way of doing things like this.

class BooksApp extends React.Component {
  state = {
    books: [],
    searchResults: [],
    newBooksFromSearch: [],
  }
  //format the books array
  formatBooks = () => {
    const currentlyReading = []
    const read = []
    const wantToRead = []
    this.state.books.forEach( item => {
      if(item.shelf === "currentlyReading" || item.shelf === "Currently Reading"){
          item.setShelf = "Currently Reading"
          currentlyReading.push(item)
      }
      if(item.shelf === "read" || item.shelf === "Read" ){
          item.setShelf = "Read"
          read.push(item)
      }
      if(item.shelf === "wantToRead" || item.shelf === "Want to Read"){
          item.setShelf = "Want to Read"
          wantToRead.push(item)
      }
    })
    return(
      {
        currentlyReading: currentlyReading,
        read: read,
        wantToRead: wantToRead
      }
    )
  }


texts:
If you input the number 3 from the keyboard, the program will show this:

      0
    0 1 0
  0 1 2 1 0
0 1 2 3 2 1 0
  0 1 2 1 0
    0 1 0
      0

Here is my code:

#include <iostream>

using namespace std;

int main()
{
    unsigned i,k=0,n;
    cout<<"n= "; cin>>n;

    while(k<=n)
        {

            for (i=0;i<=k;i++)
                cout<<i;
            for (i=k;i>0;i--)
                cout<<i-1;
            cout<<endl;
            k++;
        }

    k=n;

    while (k)
        {
            k--;
            for (i=0;i<=k;i++)
                cout<<i;
            for (i=k;i>0;i--)
                cout<<i-1;
            cout<<endl;

        }
}

I have two questions:

Is there a better/easier/clever way to do this?
How to deal with spaces? How to show them? (because my code is working but it doesn't show spaces to make this diamond look)


texts:
I have this code in a class sharing a private static array of data. Internally it's encoded, but I need the iterator for a foreach loop to show the decoded values.

Is there a native array function that can remap the keys and values via a callback function?

public function getIterator( )
{
  $arr = array();
  foreach ( self::$data as $encName => $encValue )
  {
    $name = $this->decode( $encName );
    $value = $this->decode( $encValue );
    $arr[$name] = $value;
  }
  return new ArrayIterator( $arr );
}


texts:
I want to make sure that I am writing the code correctly and fully understand what is needed. My biggest concern is what tags to use, (? * | etc.)

  The element stories
  5.1.  The element stories contains 0 or more story elements.
  The element story
  6.1.  The element story has an enumerated attribute updated that can only have the values true, false, or unknown. The default is true.
  Represents whether or not the story was updated since the last time
  the feed was downloaded.
  6.2.  The element story’s first element is the url element. Must appear exactly once. A link to the story.
  6.3.  The element story’s second element is the title element. Must appear exactly once.
  6.4.  The element story’s third element is the preview element. Must appear exactly once. A short introduction to the story. Usually, about
  1 sentence.
  6.5.  The element story’s element content is optional, but if present, appears no more than once. The story. Some sites allow the story text
  in feeds, some don’t. That is why it is optional
  6.6.  The element story’s element video is optional, but if present, appears no more than once. A link to an optional video.
  6.6.1.    The order of the elements content and video does not matter. If both are present, content can be first or video can be first.
  6.7.  The element story’s last element publication-date is optional, but if present, appears no more than once and must be the last
  element. The date the story was published.
  The element title
  7.1.  The element title can contain text

My code:

<!ELEMENT stories (stories*)>
<!ELEMENT story (update true|false, url?, title?, preview?, content?, video?, publication-date?>
<!ELEMENT title >


texts: Problems with backtracking algorithm in C++

texts:
I have to implement an algorithm that generates a modified version of a Thue Sequence, being that there can't be any adjacent sub-sequence can repeat itself using the letters N,P and O.

For example, NOPNO is a valid output but NOPNPNO is not because it repeats here NOPNPNO.

I tried to approach the problem using backtracking. My idea is to add a letter and check for repetitions until I get the right length that is required. You can check for more details of the problem here.

This is the code that I came up:

#include <string>
#include <iostream>

using namespace std;

bool found;

/* This function check, for every time a letter is added, if the sequence
 * is going to repeat itself. For each pair of substrings with length i
 * they are compared to check if they are equal.
 * ex:
 *  The sequence NONPNOPN will check if N = P, PN = NO, OPN = NPN, NOPN = NONP
 *
 * The function returns True if it should reject the sequence and False otherwise.
*/
bool reject(string str){
    int i = 1, len = str.size();
    while(i <= len/2){
        if(str.substr(len-2*i,i) == str.substr(len-i,i)) return true;
        i++;
    }
    return false;
}

/* This function uses backtracking to generate the answers. It recursively adds
 * a letter to the string and checks if it is a probable candidate, printing the answer if
 * it's the right answer and returning otherwise
*/
void Thue(int n, string str){
    if(found) return;
    if(reject(str)) return;

    if(str.size() == n){
        cout << str << endl;
        found = true;
        return;
    }

    Thue(n,str+"N");
    Thue(n,str+"O");
    Thue(n,str+"P");
}

int main(){
    int n;
    while(cin >> n && n){
        found = false;
        cin.ignore();
        Thue(n,"");
    }
    return 0;
}

It is working fine but my problem is, it's too slow. I think my problem is the function to check for repetitions but I don't know how I can make it faster. How can I speed this up?


texts: Filter out strings that are short or that are outside the alphabet of a language

texts:
I wrote this function to remove from the array those words that are less than n values. More precisely, I updated my old function and added some functionality. Since I am a beginner in this programming language and so I could in my code allow for various illogical errors: Old version of my function:

$words = array("ӯтар","ӯро","ӯт","ғариб","афтода","даст", "ра", "I","Hello", "World"); // Simple array for using

function delValByLessOld($array)
{
    return preg_grep('~\A[^qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM]{2,}\z~u', $array);
}

Simple usage:

echo "
";
   print_r(delValByLessOld($words));
echo "
";

Output:

Array
(
    [0] => ӯтар
    [1] => ӯро
    [2] => ӯт
    [3] => ғариб
    [4] => афтода
    [5] => даст
    [6] => ра
)

My new (updated) function:

function delValByLess(&$array, $less = 2, $lang = 'en')
{

    $search =  array('english','eng', 'russian', 'rus', 'tajik', 'taj', 'tjk');
    $replace = array('en', 'en', 'ru', 'ru', 'tj', 'tj', 'tj');

    if(is_string($lang))
    {
        $lang = mb_strtolower($lang);
        $lang = str_replace($search, $replace, $lang);
    }

    if(is_array($lang))
    {
        foreach ($lang as $lan)
        {
            $lan = mb_strtolower($lan);
            $lang[$lan] = str_replace($search, $replace, $lan);
        }
    }

    $languages =
    [
        'en' => 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM',
        'ru' => 'ёйцукенгшщзхъфывапролджэячсмитьбюЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ',
        'tj' => 'ғӯқҳҷӣҒӮҚҲҶӢ'
    ];

    if (is_array($array) && is_numeric($less))
    {
        if(is_string($lang))
        {
            if (isset($languages[$lang]))
            {
                return preg_grep('~\A[^'.$languages[$lang].']{'.$less.',}\z~u', $array);
            }
        }

        if(is_array($lang))
        {
            foreach ($lang as $lan)
            {
                if (isset($languages[$lan]))
                {
                    $array = preg_grep('~\A[^'.$languages[$lan].']{'.$less.',}\z~u', $array);
                }
            }

            return $array;
        }
    }

    return false;
}

Simple usage:

echo "
";
   print_r(delValByLess($words,'3', ['ENGLISH','TAJIK']));
echo "
";

Output:

Array
(
    [4] => афтода
    [5] => даст
)


texts: Counting the UpperCase, LowerCase, Numbers and Special Characters in a String

texts:
I'm making a Java program that will analyze the given String by counting the lowercase, uppercase, numbers and special characters. Is there a way by making it functional?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class PassTest {

    public static String password = "";
    public static int upperCase = 0;
    public static int lowerCase = 0;
    public static int numberCount = 0;
    public static final String FINAL_CHAR_REGEX = "[!@#$%^&*()[\\\\]|;',./{}\\\\\\\\:\\\"<>?]";

public static void main(String[] args) throws IOException {
    BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your password: ");
             password = dataIn.readLine();
            for ( int i = 0; i < password.length() ; i++ ) {
                if (Character.isUpperCase(password.charAt(i))){ upperCase++; }
                if (Character.isLowerCase(password.charAt(i))){ lowerCase++; }
                if (Character.isDigit(password.charAt(i)))    { numberCount++;}
            }
        int specialCharCount = password.split(FINAL_CHAR_REGEX, -1).length - 1;
            System.out.printf("Your password contains %d uppercases, %d lowercases, %d digits and %d special characters.\n\n", upperCase, lowerCase, numberCount, specialCharCount);
        ;
       }
}


texts: C++ Calculate euclidean distance between tuples, for specified indices

texts:
I wrote a small utility function that will take two tuples and returns the Euclidean distance for the given indices only:

#include <cmath>
#include <tuple>

namespace {
    template <typename T> constexpr auto sq(const T& val) { return val * val; }
}

template <int... I, typename... Tp>
constexpr auto euclidean_distance(const std::tuple<Tp...>& ta, const std::tuple<Tp...>& tb) {
    return static_cast<std::common_type_t<std::tuple_element_t<I, std::decay_t<decltype(ta)>>...>>(
        sqrt(
                (
                    sq(
                        static_cast<std::common_type_t<std::tuple_element_t<I, std::decay_t<decltype(ta)>>...>>(std::get<I>(tb)) -
                        static_cast<std::common_type_t<std::tuple_element_t<I, std::decay_t<decltype(ta)>>...>>(std::get<I>(ta))
                    ) + ...
                )
            )
        );
}

constexpr std::tuple a { (int8_t)-10, -20, (uint16_t)50, "String", 1.2f };
constexpr std::tuple b { (int8_t)20, 120, (uint16_t)150, "Another", 9.1f };

int main() {
    volatile auto res_i = euclidean_distance<0,1,2>(a, b);
    volatile auto res_f = euclidean_distance<0,1,2,4>(a, b);
}

Right now it only takes tuples of completely equal type, but the template logic could be adapted to use tuples that only share similar types for the used indices.
I'd love to hear any comments and critiques!


texts:
Please review this code, which should calculate the tax percentage a person will pay in a progressive tax system. The goal is to have a perfect program.

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

namespace ConsoleApplication1
{
    class TaxLevel
    {
        private decimal _Money=-1;
        /// <summary>
        /// the money count that the tax applies to
        /// </summary>
        public decimal Money
        {
            get { return _Money; }
            set { if (value > 0) { _Money = value; } else { throw new ArgumentOutOfRangeException("Money must be grater than 0"); } }
        }

        private decimal _TaxDeduction=-1;
        /// <summary>
        /// the tax level where 1.0 is 100% tax
        /// </summary>
        public decimal TaxDeduction
        {
            get { return _TaxDeduction; }
            set { if (value > 0 && value < 1.0m) { _TaxDeduction = value; } else { throw new ArgumentOutOfRangeException("TaxDeduction must be between 0.0 and 1.0"); } }
        }

     }

     class TaxCalculator
    {
        List<TaxLevel> _TaxLevels;

        public bool DeterminateTaxLevels(){

            _TaxLevels = new List<TaxLevel>();
            _TaxLevels.Add(new TaxLevel {Money = 4770m, TaxDeduction =  0.10m });
            _TaxLevels.Add(new TaxLevel { Money = 3700, TaxDeduction = 0.14m });
            _TaxLevels.Add(new TaxLevel { Money = 4249m, TaxDeduction = 0.20m });
            _TaxLevels.Add(new TaxLevel { Money = 5529m, TaxDeduction = 0.28m });
            _TaxLevels.Add(new TaxLevel { Money = 21089m, TaxDeduction = 0.31m });
            _TaxLevels.Add(new TaxLevel { Money = decimal.MaxValue, TaxDeduction = 0.42m });
        return true;
        }
         /// <summary>
         /// Gets Salley In Bruto Calculates Netto Sallery
         /// </summary>
         /// <param name="SalleryInNis">Employee Bruto Sallery</param>
         /// <returns>Neto Sallery</returns>
        public  decimal CalculateNetto(decimal SalleryInNis)
        {
            if (SalleryInNis < 0) throw new ArgumentOutOfRangeException("SalleryInNis must be greater than 0");
            if (_TaxLevels == null) throw new ArgumentNullException("DeterminateTaxLevels First");
            decimal TmpSallery =SalleryInNis;
            decimal Netto = 0.0m;
            foreach (var taxlevel in _TaxLevels)
            {
                if (TmpSallery <= 0) break;
                if (TmpSallery > taxlevel.Money)
                {
                    Netto += taxlevel.Money * (1-taxlevel.TaxDeduction);
                }
                else {
                    Netto += TmpSallery * (1-taxlevel.TaxDeduction);
                }
                TmpSallery -= taxlevel.Money;
            }
            return Netto;
        }
         /// <summary>
         /// Calculates Average Tax for employee
         /// </summary>
        /// <param name="SalleryInNis">Employee Bruto Sallery</param>
        /// <returns>AverageTax</returns>
        public  decimal CalculateAverageTax(decimal SalleryInNis)
        {
            if (SalleryInNis < 0) throw new ArgumentOutOfRangeException("SalleryInNis must be greater than 0");
            return 1- (CalculateNetto(SalleryInNis) / SalleryInNis);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            decimal Sal= 11712000;
            TaxCalculator TaxCalculator = new TaxCalculator();
            TaxCalculator.DeterminateTaxLevels();
            Console.WriteLine("Brutto " + Sal);
            Console.WriteLine("Netto " + TaxCalculator.CalculateNetto(Sal));
            Console.WriteLine("Average Tax " + TaxCalculator.CalculateAverageTax(Sal));
            Console.Read();
        }
    }
}


texts:
Write a recursive version of the function reverse(s), which reverses the string s in place.

Here is my solution:

void reverse(char a[], int i, int j) {
    char tmp;

    if(i >= j) {
        return;
    }

    reverse(a, i + 1, j - 1);
    tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
}

This exercise is right after the presentation of the quicksort algorithm.

This is the signature of the quicksort function presented in the book:

void qsort(int v[], int left, int right)

This is why I added 2 new parameters to the functions - to narrow the size of the array.

There are 2 base cases:

When i == j, so n is even
When i > j, so n is odd

n represents the number of characters in string s.


texts:
I am very new to Scala. I have done an exercise using Scala to solve the maximum path problem.

Basically, I have a triangle of integers, I want to find the path from the top to bottom which the numbers on the route produces the largest sum. For example:

       5
    12    3
  2    4     9
1    9    12    7

Should return:

5 -> 12 -> 4 -> 12
Sum = 33

Could someone please help review the code and make some suggestions about:

Better algorithm
Writing better scala code

Here is the code:

import scala._

class MaxPath {
  def sumTree(input : List[List[Int]], tempResult : List[List[Int]], currentlevel : Int) : List[List[Int]] = {
    if(currentlevel == input.size) return tempResult

    val updatedRow : List[Int] = currentlevel match {
      case 0 => input(currentlevel)
      case _ => {
        val lastRow = tempResult(currentlevel - 1)
        val currentRow = input(currentlevel)

        val newHead = currentRow.head + lastRow.head
        val newLast = currentRow.last + lastRow.last
        val middleSection = currentRow.drop(1).dropRight(1)

        val newMiddle : List[Int] = for {
          (value, index) <- middleSection.zipWithIndex
          middle = value + Math.max(lastRow(index), lastRow(index + 1))
        } yield middle

        newHead::newMiddle:::List(newLast)
      }
    }

    sumTree(input, tempResult:::List(updatedRow), currentlevel + 1)
  }

  def traceBack(input : List[List[Int]], transformed : List[List[Int]], index : Int, currentLevel : Int) : List[Int] = {
    if(currentLevel == input.size) return Nil

    val row = input(currentLevel)
    val rowTransformed = transformed(currentLevel)
    val max = index match {
      case -1 => {
        val maxIndex = rowTransformed.zipWithIndex.maxBy(_._1)._2
        (row(maxIndex), maxIndex)
      }
      case x  => {
        val rowSize = row.size
        x match {
          case 0 => (row.head, 0)
          case `rowSize` => (row.last, 0)
          case _ => {
            val maxIndex = List(rowTransformed(index-1), rowTransformed(index)).zip(List(index - 1, index)).maxBy(_._1)._2
            (row(maxIndex), maxIndex)
          }
        }
      }
    }

    traceBack(input, transformed, max._2, currentLevel + 1) ::: List(max._1)
  }

  def calcualte(input : List[List[Int]]) : (List[Int], Int) = {
    val transformed = sumTree(input, Nil, 0)
    val path = traceBack(input.reverse, transformed.reverse, -1, 0)
    (path, path.sum)
  }
}

object MaxPath {
  val input : List[List[Int]] = List(
    List(5),
    List(12, 3),
    List(2, 4, 9),
    List(1, 9, 12, 7)
  )

  def main(args : Array[String]) = {
    val mp = new MaxPath
    val result = mp.calcualte(input)

    println(result._1.mkString(" -> "))
    println("Sum = " + result._2)
  }
}


texts: Splitting an NSArray into an NSDictionary of array more elegantly

texts:
I need to split one NSArray into NSDictionary. Every key in NSDictionary will contain an NSArray with the object with the same value.

i.e. I have an array with 1000 customers and I want create an NSDictionary based on their zip code.

I wrote this code into an NSArray category and it works, but I'm looking for a better name and a way (if it exists) to do the same job with the KVC.

-(NSDictionary *)groupArrayWithBlock:(id<NSCopying> (^)(id obj))block {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    for (id obj in self) {
        id<NSCopying> key = block(obj);
        if (! dictionary[key]) {
            NSMutableArray *arr = [NSMutableArray array];
            dictionary[key] = arr;
        }
        [dictionary[key] addObject:obj];
    }
    return [dictionary copy];
}


texts:
I have written the code for linked list in c++. It has function list_search(int)
which returns the node of the given number. list_insertfront(int) inserts the first element. list_insert(int) inserts the element. list_delete(int) deletes the element after searching its node.

#include <iostream>

class double_list{
  struct Node{
       int data;
       struct Node *next; //next will hold the address and *next will show value at that address
       struct Node *prev; //prev will hold the address and *prev will show value at that address
    } *head;
 public:
    double_list(){
    head=NULL; // all address in head are initialised to NULL
    }
     void list_insert(int);
     void list_insertfront(int);
     struct Node *list_search(int n){
        Node *node =new Node();
        node=head;
        while(node!=NULL){
            if(node->data==n) return node;
        node=node->next;}
        std::cout<<"No such elementin the list \n";
   }
    void list_delete(int);
    void display();
};
void double_list::list_insertfront(int n){
Node *node=new Node();
node->data=n;
node->next=head;
head=node;
node->prev=NULL;
}

void double_list::list_insert(int n){
   Node *node =new Node();
   Node *temp =new Node();
   node->data=n;
   node->next=NULL;
   temp=head;
   while(temp){
    if(temp->next==NULL){
        temp->next=node;
        break;
        }
        temp=temp->next;
   }
}

void double_list::list_delete(int n){

   Node *node=list_search(n);//to search node of the given number
   Node *temp=new Node();
   temp=head;
   if(temp==node){
    head=temp->next;
   }
   while(node!=NULL){
      if(temp->next==node) temp->next=node->next;
      temp=temp->next;
      return;
       }
}

void double_list::display(){
    Node *node=new Node();
    node =head;
   while(node!=NULL){
        std::cout<<node->data<<" ";
        node=node->next;
    }
}
int main()
{
    double_list list1;
   list1.list_insertfront(5);
    list1.list_insert(1);
    list1.list_insert(6);
    list1.list_insert(7);
    list1.display();
    list1.list_delete(1);
    std::cout<<"\n";
    list1.display();
    std::cout<<"\n";

    return 0;
}

What should I do to improve this code.


texts:
for (var i = 1; i <= 100; ++i) {
    var fizzBuzz = ""

    if i % 3 == 0 {
        fizzBuzz += "Fizz"
    }

    if i % 5 == 0 {
        fizzBuzz += "Buzz"
    }

    if fizzBuzz == "" {
        fizzBuzz += "\(i)"
    }

    println(fizzBuzz)
}

I don't really like comparing strings with ==, but apparently, that's how you do it in Swift (and there's not another option).

The parenthesis in if statements are optional in Swift.  Should that be a thing, or should we stick with them?  The curly-braces were optional in Objective-C (and lots of programming languages) but they're not in Swift.  Despite their former optionality, I never thought it was a good idea to not use them--is it a good idea to not use parenthesis here?

Not explicitly declaring the type of variable is now a thing in Swift (although the variable still has an explicit type, it's just implicitly determined).  Is it okay to let the type be implicitly determined, or should we stick with explicitly declaring the type?


texts: The opposite of CodeLess Questions query

texts:
What's the opposite of CodeLess Questions?
Perhaps CodeOnly Answers? (Also known as code dumps.)

Inspired by the opposite question, here's the opposite query:

SELECT Id AS [Post Link], Score, CreationDate
FROM Posts
WHERE PostTypeId = 2  -- answers
  AND Body LIKE '
%'
  AND CHARINDEX('
', Body) + LEN('
') = LEN(Body)
  AND ClosedDate IS NULL
ORDER BY CreationDate

Checking a couple of the results, this successfully finds the code only answers, and pretty fast.

I'm wondering if there's a better, cleaner approach that the hack with the CHARINDEX.


texts:
This is my battle system that I wrote in Lua. Bear with me on this one, this is my first real program that does something besides write hello world. If there is anything that I could have done differently, drop an answer down there and I will take your advice for my next program. Huge shoutout to Jakuje for helping me make this, he refined my code for me and told me how to do things correctly.

math.randomseed( os.time() )
math.random(); math.random(); math.random()
local function battle()
  n = math.random(10) + 1 -- Everybody's HP, enemy HP randomly generated number from 10 to 100
  enemyhp = 10*n
  exp = enemyhp*0.5
  g_herohp = 100
  print("You have encountered an enemy!")
  io.write("Your HP: ")
  io.write(g_herohp)
  io.write(" ")
  io.flush()
  io.write("Enemy HP: ")
  io.write(enemyhp)
  io.write(" ")
  io.flush()
end
local function attack()  -- Attacking the enemy or running away
  print("|Attack|Flee| ")
  input = io.read()
  if input == "attack" then
    attackdamage = math.random(51)
    if attackdamage == 51 then
      print("Critical Hit! 100 damage!")
      enemyhp = enemyhp - 100
    else
      enemyhp = enemyhp - attackdamage
      io.write("You dealt ")
      io.write(attackdamage)
      io.write(" damage!")
    end
  elseif input == "flee" then
    escapechance = math.random(2)
    if escapechance == 1 then
    escape = true
    end
  end
end
local function enemyattack() -- Enemy attacks you with a random amount of damage
  print(" Enemy is attacking!")
  eattackdamage = math.random(40)
  g_herohp = g_herohp - eattackdamage
  io.write("Enemy dealt ")
  io.write(eattackdamage)
  io.write(" damage!")
end
local function battleinprogress() -- If I used battle then it would reset everyones health.
  if g_herohp <= 0 then
    print(" You have died!")
    end
  io.write(" Your HP: ")
  io.write(g_herohp)
  io.write(" ")
  io.flush()
  io.write("Enemy HP: ")
  io.write(enemyhp)
  io.write(" ")
  io.flush()
  if enemyhp <= 0 then
    print("You won!")
  end
  if escape == true then
  print("You have run away!")
  end
end
battle()
repeat
attack()
enemyattack()
battleinprogress()
until g_herohp <= 0 or enemyhp <= 0 or escape == true
end


texts: Validate that a relative path exists or is an external URI

texts:
I sent a PR to a repo the other day and want to make sure I have the right idea for URI validation.

function validateURI(files) {
    //...
    // files can be either a string or an array of paths
    // validates the relative path exists or is an http(s) URI
    // returns a filtered list of valid paths
    // (e.g.) ["../dne.js", "//cdn.jsdelivr.net/jquery/2.1.0/jquery.min.js"] => ["//cdn.jsdelivr.net/jquery/2.1.0/jquery.min.js"]
    if(typeof files !== "object") files = [files]; //wrap string
    var local = grunt.file.expand(opt, files),
        remote = _.map(files, path.normalize).filter(function(path) { //for loading from cdn
            return /^((http|https):)?(\\|\/\/)/.test(path); //is http, https, or //
        });
    return _.uniq(local.concat(remote));
}


texts: Tic Tac Toe / Noughts and Crosses - First Program

texts:
This is my first program. Its a two player noughts and crosses game. I would really appreciate any comments on how to improve my code or make it more efficient. Many Thanks.

It is written in Python 3.6.

#Noughts and Crosses Game

#Grid
grid = [0, 1, 2, 3, 4, 5, 6, 7, 8]

#Welcome
print("Welcome to Noughts and Crosses Game")

#Player name inputs
p1_name = input("What is name of Player 1? Player 1 is 'x': ")
p2_name = input("What is name of Player 2? Player 2 is 'o': ")

#Draw Grid
def draw_grid():
    print("-------------")
    print('|', grid[0], '|', grid[1], '|', grid[2], '|')
    print("-------------")
    print('|', grid[3], '|', grid[4], '|', grid[5], '|')
    print("-------------")
    print('|', grid[6], '|', grid[7], '|', grid[8], '|')
    print("-------------")

#Move input for player 1
def p1():
        try:
            p1_input = int(input(p1_name + " select a space on the grid by entering a \
number to place an 'x': "))
        except ValueError:
            print("Error: Please enter a number, not a letter or symbol")
            p1()
        else:
            if p1_input not in range(9):
                print("Error: Please select a number on the grid 0-8 to place an 'x'")
                p1()
            elif grid[p1_input] == "x" or grid[p1_input] == "o":
                print("Error: This spot has been taken.")
                p1()
            else:
                grid[p1_input] = "x"
                draw_grid()

#Move input for player 2
def p2():
        try:
            p2_input = int(input(p2_name + " select a space on the grid by entering a \
number to place an 'o': "))
        except ValueError:
            print("Error: Please enter a number, not a letter or symbol")
            p2()
        else:
            if p2_input not in range(9):
                print("Error: Please select a number on the grid 0-8 to place an 'o'")
                p2()
            elif grid[p2_input] == "x" or grid[p2_input] == "o":
                print("Error: This spot has been taken.")
                p2()
            else:
                grid[p2_input] = "o"
                draw_grid()

#Check for three x in a row
def p1_check():
    if grid[0] == "x" and grid[1] == "x" and grid[2] == "x" or \
        grid[3] == "x" and grid[4] == "x" and grid[5] == "x" or \
        grid[6] == "x" and grid[7] == "x" and grid[8] == "x" or \
        grid[0] == "x" and grid[3] == "x" and grid[6] == "x" or \
        grid[1] == "x" and grid[4] == "x" and grid[7] == "x" or \
        grid[2] == "x" and grid[5] == "x" and grid[8] == "x" or \
        grid[6] == "x" and grid[4] == "x" and grid[2] == "x" or \
        grid[0] == "x" and grid[4] == "x" and grid[8] == "x":
            print(p1_name + " Wins!")
            return "End Game"

#Check for three o in a row
def p2_check():
    if grid[0] == "o" and grid[1] == "o" and grid[2] == "o" or \
         grid[3] == "o" and grid[4] == "o" and grid[5] == "o" or \
         grid[6] == "o" and grid[7] == "o" and grid[8] == "o" or \
         grid[0] == "o" and grid[3] == "o" and grid[6] == "o" or \
         grid[1] == "o" and grid[4] == "o" and grid[7] == "o" or \
         grid[2] == "o" and grid[5] == "o" and grid[8] == "o" or \
         grid[6] == "o" and grid[4] == "o" and grid[2] == "o" or \
         grid[0] == "o" and grid[4] == "o" and grid[8] == "o":
            print(p2_name + " Wins!")
            return "End Game"

#Check for a tie
def tie_check():
    if grid.count("x") + grid.count("o") == len(grid):
        print("Game is a tie")
        return "End Game"

#Play the game
def play():
    draw_grid()
    while True:
        p1()
        if p1_check() == "End Game":
            break
        if tie_check() == "End Game":
            break
        p2()
        if p2_check() == "End Game":
            break
        if tie_check() == "End Game":
            break

play()


texts:
I have the following ajax call:

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'json',
        data: 'source=' + $('#markItUp').val(),
        success: function (data) {
            $('#previewMode').html(data.RenderedSource);
        }
    });
};

Controller action:

[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Json(new { RenderedSource = m_wikiEngine.Render(source, GetRenderers()) });
}

And modal window:

I can switch between the design and preview tabs instantly which allows me to make changes in "Design Mode" and then instantly preview the effect of those changes before saving it to the Wiki. This works as I expect it to but I suspect that A. somehow I can accomplish this with get instead of post and B. I might not be going about this the right way.

Sure, it works exactly as I want it to but this is my first real web app and I'm confident that I'm "doing things right" here.


texts: Comparing arrays with source questions and user answers

texts:
I'm trying to realize simple testing application. And I ran into a problem. I have two arrays. The first is an array with the initial questions, the second array is the answers of users. And now I need to count the number of correct answers. I wrote the following code. I wonder: how optimal is it and, if it's bad, how to optimize it?
I tried to change the "filter" to "find", but this did not affect the execution time of the code.

const questions = [
 {
  questionId: 1,
  question: 'question?',
  answers: [
   { value: '1', right: true },
   { value: '2', right: false },
   { value: '3', right: false },
   { value: '4', right: false },
  ],
 },
 {
  questionId: 2,
  question: 'question?',
  answers: [
   { value: '1', right: false },
   { value: '2', right: false },
   { value: '3', right: false },
   { value: '4', right: true },
  ],
 },
 {
  questionId: 3,
  question: 'question?',
  answers: [
   { value: '1', right: false },
   { value: '2', right: true },
   { value: '3', right: false },
   { value: '4', right: false },
  ],
 },
 {
  questionId: 4,
  question: 'question?',
  answers: [
   { value: '1', right: true },
   { value: '2', right: false },
   { value: '3', right: false },
   { value: '4', right: false },
  ],
 },
 {
  questionId: 5,
  question: 'question?',
  answers: [
   { value: '1', right: false },
   { value: '2', right: false },
   { value: '3', right: true },
   { value: '4', right: false },
  ],
 },
]

const answersFromUser = [
 {
  questionId: 1,
  value: '1',
 },
 {
  questionId: 2,
  value: '1',
 },
 {
  questionId: 3,
  value: '1',
 },
 {
  questionId: 4,
  value: '1',
 },
 {
  questionId: 5,
  value: '1',
 },
]

const createObj = (questionId, value, right) => {
 return { questionId, value, right }
}

const checkAnswers = (questionsArr, answersArr) => {
 return answersArr.map(answer => {
  const currentQuestion = questionsArr.filter(
   question => question.questionId === answer.questionId
  )

  const currentAnswer = currentQuestion[0].answers.filter(
   answerInCurrentQuestion => answerInCurrentQuestion.value === answer.value
  )[0]

  return createObj(
   answer.questionId,
   currentAnswer.value,
   currentAnswer.right
  )
 })
}

const countRightAnswers = answers => {
 return answers.filter(answer => answer.right).length
}

const countWrongAnswers = answers => {
 return answers.filter(answer => !answer.right).length
}

console.log(checkAnswers(questions, answersFromUser))
console.log("Right Answers " + countRightAnswers(checkAnswers(questions, answersFromUser)))
console.log("Wrong Answers " + countWrongAnswers(checkAnswers(questions, answersFromUser)))


texts:
I am still fairly green when it comes to SQL joins. The below code works but I want to check that I am doing it the best way before I copy and paste errors into other work in the future.

The idea of the below code is to get the PropertyID and Name of a property from the first Table and using the PropertyID join them. In this case I am actually using every field in Table B (thus the *).

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQL %>"
    SelectCommand="
        select TblA.PropertyID as PId, TblA.Propertyname as PNa, TblB.*
        from TbPropertyDetails as TblA
            inner join TbPropertyDetailsSafeguarding as TblB on TblA.PropertyID = TblB.PropertyID
       where TblA.RegionID <> '0' and TblA.PropertyID LIKE '%' + @PropertyID + '%'
       order by TblA.PropertyID asc;"
>

<SelectParameters>
    <asp:SessionParameter DefaultValue="" Name="PropertyID" SessionField="PropertyID"
        Type="string" />
</SelectParameters>
</asp:SqlDataSource>

I am programming in VB.net but this is really standalone SQL.


texts:
I have a plan to make something to solve this stuff:
You have 7   chips that are on the run. each has some cargo loaded. And also there's where record on each.Latter could be either track means running(or gone offroad)  or tobeauty means it reaches its finish. Where .cargo = -1 means it's gone . And finally i need one of three : all is gone, at least one is on finish and others either are on finish or gone , and show is in progress so neither of these two. Only first two will be checked so thrd will be just anything else.
I've done it like this finally:
uses crt;

type
    trail_type = (blue ,desert ,white ,green ,violet ,wood ,coldgreen) ;
    palmtree = (none ,apple ,appricot ,grape ,pineapple ,lemon);
    catchinon  = (track, tobeauty);
type
    ontherun = Record
    trail : trail_type;
    cargo : Currency;
    miles : Integer;
    where : catchinon;
end;

Var
    rec_b : array[1..7] of ontherun;
    fruit : palmtree;
    k  : Integer;

Function Ternary(x : Boolean ; b : palmtree ; c  : palmtree ) : palmtree;
begin
    if x then
        Ternary := b
    else
        Ternary := c;
end;
begin
    {testing part}

{       rec_b[4].cargo := -1;
        rec_b[5].where := tobeauty;
        rec_b[7].where := tobeauty;
        rec_b[1].cargo := -1;
        rec_b[3].where := tobeauty;
        fruit := none;}

    {for k := 1 to 7 do
                        rec_b[k].where := tobeauty;}
    for k := 1 to 7 do
        rec_b[k].cargo := -1;
    rec_b[7].where := tobeauty;
    rec_b[7].cargo := 20;

    {testing part ended}

    fruit := none;

    for k := 1 to 7 do
    begin
        fruit := Ternary((rec_b[k].where = tobeauty) and ( fruit in [none , pineapple]), appricot , fruit );
        fruit := Ternary((rec_b[k].cargo = -1) and ( not (fruit in  [grape])), lemon ,  fruit);
        fruit := Ternary((rec_b[k].where = track) and ( fruit in [ none , appricot , apple , pineapple]), grape , fruit);
        fruit := Ternary((rec_b[k].cargo = -1) and ( fruit  in  [lemon ]), pineapple ,  fruit);
        fruit := Ternary((rec_b[k].where = tobeauty) and ( fruit in [pineapple, appricot]), apple , fruit );
    end;
    Writeln(fruit);
end.

Are there some tricks on that do you know?