texts: Check for balanced parentheses in JavaScript

texts:
I just implemented the balanced parentheses problem in JavaScript. For those of you who are new to this problem, a statement of it would be:

  Give a string of parentheses (including braces and square brackets),
  check to see if they are opened and closed in order.  The last opened
  parens should be closed first before others. '[()]{}{()()}' is
  balanced.  However, '( (] ([)]' is not.

Here is my solution:

  Algorithm

  Take a string input, such as '{([])}'. (Let's call each of
  the characters a 'paren'.)

  We validate the input, check if it is a string and has at least one paren.
  We initialize a stack and iterate through the string input.
  If the character is a closing paren, we check to see if it is the matching, closing paren of the top stack element. Note: This checks
  for the order, as the latest open parens have to be closed first in a
  balanced string of parens.
  If the character is an open paren, we push it onto the stack.
  If step 3 fails, even once, return false.
  After the loop, if the stack is empty, return true. (If all open parens were closed in order, the stack will be empty.)

var parenthesesAreBalanced = function(str) {
    var stack = new Stack(), l = str.length,
        currentVal, position, parenType,
        parentheses = '[]{}()';

    /* If it is not a string, return false */
    if(typeof str != 'string') {
        return false;
    }

    var foundParen = str.split('').some(function(el) {
        return (parentheses.indexOf(el) > -1);
    });

    /* If there is not a single instance of a paren, return false */
    if(!foundParen) return false;

    for(var i = 0; i < l; i++) {
        currentVal = str[i];

        position = parentheses.indexOf(currentVal);

        if(position === -1) {
            continue;
        }

        var parenType = (position % 2) ? 'closed' : 'open';

        if(parenType == 'closed') { /* 2. */
            var el = stack.pop();
            if(parentheses.indexOf(el) !== position - 1) {
                return false;
            }
        } else { /* 3. */
            stack.push(currentVal);
        }
    }
    /* 5. */
    return !stack.length();
};

I would appreciate any feedback on the performance and correctness of this implementation.

It looks like the time complexity is \$O(N)\$. How can it be improved with respect to the multiple, \$k\$, in \$O(N)\$?
What are some edge cases I should be testing? I tested the empty string, non-string values, and non-paren characters.


texts:
I've implemented 12 Days of Christmas just by using pattern matching. It's not very efficient as it performs 12 iterations, each performing its own iteration (potentially from 12 down to 1... does tail recursion kick in here though?) but I supposed I can live with that at the moment. I'm more concerned with learning how idiomatic F# is written. Would an F# programmer be more concerned with creating types, etc.?

module Christmas
let getOrdinal num =
    match num with
    | 1 -> sprintf "%ist" num
    | 2 -> sprintf "%ind" num
    | 3 -> sprintf "%ird" num
    | _ -> sprintf "%ith" num

let getPreamble num =
    sprintf "On the %s day of Christmas, my true love gave to me" (getOrdinal num)

let rec getVerse verse num =
    match num with
    | 12 -> getVerse (List.append verse ["12 drummers drumming"]) (num - 1)
    | 11 -> getVerse (List.append verse ["11 pipers piping"]) (num - 1)
    | 10 -> getVerse (List.append verse ["10 lords a-leaping"]) (num - 1)
    | 9 -> getVerse (List.append verse ["9 ladies dancing"]) (num - 1)
    | 8 -> getVerse (List.append verse ["8 maids a-milking"]) (num - 1)
    | 7 -> getVerse (List.append verse ["7 swans a-swimming"]) (num - 1)
    | 6 -> getVerse (List.append verse ["6 geese a-laying"]) (num - 1)
    | 5 -> getVerse (List.append verse ["5 golden rings"]) (num - 1)
    | 4 -> getVerse (List.append verse ["4 calling birds"]) (num - 1)
    | 3 -> getVerse (List.append verse ["3 French hens"]) (num - 1)
    | 2 -> getVerse (List.append verse ["2 turtle doves, and"]) (num - 1)
    | _ -> List.append verse ["A partridge in a pear tree"]

let composeVerse num =
    List.append [getPreamble num] (getVerse [] num)
    |> List.fold (fun r s -> r + s + "\n") ""

[1 .. 12]
|> Seq.iter (fun a -> printfn "%s" (composeVerse a))


texts:
I've written a python program do perform synthetic division on a polynomial. There are a few constraints (listed in the module docstring of the program) on the polynomial, mainly because I haven't had the time to work out all the edge cases. I would like feedback on everything possible, as I plan to use this to solve other polynomials. All feedback is welcome, appreciated, and considered!

Constraints

  Coefficients must only be one digit, if present

  Constant must be one digit, and must be present (even 0)

  Constant must be positive

synthetic_division.py

"""

SYNTHETIC DIVISION CALCULATOR

This program accepts a polynomial and returns all the
x intercepts.

Program has some constraints:
    - Coefficients must only be one digit, if present
    - Constant must be one digit, and must be present (even 0)
    - Constant must be positive

EX:
    Input: x^3 -4x^2 +x +6
    Output: X = [3, -1, 2]

"""

from functools import reduce

def get_coefficients(equation):
    """

    Returns the coefficients of the passed polynomial. If no coefficent, then 1 is returned.
    Only works for single digit coefficents, if present.

    :param equation: The equation to be analyzed

    """
    parts = equation.split()
    coeffs = []
    for part in parts:
        if part[0] == "x":
            coeffs.append(1)
        if part[0] == "-":
            coeffs.append(int(part[1]) * -1)
        if part[0] == "+" and "x" in part:
            if len(part) == 2:
                coeffs.append(1)
            else:
                coeffs.append(int(part[1]))
    return coeffs

def get_factors(equation):
    """
    Returns a list of factors of the constant

    :param n: Number to get factors from

    """

    constant = int(equation[len(equation) - 1])

    ###########################################
    """
    ===========================================
    Equation from StackOverflow user @agf
    https://stackoverflow.com/a/6800214/8968906
    ===========================================
    """
    factors = list(
        set(
            reduce(
                list.__add__, (
                    [i, constant//i] for i in range(1, int(constant**0.5) + 1) if constant % i == 0
                )
            )
        )
    )
    ###########################################

    #Add negatives
    length = len(factors)
    for i in range(length):
        factors.append(-factors[i])
    return factors

def synthetic_division(coefficients, factors):
    """
    Performs synthetic division with the passed coefficients and factors
    Returns a list of intercepts

    :param coefficients: Coefficients to use in the calculation
    :param factors: Factors to test

    """

    coeffs = coefficients
    facs = factors
    ints = []

    for fac in facs:
        current_sum = 0
        for coeff in coeffs:
            current_sum += coeff
            current_sum *= fac
        if current_sum == 0:
            ints.append(fac)

    return ints

def main(equation):
    """

    Gathers the coefficients, factors and intercepts from the equation

    :param equation: The polynomial to be solved

    """
    coefficients = get_coefficients(equation)
    constant = int(equation[len(equation) - 1])
    coefficients.append(constant)

    factors = get_factors(equation)
    intercepts = synthetic_division(coefficients, factors)

    return intercepts

if __name__ == '__main__':
    EQUATION = "x^3 -4x^2 +1x +6"
    print(f"X = {main(EQUATION)}")


texts: Refactor selective item by highest create date or update date

texts:
I have to check for the Highest Date from CostRepository whether it is create date or edit date then i have to get value in that field. edit date can be null. i don't know how to fix the codesmell.

var allCostsInThisPo = CostRepository
                       .GetAll()
                       .WhereInPo(po.po_surr_key);

if (allCostsInThisPo.Any())
{
    var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item => item.create_date).First();
    var allEditedCosts = allCostsInThisPo.Where(item=>item.update_date != null);

    if (allEditedCosts.Any())
    {
        var costWithMaxEditedDate = allEditedCosts.OrderByDescending(item => item.update_date).First();

        if (costWithMaxCreatedDate.create_date > costWithMaxEditedDate.update_date)
        {
            history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date);
        }
        else
        {
            history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxEditedDate.EditedByUser.user_fullname, costWithMaxEditedDate.update_date.Value);
        }

    }
    else
    {
        history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date);
    }

}


texts: Re-interpolating a value from jq back into jq

texts:
I have an almost-json document in a file named "versions.json" like this:

{
  "package_a": {
    "sha_darwin": "6d94f041d06670977b2e5604b827f7e8bd46a1d200d14545ba75c17314ec12ad",
    "sha_linux": "6daa0fae252dc32e0af6ad89119555b277456349c55dfc9f276ee83718c6a9e2",
    "url": "https://github.com/someone/package_a/releases/download/v\(.version)/package_a_\(.version)_\(.platform)_x86_64.tar.gz",
    "version": "1.2.3"
  }, "package_b": {
    "sha_darwin": "6d94f041d06670977b2e5604b827f7e8bd46a1d200d14545ba75c17314ec12ad",
    "sha_linux": "6daa0fae252dc32e0af6ad89119555b277456349c55dfc9f276ee83718c6a9e2",
    "url": "https://storage.googleapis.com/package_b/release/v\(.version)/package_b_\(.version)_\(.platform)/amd64/package_b",
    "version": "6.3.0"
  }
}

It's input from a third party and I can't change it. What I need to do is interpolate the platform and version into the url. The problem is that that version value comes from the version in the file itself. I can't quite get it in the raw file because it's not actually valid json.

jq -r . versions.json
parse error: Invalid escape at line 5, column 129

I can get this in two passes:

echo '{"platform":"darwin","version":""}' |
  jq -f versions.json |
  jq -r '{version:.package_a.version,platform:"darwin"}' |
  jq -f versions.json |
  jq -r '"curl -sSL \(.package_a.url | @sh)"' |
  sh

But I'm not happy with the number of pipes and invocations of jq here, and looking to improve this all around. I would prefer a solution that involves a single invocation of jq, if that can be done.


texts:
I solve this problem in Swift. However, some cases I got terminated due to timeout because the solution isn't efficient enough. I did check the solutions and they are correct. Any tips on making it more efficient and code review?

import Foundation

func readInteger() -> Int {
    guard let line = readLine() else { fatalError("cannot read line") }
    guard let i = Int(line) else { fatalError("cannot convert line to int") }
    return i
}

func readStrings() -> [String] {
    guard let line = readLine() else { fatalError("cannot read line") }
    let strings = line.componentsSeparatedByString(" ").map { $0 }
    return strings
}

var stack = [String]()

var string = String()

enum Type: Int {
    case append = 1, delete, print, undo
}

func textEditor(operation: [String]) {
    guard let type = Type(rawValue: Int(operation[0])!) else { fatalError("unknown type") }
    switch type {
    case .append:
        stack.append(string)
        string += operation[1]
    case .delete:
        guard string.characters.count > Int(operation[1]) else { stack.append(string); string = ""; return }
        stack.append(string)
        string = string.substringToIndex(string.endIndex.advancedBy(-Int(operation[1])!))
    case .print:
        print(string[string.startIndex.advancedBy(Int(operation[1])!-1)])
    case .undo:
        if !stack.isEmpty {
            string = stack.last!
            stack.popLast()
        }
    }
}

func inputs() {
    let operations = readInteger()
    for _ in 0..<operations {
        let operation = readStrings()
        textEditor(operation)
    }
}

inputs()


texts: Logging the caller ip in a asmx web service using NLog

texts:
private void log(MethodExecutionArgs args, string message, LogLevel level)
{
    var calling_ip = ((System.Web.Services.WebService)args.Instance).Context.Request.UserHostAddress;
    string method = args.Method.Name;
    LogEventInfo logInfo = new LogEventInfo(level, logger.Name, message);
    logInfo.Properties.Add("method", method);
    logInfo.Properties.Add("calling_ip", calling_ip);
    logger.Log(logInfo);
}

I have written this method to log the ip address of the caller. The calling_ip value is accessed in the NLog.config via the event_context ${event-context:item=calling_ip}

Can this code be improved?


texts: GroupBy by nodeJS or ES6 of very nested JSON Objects with condition

texts:
The following code should return an array (flatFeatures) which will include feature.name and the most far subscription.expDate. for example if I have some subscriptions with the same features, the flatFeatures array will include distinct of all features from all the subscriptions but for every feature we will have the most later date of the subscription it belongs to. Something like that in SQL:
SELECT Features.Name, MAX(subscriptions.expDate)
FROM Subscriptions
INNER JOIN Plans ON Subscriptions.planId = Plans.planId
INNER JOIN Features ON Plans.PlanId = Features.PlanId

But i need it to be done by NodeJS for the JSON i already have from MongoDB.
    const flatFeatures = new Array();

    allActiveSubscriptions.forEach(subscription => {

      if (subscription.plan && subscription.plan.featuresList) {
        subscription.plan.featuresList.forEach(feature => {
          const existingFlatFeature = flatFeatures.find(flatFeatureItem => {
            return (flatFeatureItem.name === feature.name);
          });

          if (existingFlatFeature) {
            existingFlatFeature.expDate = (subscription.expDate > existingFlatFeature.expDate) ? subscription.expDate : existingFlatFeature.expDate;
          } else {
            flatFeatures.push({
              name: feature.name,
              expDate: subscription.expDate
            });
          }

        });
      }
    });


texts: Multiple choice quiz with difficulty and topic options

texts:
This is my code for an MCQ with difficulty and question options. It uses a namedtuple for the questions, and puts them in an array, and uses a difficulty parameter to decide how many options are displayed. This is so that I can have 3 difficulty options: one which outputs 2, one 3, and one outputting 4.

from collections import namedtuple
Question = namedtuple("Question", "question answer choices correct")

maths_questions = [Question("What is 1 + 1", "1 + 1 is 2", ["1", "2", "3", "4"], {"b", "2"}),
                   Question("What is 2 + 3", "2 + 3 is 5", ["5", "4", "2", "1"], {"a", "5"})]

music_questions = [Question("Who sung Gangsta's paradise?", "Coolio", ["1", "2", "Coolio", "4"], {"c", "coolio", "3"}),
                   Question("What is DANK", "Weed is DANK", ["5", "4", "DANK", "1"], {"c", "dank", "3"})]
ansdict = []

def quiz(questions, difficulty):
    score = 0
    for question in questions:
        global ansdict; ansdict = question.choices
        print(question.question)  # PRINTS OUT QUESTION
        output(difficulty, ansdict)
        users_answer = input().lower()
        if users_answer in question.correct:  # checks whether users input is in the answer tuple
            print("Correct")
            score += 1
        else:
            print("Incorrect", question.answer)  # if incorrect outputs correct answer
    print("{} out of {}".format(score, len(questions)))

def output(difficulty, dicti):
    for i in range(difficulty):
        print(dicti[i])

quiz(music_questions, 4)


texts: Determine if a String can be parsed to LocalDateTime or Int

texts:
I have the following kotlin function that takes in a string "value", then attempts to parse "value" as both a LocalDateTime and an Int. It returns a Pair of the parsed value of "value" and an enum that specifies which of the three types it was determined to be.

enum class RangeValueType{
    Int,
    Date,
    String
}

fun parseValue(value: String): Pair<RangeValueType, Any> {
    val rangeDate: LocalDateTime
    val rangeInt: Int
    //try date first
    try {
        //ISO_LOCAL_DATE_TIME e.g. 2011-12-03T10:15:30 for Dec. 3rd, 2011 & 10:15 30 sec.
        //can't use basic date b/c e.g. 20111203 is indistinguishable from an int.
        rangeDate = LocalDateTime.parse(value)
        //it parsed to a date, so return the date
        return Pair(RangeValueType.Date, rangeDate)
    }catch (dtpe: DateTimeParseException) {
        //not a date
    }
    //try number next
    try{
        rangeInt = value.toInt()
        //it parsed to an int, so return the int
        return Pair(RangeValueType.Int, rangeInt)
    }catch (nfe: NumberFormatException)
    {
        //not an int
    }
    //not date or int, must be a string
    return Pair(RangeValueType.String, value)
}

My principal concern is that I am using caught exceptions as a means of flow control, which I understand to generally be a Bad Idea. I know C# has a "TryParse" method for exactly this kind of case, but I wasn't able to find anything for Kotlin / Java.

Is there a better way to parse the values into their proper types?


texts: Function to trigger animation with mouse wheel events

texts:
I am new in the JavaScript world and I just want to know if I can optimize my function by making it shorter. It already works but I plan to add five timelines to trigger with my slidenum variable. Here is the code :

var slidenum = 0;
var skrollViewport = document.getElementById('wrapper');
skrollViewport.addEventListener('wheel', skrollSlide);

function skrollSlide(event) {
    var delta;
    if (event.wheelDelta) {
        delta = event.wheelDelta;
    } else {
        delta = -1* event.deltaY;
    }
    if (delta <0) {
        slidenum++;
    } else if (delta >0) {
        slidenum = slidenum>0 ? --slidenum : 0;
    }
    if (slidenum > 0) {
        slide1.play()
    } else if (slidenum < 1) {
        slide1.reverse()
    }
    if (slidenum > 1) {
        slide2.play()
    } else if (slidenum < 2) {
        slide2.reverse()
    }
    console.log(slidenum);
}


texts: Efficiently read a file into a (C) string using POSIX APIs

texts:
Exactly what the title says, this is a C++ class that attempts to read a file into a null-terminated string as efficiently as possible, using POSIX APIs. Obviously this is not intended to be portable code (other than between POSIX-compliant operating systems and GCC or clang), and the Slurp class would have a more extensive API in "real" code.
But, is there any room for improvement in terms of correctness or efficiency?
#ifndef SLURP_H
#define SLURP_H

class Slurp {
    void *begin_{nullptr};
    void *end_;
public:
    Slurp() = delete;
    Slurp(Slurp&) = delete;
    Slurp &operator=(Slurp) = delete;

    [[gnu::nonnull]] Slurp(const char path[]);

    ~Slurp();

    [[gnu::const, gnu::returns_nonnull]] const char *begin() const noexcept;
    [[gnu::const, gnu::returns_nonnull]] const char *end() const noexcept;
};

#endif //SLURP_H

// Slurp.cc
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <system_error>

using namespace std;

#define ERROR_IF(CONDITION) do {\
        if (__builtin_expect((CONDITION), false))\
            throw system_error(errno, system_category());\
    } while (false)

#define ERROR_IF_POSIX(POSIX_PREFIXED_FUNCTION_CALL) do {\
        const int error_number = posix_##POSIX_PREFIXED_FUNCTION_CALL;\
        if (__builtin_expect(error_number, 0))\
            throw system_error(error_number, system_category());\
    } while (false)

Slurp::Slurp(const char path[]) {
    class FileDescriptor {
        const int fd_;
    public:
        FileDescriptor(int fd) : fd_{fd} {ERROR_IF(fd_ == -1);}
        ~FileDescriptor() {close(fd_);}
        [[gnu::const]] operator int() const noexcept {return fd_;}
    };

    FileDescriptor fd{open(path, O_RDONLY)};

    ERROR_IF_POSIX(fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL));

    struct stat file_statistics;

    ERROR_IF(fstat(fd, &file_statistics));

    constexpr char32_t NullChar = U'\0';

    const size_t fsize = static_cast<size_t>(file_statistics.st_size),
        blksize = static_cast<size_t>(file_statistics.st_blksize),
        bufsize = fsize + sizeof NullChar;

    ERROR_IF_POSIX(memalign(&begin_, blksize, bufsize));

    end_ = static_cast<char*>(begin_) + fsize;

    ERROR_IF_POSIX(madvise(begin_, bufsize, POSIX_MADV_SEQUENTIAL));

    ERROR_IF(read(fd, begin_, fsize) == -1);

    memcpy(end_, &NullChar, sizeof NullChar); // ensure null termination
}

Slurp::~Slurp() {free(begin_);}

const char *Slurp::begin() const noexcept {return static_cast<char*>(begin_);}
const char *Slurp::end() const noexcept {return static_cast<char*>(end_);}


texts:
I am building a simple calculator with jQuery.

I can append the value to the screen and when the user clicked the operator the first values are clear or empty.

My question is, how can I store first and second values from the input field to use those values to perform the calculation?

$(document).ready(function() {
  console.log("ready!");
  let firstVal = 0;
  let secVal = 0;
  let latestNumber = 0;

  $(".btn").on("click", function(event) {
    let currentVal = $("input").val();
    console.log("currentVal is " + currentVal);
    let val = $(this).data("val");
    console.log("val is " + val);
    firstVal = $("input").val(currentVal + val);

    switch (val) {
      case "+":
        latestCalculationMethod = val;
        $("input").val("");
        return;
      case "-":
        latestCalculationMethod = val;
        $("input").val("");
        return;
      case "x":
        latestCalculationMethod = val;
        $("input").val("");
        return;
      case "/":
        latestCalculationMethod = val;
        $("input").val("");
        return;
      default:
        latestNumber = 0;
    }

    if (firstVal === "") {
      firstVal = latestNumber;
    } else {
      secVal = latestNumber;
    }
  });


texts:
I recently watched this video about the random number generation in Super Mario World. The technique that is used, as seen in the image below, multiplies one of the seeds by 5 and adds 1, the other seed is multiplied by 2, and then depending on whether the 4th and 7th bits are the same, 1 is added. So as stated in the video, the sequence of numbers will repeat after 27776 successive calls.

In my implementation of a pseudo random number generator, I have used 16 bit values for the two seeds to allow for a greater range of numbers, and my get_rand() function returns the two 16 bit strings joined together, resulting in a 32 bit number. This means that the sequence of numbers repeats after 526838144 successive calls, which is far greater than that achieved with the pseudo random number generator used in Super Mario World.

I have also created a rand_int() and a random() function that allow for better use of the numbers generated, these simply divide the number returned by 2 ** 32 over the difference between the integer range.

The PRNG Test.py is there only so that I can make sure that all the functions work as expected, and it seems to provide evenly split pseudo random numbers. So I am just after a review of the PRNG.py file, as it is that which I would like to optimize and improve.

PRNG.py

#Make sure Seeds.txt exists
try:
    file = open('Seeds.txt')
except FileNotFoundError:
    file = open('Seeds.txt', 'a+')
    file.write('0\n0')

#Gets the values of the seeds from the file
values = file.readlines()
file.close()

S = int(values[0].rstrip('\n'))
T = int(values[1])

def seed(seed_value):
    '''Resets the seed for the PRNG to make values predictable'''
    global S, T

    with open('Seeds.txt', 'w') as file:
        file.write(str(seed) + '\n' + str(seed))
        file.close()

    S = seed
    T = seed

def update_seeds(S, T):
    '''Generates the next two seeds'''
    S = 5 * S + 1

    try: bit_11 = '{0:b}'.format(T)[-11]
    except IndexError: bit_11 = '0'

    try: bit_16 = '{0:b}'.format(T)[-16]
    except IndexError: bit_16 = '0'

    if bit_11 == bit_16: T = 2 * T + 1
    else:                T = 2 * T

    return S, T

def get_rand(): #Has 526838144 Possible numbers
    '''Produces a random number in the range 0 to 2 ** 32'''
    global S, T

    S, T = update_seeds(S, T)
    S = int('{0:b}'.format(S)[-16:], 2)
    T = int('{0:b}'.format(T)[-16:], 2)
    K = '{0:b}'.format(S ^ T)

    S, T = update_seeds(S, T)
    S = int('{0:b}'.format(S)[-16:], 2)
    T = int('{0:b}'.format(T)[-16:], 2)
    J = '{0:b}'.format(S ^ T)

    with open('Seeds.txt', 'w') as file:
        file.write(str(S) + '\n' + str(T))
        file.close()

    for i in range(16 - len(K)): K = '0' + K
    for i in range(16 - len(J)): J = '0' + J

    return int(K + J, 2)

def rand_int(a, b):
    '''Produces in a random integer in the range a to b'''
    difference = (b + 1) - a
    factor = 2 ** 32 / difference
    return a + int(get_rand() / factor)

def random():
    '''Returns a random float between 0 and 1'''
    return get_rand() / 2 ** 32

PRNG Test.py

import PRNG

l = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(10000):
    number = PRNG.rand_int(0, 9)
    l[number] += 1

for i in l:
    print(str(round(i / 10000 * 100, 2)) + '% :', i)


texts:
This is a Leetcode problem -

  A password is considered strong if below conditions are all met -

  1. It has at least 6 characters and at most 20 characters.

  2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.

  3. It must NOT contain three repeating characters in a row (...aaa... is weak, but ...aa...a... is strong, assuming other
  conditions are met).

  Write a function strong_password_checker(s), that takes a string s
  as input, and returns the MINIMUM change required to make s a
  strong password. If s is already strong, return 0.

  Insertion, deletion or replacements of any one character are all
  considered as one change.

Here is my solution to this challenge -

def strong_password_checker(s: str) -> int:
    def has_lower(s):
        for c in s:
            if c.islower(): return 1
        return 0

    def has_upper(s):
        for c in s:
            if c.isupper(): return 1
        return 0

    def has_digits(s):
        for c in s:
            if c.isnumeric(): return 1
        return 0

    def find_repeats(s):
        i = 0
        j = 0
        repeats = []
        while i < len(s) - 1:
            if s[i+1] == s[i]:
                i += 1
                continue
            if (i - j + 1) > 2: repeats.append(i - j + 1)
            i += 1
            j = i
        if (i - j + 1) > 2: repeats.append(i - j + 1)
        return repeats

    def repeats_after_delete(reps, d):
        if d >= sum([r - 2 for r in reps]):
            return []
        reps = sorted(reps, key=lambda d: d%3)
        while d > 0:
            for i in range(len(reps)):
                if reps[i] < 3:
                    continue
                r = reps[i] % 3 + 1
                reps[i] -= min(r, d)
                d -= r
                if d <= 0:
                    break
        return [r for r in reps if r > 2]

    def num_repeats_change(repeats):
        return sum([r // 3 for r in repeats])

    total_changes = 0
    format_changes = (1 - has_lower(s)) + (1 - has_upper(s)) + (1 - has_digits(s))
    repeats = find_repeats(s)
    if len(s) < 6:
        repeat_change = num_repeats_change(repeats)
        total_changes = max([6 - len(s), format_changes, repeat_change])
    elif len(s) > 20:
        repeats = repeats_after_delete(repeats, len(s) - 20)
        repeat_change = num_repeats_change(repeats)
        total_changes = len(s) - 20 + max([repeat_change, format_changes])
    else:
        repeat_change = num_repeats_change(repeats)
        total_changes = max([repeat_change, format_changes])
    return total_changes

Here are some example outputs -

#print(strongPasswordChecker("aaaaaaaaaaaaAsaxqwd1aaa"))

>>> 6

#Explanation - aa1aa1aa1aAsaxqwd1aa (just an example - delete three characters, add three digits to replace consecutive a's)

#print(strongPasswordChecker("aaaaa"))

>>> 2

#Explanation - aaAaa1 (just an example - add a character (so the length is at least 6), add an uppercase letter to replace consecutive a's)

#print(strongPasswordChecker("aAsaxqwd2aa"))

>>> 0

#Explanation - A strong password (all conditions are met)

Here are the times taken for each output -

%timeit strongPasswordChecker("aaaaaaaaaaaaAsaxqwd1aaa")
>>> 18.7 µs ± 1.75 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit strongPasswordChecker("aaaaa")
>>> 5.05 µs ± 594 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit strongPasswordChecker("aAsaxqwd2aa")
>>> 7.19 µs ± 469 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts: K-combination recursive algorithm implementation

texts:
Tried to implement this solution for finding n choose k.
I have used recursion and this is how it goes for k as 4 and n as 6. Zero based

The idea is to have array of size k keeping sequence of indices of elements from the input array (which are numbers from 0 to n - 1) in increasing order. On each step, algorithm looks for the closest to the end item which can be incremented, increments it and fills up items right to that item.

 def get_combinations(str_index, k, n, index, limit, increment):
     if increment < limit:
         str_index[index] = increment
         result.add(tuple(str_index[0:index]+[increment]+str_index[index+1:]))
         get_combinations(str_index[:], k, n, index, limit, increment+1)
         if index >= 0 and str_index[index-1]+1 < increment:
             get_combinations(str_index[:], k, n, index-1, increment, str_index[index-1])

 result = set()
 word = "happyco"
 k = 4
 n = len(word)
 str_index = [i for i in range(k)]
 result.add(tuple(str_index))
 get_combinations(str_index, k, n, k-1, n, k)
 for combination in result:
     print("".join([word[i] for i in combination]))

However, there are some problems with this recursive approach:

a. It will cause stack overflow if n and k is huge.

b. I am using set to fix duplicates in the result.


texts: Immutable recursive binary search of a generic array

texts:
I am new to F#. Is the following code, which represents about three hours of work, a canonical way to achieve binary search? If not, how can it be improved for readability and maintainability?

let binarySearch (array: 'a[]) (target: 'a) =
    let rec search min max =
        match (min, max) with
        | (min, max) when max < min -> -1
        | _ ->
            let guess = ((min + max) / 2);
            match array.[guess] with
            | x when x = target -> guess
            | x when x < target -> search (guess + 1) (max)
            | _ -> search (min) (guess - 1)
    search (0) (array.Length - 1)

Aspects that I already like:

hiding the recursive function within the non-recursive function.
using pattern matching instead of if-else-then, based on suggestions here,
accepting generic types with `a.


texts:
I am using the following to retrieve some user info based on IP address. ClientLocation() returns an array with city, state and coordinates.

My concern with this is the function is called whenever I want to retrieve different array values. How can this be optimized so that the function is called once, but still retrieve multiple array values.

Public Function ClientLocation() As Object

    Dim Result As ArrayList = New ArrayList
    Dim XMLDoc As XmlDocument = New XmlDocument()
    Dim APIKey = "apikey"
    Dim GetXML = "url in xml"

    Try
        XMLDoc.Load(GetXML)
        Dim XMLResponse As XmlNodeList = XMLDoc.SelectNodes("Response")
        For Each Item As XmlNode In XMLResponse
            Result.Add(Item("cityName").InnerText & ", " & Item("regionName").InnerText)
            Result.Add(Item("latitude").InnerText & "," & Item("longitude").InnerText)
            Return (Result)
        Next
    Catch err As Exception
        Result.Add("Not Available")
        Result.Add("Not Available")
        Return (Result)
    End Try

    Return Nothing
End Function

Calling function

Dim UserProfile As ProfileCommon = Profile.GetProfile(User.Identity.Name)

UserProfile.Location = ClientLocation.Item(0)
UserProfile.Coordinates = ClientLocation.Item(1)
UserProfile.Save()


texts:
I've been programming for what is a probably a little bit and made a very simple logging system for my personal projects. While it works out fairly well so far, I would like advice on how to make it perform better and stuff I can do to make it more usable in general.

Main questions include:

Is my code thread safe? If not, how do I make it thread safe?
Is there a way to make the interface a bit cleaner for use? Right now #define feels a bit hacky.
Is there a way to avoid the use of a global unique_ptr?
Should I just make it a header only library? Is there any benefits in doing so?

.hpp:

#pragma once

/*
Use it by including this header in every file required, and in your main function start a new log.
    Logger::startLog("Log.txt");
Use the various error levels by naming them and simply passing the info and what you want to output.
    Logger::log(ERROR, "Something went wrong.");
*/

// For the unique pointers.
#include <memory>
// Filestream.
#include <fstream>
// String class for names and parameters passed around.
#include <string>

#define FATAL Logger::Level::Fatal
#define ERROR Logger::Level::Error
#define WARNING Logger::Level::Warning
#define INFO Logger::Level::Info
#define DEBUG Logger::Level::Debug

namespace Logger {
    // Severity level enum.
    enum class Level {
        Fatal,
        Error,
        Warning,
        Info,
        Debug
    };

    // Initialize the log.
    void startLog(const std::string& filepath);

    // Log a message.
    void log(Level s, const std::string& msg);

    // Logging class.
    class Log {
    public:
        Log(const std::string& filepath);
        void addLog(Level s, const std::string& msg);
        ~Log();
    private:
        // File for logging.
        std::ofstream m_logfile;
        std::string levels[5] = {"Fatal", "Error", "Warning", "Info", "Debug"};
    };
}

.cpp:

#include "Log.hpp"

namespace Logger {
    // Global Logging Object.
    std::unique_ptr<Log> g_log;

    // Initalize our logging object.
    void startLog(const std::string& filepath) {
        g_log = std::make_unique<Log>(filepath);
        Logger::log(Level::Info, "Started logging system.");
    }

    // Method which logs.
    void log(Level s, const std::string& msg) {
        g_log->addLog(s, msg);
    }

    // Create our global logging object.
    Log::Log(const std::string& filepath) : m_logfile{} {
        m_logfile.open(filepath);
    }

    // Add a message to our log.
    void Log::addLog(Level s, const std::string& msg) {
        if (m_logfile.is_open()) {
            m_logfile << levels[static_cast<int>(s)] << ": " << msg << std::endl;
        }
    }

    Log::~Log() {
        addLog(Level::Info, "Stopped logging system.");
        m_logfile.close();
    }
}


texts: Sorting a list into different bags according to predicate

texts:
I've just started with F# (I'm coming from a mostly OO background) and I'm looking for

feedback on the code, particularly: is this the way F# code should be written like?
have I overlooked an existing library function which would make this easier or could replace it completely?

The goal is:

Take an input list and sort it according to certain conditions into several bags, keeping also those items not fitting any condition. (Which is why groupBy doesn't do the trick, unless I'm overlooking something).

The function:

let sortIntoBags<'T, 'TBag> (predicate: 'TBag*'T->bool) (bags: 'TBag list)
(lst: 'T list)=
    let take (lst: 'T list) (bag: 'TBag)=
        let isInBag e = predicate (bag, e)
        let (inBag, remaining) = lst |> List.partition isInBag
        ((bag, inBag), remaining)
    let (bagSets, leftOver) = bags |> List.mapFold take lst
    (bagSets, leftOver)

A simple example for usage is:

> let l= [1..25];;

val l : int list =
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21;
 22; 23; 24; 25]

> let bags= [2; 3; 5; 7];;
val bags : int list = [2; 3; 5; 7]

> let isDivisorFor (x, y) = 0=y%x ;;
val isDivisorFor : x:int * y:int -> bool

> l |> sortIntoBags isDivisorFor bags;;
val it : (int * int list) list * int list =
([(2, [2; 4; 6; 8; 10; 12; 14; 16; 18; 20; 22; 24]); (3, [3; 9; 15; 21]);
(5, [5; 25]); (7, [7])], [1; 11; 13; 17; 19; 23])


texts: ERP-system with UserForm that transfers data to next available row in an archive spreadsheet

texts:
I made this huge code (Edit: huge for such a simple task) for transferring data and adding an ID number to every new row of data. The only functionality flaw I see is that it creates new ID numbers if you transfer blank cells. I was wondering if anyone can help me improve this code? I'm very bad at loops so if there is any possibilities for loops that I overlooked please tell me.

Edit: also had to add another worksheet for temporarily storing the data, so I could copy it as a range, since it is first saved as a value.

Private Sub CommandButton2_Click()

'Variabler for inputs
shipFrom = TextBox1.Text
shipTo = TextBox2.Text
shipDate = TextBox3.Text
NP = TextBox4.Text
desc = TextBox10.Text
gramEx = TextBox6.Text
tareWeight = TextBox7.Text
weight = TextBox8.Text
dims = TextBox9.Text

Sheets("test").Range("b2").Value = shipFrom
Sheets("test").Range("c2").Value = shipTo
Sheets("test").Range("d2").Value = shipDate
Sheets("test").Range("e2").Value = NP
Sheets("test").Range("f2").Value = desc
Sheets("test").Range("g2").Value = gramEx
Sheets("test").Range("h2").Value = tareWeight
Sheets("test").Range("i2").Value = weight
Sheets("test").Range("j2").Value = dims

Dim sf As Range
Set sf = Sheets("test").Range("b2")

Dim st As Range
Set st = Sheets("test").Range("c2")

Dim d As Range
Set d = Sheets("test").Range("d2")

Dim l As Range
Set l = Sheets("test").Range("e2")

Dim i As Range
Set i = Sheets("test").Range("f2")

Dim g As Range
Set g = Sheets("test").Range("g2")

Dim t As Range
Set t = Sheets("test").Range("h2")

Dim w As Range
Set w = Sheets("test").Range("i2")

Dim di As Range
Set di = Sheets("test").Range("j2")

Dim nextRowB As Range
Set nextRowB = Sheets("Arkiv").Range("B" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowC As Range
Set nextRowC = Sheets("Arkiv").Range("C" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowD As Range
Set nextRowD = Sheets("Arkiv").Range("D" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowE As Range
Set nextRowE = Sheets("Arkiv").Range("E" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowF As Range
Set nextRowF = Sheets("Arkiv").Range("F" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowG As Range
Set nextRowG = Sheets("Arkiv").Range("G" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowH As Range
Set nextRowH = Sheets("Arkiv").Range("H" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowI As Range
Set nextRowI = Sheets("Arkiv").Range("I" & Rows.Count).End(xlUp).Offset(1, 0)

Dim nextRowJ As Range
Set nextRowJ = Sheets("Arkiv").Range("J" & Rows.Count).End(xlUp).Offset(1, 0)

sf.Copy nextRowB
st.Copy nextRowC
d.Copy nextRowD
l.Copy nextRowE
i.Copy nextRowF
g.Copy nextRowG
t.Copy nextRowH
w.Copy nextRowI
di.Copy nextRowJ

Dim ID As Range
Set ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

If IsEmpty(Sheets("Arkiv").Range("B2").Value) Then

    MsgBox "Please fill in the <Ship From> box"

Else

    'Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = "1"
    Sheets("Arkiv").Range("A2").Value = "1"

End If

If IsEmpty(Sheets("Arkiv").Range("C2").Value) Then

Else

    ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value + 1

End If

Sheets("Arkiv").Activate
MsgBox "The ID number for this data is: " & Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value

End Sub


texts: Replacing if validations with a better error handling

texts:
I have this little piece of front-end code, and I had a little code smell about the handling of errors.

  request
   .post(('/api/comment/:id/upvote').replace(':id', this.comment.id))
      .end(function (err, res) {
      if (err) {
        log('Fetch error: %s', err);
        return classes(targetElement).remove('selected');
      }

      if (res.status == 401) {
        return errorContainer.innerHTML = t(res.body.error);
      }

      if (!res.ok) {
        log('Fetch error: %s', res.error);
        return classes(targetElement).remove('selected');
      }

      if (res.body && res.body.error) {
        log('Fetch response error: %s', res.body.error);
        return classes(targetElement).remove('selected');
      }

      log('successfull upvote %s', self.comment.id);
      });

In all error conditions, I should "rollback" an status of html element.

classes(targetElement).remove('selected');

I can chain all conditions in one if in order to handle errors, but there's still a code smell.

Does someone have some ideas on how to wrap this in a better error handling?


texts:
I'm implementing a CSR and CSC class! I found a lot of algorithms for computing a CSC * vector product but I didn't find any routine for the CsC * CsC matrix product, in order to save time when the size of the matrix becomes very large !

So I used the classical way of product ... in order to do this I have implemented operator()(i,j) that returns a value if it is different from zero, otherwise zero. For doing so I wrote a findindex utility function as follow :

template<typename T>
inline auto CSCmatrix<T>::findIndex(const std::size_t row, const std::size_t col) const noexcept
{
    auto ijt = std::find(ia_.begin()+ja_.at(col) , ia_.begin()+ja_.at(col+1), row );

    return static_cast<std::size_t>(std::distance(ia_.begin(), ijt ) );

}

//
// operator ()
template<typename T>
inline const T CSCmatrix<T>::operator()(const itype row,const itype col)const noexcept
{
    const auto i = findIndex(row,col);

    if(i < ja_.at(col+1))
      return a_.at(i) ;
    else
      return 0.0 ;
}

using this expansive operator .. I've implemented the product as follow :

template<typename T>
CSCmatrix<T> operator*(const CSCmatrix<T>& m1, const CSCmatrix<T>& m2)
{

      if( m1.size2() != m2.size1() )
      {
          throw std::runtime_error("Exception in operator * :  Matrix dimension must agree !");
      }

      CSCmatrix<T> res(m1.size1(), m2.size2());
      double sum ;
      for(std::size_t i=0 ; i < res.size1() ; i++ )   //
      {
            for(std::size_t j=0; j< res.size2() ; j++ )
            {
                  sum = 0;
                  for(std::size_t k=0; k< m1.size2() ; k++ )
                  {
                     sum += m1(i,k)*m2(k,j) ;
                  }
                  res(i,j,sum);
            }
      }
      return res;

}

I am looking for a way to improve my code. What can I do?


texts:
We were discussing Standard Deviations in chat, so I decided to write a standard deviation calculator:

static double PopulationStandardDeviation(List<double> numberSet)
{
    double mean = numberSet.Average();

    return Math.Sqrt(numberSet.Sum(x => Math.Pow(x - mean, 2)) / numberSet.Count);
}

static double SampleStandardDeviation(List<double> numberSet)
{
    double mean = numberSet.Sum() / numberSet.Count;

    return Math.Sqrt(numberSet.Sum(x => Math.Pow(x - mean, 2)) / (numberSet.Count - 1));
}

How could these be improved?  Because they are both Standard Devation calculators, should I combine them into one method with a header of static double StandardDeviation(List<double> numberSet, bool isSample)?  Are they an optimal solution for the problem?


texts:
I am trying out different data structures to learn more about smart pointers. I have created a queue implementation which has push, pop, front, back and size functions.

#include <iostream>
#include <memory>
#include <cstddef>

template<typename T>
class Queue
{
    std::unique_ptr<T[]> q_ptr;
    int front_idx = -1;
    int back_idx = -1;
    int capacity = 0;
public:
    Queue(std::size_t space)
    {
        q_ptr = std::unique_ptr<T[]>(new T[space]);
        capacity = space;
    }
    void push(T value);
    void pop();
    T front() const;
    T back() const;
    std::size_t size() const;
};

template<typename T>
void Queue<T>::push(T value)
{
    if(front_idx == -1)
    {
        front_idx++;
    }
    if(back_idx - front_idx + 1 == capacity)
    {
        std::cerr << "Queue full\n";
        return;
    }
    q_ptr[++back_idx] = value;
}

template<typename T>
void Queue<T>::pop()
{
    if(front_idx == -1)
    {
        std::cerr << "Empty queue\n";
        return;
    }
    q_ptr[front_idx++] = T{};
}

template<typename T>
T Queue<T>::front() const
{
    return q_ptr[front_idx];
}

template<typename T>
T Queue<T>::back() const
{
    return q_ptr[back_idx];
}

template<typename T>
std::size_t Queue<T>::size() const
{
    return back_idx - front_idx + 1;
}

int main()
{
    Queue<int> q1{20};
    q1.pop();
    for(int i = 0; i < 23; i++)
    {
        q1.push(i);
    }
    std::cout << "Queue size: " << q1.size() << "\n";
    std::cout << "Queue front: " << q1.front() << "\n";
    std::cout << "Queue back: " << q1.back() << "\n";
    q1.pop();
    std::cout << "Queue size: " << q1.size() << "\n";
    std::cout << "Queue front: " << q1.front() << "\n";
    q1.pop();
    std::cout << "Queue size: " << q1.size() << "\n";
    std::cout << "Queue front: " << q1.front() << "\n";
    q1.push(12);
    std::cout << "Queue size: " << q1.size() << "\n";
    std::cout << "Queue back: " << q1.back() << "\n";
}

The attempt is to use unique_ptr as an array similar to a raw pointer. Is the usage and approach correct? Can it be improved?
As far as I know, I cannot use shared_ptr this way in C++11 or C++14. Is this the best approach with shared_ptr?


texts:
I've been tasked with writing a function that executes a passed function every interval, passed to the function by the user. Below is the code, and how to call it:
import time
from typing import Callable

last_milliseconds: int = 0
def set_timer(interval: int, function: Callable) -> bool:
    global last_milliseconds
    milliseconds: int = int(round(time.time() * 1000))
    done: bool = (milliseconds - last_milliseconds) >= interval
    if done:
        function()
        last_milliseconds = milliseconds

Called by:
p: Callable = lambda: print("set_timer called.")

while True:
    set_timer(1000, p)

Is there a better way to go about this? I'm unsure with the use of the global variable, and the function must be called in an infinite loop structure in order to work. Any and all feedback is accepted and appreciated.


texts:
I'm working to implement some simple bigint functions for addition, multiplication and powers. They work correctly but the larger the numbers the longer the time it takes.
For example 210000 takes a very long time.
Here are all the functions I'm using.

char    *ft_strnew(size_t size)
    {
    char    *temp;
    size_t  i;

    if (!(temp = (char*)malloc(sizeof(char) * (size + 1))))
        return (NULL);
    i = 0;
    while (i < size)
    {
        temp[i] = '\0';
        i++;
    }
    temp[i] = '\0';
    return (temp);
}

char    *ft_strjoin(char const *s1, char const *s2)
{
    char    *temp;
    int     i;
    int     j;

    if (!(temp = (char*)malloc(sizeof(char) *
        (ft_strlen(s1) + ft_strlen(s2) + 1))))
        return (NULL);
    i = 0;
    j = 0;
    while (s1[i])
    {
        temp[j] = s1[i];
        i++;
        j++;
    }
    i = 0;
    while (s2[i])
    {
        temp[j] = s2[i];
        i++;
        j++;
    }
    temp[j] = '\0';
    return (temp);
}

int         left_one(int *i, char c)
{
    if (--(*i) < 0)
        return (0);
    else
        return (c - '0');
}

char        *add_char(char *nbr1, char *nbr2)
{
    int     i;
    int     j;
    int     left[4];
    char    *temp;

    left[0] = 0;
    temp = ft_strnew(0);
    i = ft_strlen(nbr1);
    j = ft_strlen(nbr2);
    if (i > j)
        left[3] = i;
    else
        left[3] = j;
    while (--left[3] >= 0)
    {
        left[1] = left_one(&i, nbr1[i - 1]);
        left[2] = left_one(&j, nbr2[j - 1]);
        left[0] += left[1] + left[2];
        temp = ft_charjoin((left[0] % 10) + '0', temp, 'l');
        left[0] /= 10;
    }
    if (left[0] > 0)
        temp = ft_charjoin((left[0] % 10) + '0', temp, 'l');
    return (temp);
}

char        *multi1_char(char *nbr1, int nbr2)
{
    int     i;
    char    *temp;

    if (nbr1[0] == '0' || nbr2 == 0)
        return ("0");
    i = -1;
    temp = ft_strdup(nbr1);
    while (++i < nbr2 - 1)
        temp = add_char(temp, nbr1);
    return (temp);
}

char        *multi_char(char *nbr1, char *nbr2)
{
    int         i;
    char        *temp;
    int         j;
    char        *temp1;
    int         t;
    char        *mul;

    mul = ft_strnew(0);
    temp = ft_strnew(1);
    j = 0;
    i = ft_strlen(nbr2);
    while (--i >= 0)
    {
        t = -1;
        temp1 = multi1_char(nbr1, nbr2[i] - '0');
        //temp1 = multi1_char(temp1, 10*j);
        /*while (++t < j)
            temp1 = ft_strjoin(temp1, "0");*/
        temp1 = ft_strjoin(temp1, mul);
        temp = add_char(temp, temp1);
        mul = ft_strjoin("0", mul);
        j++;
    }
    return (temp);
}

char    *power_char(int nbr1, int nbr2)
{
    char        *temp;

    temp = ft_strnew(0);
    if (nbr2 == 1)
        return (ft_itoa(nbr1));
    if (nbr2 % 2 == 0)
    {
        temp = power_char(nbr1, nbr2 / 2);
        return (multi_char(temp, temp));
    }
    else
    {
        nbr2 -= 1;
        temp = power_char(nbr1, nbr2 / 2);
        return(multi_char(ft_itoa(nbr1), multi_char(temp, temp)));
    }
}

I came up with a way to make the function that handles powers work faster but still the multiplication function is slow for big numbers.

Is there any way of improving my functions or are they bad from the start and I should start all over?


texts: Implementing a copy on write String class using reference counting in C++

texts:
I have tried to implement a copy on write string class with value semantics and reference counting.

I wanted to support indexing, so I have overloaded the operator[] and to differentiate between the l-value and r-value usage it is returning a proxy object.

#include <iostream>
#include <string.h>
class proxy;

//Reference counting class.Also holds the string.
class RC
{
    public:
        RC(const char * str);
        ~RC();
    private:
        char* str;
        int count;

    friend class mystring;
    friend class proxy;

};

class mystring
{
    public:
        mystring(const char*  str);
        mystring& operator=(const mystring& str);
        mystring(const mystring& str);
        ~mystring();

        void print() const;
        proxy operator[](int n);

    private:
        RC *pRC;

    friend class proxy;
};
class proxy
{
    public:
        proxy(mystring* r,int n);
        proxy& operator=(const char& c);
        proxy& operator=(const proxy& c);
        operator char() const;

    private:
        int n;
        mystring* ptr;
};

RC::RC(const char * str1)
:str(new char[strlen(str1)+1]),count(1)
{
    strcpy(str,str1);
}

RC::~RC()
{
    if(--count == 0)
        delete [] str;
}

proxy mystring::operator[](int n)
{
    return proxy(this,n);
}

mystring::mystring(const char*  str)
:pRC(new RC(str))
{
}
mystring& mystring::operator=(const mystring& rhs)
{
    if(this != &rhs)
    {
        if(--pRC->count == 0)
            delete pRC;
        pRC = rhs.pRC;
        ++pRC->count;
    }
    return *this;
}
mystring::mystring(const mystring& rhs)
{
    pRC = rhs.pRC;
    ++pRC->count;
}

mystring::~mystring()
{
    if(--pRC->count == 0)
        delete pRC;
}
void mystring::print() const
{
    std::cout << pRC->str << ":" << pRC->count << '\n';
}

proxy::operator char() const
{
    return ptr->pRC->str[n];
}

proxy::proxy(mystring* r,int n)
:ptr(r),n(n)
{}

proxy& proxy::operator=(const char& c)
{

    if(c != ptr->pRC->str[n])
    {
        char cpy[strlen(ptr->pRC->str)+1];
        strcpy(cpy,ptr->pRC->str);
        ptr->pRC->~RC();
        cpy[n] = c;
        ptr->pRC = new RC(cpy);
    }

    return *this;
}

proxy& proxy::operator=(const proxy& rhs)
{
    if(this != &rhs)
    {
        *this = (char)rhs;

    }

    return *this;
}

Can you please help me improve the code?


texts:
I've created a program that will list all hung print jobs on a specified server, from there it will load them and strip the jobs down to their Job ID then cancel the jobs on that server only.

I would like a critique of my work please.

How does this look as an OOP script?
Is there anything I can do differently?
Is calling the Net::SSH.start twice really necessary?

Source:

#!/usr/local/bin/ruby

require 'rubygems'
require 'net/ssh'
require 'etc'

class PrintJobs

  HOST = ARGV[0]
  USERNAME = Etc.getlogin
  PASSWORD = nil

  def scan_for_jobs
    check_jobs = Net::SSH.start(HOST, USERNAME, :password => PASSWORD) do |ssh|
      cmd = "prt_jobs"
      info = ssh.exec!(cmd)
      if info == nil
        puts "No print jobs on server #{HOST}"
      else
        res = info.split("\n").reject {|line| line.match(/\s+2016\s+/)}.join("\n")
        puts res
        print "Process into kill que: "
        input = STDIN.gets.chomp.upcase
        if input == "YES"
          kill_que(check_jobs, res)
        else
          exit 1
        end
      end
    end
  end

  def kill_que(check_jobs, res)
    puts "Loading jobs into kill que.."
    column = 0
    job_ids = res.lines.map { |job| job.split(/\s+/)[0] }.each do |task_id|
      kill_jobs(task_id)
    end
  end

  def kill_jobs(task_id)
    execute = Net::SSH.start(HOST, USERNAME, :password => PASSWORD)
    id_to_strip = task_id.gsub(/\-/," ")
    column = 1
    stripping_id = id_to_strip.lines.map { |task| task.split(/\s+/)[1] }.each do |id|
      id.strip
      puts "Cancelling job: #{id}"
      #`sudo cancel #{id}`
      execute.exec!("sudo cancel #{id}")
    end
  end
end

killer = PrintJobs.new
killer.scan_for_jobs

Usage example:

closing_2-254128        root            933888   Thu 03 Dec 2015 03:49:13 PM CST
closing_2-254129        root            933888   Thu 03 Dec 2015 03:50:16 PM CST
laser42-254144          root            192512   Thu 03 Dec 2015 04:24:02 PM CST
laser42-254145          root            171008   Thu 03 Dec 2015 04:25:10 PM CST
ship_audit-254143       root            141312   Thu 03 Dec 2015 04:23:13 PM CST
Process into kill que: yes
Loading jobs into kill que..
Cancelling job: 254128
Cancelling job: 254129
Cancelling job: 254144
Cancelling job: 254145
Cancelling job: 254143

No print jobs on server


texts:
First I've to indicate that this is my homework.

An example of a given input is:

s1 = {'p1': (x1, y1), 'p2': (x2, y2)}

where all names and coordinations are user input, only the input format is predefined; also p1 is the upper leftmost point and p2 is the lower rightmost point as shown below:

I can go on to get area, surrounding, midpoint, height and width based on this input.

I wrote a code that works as demanded but I don't like it. it doesn't seem I followed the Pythonic approach here; how can I improve this?

class rectangle:
    def __init__(self, dct):
        # ['name', [x, y]]
        names = list(dct.keys())
        coords = list(dct.values())
        start = [names[0], coords[0]]
        end = [names[1], coords[1]]
        self.start = start
        self.end = end

        # int
        start_coords = self.start[1]
        end_coords = self.end[1]
        width = end_coords[0] - start_coords[0]
        height = end_coords[1] - start_coords[1]
        self.width = width
        self.height = height

        # [x, y]
        midpoint = [self.width / 2, self.height / 2]
        self.midpoint = midpoint

        # int
        area = (self.width + self.height) * 2
        surr = self.width * self.height
        self.area = area
        self.surr = surr

s1 = rectangle({'p1': (1,1), 'p2': (2,2)})
print('point one: ', s1.start)
print('point two: ', s1.end)
print('width: ', s1.width)
print('height: ', s1.height)
print('midpoint: ', s1.midpoint)
print('area: ', s1.area)
print('surrounding: ', s1.surr)


texts:
What could I improve on this code?

from random import randint
guesses = 0
randomNum = (randint(0,100))
numPlayer = 0
while (numPlayer!=randomNum):
    numPlayer = int(input("Guess the number(0-100)"))
    if (numPlayer>randomNum) :
        print "It's -"
    elif (numPlayer<randomNum) : print("It's +")
    guesses=guesses+1

print ("Well done you guessed my number in %d guesses" % guesses)


texts: Count the number of ways to make a given sum using one number from each array

texts:
I have three arrays, each of which contains only numbers. Given a target number, I need to return the number of ways I can make that sum, using exactly one number from each of the arrays.

For example: If I have 2 arrays [[1,2,3], [1,2,3]] and the target sum is 4, I must return the number of combinations that will sum to 4. In this case, they are:

1+3 = 4
2+2 = 4
3+1 = 4

So the function will return 3.

I wrote the function below, and it works well, but I am looking for a way to make more efficient, as well as make it scale to more input arrays - I have less than 6 arrays, but I want it to work if I have a hundred arrays. Is there any array function that can help me here?

This is the code:

<?php
function get_sum ($dice, $sum) {
    $sumcount = array();
    $num_of_dice = count($dice);
    foreach($dice[0] as $die1){
        foreach($dice[1] as $die2){
            if($num_of_dice == 5){
                foreach($dice[2] as $die3){
                    foreach($dice[3] as $die4){
                        foreach($dice[4] as $die5){
                            if($die1 + $die2 + $die3+ $die4 + $die5 == $sum){
                                $good_res = array();
                                array_push( $good_res, $die1, $die2, $die3, $die4, $die5);
                                array_push($sumcount, $good_res);
                            }
                        }
                    }
                }
            }
            if($num_of_dice == 4){
                foreach($dice[2] as $die3){
                    foreach($dice[3] as $die4){
                        if($die1 + $die2 + $die3+ $die4 == $sum){
                            $good_res = array();
                            array_push( $good_res, $die1, $die2, $die3, $die4);
                            array_push($sumcount, $good_res);
                        }
                    }
                }
            }elseif ($num_of_dice == 3){
                foreach($dice[2] as $die3){
                    if($die1 + $die2 + $die3 == $sum){
                        $good_res = array();
                        array_push( $good_res, $die1, $die2, $die3);
                        array_push($sumcount, $good_res);
                    }
                }
            }else{
                if($die1 + $die2 == $sum){
                    $good_res = array();
                    array_push( $good_res, $die1, $die2);
                    array_push($sumcount, $good_res);
                }
            }

        }
    };

    echo count($sumcount);
}

get_sum([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 9)
?>


texts:
I am implementing atoi() by traversing a string from the beginning as well as from the end. Is there anything I can improve?

using namespace std;

int atoiLefttoRight(char *s){
    int num = 0;
    int negative = 1;
    if(s)
        {
        if(*s == '-')
            {
            negative = -1;
            s++;
            }
            while(*s && (*s <= '9') && (*s >= '0'))
            {
            num = (num * 10) + (*s - '0');
            s++;
            }
        }
return (negative * num);
}

int atoiRighttoLeft(char *s){
    int i = 1;
    int num = 0;
    int negative = 1;

    if(s){
        if(*s == '-')
                      {
            negative = -1;
            s++;
           }
    char *temp = s;
    while(*temp)
    temp++;
    temp--;

    while(*temp && temp >= s)
    {
        if( *temp <= '9' && *temp >= '0'){
        num = num + ( (*temp - '0') * i);
        i = i*10;
        temp--;
        }
        else
        {
        temp--;
        num = 0;
        i = 1;
        }
    }
    }
return (negative * num);
}

int main()
{
cout<<atoiLefttoRight("-12ab3")<<"\n";
cout<<atoiRighttoLeft("1234h5")<<"\n";
}


texts: Generate an ID number for each new row of text that is pasted into the worksheet

texts:
This code checks if "B2" and so on is filled in and if it is then it will generate a new ID number for the row of data that was transferred to the worksheet on the next empty row, I know this code creates opportunities for bugs so I want to make it better but I don't really know how I could do it. (PS: I am very bad at loops so if the solution is a loop please word yourself as if you were talking to a newcomer

'Creating a variable for all the inputs from the textboxes
Dim inputs As Variant
    inputs = Array(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox10.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, TextBox9.Text)
    ' shipFrom, shipTo, shipDate, NP, desc, gramEx, tareWeight, weight, dims

'Declaring a variable for the next available row where the inputs are going
Dim nextRowB As Range
    Set nextRowB = Sheets("Arkiv").Range("B" & Rows.Count).End(xlUp).Offset(1, 0)
    nextRowB.Resize(1, UBound(inputs) + 1).Value = inputs

'Delaring ID number for each row as a variable
Dim ID As Range
    Set ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
    If IsEmpty(Sheets("Arkiv").Range("B2").Value) Then 'How can I make this line better? I know this way of doing it creates oppertunities for many bugs

        MsgBox "Please fill in the <Ship From> box"

    Else

        Sheets("Arkiv").Range("A2").Value = "1"

    End If

    If Not IsEmpty(Sheets("Arkiv").Range("C2").Value) Then

        ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value + 1

    End If

    Sheets("Arkiv").Activate
    MsgBox "The ID number for this data is: " & Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value


texts: Assigned a System resource to an image based on variable

texts:
I have a mapping application and the marker I'm using is based on the field rep assigned to that visit.  My code is just a Select Case based on the rep's name and then it sets the bitmap for that person.

My code works fine, but there are 19 different field reps and I feel there must be a better way.

The code loops through a CSV file and grabs the Field Rep's name.  Based on who it is, a System Resource image for that person is assigned to the image.

Select Case CurrentRecord(iAssignedToCol)
  Case "Al B. Connor"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_ABC)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_ABC)
    End If
  Case "Donald E. Firestone"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_DEF)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_DEF)
    End If
  Case "3rd name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_GHI)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_GHI)
    End If
  Case "4th name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_JKL)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_JKL)
    End If
  Case "5th name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_MNO)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_MNO)
    End If
  Case "6th name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_PQR)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_PQR)
    End If
  Case "7th name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_STU)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_STU)
    End If
  Case "8th name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_VWX)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_VWX)
    End If
  Case "9th name"
    If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Scheduled_YZA)
    ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(My.Resources.Tentative_YZA)
    End If
End Select

marker = New GMarkerGoogle(New PointLatLng(sSearchLat, sSearchLong), MapIcon)

Thanks!


texts:
After reading about the Visitor pattern, I wrote this example in Ruby, loosely based on a Java implementation on the wikipedia page.

The choice between modules and classes felt somewhat arbitrary for some of these components. I mostly stuck with modules, opting for classes only for the car-elements. Even there I chose composition over inheritance when defining the accept method. It's so generic it's easy to imagine reusing it for other, non-car-related stuff.

I'm open to any thoughts and brutal criticisms this might incite :)

Car parts:

module Visitable
  def accept(visitor)
    visitor.visit(self)
  end
end

class Wheel
  include Visitable

  attr_reader :name

  def initialize(name)
    @name = name
  end
end

class Engine
  include Visitable
end

class Body
  include Visitable
end

class Car
  include Visitable

  def initialize
    @elements = [
      Wheel.new('front left'),
      Wheel.new('front right'),
      Wheel.new('back left'),
      Wheel.new('back right'),
      Body.new,
      Engine.new
    ]
  end

  def accept(visitor)
    @elements.each { |e| e.accept(visitor) }
    super
  end
end

Visitors

module CarElementVisit
  # required methods
  %i(
    visit_wheel
    visit_engine
    visit_body
    visit_car
  ).each do |method|
    define_method(method) { |*args| raise(NoMethodError, "Please implement #{method}") }
  end

  def visit(element)
    visit_method = visit_method_for(element)
    send(visit_method, element)
  end

  private

  def visit_method_for(element)
    case element
    when Wheel  then :visit_wheel
    when Engine then :visit_engine
    when Body   then :visit_body
    when Car    then :visit_car
    else raise(NotImplementedError, ":visit not implemented for #{element.class}")
    end
  end
end

module CarElementPrintVisitor
  extend CarElementVisit

  class << self
    def visit_wheel(wheel)
      puts("Visiting #{wheel.name} wheel")
    end

    def visit_engine(engine)
      puts('Visiting engine')
    end

    def visit_body(body)
      puts('Visiting body')
    end

    def visit_car(car)
      puts('Visiting car')
    end
  end
end

module CarElementDoVisitor
  extend CarElementVisit

  class << self
    def visit_wheel(wheel)
      puts("Kicking my #{wheel.name} wheel")
    end

    def visit_engine(engine)
      puts('Starting my engine')
    end

    def visit_body(body)
      puts('Moving my body')
    end

    def visit_car(car)
      puts('Starting my car')
    end
  end
end

car = Car.new
car.accept(CarElementPrintVisitor)
car.accept(CarElementDoVisitor)


texts:
I've been slowly learning Haskell over the past few months. I made a small module to graph functions using Gloss, and I would like feedback on how idiomatic it is (looking for ways to simplify using standard functions and to make it more pointfree).

Graph.hs

module Graph (graph) where

import Graphics.Gloss

graph :: (Float -> Float) -> (Float, Float, Float, Float) -> Float -> Picture
graph f (l, r, b, t) dx = pictures $ map Line visible
    where
        points :: [(Float, Float)]
        points = [(x, f x) | x <- [l,l+dx..r]]

        pairs :: [[(Float, Float)]]
        pairs = zipWith (\x y -> [x,y]) points $ tail points

        visible :: [[(Float, Float)]]
        visible = filter (all (\(_,y) -> b <= y && t >= y)) $ pairs

Main.hs

import Graphics.Gloss

import Graph

main :: IO ()
main = display FullScreen white . scale 20 20 . pictures $ [
        color blue $ graph f (-10, 10, -10, 10) 0.001,
        color black $ Line [(0, -10), (0, 10)],
        color black $ Line [(-10, 0), (10, 0)]
    ]
    where
        f :: Float -> Float
        f x = 1 / (x - 1)

Output


texts: DRY up ivar assignment in Rails new and create controller actions

texts:
When creating a new model in Rails, I need to pass a bunch of other models into the view so I can define the correct associations. All I’m really doing here is querying the persistence layer for models and assigning them to instance variables, but I’m having to do it twice. What’s the best way of extracting the assignment? Just creating a controller method and calling it? I’m not sure.

class ProjectsController < ApplicationController
  def new
    @project = Project.new
    @companies = Company.as_select_options
    @project_varieties = ProjectVariety.as_select_options
    @prices = Price.as_select_options
    @users = User.as_select_options
  end

  def create
    @project = Project.new(project_params)
    @companies = Company.as_select_options
    @project_varieties = ProjectVariety.as_select_options
    @prices = Price.as_select_options
    @users = User.as_select_options
    if @project.save
      flash[:success] = "#{@project.name} has been created."
      redirect_to @project
    else
      render :new
    end
  end
end


texts:
Note: I have a working solution, my question is about optimization and other approaches.
Problem Description
Hello, I'm re-writing an old program I made that solves nonograms.
As part of solving it, I generate (for some of the lines) an array of all possible ways to fit the numbers in.
I want to create a piece of code, that will iterate all the positions in which I can put the spaces, for example: if there's a line with size 5, and the numbers are 1, 1, there are multiple ways do order the numbers, like 1-1--, 1--1-, 1---1, --1-1, ... (- is a white box, while 1 will be black).
Problem Breakdown
So if we look at the example above, we can describe the options like this:

The total size is 5, and we have two 1, therefore we have 2 white boxes to play around with (1 must be between the numbers), I have another function that calculates that "free space".

We can index the possible places for the spaces this way: [0] 1 [1] 1 [2], meaning the spaces can go in each of the [indexes].

All the options of placing the spaces can be solved with nested loops, but since the "free space" and the possible indexes are dynamic, this is not an option.

For solution I try to create "dynamic" nested loops, with any range and depth, the question is:

Is there a more efficient way of doing so?
Possible Solution
The scope my question refers to is not related specifically to solving a nonorgram or even a specific language, but since I'm writing this in C++, I will post my attempt for a code that does so:
#include <vector>
#include <iostream>

using namespace std;

int main() {
    int iterators_number = 3; // Number of iterators, bubble sort for example uses 2, note: this is not for bubble sorting.
    int iterators_range = 3; // The maximum value for the iterators values, can be the size of the array for example.
    int move_index;

    vector<int> options_iteration(iterators_number, 0);

    while (true) {
        for (int i = 0; i < iterators_number; i++) cout << options_iteration[i] << " ";
        cout << endl;

        for (move_index = iterators_number - 1;
             (move_index >= 0) && (options_iteration[move_index] > iterators_range - 1); move_index--);
        if (move_index < 0) break;
        int new_value = options_iteration[move_index] + 1;
        for (; move_index < iterators_number; move_index++) options_iteration[move_index] = new_value;
    }

    return 0;
}

Output:
0 0 0
0 0 1
0 0 2
0 0 3
0 1 1
0 1 2
0 1 3
0 2 2
0 2 3
0 3 3
1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 3 3
2 2 2
2 2 3
2 3 3
3 3 3

If anyone is interested in the full implementation, once it's done and fully documented, I will upload it to my GitHub account.
Thanks in advance for the helpers and commentators.


texts: Rust Iterative and Recursive Merge Sort Implementation

texts:
I'm in the process of learning both Rust and algorithms after primarily focusing on web development. As such I've had a go at implementing merge sort both iteratively and recursively.

I've looked for various implementations in Rust online and found them either to be quite complex, quite specific (for types/use-cases) or quite hard to reason the flow of logic through - although MergeSort in Rust and the comment by Zeta proved to be very useful!

Both implementations appear to be passing all the test cases, however if anyone is able to provide me with any feedback/pointers on how to improve/optimise the algorithms (or any missed test scenarios) it would be greatly appreciated.

I'm particularly interested in ensuring both would have O(nlog(n)) time complexity - which I think the recursive one would, but I'm not so sure about the iterative one?

Recursive Merge Sort

pub fn recursive_merge_sort<T>(collection: &mut [T])
where
    T: Ord + Copy,
{
    if collection.len() > 1 {
        let (lhs, rhs) = collection.split_at_mut(collection.len() / 2);
        recursive_merge_sort(lhs);
        recursive_merge_sort(rhs);
        merge(collection, collection.len())
    }
}

Iterative Merge Sort

pub fn iterative_merge_sort<T>(collection: &mut [T])
where
    T: Ord + Copy,
{
    let length = collection.len();
    if length <= 1 {
        return;
    }

    let mut current_sub_array_multiplier = 1;
    let mut current_sub_array_size = 2;

    loop {
        collection
            .chunks_mut(current_sub_array_size)
            .for_each(|sub_arr| merge(sub_arr, current_sub_array_size));

        if current_sub_array_size > length {
            break;
        }

        current_sub_array_multiplier += 1;
        current_sub_array_size = 2f64.powi(current_sub_array_multiplier) as usize;
    }
}

Merge Function

pub fn merge<T>(collection: &mut [T], sub_array_length: usize)
where
    T: Ord + Copy,
{
    if sub_array_length < 2 {
        return;
    }

    let mut temp_vec = Vec::with_capacity(collection.len());
    {
        let mid = sub_array_length / 2;
        let mut lhs = collection.iter().take(mid).peekable();
        let mut rhs = collection.iter().skip(mid).peekable();

        while let (Some(&lhs_el), Some(&rhs_el)) = (lhs.peek(), rhs.peek()) {
            if *lhs_el <= *rhs_el {
                temp_vec.push(*lhs.next().unwrap())
            } else {
                temp_vec.push(*rhs.next().unwrap())
            }
        }

        for el in lhs {
            temp_vec.push(*el);
        }

        for el in rhs {
            temp_vec.push(*el);
        }
    }

    assert_eq!(temp_vec.len(), collection.len());
    temp_vec
        .iter()
        .enumerate()
        .for_each(|(i, el)| collection[i] = *el);
}

Sample Test cases:

#[cfg(test)]
mod recursive_tests {
    use super::*;

    #[test]
    fn test_semi_sorted() {
        let mut arr = vec![1, 23, 2, 32, 29, 33];
        recursive_merge_sort(&mut arr);
        assert_eq!(arr, [1, 2, 23, 29, 32, 33]);
    }

    #[test]
    fn test_backwards() {
        let mut arr = vec![50, 25, 10, 5, 1];
        recursive_merge_sort(&mut arr);
        assert_eq!(arr, [1, 5, 10, 25, 50]);
    }

    #[test]
    fn test_sorted() {
        let mut arr = vec![1, 5, 10, 25, 50];
        recursive_merge_sort(&mut arr);
        assert_eq!(arr, [1, 5, 10, 25, 50]);
    }

    #[test]
    fn test_empty() {
        let mut arr: Vec<u32> = vec![];
        recursive_merge_sort(&mut arr);
        assert_eq!(arr, []);
    }

    #[test]
    fn test_len_two() {
        let mut arr = vec![5, 1];
        recursive_merge_sort(&mut arr);
        assert_eq!(arr, [1, 5]);
    }

    #[test]
    fn test_partially_sorted() {
        let mut arr = vec![50, 75, 1, 1, 3, 4, 5, 6, 50];
        recursive_merge_sort(&mut arr);
        assert_eq!(arr, [1, 1, 3, 4, 5, 6, 50, 50, 75]);
    }
}

```


texts:
I am learning algorithms in graphs.  I have implemented topological sort using Java. Kindly review my code and provide me with feedback.

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class TopologicalSortGraph {

    /**
     *  This Topological Sort implementation takes the example graph in
     *  Version 1: implementation with unweighted
     *  Assumption : Graph is directed
     */
    TopologicalSortGraph Graph = new TopologicalSortGraph();
    //public LinkedList<Node> nodes  = new LinkedList<Node>();

    public static void  topologicalSort(Graph graph) {
        Queue<Node> q = new LinkedList<Node>();
        int vertexProcessesCtr = 0;
        for(Node m : graph.nodes){
            if(m.inDegree==0){
                ++vertexProcessesCtr;
                q.add(m);
                System.out.println(m.data);
            }
        }
        while(!q.isEmpty()) {
            Node m = q.poll();

            //System.out.println(m.data);
            for(Node child : m.AdjacenctNode){
                --child.inDegree;
                if(child.inDegree==0){
                    q.add(child);
                    ++vertexProcessesCtr;
                    System.out.println(child.data);
                }
            }

        }
        if(vertexProcessesCtr > graph.vertices) {
            System.out.println();
        }

    }

    public static void main(String[] args) {
        Graph g= new Graph();
        g.vertices=8;

    Node TEN = new Node("10");
    Node ELEVEN = new Node("11");
    Node TWO = new Node("2");
    Node THREE = new Node("3");
    Node FIVE = new Node("5");
    Node SEVEN = new Node("7");
    Node EIGHT = new Node("8");
    Node NINE = new Node("9");

    SEVEN.AdjacenctNode.add(ELEVEN);
    ELEVEN.inDegree++;
    SEVEN.AdjacenctNode.add(EIGHT);
    EIGHT.inDegree++;
    FIVE.AdjacenctNode.add(ELEVEN);
    ELEVEN.inDegree++;
    THREE.AdjacenctNode.add(EIGHT);
    EIGHT.inDegree++;
    THREE.AdjacenctNode.add(TEN);
    TEN.inDegree++;
    ELEVEN.AdjacenctNode.add(TEN);
    TEN.inDegree++;
    ELEVEN.AdjacenctNode.add(TWO);
    TWO.inDegree++;
    ELEVEN.AdjacenctNode.add(NINE);
    NINE.inDegree++;
    EIGHT.AdjacenctNode.add(NINE);
    NINE.inDegree++;

    g.nodes.add(TWO);
    g.nodes.add(THREE);
    g.nodes.add(FIVE);
    g.nodes.add(SEVEN);
    g.nodes.add(EIGHT);
    g.nodes.add(NINE);

    System.out.println("Now calling the topologial sorts");

    topologicalSort(g);

    }
}

Graph class:

class Graph {
    public int vertices;
    LinkedList<Node> nodes = new LinkedList<Node>();
}

Node Class:

class Node {
    public String data;
    public int dist;
    public int inDegree;
    LinkedList<Node> AdjacenctNode = new LinkedList<Node>( );

    public void addAdjNode(final Node Child){
        AdjacenctNode.add(Child);
        Child.inDegree++;
    }

    public Node(String data) {
        super();
        this.data = data;
    }
}


texts: Recursive Error Handling in Python with a limited amount of tries

texts:
I have a class method that is set up to make requests to an API and I'm having issues handling the possible errors that could arise by trying to communicate with that server. The idea is if an error were to pop up, then it would call on itself until either it no longer needs to (because it worked), or it reaches a limit I set up for it; in this case, I would want it to just simply raise an exception that would be caught somewhere else in the code. What I don't know is how to properly return the response if it crapped out the first time it made the call and had to call on itself from the except block.

I'm not 100% clear if this actually gets the job done. Additionally, I dont know if this is the best way to do it. I know a possible suggestion is to make error handling more specific, given the requests library myriad exceptions, but I figured that any exception should just be handled by trying X amount of time and then quitting if it doesn't work.

def getRequest(self, endpoint, attempts):
        baseUrl = self.baseUrl
        url = baseUrl + endpoint
        if self.expirationT <= datetime.datetime.now():
            self.token, self.expirationT = self.auth(client_id, client_secret)
        else:
            pass
        try:
            response = requests.get(url, auth = BearerAuth(self.token))
            response.raise_for_status()
        except:
            if attempts < 20:
                time.sleep(3)
                response = self.getRequest(endpoint, attempts + 1)
                return response
            else:
                raise Exception
        else:
            return response


texts: Determining length of a char* string in C++

texts:
I was looking to do this with sizeof() and I just gave up. As minimal as I can make it, I was wondering if there was a less crude way of doing the const char * as a convenience. I thought about doing this as a template, but I thought having another bit of generated code every time it is called seemed kinda dumb for me.

#include "misc.hh"
namespace mlcppl
  {
    int cpl(char * c)
    {
    char ct;
    int i = 0;

    while (ct = *(c+i))
      {
        if (ct == '\0')
          {
            break;
          }
        else
          {
            i++;
          }
      }
    return i;
  }

  int cpl(const char * c)
  {
    char * ct = (char*) c;
    return cpl(ct);
  }
}


texts: PowerShell script creates a computer list from an AD OU, and add exclusions to a specific file via Invoke-Command

texts:
My code is working, however, in the foreach section, when it runs the invoke-command if I don't use "-ErrorAction SilentlyContinue" the red error text that states a computer cannot be connected to shows up. The code still works fine, I just wanted to know if there is a way to add "nicer" text, so that when the invoke-command fails to connect, it'll show "This computer cannot be reached"

Any help is appreciated.

$output_dir = "$env:USERPROFILE\Desktop\ad_computer_list"
$output_file = "$output_dir\computerlist.txt"
$computers_input_file = "computerlist.txt"
$script_name = "Create Spectrum Protect exclusions script"

Import-Module ActiveDirectory
New-Item -Force -ItemType Directory $output_dir | Out-Null
New-Item -Force -ItemType File $output_file

Set-Location $env:USERPROFILE\Desktop\ad_computer_list

#
# MAIN code body
#

Write-Host "`n`n################################################################" -ForegroundColor Gray
Write-Host "Running $($script_name)..." -ForegroundColor Cyan
Write-Host "################################################################" -ForegroundColor Gray

function Get-ComputerList {
param(
$OU_Base = $(Read-Host "Enter distinguished name of OU")
)

Get-ADComputer -Filter "*" -SearchBase "$OU_Base" |
Select-Object -ExpandProperty Name |
Sort |
Out-File -Encoding ASCII -FilePath $env:USERPROFILE\Desktop\ad_computer_list\computerlist.txt

try {
# Get entries in text file, strip away whitespace, blank lines and lines starting with '#' characters
$computers = Get-Content $computers_input_file -ErrorAction Stop | Where-Object { ($_.Trim() -ne '') -and ($_ -NotMatch "^#") }
}
catch {
    Write-Error "Unable to open $computers_input_file. Please create or move the file to the same directory as this script."
break
}

Write-Verbose "$($computers.Count) computer entries found in input file."

foreach ($computer in $computers) {

Write-Host "Opening connection to $computer ..."

try {Invoke-Command -ErrorAction SilentlyContinue -ComputerName $computer -ScriptBlock {if(!(Get-Content -Path "C:\program files\tivoli\tsm\baclient\dsm.opt" -ErrorAction SilentlyContinue | Select-String "Excludedir", "Program Files"))

{Write-Host "Spectrum Protect is not installed or exclusions already exist." -ForegroundColor "Yellow"}

else

{add-content -Path "C:\program files\tivoli\tsm\baclient\dsm.opt" -Value `r`n'EXCLUDE.DIR "C:\Program Files"'}}

} catch {
    Write-Host "Cannot connect to computer!"
}

}

}
Get-ComputerList


texts:
I wrote this function to remove whitespaces in strings. Please help me improve it. I intended to use the function for a Big Integer ADT.

#include <iostream>
#include <string>
#include <string.h>

void rs(char* str){
    int i(0);
    int j(0);

    while((*(str + i) = *(str + j++)) != '\0')
        if(*(str + i) != ' ')
            i++;
    return;
}

int main()
{
    std::string str = "Hello World";
    char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
    rs(result);

    std::cout << result << std::endl;

    return 0;
}


texts: Google Script is slow. Using arrays. Anything else I'm missing?

texts:
I'm trying to add students to Google Classrooms ('Courses') from a Google Sheet with code below (function AddStudents).
It's very slow and, if I do too many, it exceeds allowed execution time. Is there anything that I can do to speed it up?
function AddStudent(argStudent, argCourseCode) {
  Classroom.Courses.Students.create({
    userId: argStudent,
  }, argCourseCode);
}

function AddStudents() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var shtStudents = ss.getSheetByName('Students');

  var rngStudentCourses = shtStudents.getRange(2,6,645,2);
  var arrStudentCourses = rngStudentCourses.getValues();

  for (var i = 0; i < arrStudentCourses.length; i++) {
    AddStudent(arrStudentCourses[i][0], arrStudentCourses[i][1]);
  }
}


texts:
I just finished Project Euler #7 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?

import Foundation

func isPrime(number:Int) -> Bool {

    if number == 1 {
        return false
    }
    else if number < 4 {
        return true
    }
    else if number % 2 == 0 {
        return false
    }
    else if number < 9 {
        return true
    }
    else if number % 3 == 0 {
        return false
    }
    else {
        let maxPrime = Int(ceil(sqrt(Double(number))))

        for var i = 5; i <= maxPrime; i += 6 {
            if number % i == 0  || number % (i + 2) == 0 {
                return false
            }
        }
    }

    return true
}

func getNumberForXthPrime(prime:Int) -> Int {

    var xThPrime = prime - 1 // We skip the prime 2 with the += 2
    var number = 1

    while xThPrime > 0 {

        number += 2
        if isPrime(number) {
            xThPrime--
        }
    }

    return number
}

func printTimeElapsedWhenRunningCode(operation:(xThPrime:Int) -> Int) {
    let startTime = CFAbsoluteTimeGetCurrent()
    let number = operation(xThPrime: 10_001)
    println(number)
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(getNumberForXthPrime)

The code executes in 0.0181439518928528 s.


texts: Generate a matrix of booleans from another one

texts:
Let's say that I have a bool[,] with random values

FFFFFFFF
FFFFFTTT
TTTTTTTT
FFFFFFFF

What would be the smartest way to create a new bool[,] that build on top of the previous one. That means, that it can have random values where the previous one was true, but that it preserves the falses from the original?

So this could be a possible result

FFFFFFFF
FFFFFTFT
TTFFFTTT
FFFFFFFF

But this not...

TTTTTFFF
TTTTTFFF
TTTTTTTT
FFFFFFFF

So far I have come with the classical solution. First create a matrix of random values, and the overwrite them.

for (int x = 0; x < cols; x++)
    for (int y = 0; y < rows; y++)
        if (matrix1[x, y] == false)
            matrix2[x, y] = false;

But I was wondering if there is a better way.


texts: Best way to access lists and nest them with if statements

texts:
Trying to improve my Python skills by creating a small text adventure. I have used lists to access certain information, but I am not sure if I am using them correctly. For instance, I have used a list to store weapons but wasn't sure of the syntax for accessing them in an if statement. Also, if there is any advice on how to improve the code in general that would be appreciated. I am a beginner so would prefer a simple alternative.
weapon = ["sword", "stone", "flower"]

# Create user defined functions for the game first.

def title():
    print("In front of you there is a portal. You have no idea where it leads")
    print("portal #1")

# Call function

title()
portal = input("Type 1: ")

if portal == "1":
    print("There's a wizard conjuring a spell.")
    print("What do you do?")
    print("1. Talk to the wizard.")
    print("2. Attack the wizard.")
    print("3. Run away.")

    choice_wizard = input("Type 1,2,3: ")

    if choice_wizard == "1":
        print("The wizard turns you into a frog. Ribbit!")

    elif choice_wizard == "2":
        print("You see a sword laying on the ground")
        print("Would you like to take the sword? Press y or n to continue")

        weapon_input = input("Type y or n: ")
        if weapon_input == "y" or weapon_input == "Y":
            weapon = []
            weapon.append("sword")
            print("You are now carrying a " + weapon[0] + ", You kill the wizard")
        elif weapon_input == "n" or weapon_input == "N":
            weapon = []
            weapon.append("stone")
            print("You are now carrying a " + weapon[0] + ", You hit the wizard in the head with it")
            print("He falls over unconscious and dies")
    elif choice_wizard == "3":
        print("The wizard tries turning you into a frog but misses.")
        print("...You escape.")


texts: Structure and readability of basic calculator

texts:
I created this code to make a basic calculator after viewing a few examples. I added the function to continue the calculations myself. I am wondering if there is a way to make this more efficient as I feel I've used some unnecessary code but I can't make it work without.

I also was looking for feedback on my codes readability and how to improve if it is of a poor quality.

#include <stdio.h>

int main ()
{
int cancel = 1;
char o, end  = 'Y';
float numone = 0.0, numtwo = 0.0;

         /* Explaining structure and receiving inputs */

         printf("Please enter the two numbers you wish to manipulate!\n");
         scanf("%f", &numone);

         do {
                 scanf("%f", &numtwo);
                 printf("Please enter the operation you wish to perform (+, -, *, /)\n");
                 scanf(" %c", &o);

                 /* Checking for correct input and manipulating numbers with regards to user input */

                 switch(o){

                         case '+':
                                 printf("%.1f + %.1f = %.1f\n", numone, numtwo, numone + numtwo);
                                 break;
                         case '-':
                                 printf("%.1f - %.1f = %.1f\n", numone, numtwo, numone - numtwo);
                                 break;
                         case '*':
                                 printf("%.1f * %.1f = %.1f\n", numone, numtwo, numone * numtwo);
                                 break;
                         case '/':
                                 printf("%.1f / %.1f = %.1f\n", numone, numtwo, numone / numtwo);
                                 break;
                         default:
                                 /* Error message for incorrect input */
                                 printf("Error! Incorrect input!\n");
                                 break;
                 }`enter code here`
                 /* Option to continue calculations */

                 printf("Would you like to perform a further calculation? (Y/N)\n");

                 /* Checking for answer and terminating if N, resuming if Y */

                 scanf(" %c%", &end);
                        if (end == 'N') {
                         return 0;
                        }
                        else {}
                 numtwo = 0;

                 /* Requesting new number to use as numtwo for calculations */

                 printf("Current number = %f please input a second number!\n", numone);
                 } while (end == 'Y');

         return 0;
}


texts: Convert dictionary of lists of tuples to list of lists/tuples in python


texts:
I've recently learned BEM & SASS, and I'd like to know if my BEM syntax is correct. I'm trying to create just the header of this page: https://blackrockdigital.github.io/startbootstrap-agency/

Are there any differences you would make to my class names? I get very confused about how to deal with elements when they are nested within other elements. I find that I often want to chain elements, like class="header__navbar__logo", but I've heard this is not good BEM.

Start Bootstrap

Services

Portfolio

About

Team

Contact

        Welcome To Our Studio!
        It's Nice To Meet You

```


texts: Simple read/write lock implementation without starvation

texts:
I've built a read/write lock and have been testing it without encountering any problems. It was made to avoid writer starvation, but I believe it works against reader starvation as well. I've seen alternatives online, but was wondering if this is a solid implementation.
If you use a normal shared mutex, new read actions can still be queued, which will prevent write actions from ever being processed while there is any read action present. This will cause starvation. I used a second mutex which will be locked by the write process and prevents any new read processes to be queued. Thank you!
class unique_priority_mutex
{
public:

    void lock_shared(void)
    {
        // If there is a unique operation running, wait for it to finish.
        if( this->_is_blocked ){
            // Use a shared lock to let all shared actions through as soon as the unique action finishes.
            std::shared_lock<std::shared_mutex> l(this->_unique_mutex);
        }

        // Allow for multiple shared actions, but no unique actions.
        this->_shared_mutex.lock_shared();
    }

    void unlock_shared(void)
    {
        this->_shared_mutex.unlock_shared();
    }

    void lock(void)
    {
        // Avoid other unique actions and avoid new shared actions from being queued.
        this->_unique_mutex.lock();

        // Redirect shared actions to the unique lock.
        this->_is_blocked = true;

        // Perform the unique lock.
        this->_shared_mutex.lock();
    }

    void unlock(void)
    {
        this->_shared_mutex.unlock();
        this->_is_blocked = false;
        this->_unique_mutex.unlock();
    }

    std::shared_mutex _shared_mutex;
    std::shared_mutex _unique_mutex;
    std::atomic<bool> _is_blocked = false;
};


texts:
In my Java program, I need to operate on the sublists a of ArrayList or LinkedList often, like removing a sublist, comparing two sublists.

For ArrayList or LinkedList, I didn't find any good APIs to do these. My current implementation is as below. Basically, it takes an input like:

u1234 u1236 u1236 u2def u1236 u1236 u2def

and outputs the following:

u1234 ( ( u1236 ) * u2def ) *

Core function:

ArrayList<String> toRegex(ArrayList<String> tokenArray)
{
    /* check different length of continuous duplication */
    for(int len=1; len<=tokenArray.size()/2; len++)
    {
        boolean match = false;
        /* given a length, scan for duplication */
        for(int i=0; i<tokenArray.size()-(2*len-1); i++)
        {
            ArrayList<String> first = new ArrayList<String>();
            ArrayList<String> second = new ArrayList<String>();
            for(int j=i; j<i+len; j++)
                first.add(tokenArray.get(j));
            for(int j=i+len; j<i+2*len; j++)
                second.add(tokenArray.get(j));

            if(isSpecial(first)) {       /* skip the cases */
                continue;
            }

            while(isIdentical(first, second))
            {
                match = true;
                for(int j=i+len; j<i+2*len; j++)
                    tokenArray.remove(i+len);
                if(i+2*len > tokenArray.size())
                    break;
                second.clear();
                for(int j=i+len; j<i+2*len; j++)
                    second.add(tokenArray.get(j));
            }

            if(match == true) {
                tokenArray.add(i, "(");
                tokenArray.add(i+1+len, ")");
                tokenArray.add(i+2+len, "*");
                i = i+3+len;
                match = false;
            }
       }
    }

    return tokenArray;
}

Currently, the performance is not good. Could you find the bad design or inappropriate usage of data structures/APIs? What are the good common ways of operating sublists?


texts: Threads with lambdas and runnable in Java

texts:
I'm learning Java and I've started writing some tasks. Could you give me feedback for it?

  Write a static method andThen that takes as parameters two Runnable instances
   and returns a Runnable that runs the first, then the second. In the main method,
   pass two lambda expressions into a call to andThen , and run the returned
   instance.

public class Exercise7 {

    public static class Thread1 implements Runnable {

        @Override
        public void run() {
            System.out.println("Echo from thread1");
        }
    }

    public static class Thread2 implements Runnable {

        @Override
        public void run() {
            System.out.println("Echo from thread2");
        }
    }

    public static Runnable andThen(Runnable thread1, Runnable thread2) {

        return () -> {
            thread1.run();
            thread2.run();
        };

    }

    public static void main(String[] args) {

        Runnable thread1 = new Thread1();
        Runnable thread2 = new Thread2();

       andThen(thread1,thread2).run();
    }
}