texts: Cryptographic range based random number generator class 2.0

texts:
I've corrected the bug in the first version and fixed up the error messages.

As for using floating arithmetic, since i'm not using more than 10 digits of the generated double, which, to my understanding, has at least 14 significant digits I can't see how the rounding will effect the outcome.

As for the randomness of the results, I can't seem to find any bias in the results of this algorithm.  Perhaps someone has a better test and hard numbers, instead of blind theory.

        public static class CryptoRandom
        {
            const double MAX_RANGE = (double)UInt64.MaxValue + 1;

            /// <summary>
            /// Internal algorithm to generate the range based integers.
            /// </summary>
            static int Next(UInt64 min, UInt64 max)
            {
                if (max < min)
                {
                    throw new ArgumentException($"max is less than min.  The values are, min = {min}, max = {max}");
                }
                if(min < 0)
                {
                    throw new ArgumentException($"min is negative.  The value is min = {min}");
                }
                if (min == max)
                {
                    throw new ArgumentException($"min equals max.  The values are, min = {min}, max = {max}");
                }

                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                    byte[] randomNumber = new byte[8];

                    rng.GetBytes(randomNumber);
                    double baseNum = BitConverter.ToUInt64(randomNumber, 0) / MAX_RANGE;

                    UInt64 range = max - min;

                    return (int)((baseNum * range) + min);
                }

            }
            /// <summary>
            /// Get a cryptographic random 32-bit integer in the range from
            /// min(inclusive) to max(exclusive)
            /// </summary>
            public static int Next(int min, int max)
            {
                return (int)Next((UInt64)min, (UInt64)max);
            }
            /// <summary>
            /// Get a cryptographic random 32-bit integer in the range from
            /// 0 to max(exclusive)
            /// </summary>
            public static int Next(int max)
            {
                return (int)Next(0, (UInt64)max);
            }

            /// <summary>
            /// Get a cryptographic random 32-bit integer
            /// </summary>
            public static int Next()
            {
                return (int)Next(0, (UInt64)Int32.MaxValue+1);
            }

        }


texts:
Previous question: C# Logging System

I have took your answers on board and added the following changes to my LogManager.cs class:

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

namespace Sahara.Sahara.Core.Logging
{
    class LogManager
    {
        /// <summary>
        /// Holds the logging settings class.
        /// </summary>
        private readonly LogSettings logSettings;

        public LogManager()
        {
            this.logSettings = new LogSettings
            {
                TypesToSave = new List<LogType>(),
                LogFile = "Logs/line_logs.txt"
            };
        }

        /// <summary>
        /// Prints a line to the console using custom settings.
        /// </summary>
        /// <param name="line">Line you want to print.</param>
        /// <param name="logType">Type of line you want to print.</param>
        public void Log(string line, LogType logType)
        {
            ConsoleColor existingColor = Console.ForegroundColor;
            PrintLine(line);
            Console.ForegroundColor = existingColor;

            if (logSettings.TypesToSave.Contains(logType))
                WriteContentToFile(logSettings.LogFile, line);
        }

        /// <summary>
        /// Prints a line to the console.
        /// </summary>
        /// <param name="line">Line to print to the console.</param>
        private void PrintLine(string line)
        {
            Console.WriteLine(GetLogDateTime() + line);
        }

        /// <summary>
        /// Retruns a short string with the current time in brackets
        /// </summary>
        /// <returns></returns>
        private string GetLogDateTime()
        {
            return "[" + DateTime.Now.ToLongTimeString() + "] ";
        }

        /// <summary>
        /// Adds text to the log file.
        /// </summary>
        /// <param name="filePath">The path of the log file.</param>
        /// <param name="content">The text to write in the file.</param>
        private void WriteContentToFile(string filePath, string content)
        {
            try
            {
                using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(fileStream, Encoding.Unicode))
                {
                    writer.Write(content);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }
}


texts: PHP handle array when query database with one-to-many relationship

texts:
Well, I am writing a web service using PHP to return data from a DB in JSON format. I need to query 3 tables, which have a one-to-many relationship, like shown below:

Contact Group ---(has)---> Contact ---(has)---> Phone number

Here I want to get an array of each group, in each group, get an array of all contacts and in each contact, get an array of all phone numbers. Because I am new to PHP, this might not be following best practices for PHP. The code I wrote is below:

$sql = "SELECT r.contact_id, contact_name, group_id, group_name, phone_id, phone_number FROM contact r LEFT JOIN contact_group s ON r.contact_group = s.group_id LEFT JOIN phone_numbers t ON r.contact_id = t.contact_id ORDER BY group_id, contact_id, phone_id";
$query = mysqli_query($conn,$sql);
$data = array();

while ($row = mysqli_fetch_array($query)) {
    $data[$row["group_id"]]["group_id"] = $row["group_id"];
    $data[$row["group_id"]]["group_name"] = $row["group_name"];

    $data[$row["group_id"]]["contacts"][$row["contact_id"]]["id"] = $row["contact_id"];
    $data[$row["group_id"]]["contacts"][$row["contact_id"]]["name"] = $row["contact_name"];

    $data[$row["group_id"]]["contacts"][$row["contact_id"]]["phone_number"][$row["phone_id"]]["id"] = $row["phone_id"];
    $data[$row["group_id"]]["contacts"][$row["contact_id"]]["phone_number"][$row["phone_id"]]["number"] = $row["phone_number"];
}

I think my code is very ugly and seems difficult to read. Could you help me review my code and refactor it to make it more beautiful or introduce new ways to solve that problem?


texts: A simple implementation of a mutable String in C

texts:
The following code implements a simple interface to operate on mutable* Strings in C. It is composed of two files: one for the structure definition and the available operations, and the other with the actual implementation.

*This can be inexact, as only adding characters to the end is implemented.

Any comments on coding style and improvements are greatly appreciated.

String.h

#ifndef __STRING_H__
#define __STRING_H__

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

#define BLOCK_SIZE 256

typedef struct {
    char *data;
    int length;
    int blocks;
} String;

String * string_create();
void string_dispose(String *str);

bool string_empty(String *str);
void string_append_char(String *str, char c);

char * string_get_all(String *str);
char string_get(String *str, int pos);

int string_find(String *str, char c);

#endif /* __STRING_H__ */

String.c

#include "String.h"

/** Create a String */
String * string_create() {
    String *ans = calloc(1, sizeof *ans);

    if (ans != NULL) {
        ans->data = malloc( BLOCK_SIZE * sizeof *(ans->data) );

        ans->length = 0;
        ans->blocks = (ans->data == NULL) ? 0 : 1;
    }

    return ans;
}

/** Free the memory associated with a String */
void string_dispose(String *str) {
    if (str != NULL) {
        free(str->data);
        free(str);
    }
}

/** Is the String empty? */
bool string_empty(String *str) {
    if (str == NULL) return true;
    if (str->length == 0) return true;
    return false;
}

/** Add a character to the end of the String */
void string_append_char(String *str, char c) {
    if (str != NULL) {
        if (str->length == str->blocks * BLOCK_SIZE) {
            char *new_str = realloc( str->data, BLOCK_SIZE * (str->blocks + 1) * sizeof *(str->data));

            if (new_str != NULL) {
                str->data = new_str;
                ++(str->blocks);
            }
        }

        if (str->length < str->blocks * BLOCK_SIZE) {
            str->data[str->length] = c;
            ++(str->length);
        }
    }
}

/** Get a C-String with the proper null-terminator */
char * string_get_all(String *str) {
    char *res = NULL;

    if (str != NULL) {
        res = malloc((str->length + 1) * sizeof *str->data);

        if (res != NULL) {
            memcpy(res, str->data, str->length);
            res[str->length] = '\0';
        }
    }

    return res;
}

/** Get a character at a given position in the String */
char string_get(String *str, int pos) {
    char res = '\0';

    if (str != NULL) {
        if (pos >= 0 && pos < str->length) {
            res = str->data[pos];
        }
    }

    return res;
}

/** Get where the first occurrence of a character in the String is */
int string_find(String *str, char c) {
    int pos = -1;

    if (str != NULL) {
        pos = 0;
        while (str->data[pos] != c) ++pos;

        if (pos == str->length) pos = -1;
    }

    return pos;
}

This is a test file that uses some of the core methods implemented in a String. This file is called test_string.c.

#include <stdio.h>

#include "String.h"

int main() {
    String *str = string_create();

    char i;
    for (i = 'a'; i <= 'z'; i++)
        string_append_char(str, i);

    char *cstr = string_get_all(str);

    printf("%s\n", cstr);

    int pos = string_find(str, 'f');

    printf("Character 'f' occurs at position %d.\n", pos);
    printf("Reading from the String, we get \"%c\".\n", string_get(str, pos));

    free(cstr);
    string_dispose(str);

    return 0;
}


texts:
code review friends/teachers! This is a trivial(no dfs/permutations/backtrace required) n queen problem from codeforces: B. 8 Queens, Again!!

input

2
A1 B5 C8 D6 E3 F7 G2 H4
C3 E4 C4 E1 C4 F4 A8 G6

output

Valid
Invalid

Here is my solution:
queen.h
#ifndef QUEEN
#define QUEEN
#include <array>
constexpr int N = 8;

void paint(std::array<std::array<int, N>, N>& m, int x, int y);

bool check(const std::array<std::array<int, N>, N>& m, int x, int y);

#endif

queen.cpp
#include "queen.h"

#include <cstdlib>
#include <iostream>
#include <string>

void paint(std::array<std::array<int, N>, N>& m, int x, int y)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            if(i == x || j == y || abs(i - x) == abs(j - y))
            {
                m[i][j] = 1;
            }
        }
    }
}

bool check(const std::array<std::array<int, N>, N>& m, int x, int y)
{
    if(m[x][y] == 1)
    {
        return false;
    }
    return true;
}

testqueen.h
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this
                          // in one cpp file
#include "catch.hpp"
#include "queen.h"

#include <iostream>
#include <sstream>

TEST_CASE("eight queens test")
{
    std::ostringstream out;
    std::streambuf* coutbuf = std::cout.rdbuf();

    std::cout.rdbuf(out.rdbuf()); // redirect cout to out
    int n;
    std::cin >> n;

    for(int i = 0; i < n; i++)
    {
        std::array<std::array<int, 8>, 8> arr{};
        std::string s;
        for(int j = 0; j < N; j++)
        {
            std::cin >> s;
            auto x = s[0] - 'A', y = s[1] - '1';
            if(check(arr, x, y) == true)
            {
                paint(arr, x, y);
            }
            else
            {
                std::cout << "Invalid" << '\n';
                for(int k = j + 1; k < N; k++)
                {
                    std::cin >> s;
                }
                break;
            }
            if(j == N - 1)
            {
                std::cout << "Valid" << '\n';
            }
        }
    }
    std::cout.rdbuf(coutbuf);
    REQUIRE(out.str() == "Valid\nInvalid\n");
}

Test:
~/.../codeforces/100947-B(eight-queen) >>> ./build/test/tests                       ±[●●][master]
2
A1 B5 C8 D6 E3 F7 G2 H4
C3 E4 C4 E1 C4 F4 A8 G6
===========================================================
All tests passed (1 assertion in 1 test case)

Please help me to point out any bad habits, better algorithms or better c++ paradigms
Thanks in advance!


texts: Calculate date for ordinal day of week in month

texts:
I am writing some date utility methods for a project.
One of the methods will answer the following questions (for example):

'When is the (3rd) (Monday) of (February) in the year (2018)'
'When is the (1st) (Wednesday) of (October) in the year (2020)'

The method accepts the 4 int value parameters as arguments, and will return a Date.

Here is the method as written:

/**
 * Example usage:
 * find the 3rd Monday of February, in the year 2018 getDayOfMonth(3, Calendar.MONDAY, Calendar.FEBRUARY, 2018)
 * find the 1st Tuesday of October, in the year 2017 getDayOfMOnth(1, Calendar.TUESDAY, Calendar.OCTOBER, 2017)
 * @param n occurrence count
 * @param dayOfWeek day of week to find
 * @param month month to use
 * @param year year to use
 * @return Date that the nth dayOfWeek occurs
 */
public static Date getDate(int n, int dayOfWeek, int month, int year){
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, 1);

    int matchCount = 0;

    while(true){
        if(calendar.get(Calendar.DAY_OF_WEEK) == dayOfWeek) {
            matchCount++;
        }
        if(matchCount == n){
            break;
        }
        calendar.add(Calendar.DATE, 1);
        if(calendar.get(Calendar.MONTH) != month){
            break;
        }
    }

    if(matchCount != n){
        throw new RuntimeException("error");
    }

    return calendar.getTime();
}

I am struggling to come up with a good name for the method and the 1st parameter.


texts:
I'm developing programs on Golang. But now you have to study at the university and have the following task.

  Calculate the continued fraction using the function indicators. The
  number of fractional elements must be specified from the keyboard. 1 +
  1 / (1 + 1 / (1 + 1 / (1 + 1 / ....))). The number of elements of the
  fraction must be at least 5. Consider three cases, for example, 5, 7
  and 10.

Enter the number of elements of the continued fraction: 6
Solution - 1.61538

Please check my code.

#include <iostream>
using namespace std;
int main(){

    int n;
    double t;
    t=2;
    bool exit;

    while (exit != true) {
        printf("To exit the programs, type 0\n");
        cout << "Enter the number of continued fractions: " << endl;
        cin >> n;

        if (n == 0) {
            exit = true;
        } else {
            if (n < 5) {
                printf("The number of elements of a fraction must be at least 5");
                cin.get();
            } else {
                for (int a = 1; a < n; a++) {
                    t = 1 / t + 1;
                }
                cout << "Decision - " << t << endl;
            }
        }
    }
    printf("Exiting the program");
    return 0;
}


texts:
I'm just a few months in learning to code and never had my code reviewed.
Is this class structure ok? Should I split it differently? How is the code overall?

require "json"
class Hangman

  def initialize
    @secret_word = select_word
    @display_content = "_" * @secret_word.length
    @failed_attemps = 0
  end

  def main_menu
    option = "3"
    until option == "1" || option == "2"
      puts "(1) New game"
      puts "(2) Load game"
      print "Play new game or load the saved game? "
      option = gets.chomp[0]
      if option == "2"
        if File.exist?("saved_state.json")
          load_state
        else
          puts "There is no saved game, save one first"
          option = "3"
        end
      end
    end
    start_game
  end

  private

  def save_state
    json_object = {
      :secret_word => @secret_word,
      :display_content => @display_content,
      :failed_attemps => @failed_attemps
    }.to_json
    File.open("saved_state.json", "w") { |file| file.write(json_object) }
  end

  def load_state
    save_file = File.read("saved_state.json")
    json_hash = JSON.parse(save_file)
    @secret_word = json_hash["secret_word"]
    @display_content = json_hash["display_content"]
    @failed_attemps = json_hash["failed_attemps"]
  end

  def start_game
    player_won = false
    while @failed_attemps != 10
      puts @display_content
      puts "#{10 - @failed_attemps.to_i} turns left"
      print "Enter a letter or attempt the full word: "
      letters = gets.chomp
      if letters == "save"
        save_state
        next
      end
      break if letters == "exit"
      update_display(letters) if letters
      player_won = player_won?
      break if player_won
    end
    puts "Game over, the secret word was: #{@secret_word}" if @failed_attemps == 10
  end

  def select_word
    words = File.readlines("5desk.txt").select { |word| word.length.between?(5, 12) }
    words[rand(words.length)].strip
  end

  def update_display(letters)
    letters.downcase!
    current_state = "#{@display_content}"
    if letters.length == 1
      @display_content.length.times do |index|
        @display_content[index] = letters if @secret_word[index].downcase == letters
      end
    else
      @display_content = letters if letters == @secret_word.downcase
    end

    current_state == @display_content ? print_toon(1) : print_toon(0)
  end

  def player_won?
    unless @display_content.include?("_")
      puts "You found the correct word!"
      true
    end
  end

  def print_toon(increment)
    @failed_attemps += increment

    case @failed_attemps
    when 0
      puts "  ______"
      puts "        |"
      puts "        |"
      puts "        |"
      puts "        |"
    when 1
      puts "  ______"
      puts " |      |"
      puts "        |"
      puts "        |"
      puts "        |"
    when 2
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "        |"
      puts "        |"
    when 3
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts " |      |"
      puts "        |"
    when 4
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts " ||     |"
      puts "        |"
    when 5
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||     |"
      puts "        |"
    when 6
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||\\    |"
      puts "        |"
    when 7
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||\\    |"
      puts "/       |"
    when 8
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||\\    |"
      puts "/  \\    |"
    when 9
      puts "  ______"
      puts " |      |"
      puts "(ox)    |"
      puts "/||\\    |"
      puts "/  \\    |"
    when 10
      puts "  ______"
      puts " |      |"
      puts "(xx)    |"
      puts "/||\\    |"
      puts "/  \\    |"
    end
    puts ""
  end

end

my_game = Hangman.new
my_game.main_menu


texts: Converts the JSON object to another structure of JSON

texts:
I want a JSON object of the following structure to plot a chart

chartGroup = [{name: 'A<->B', to: 254, from: 247},
              {name: 'C<->D', to: 208, from: 211},
              {name: 'A<->C', to: 46, from: 41},
              {name: 'A<->D', to: 10, from: 38},
              {name: 'B<->C', to: 56, from: 55},
              {name: 'B<->D', to: 44, from: 45}
             ];

from the below JSON object which I get from Database

data = [{from: "B", to: "D", count: 44},
        {from: "D", to: "B", count: 45},
        {from: "A", to: "B", count: 254},
        {from: "C", to: "D", count: 208},
        {from: "B", to: "A", count: 247},
        {from: "C", to: "A", count: 41},
        {from: "A", to: "D", count: 10},
        {from: "A", to: "C", count: 46},
        {from: "D", to: "C", count: 211},
        {from: "D", to: "A", count: 38},
        {from: "C", to: "B", count: 55},
        {from: "B", to: "C", count: 56}];

To create chartGroup from data, I'm using the below code :

     var chartPoints = {};
     data.forEach(function(s) {
        if((s.from == "A" && s.to == "B") || (s.from == "B" && s.to == "A")) {
            if(s.to == "B"){
                chartPoints["to"] = s.count;
            }else{
                chartPoints["from"] = s.count;
            }
            chartPoints["name"] = "A<->B";

         }
     });
   chartGroup.push(chartPoints);

   var chartPoints = {};
   data.forEach(function(s) {
       if((s.from == "C" && s.to == "D") || (s.from == "D" && s.to == "C")) {
           if(s.to == "D"){
               chartPoints["to"] = s.count;
           }else{
               chartPoints["from"] = s.count;
           }
           chartPoints["name"] = "C<->D";
       }
   });
   chartGroup.push(chartPoints);

   var chartPoints = {};
   data.forEach(function(s) {
       if((s.from == "A" && s.to == "C") || (s.from == "C" && s.to == "A")) {
           if(s.to == "C") {
               chartPoints["to"] = s.count;
           }else{
               chartPoints["from"] = s.count;
           }
           chartPoints["name"] = "A<->C";
    }
  });
  chartGroup.push(chartPoints);

  var chartPoints = {};
  data.forEach(function(s) {
      if((s.from == "A" && s.to == "D") || (s.from == "D" && s.to == "A")) {
          if(s.to == "D") {
             chartPoints["to"] = s.count;
          }else{
             chartPoints["from"] = s.count;
          }
          chartPoints["name"] = "A<->D";
     }
  });
  chartGroup.push(chartPoints);

  var chartPoints = {};
  data.forEach(function(s) {
      if((s.from == "B" && s.to == "C") || (s.from == "C" && s.to == "B")) {
          if(s.to == "C") {
              chartPoints["to"] = s.count;
          }else{
              chartPoints["from"] = s.count;
          }
          chartPoints["name"] = "B<->C";
     }
   });
   chartGroup.push(chartPoints);

   var chartPoints = {};
   data.forEach(function(s) {
       if((s.from == "B" && s.to == "D") || (s.from == "D" && s.to == "B")) {
       if(s.to == "D"){
           chartPoints["to"] = s.count;
       }else{
           chartPoints["from"] = s.count;
       }
       chartPoints["name"] = "B<->D";
    }
  });
  chartGroup.push(chartPoints);

would like to know if there is a better way to reduce the JSON object. As it can be seen that there is lot of loops and conditions which is not good. Please don't give importance to typo as I have modified the data to a example.


texts:
This script tries to determine the time when you woke up.

Of course, it only applies if you turn your computer on not too long ago after getting out of bed.

If not, it might still be useful as an indicator of when you turned your computer on.

It works by getting information from journalctrl, sleep-resume dates and boot dates.

It then loops through them and tries to find when the difference is above a certain gap (5 hours by default, it can be configured with the -g flag).

Then it prints the time and "timeago" information of when you probably woke up.

#!/bin/bash

gap=18000

while [ ! $# -eq 0 ]
do
    case "$1" in
        --help | -h)
            printf "Version: 1.2.1\nFlags:\n\t-g or --gap: Specifies the chunks of time between two dates to determine when you probably woke up (default is 5)\n"
            exit
            ;;
        --gap | -g)
            gap=$(($2 * 3600))
            ;;
    esac
    shift
done

current_date=$(date +%s)
readarray -t sleep_dates < <(journalctl -o short-unix -t systemd-sleep | grep resumed | tail -50 | awk -F. '{print $1}')
readarray -t boot_dates < <(journalctl --list-boots | tail -50 | awk '{ d2ts="date -d \""$3" "$4" " $5"\" +%s"; d2ts | getline $(NF+1); close(d2ts)} 1' | awk 'NF>1{print $NF}')
dates=( "${sleep_dates[@]}" "${boot_dates[@]}" )
readarray -t sorted_dates < <(printf '%s\n' "${dates[@]}" | sort)

for (( i=${#sorted_dates[@]}-1 ; i>=0; i-- )); do
    diff=$((sorted_dates[i] - sorted_dates[i - 1]))
    diff2=$((sorted_dates[i - 1] - sorted_dates[i - 2]))

    if [ "$diff" -gt "$gap" ] && [ "$diff2" -lt "$gap" ]; then
        sdate=$(date --date @${sorted_dates[i]} +"%r")
        diff2=$((current_date - sorted_dates[i]))
        hours_ago=$(echo "scale=2; ${diff2}/3600" | bc)
        whole_hours=$(echo "(${hours_ago})/1" | bc)
        decimals=$(echo "${hours_ago}" | grep -Eo "\.[0-9]+$")
        minutes_ago=$(echo "(${decimals}*60)/1" | bc)

        if [ "$whole_hours" -eq "1" ];
        then
            shours="hour"
        else
            shours="hours"
        fi

        if [ "$minutes_ago" -eq "1" ];
        then
            sminutes="minute"
        else
            sminutes="minutes"
        fi

        message="${whole_hours} ${shours} and ${minutes_ago} ${sminutes} ago ( ${sdate} )"
        echo "$message"
        break
    fi
done


texts: Counting pairs of relatively prime numbers

texts:
Problem from Hacker Earth:

  Inverted GCD:

  Given an array a of \$N\$ numbers , you have to find the number of pair of indices \$i\$ and \$j\$ that satisfy the following relation:

  \$i < j\$
  \$a_i > a_j\$
  gcd\$(a_i , a_j) = 1\$

  Input:

  The first line of the input contains a single integer N - denoting the size of the array.
  The next line contains N space separated integers denoting the array a.

  Output:
  Output a single integer - the answer to the problem stated above.

  Constraints:
  \$1 \le N \le 10^5\$
  \$1 \le a_i \le 10^5\$

For this problem I've submitted the following solution in Python:

from fractions import gcd
n = int(input())
count = 0;
a = [int(x) for x in input().split()]
for i in range(n):
    for j in range(n):
        if(a[i]>a[j] and i<j and gcd(a[i] , a[j]) == 1):
            count +=1;
print(count)

I'm not sure what is the complexity of gcd() function in Python, but it clear due to two for loop that the time complexity is minimum \$O(n^2)\$.I can't understand how to reduce it. Because here we have to check these conditions between every pair of integers. I've seen such question here but there is no condition for gcd(), so can't relate these two questions. I'm newbie to Python.


texts:
I have this obsession with esoteric programming languages. So I decided to spiff up my previous Brainfuck interpreter.

# Simple BrainF*** interpreter

# Class that stores lang variables
class Lang(object):
    step = 0
    cell = [0] * 30000
    test_cell = [0] * 30000
    pos = 0
    test_pos = 0
    loop = False
    loop_ret = 0

# Main interpreter function
def interpreter():

    code_input = raw_input('Code: ')
    steps = len(code_input)

    while Lang.step < steps:

        if code_input[Lang.step] == '+':
            Lang.cell[Lang.pos] += 1

        elif code_input[Lang.step] == '-':
            Lang.cell[Lang.pos] -= 1

        elif code_input[Lang.step] == '>':
            if Lang.pos < 30000:
                Lang.pos += 1
            elif Lang.pos > 30000:
                Lang.pos = 0

        elif code_input[Lang.step] == '<':
            if Lang.pos > 0:
                Lang.cell_pos -= 1
            elif Lang.pos < 0:
                Lang.pos = 30000

        elif code_input[Lang.step] == '[':
            if Lang.loop == False:
                Lang.loop_ret = Lang.step
                Lang.loop = True

        elif code_input[Lang.step] == ']':
            if Lang.cell[Lang.pos] != 0:
                Lang.step = Lang.loop_ret
            elif Lang.cell[Lang.pos] == 0:
                Lang.loop = False

        elif code_input[Lang.step] == '.':
            print str(chr(Lang.cell[Lang.pos]))

        elif code_input[Lang.step] == ',':
            Lang.cell[Lang.pos] = int(raw_input())

        elif code_input[Lang.step] == ":":
            Lang.test_cell[Lang.test_pos] += 1

        elif code_input[Lang.step] == ";":
            Lang.test_cell[Lang.test_pos] -= 1

        elif code_input[Lang.step] == "}":
            if Lang.test_pos > 30000:
                Lang.test_pos += 1
            elif Lang.test_pos < 30000:
                Lang.test_pos = 0

        elif code_input[Lang.step] == "{":
            if Lang.test_pos > 0:
                Lang.test_pos -= 1
            elif Lang.test_pos < 0:
                Lang.test_pos = 30000

        elif code_input[Lang.step] == "$":
            if Lang.test_cell[Lang.test_pos] == Lang.cell[Lang.pos]:
                print True
            elif Lang.test_cell[Lang.test_pos] != Lang.cell[Lang.pos]:
                print False

        Lang.step += 1

# Running the program
if __name__ == "__main__":
    interpreter()

If there are any issues, please mention them. All I'm looking for is any general improvements.


texts: Overriding equals and hashCode vs providing only Single Instance on immutable Objects

texts:
Let's say we have a class SomeInt which holds just one single final int value:

public class SomeInt
{
    private final int value;

    public SomeInt(int value)
    {
        this.value = value;
    }

    public int getValue()
    {
        return this.value;
    }
}

Option A - Overring equals and hashCode:

public class SomeInt
{
    private final int value;

    public SomeInt(int value)
    {
        this.value = value;
    }

    public int getValue()
    {
        return this.value;
    }

    @Override
    public boolean equals(Object other)
    {
        if (!(other instanceof SomeInt))
        {
            return false;
        }

        return ((SomeInt) other).hashCode() == hashCode();
    }

    @Override
    public int hashCode()
    {
        return this.value;
    }
}

Option B - Providing only one Instance per Value:

import java.util.Map;
import java.util.HashMap;
import java.lang.ref.WeakReference;

public class SomeInt
{
    private static final Map<Integer, WeakReference<SomeInt>> INSTANCES = new HashMap<>();
    private final int value;

    private SomeInt(int value)
    {
        this.value = value;
    }

    public synchronized static SomeInt of(int value)
    {
        WeakReference<SomeInt> weakRef = INSTANCES.get(value);
        SomeInt instance = null;

        if (weakRef != null)
        {
            // keep reference before asking isEnqueued to ensure
            // it's not getting garbage collectedbetween the calls
            instance = weakRef.get();
        }

        if (weakRef == null || instance == null || weakRef.isEnqueued())
        {
            instance = new SomeInt(value);
            INSTANCES.put(value, new WeakReference<>(instance));
        }

        return instance;
    }

    public int getValue()
    {
        return this.value;
    }
}

Pros of A:

If the Object holds references to other Complex-Types the implementation is much easier and will be easy to customize when something changes
Can also be used with mutable Objects

Cons of A:

There may be many Objects with the same information

Pros of B:

There will always be only one Object holding this information
== comparison possible since equality is guaranteed by the generating method

Cons of B:

Can only be used with immutable Objects

Question:
What is the better approach to ensure comparisons and occurences in Maps and Collections don't fail?


texts:
This is code to merge two sorted linked lists. l1 and l2 are sorted. While calling the merge function via l3, I am passing l3 as an object by reference in that function. The code is running fine, but can someone suggest how I can code better, with regards to dealing with class objects and passing them in a function?

#include<iostream>
using namespace std;

class linklist{
    private:
        struct node{
            int data;
            node* link;
        }*start;

    public:
        linklist(){
            start=NULL;
        }
        void append(int);
        void display();
        void merge(linklist, linklist,linklist &);
        ~linklist()
        {
            node *q;
            while(start!=NULL)
            {
                q=start->link;
                delete start;
                start=q;
            }
        }
};
void linklist::append(int num){

    node *temp, *r;
    temp=start;
    if(start==NULL)
    {temp=new node;
    temp->data=num;
    temp->link=NULL;
    start=temp;
    }
    else{

        while(temp->link!=NULL)
        {
            temp=temp->link;
        }
        r= new node;
        r->data=num;
        r->link=NULL;
        temp->link=r;
    }
}
void linklist::display() {
    node *temp;
    temp=start;
    cout<<"Linked List is"<<endl;
    while(temp!=NULL)
    {
        cout<<temp->data<<"  ";
        temp=temp->link;
    }
    cout<<endl;
}

void linklist::merge(linklist l1, linklist l2,linklist& l3) // Here is my doubt
{
    node *p, *q;
    p=l1.start;
    q=l2.start;

    int dat;
    while(p!=NULL && q!=NULL)
    {
        if(p->data > q->data)
        {
            dat=q->data;
            l3.append(dat);
            q=q->link;
        }

        else{
            dat=p->data;
            l3.append(dat);
            p=p->link;
        }
    }
    if(p==NULL)
    {
        while(q!=NULL)
        {
            dat=q->data;
            l3.append(dat);
            q=q->link;
        }
    }
    else{
            while(p!=NULL)
        {
            dat=p->data;
            l3.append(dat);
            p=p->link;
        }
    }
    cout<<"lists merged"<<endl;

}

int main()
{
    linklist l1,l2,l3;

    l1.append(2);
    l1.append(5);
    l1.append(23);
    l1.append(34);
    l1.append(45);

    l2.append(6);
    l2.append(9);
    l2.append(35);
    l2.append(98);

    l3.merge(l1, l2,l3);
    l3.display();

    return 0;
}


texts: Finding numbers whose product of the digits are perfect squares

texts:
How can I decrease the running time and compile time of the following code?

  Given three integers A, B and K, you need to report the Kth number
  between A and B (both inclusive), satisfying the property that: the
  number does not contain a digit 'zero' and product of digits of number
  is a perfect square. If there doesn't exist that Kth number output
  "-1"(without quotes).

  Input:

  First Line contains the number of test cases \$T\$. Next \$T\$ lines contain 3
  space separated integers A, B, K as mentioned in the task.

  Output:

  Output \$T\$ lines as answer for every test case.

  Constraints:

  \$1 ≤ T ≤ 100\$
  \$1 ≤ A ≤ B ≤ 10^{18}\$
  \$1 ≤ K ≤ 10^7\$

  Sample input:

3
1 10 4
8 14 2
1 1000 23

  Output:

-1
11
119

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int cases = in.nextInt();
    long A,B,K;

    int caseNum =0;
    while(caseNum < cases)
    {
        A = in.nextLong();
        B = in.nextLong();
        K = in.nextLong();
        ArrayList<Long> products = new ArrayList<>();
        long product = 1;
        for(long i=A,k=0;i<=B && k<(B-A+1);i++,k++)
        {
            long num = i;

            double sqrt;

            ArrayList<Long> temp = new ArrayList<>();
            while(num>0)
            {
                temp.add(num%10);
                num = num/10;
            }
            for(int j=0;j<temp.size();j++)
            {
                if(temp.get(j)==0){
                    product=-1;
                    break;

                }
                product = product*temp.get(j);
                //System.out.println("Currently processing: "+ temp.get(j));

            }
            sqrt = Math.sqrt(product);

            if( product%sqrt==0)
            {   products.add(i);

            }
            product=1;
        }
        try{
            System.out.println(products.get((int)K-1));
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println(-1);
        }

        caseNum++;
    }
}
}


texts:
Requirement:

For the input list of tuples to create single line output showing father of the family|spouse|child1,child2....

Input:

input_list = [("David","Polly","Spouse"),
          ("Roger","Patty","Spouse"),
          ("David","Lily","Child"),
          ("Roger","Max","Child"),
          ("David","Sam","Child")]

Expected output:

David|Polly|Lily,Sam
Roger|Patty|Max

I have written the code but it is very clunky. Any improvement and shorter/efficient version is much appreciated.

input_list = [("David","Polly","Spouse"),
          ("Roger","Patty","Spouse"),
          ("David","Lily","Child"),
          ("Roger","Max","Child"),
          ("David","Sam","Child")]
# Expected output
'''
David|Polly|Lily,Sam
Roger|Patty|Max
'''
priority = {"Spouse" :1,"Child" :2}
intermediate_list = []
final_list =[]
return_name = ''
input_list_w_priority = [tuple(x) + (priority[x[2]],) for x in input_list ] #  spouse has priority 1, children have 'lower' priority
sorted_input_list = sorted(input_list_w_priority)
get_father = sorted(list(set([ x[0] for  x in sorted_input_list]))) # getting 'unique' father
for x in range(len(get_father)):
    i =0
    intermediate_list =[]
    spouse_name =''
    final_name = ''
    for y in range(len(sorted_input_list)):  # traversing the input list for a single father

        i+=1

        if(get_father[x] == sorted_input_list[y][0]):
            intermediate_list.append((sorted_input_list[y][1],sorted_input_list[y][3])) # assigning spouse/child name and priority

    if(i == len(sorted_input_list)):
    final_tuple = sorted(intermediate_list,key=lambda x : x[1]) #sorting on priority

    for z in range(len(final_tuple)):
        if(final_tuple[z][1] == 1): # if spouse then pipe separated
            spouse_name = '|'+ final_tuple[z][0] + '|'
        else:
            final_name = final_name + ','+ final_tuple[z][0]
    return_name = return_name + get_father[x] + spouse_name +final_name[1:] + '\n'
print(return_name)


texts:
struct __fifo_node_t {
        void *next;
};
typedef struct __fifo_node_t fifo_node_t;

struct __fifo_list_t {
        void *next;
        void *tail;
};
typedef struct __fifo_list_t fifo_list_t;

static inline void __fifo_list_push(fifo_list_t *head, fifo_node_t *node)
{
        fifo_node_t *prev;

        node->next = head;
        prev = atomic_xchg64(&head->tail, node);
        prev->next = node;
}

static inline fifo_node_t *__fifo_list_pop(fifo_list_t *head)
{
        fifo_node_t *node;
        while ((node = ACCESS_ONCE(head->next)) != head) {
                fifo_node_t *next = ACCESS_ONCE(node->next);
                if (cmpxchg_eq(&head->next, node, next) == node) {
                        if (cmpxchg_eq(&head->tail, node, head) != node &&
                            next == head)
                                while (ACCESS_ONCE(head->next) == next)
                                        head->next = ACCESS_ONCE(node->next);
                        return node;
                }
        }
        return NULL;
}

static inline void __fifo_list_init(fifo_list_t *head)
{
        head->next = head->tail = head;
}

atomic_xchg64 - Atomic exchange 64bit with new value and return the old value

cmpxchg_eq - Atomic compare and exchange 64bit with new value and return the old value

ACCESS_ONCE - (*(volatile typeof(x) *)&(x))

Can you review it? Is this implementation thread-safe ?

Thank you.


texts: Function to generate nearly sorted numbers

texts:
I wrote function to generate nearly sorted numbers:

def nearly_sorted_numbers(n):
    if n >= 100:
        x = (int)(n/10)
    elif n >= 10:
        x = 9
    else:
        x = 4
    numbers = []
    for i in range(1,n):
        if i%x==0:
            numbers.append(random.randint(0,n))
        else:
            numbers.append(i)
return numbers

Have you any idea how improve my code?


texts: Converts numbers in range 0 through 15 into ASCII-coded character '0' through 'F'

texts:
This is an assignment and i have implemented the function hexasc from the description above. To run this code I'm using MARS-simulator.
For the sake of understanding it better i would appreciate to see different approach.

  Write a small subroutine, that converts numbers in the range 0 through 15 into a printable ASCII-coded character: '0' through '9', or 'A' through 'F', depending on the number. For numbers not in the range 0 through 15, some bits will be ignored.

  The function must be called hexasc.
  Parameter: One, in register $a0.
  The 4 least significant bits specify a number, from 0 through 15. All other bits in register $a0 can have any value and must be ignored. Return value: The 7 least significant bits in register $v0 must be an ASCII code as described below. All other bits must be zero when your function returns.

  Required action: The function must convert input values 0 through 9 into the ASCII codes for digits '0' through '9', respectively. Input values 10 through 15 must be converted to the ASCII codes for letters 'A' through 'F', respectively.

.text
main:
li      $a0,10      # change this to test different values

jal     hexasc      # call hexasc
nop             # delay slot filler (just in case)

move    $a0,$v0     # copy return value to argument register

li      $v0,11      # syscall with v0 = 11 will print out
syscall         # one byte from a0 to the Run I/O window

stop:   j   stop            # stop after one run
nop             # delay slot filler (just in case)

hexasc:
andi    $a0,$a0,0xf     #only 4 least significant bits ignore other bits
addi    $v0,$zero,0x30  #$v0 = 0x30 ('0')
addi    $t0,$zero,0x9   #t0 = 0x9

ble     $a0,$t0,L1      #branch if a0 <= 0x9
nop
addi    $v0,$v0,0x7     #v0 = v0 +0x7

L1:
add     $v0,$a0,$v0     #v0 = V0 +a0
jr      $ra
nop


texts: Nodejs functions to load and save RSA keys

texts:
I'm creating my first real life Nodejs project. I've created some files and all work, but I'm not satisfied about what my files look likes. It's unreadeble.

For example, I work of a file to manage JWT sessions and RSA keys.

For this file, I need two function to load and save the RSA private key.

This Node.js style guide says to put require at the top of documents.

'use strict';

const logger = require('./logger')(module.filename);
const NodeRSA = require('node-rsa');
const jwt = require('jsonwebtoken');
const fs = require('fs');

const loadKeyFromDisk = (path) => new Promise((resolve, reject) => fs.readFile(path, 'utf-8', (error, data) => {
  if (error) {
    reject(error);
    return;
  }
  resolve(data);
}));
const saveKeyToDisk = (path, key) => new Promise((resolve, reject) => fs.writeFile(path, key, 'utf-8', (error) => {
  if (error) {
    reject(error);
    return;
  }
  resolve();
}));

[...]

modules.exports = {...};

But, I also learn to put variables into small context as possible

'use strict';

const logger = require('./logger')(module.filename);
const NodeRSA = require('node-rsa');
const jwt = require('jsonwebtoken');

const { loadKeyFromDisk, saveKeyToDisk } = (() => {
  const fs = require('fs');

  return {
    loadKeyFromDisk: (path) => new Promise((resolve, reject) => fs.readFile(path, 'utf-8', (error, data) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(data);
    })),
    saveKeyToDisk: (path, key) => new Promise((resolve, reject) => fs.writeFile(path, key, 'utf-8', (error) => {
      if (error) {
        reject(error);
        return;
      }
      resolve();
    }))
  };
})();

[...]

modules.exports = {...};

I've also tried some others style, but I think it's don't look like professionnal and clean code...

'use strict';

const logger = require('./logger')(module.filename);
const NodeRSA = require('node-rsa');
const jwt = require('jsonwebtoken');
const fs = require('fs');

const loadKeyFromDisk = (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf-8', (error, data) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(data);
    });
  });
};
const saveKeyToDisk = (path, key) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, key, 'utf-8', (error) => {
      if (error) {
        reject(error);
        return;
      }
      resolve();
    });
  });
};

[...]

modules.exports = {...};

Did you have somes advices or idea to improve my coding style?

My complete code Here : https://pastebin.com/kXvxNd2k


texts: Improving a filter array function with Set and objects, to match elements and conditions

texts:
I've posted a similar question on: Link
With the help of the other users, I was able to improve the code, but I don't think is the "ultimate" form.
Thats my code now, any help?
Conditions entries example:
[1,2],
[9,6,4],
[3]
[7,1,5,2,3]

private filterElements(userSelectedConditions: Set<number>): Element[]{
const meetConditions: Element[] = [];

this.arrayWithAllElements.forEach(element => {

  let isPossibility: boolean = true;

  for (let ev of userSelectedConditions ) {
    if( !element.condition_matrix.includes( ev ) ){
      isPossibility = false;
      break;
    }
  }

  if(isPossibility){
    meetConditions.push(element);
  }
});

if(meetConditions.length === 0){
  meetConditions.push( { <a_filler_object> } );
}

return meetConditions;
}

The user select some conditions, and this code has to iterate on the full elements list, filter the elements that meets all the conditions passes. So if the user selects ONE condition, every element with that condition should be filtered. IF the user selects THREE conditions, every element that meet those conditions should be filtered, if they don't match ALL the selected conditions, they should be out of the list.
this.selectedConditions is already maped by ID
Elements list example:
elements: [
    {
        name: 'el1',
        condition_matrix: [1,2]
    },
    {
        name: 'el2',
        condition_matrix: [2,3]
    },
    {
        name: 'el3',
        condition_matrix: [2,1]
    }
]

Conditions list example:
conditions: [
    {
        id: 1
        name: 'cond1'
    },
    {
        id: 2
        name: 'cond2'
    },
    {
        id: 3
        name: 'cond3'
    }
]


texts: Use of Ninject and an injectable DataLayer in MVC3

texts:
I'm trying to make an MVC3 application with an exchangeable data layer. I currently have this in a single file (Global.asax.cs) for brievity.

It seems to be working as I want but as I'm new to DI I really would appreciate comments on this code.

public interface IDataLayer
{
    dynamic GetItem(int id);
    dynamic SaveItem(dynamic item);
}

public class MockDataLayer : IDataLayer
{
    public dynamic GetItem(int id)
    {
        dynamic item = new System.Dynamic.ExpandoObject();
        item.Id = id;
        item.Name = "Some name";
        return item;
    }
    public dynamic SaveItem(dynamic item)
    {
        return item;
    }
}
public class MainController : Controller
{
    public ActionResult Display(int id = 0)
    {
        dynamic viewModel = Global.DataContext.GetItem(id);
        return View(viewModel);
    }
}
public class Global : System.Web.HttpApplication
{
    public static IDataLayer dataContext;

    protected void Application_Start(object sender, EventArgs e)
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<IDataLayer>().To<MockDataLayer>();
        dataContext = kernel.Get<IDataLayer>();

        RouteTable.Routes.MapRoute("", "{id}", new { controller = "Main", action = "Display", id = UrlParameter.Optional });
    }
}


texts:
Here is a simple Python logger I would like some general feedback on.
Features:

Dynamically creates log folder and files wherever user runs the program
Abillity to create multiple logs from a single program
Names logs from time stamp to the latest second preventing name conflicts

I understand there may be far better alternatives to this but I just wanted to tinker around with this concept a bit!
Thank you!
logger.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime
import time
import os
import sys

# get user's current directory

directory = os.path.dirname(os.path.realpath(__file__)) + '/logs'

def createNewLog():

    # ensure log folder exists

    if not os.path.exists(directory):
        os.mkdir(directory)

    # get timestamp for naming the log

    timeInSeconds = time.time()
    timestamp = \
        datetime.datetime.fromtimestamp(timeInSeconds).strftime('%Y-%m-%d %H:%M:%S'
            )

    logFile = directory + '/' + timestamp + '.txt'
    mostRecentLog = directory + '/mostRecentLog.txt'

    # create log file and file with the log file's name

    with open(logFile, 'w') as log:
        with open(mostRecentLog, 'w') as recentLog:
            recentLog.write(timestamp)

def findMostRecentLog():

    # ensure logger has been intiated

    try:
        with open(directory + '/mostRecentLog.txt', 'r') as logFile:
            logName = logFile.read()
    except FileNotFoundError:

        print("Must initiate logger first!")
        sys.exit(1)

    return directory + '/' + logName + '.txt'

def log(comment):
    comment = str(comment)

    # write to log file retriving most recent log from corresponding file

    with open(findMostRecentLog(), 'a') as log:
        log.write(comment + '\n')


texts:
I'm very new to Haskell's ReadP library, and the entire concept of parser combinators, so I was wondering whether there are better ways to do some things in this program:

import Text.ParserCombinators.ReadP
import Control.Applicative
import Data.List

data Operator = Add | Subtract

instance Show Operator where
    show Add = "+"
    show Subtract = "-"

instance Read Operator where
    readsPrec _ "+" = [(Add, "")]
    readsPrec _ "-" = [(Subtract, "")]
    readsPrec _ _ = []

data Expression = Number Int
                | Infix { left :: Expression, op :: Operator, right :: Expression }

instance Show Expression where
    show (Number x) = show x
    show (Infix left op right) = "(" ++ (show left) ++ " " ++ (show op) ++ " " ++ (show right) ++ ")"

digit :: ReadP Char
digit = satisfy $ \char -> char >= '0' && char <= '9'

number :: ReadP Expression
number = fmap (Number . read) (many1 digit)

operator :: ReadP Operator
operator = fmap read (string "+" <|> string "-")

expression :: ReadP Expression
expression = do
    skipSpaces
    left <- number
    skipSpaces
    op <- Control.Applicative.optional operator
    case op of
        Nothing -> return left
        Just op -> do
            skipSpaces
            right <- expression
            return (Infix left op right)

parseExpression :: String -> Maybe Expression
parseExpression input = case readP_to_S expression input of
    [] -> Nothing
    xs -> (Just . fst . last) xs

The main area where I'm looking for improvements is the expression function, and specifically the things which seem improvable are the repeated calls to skipSpaces and the case expression to check whether an operator was parsed, but of course if you notice anything else that would be helpful too!


texts: Function to validate a GUID, an EntityState, and some data

texts:
In the beginning of my methods that handle the calls from outside, I run this method to make sure that everything's OK, or let the caller know what's wrong:

private static void Validate(Guid userId, EntityState state, object data)
{
  if (userId == Guid.Empty)
    throw new Exception("Token unrecognized!");
  if (state == EntityState.Detached)
    throw new Exception("Action unrecognized!");
  if (data == null)
    throw new Exception("Data unrecognized!");
}

I was happy with the method until R# remarked that I'm declaring the variables without using them, except for pre-condition check. Well, it's true that I do. It's kind of the whole idea.

It bothers me that the tool remarks on it, because it feels like smarter people than me have put in the message there. However, turning it off isn't an option because that'd turn off even the checks for actually unnecessarily declared variables.

Should I refactor the code? How can I improve it?


texts: Dynamically display relevant form elements

texts:
Here is a group of questions (hidden by default except the first one) with yes|no buttons

Q with 1 more option?

    <input type="button" value="true" data-value="web" />
    <input type="button" value="no" />

Q with 2 more option?

    <input type="button" value="yes" data-value="analy,seo" />
    <input type="button" value="no" />

Q3?

    <input type="button" value="yes" data-value="qwe" />
    <input type="button" value="no" />

Q4?

    <input type="button" value="yes" data-value="asd" />
    <input type="button" value="no" />

and the script to reveal the next relevant question (or multiple questions):

$('.form-item:nth-child(1)').slideDown('fast');

$('input[value="yes"],input[value="true"]').click(function () {
    next_id = $(this).attr('data-value');
    matches = [next_id];
    rx = /[^a-z|^0-9]/g;
    if (patt = next_id.match(rx)) {
        matches = next_id.split(patt[0]);
    }

    i = 0;
    while (matches[i]) {
        $('#' + matches[i]).slideDown('fast');
        i++;
    }
});

Sandbox: http://jsfiddle.net/eapo/pu53rx31/

There is any way to simplify this code?


texts: Controller with abstract methods for a delete method

texts:
I'm studying OOP and MVC structure, and all my controllers extends the main controller, and almost all of them has a delete method, basically this:

public function delete () {

        if( isset($_POST) && !empty($_POST) ) {

            $Validator = new Validator;
            $Validator->validation_rules(array(
                    'id'    => 'required|numeric',
            ));

            $validated = $Validator->run($_POST, true);
            if($validated === false) {
                    echo helperModel::toJson(
                    array(
                        'success'=>0,
                        'message'=>$Validator->get_readable_errors(true)
                    ));
            } else {
                $delete_contact = (new contactModel)->delete($validated['id']);
                if($delete_contact){
                    echo helperModel::toJson(array('success'=>1));
                }
            }
        }

    }

I created a variable in the child controller with the name $default_model to refer to the controller model.

Example: in the userController I use the userModel, and copied the structure of the method to the main controller. Instead of using the specific name of the model, I just put:

(new $this->$default_model)->delete($validated['id'])

Is it a correct/recommended practice? If not, what should I do?


texts:
I often need to loop through a list of items and need both the index position, and the item itself:

set names {John Paul George Ringo}
set i 0
foreach name $names {
    puts "$i - $name"
    incr i
}

Output:

0 - John
1 - Paul
2 - George
3 - Ringo

Since I frequently do this, I decided to implement my own loop and call it for_item_index for lack of creativity. Here is my loop and a short code segment to test it:

proc for_index_item {index item iterable body } {
    uplevel 1 set $index 0
    foreach x $iterable {
        uplevel 1 set $item $x
        uplevel 1 $body
        uplevel 1 incr $index
    }
}

# Test it
set names {John Paul George Ringo}
for_index_item i name $names {
    puts "$i - $name"
}

I have tested it with break, and continue and found my new loop performs as expected. My concern is the excessive use of uplevel command in the code. I am seeking reviewers to give me tips for improving it.

Here are my own review of my code:

Excessive use of uplevel
The index always starts at zero. There are times when I want it to start at 1 or some other values. To add that feature, I will probably introduce another parameter, startValue
Likewise, the index always get incremented by 1. The user might want to increment it by a different values such as 2, or -1 to count backward. Again, introducing another parameter, step might help, but at this point, the loop is getting complicated.


texts:
I have some experience in Java. I am reading Effective Java by Joshua Bloch, the book talks about Builder pattern which I was unaware of. So,I have assembled a quick example of what I think builder pattern is all about. Is my implementation correct? Are there any gotchas in Builder pattern?

/* Object to be built using builder */

class Car{
 public String wheels;
 public String color;
 public int speed;
}

class CarBuilder{
 private Car car = new Car();

 /* method to get car object */
 public Car getCar(){
  return car;
 }

 public CarBuilder setWheels(String brand){
  car.wheels = brand;
  return this;
 }

 public CarBuilder setColor(String color){
  car.color = color;
  return this;
 }

 public CarBuilder setSpeed(int speed){
  car.speed = speed;
  return this;
 }

 public Car build(){
  return car;
 }

}

public class builder{
 public static void main(String args[]){
  CarBuilder cb = new CarBuilder();
  Car newcar = cb.setColor("Red").setSpeed(180).setWheels("MRF").build();
  System.out.println("Your new car is "+newcar.color+" in color");
 }
}


texts:
I started out with the Rosalind problems a while back. Turns out it's a great way to learn a new language. I'm still trying to learn Ruby, and while I haven't managed to use regular expressions as much as I wanted to (learning those being one of the reasons I started learning Ruby in the first place), I put together a repository of whatever challenges I have solved so far.

I learned how easy it is to benchmark with Ruby, so I put that to the test as well. While the resulting solution is good, it's quite possible there's a better one out there.

Problem: IPRB

  Probability is the mathematical study of randomly occurring phenomena. We will model such a phenomenon with a random variable, which is simply a variable that can take a number of different distinct outcomes depending on the result of an underlying random process.

  For example, say that we have a bag containing 3 red balls and 2 blue balls. If we let \$X\$
  represent the random variable corresponding to the color of a drawn ball, then the probability of each of the two outcomes is given by \$Pr[X=red]=35\$ and \$Pr[X=blue]=25\$.

  Random variables can be combined to yield new random variables. Returning to the ball example, let \$Y\$
  model the color of a second ball drawn from the bag (without replacing the first ball). The probability of \$Y\$ being red depends on whether the first ball was red or blue. To represent all outcomes of \$X\$ and \$Y\$, we therefore use a probability tree diagram. This branching diagram represents all possible individual probabilities for \$X\$ and \$Y\$, with outcomes at the endpoints ("leaves") of the tree.

Given:

  Three positive integers \$k, m,\$ and \$n\$, representing a population containing \$k+m+n\$ organisms: \$k\$ individuals are homozygous dominant for a factor, \$m\$ are heterozygous, and \$n\$ are homozygous recessive.

Return:

  The probability that two randomly selected mating organisms will produce an individual possessing a dominant allele (and thus displaying the dominant phenotype). Assume that any two organisms can mate.

Sample dataset:

2 2 2

Sample output:

0.78333

My solution solves the sample dataset and the actual dataset given:

Dataset:

22 26 27

Solution:

0.71775

IPRB.rb:

def probability_dominant(k, m, n)
    (k * k + k * (2 * m + 2* n - 1) + m * (0.75 * m + n - 0.75)) / ((k + m + n - 1) * (k + m + n))
end

user_input = gets.chomp

split_input = user_input.split().map { |number| number.to_i() }
puts probability_dominant(split_input[0], split_input[1], split_input[2]).round(5)

The math involved appears to be the performance bottleneck.

IPRB_benchmark.rb:

def probability_dominant_1(k, m, n)
    ((k * k - k) + 2 * (k * m) + 2 * (k * n) + (0.75 * (m * m - m)) + 2 * (0.5 * m * n))/((k + m + n)*(k + m + n -1))
end

def probability_dominant_2(k, m, n)
    (k * k + k * (2 * m + 2* n - 1) + m * (0.75 * m + n - 0.75)) / ((k + m + n - 1) * (k + m + n))
end

def probability_dominant_3(k, m, n)
    (k * k + k * m + k + 0.25 * m * m + 0.75 * m)/(k + m + n) - (k * k + k * m - k + 0.25 * m * m - 0.25 * m) / (k + m + n - 1)
end

require 'benchmark'

n = 500000
Benchmark.bm(6) do |x|
  x.report("first:")   { for i in 1..n; probability_dominant_1(n, n, n); end }
  x.report("second:")   { for i in 1..n; probability_dominant_2(n, n, n); end }
  x.report("third:")   { for i in 1..n; probability_dominant_3(n, n, n); end }
end

Output:

             user     system      total        real
first:   0.594000   0.000000   0.594000 (  0.597825)
second:  0.328000   0.000000   0.328000 (  0.316578)
third:   0.500000   0.000000   0.500000 (  0.517067)

I optimized the math the best I could, but optimizing for a computer is a lot sketchier than optimizing for a human. It's quite hard to keep it fast for the machine and readable for a human at the same time. I foresee the upcoming challenges to be more and more mathematically inclined, so I better tackle this here and now.

Any and all advice about how to math in Ruby is appreciated. Nitpicks are welcome too.


texts: Binary Insert Method - handling edge cases

texts:
I've created a function that uses binary search to insert an element into an array (similar to this question).  I haven't benchmarked it, but based on my knowledge it should get \$O(1)\$ in the best case (i.e., appending an item to the end of the list) and \$O(nlogn)\$ in the average/worst case (I have no numbers to back this up - frankly I don't have much experience with benchmarking, so have mercy on me.)

Here's the binary search algorithm:

def binary_search(a, x):
    mid = 0
    min = 0
    max = len(a)

    # Deal with the edge cases
    if x < a[min]:
        return -1
    if x > a[max-1]:
        return max

    # Now that we know that the value is in range,
    # perform the actual search
    while min < max:
        mid = mid_point(min,max)
        if x < a[mid]:
            max = mid - 1
        elif x > a[mid]:
            min = mid + 1
        else:
            return mid

    # Another edge case
    return min if a[min] >= x else min + 1

This will return the index to insert the element into. The function used to perform the insertion is simple:

def binary_insert(array, value):
    index = binary_search(array,value)
    if index < 0: # Just append the value to the end of the list
        array.insert(0,value)
    else:
        array.insert(index,value)

The function works on a pre-sorted list (a requirement of a binary search) and maintains the list in sorted order. For example inserting [0..10) (aka [0,1,2,...,8,9]) into [-1, 0, 1, 4, 5, 6, 7, 8, 9, 10] yields [-1, 0, 0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10]

You may have noticed that the return statement (the last one) for binary_search is very messy, and not very intuitive.  Would like to be able to incorporate that logic into the while loop somehow, or at least simplify it.  Does anyone have an idea of how I could do this? (Side question: how do I benchmark this?)

EDIT:

This is the mid_point function.

def mid_point(x, y):
    return (x+y)/2


texts: Add three integers and report the sign of the sum

texts:
I am in my first high school programming course; the assignment is:

  Write a program that asks the user to input three integers and outputs
  a message indicating their sum and whether it is positive, negative,
  or zero. You should create 2 classes to run this program. One class
  contains all of the procedures for your program and the other has all
  of the procedure calls for your program.

I have done exactly what the assignment has asked for me to do; I was wondering if there was anything that I should change to make my code more simple and or more elegant or point out anything that might lead up to errors, since I'm in my first programming course. I really want to start programming with simple elegant code and not messy code, because I feel like it starts good habits for me later on.

import java.util.Scanner;

class ConorsList {
    int total;

    public void add(int number) {
        this.total = this.total + number ;
    }

    public void status(){
        if(this.total<0) {
                System.out.println("The sum is negative.");
        } else if (this.total>0) {
                System.out.println("The sum is positive");
        } else {
               System.out.println("The sum is equal to zero");
        }
    }

    public void status(int total){
        if(total<0) {
                System.out.println("The number is negative.");
        } else if (total>0) {
                System.out.println("The number is positive.");
        } else {
               System.out.println("The number is equal to zero.");
        }
    }
}

public class Class1_2 {

   public static void main(String args[]) {
       ConorsList list = new ConorsList();
       Scanner fromKeyboard = new Scanner(System.in);

       int amount = 3;

       for (int n=0; n<amount; n++) {
           int x =fromKeyboard.nextInt();
            list.add(x);
            list.status();
            list.status(x);
       }

   }

}
```


texts: Create array given number of larger elements to right of each member

texts:
I want to improve on my original solution to this problem,
my solution is O(n^2) and I think it's possible to solve in less time

You have two arrays: A and B. A contains ints and B has pairs: (element from A, the number of elements that are larger than that element and to the right of it in A).
for example:
A = [4,3,5]
B = [(5,0), (3,1), (4,1)]
Given array B, recreate array A

void originalArray(vector<pair<int,int>>& pairVector) {
    sort(pairVector.begin(),pairVector.end());
    int arr[pairVector.size()];
    list<int> arrList;
    list<int>::iterator it;
    for(int i=pairVector.size()-1;i>=0;i--){
        it = arrList.begin();
        advance(it, arrList.size()-pairVector[i].second);
        arrList.insert(it,pairVector[i].first);
    }
    it = arrList.begin();
    for(int i=0;i<arrList.size();i++){
        arr[i]=*it;
        it++;
    }
    for (int i = 0; i < pairVector.size(); i++)
        cout << arr[i] << " ";
}


texts:
I've created a function that takes an integer greater than zero as an input and converts it into its corresponding Roman numeral.  If you're not familiar with Roman numerals, you can read about it on Wikipedia.  I've tested this code with some examples, so it should be working correctly.

I'd be interested in hearing about any general improvements I could make on the code.  Nitpicky details are fine as well; whatever you have to say I'm willing to hear, but I hope your answer is more substantial than that.  I suppose my main concern is whether this is sufficiently efficient or if there is a way I could improve on that.  Also, do you think I've used the correct data structure in this situation?  I can't think of a better data structure for what I wanted to do, so that is why I chose arrays.

function arabicToRoman(num) {
    var roman = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"];
    var arabic = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
    var result = "";

    while(num >= 4000) {
        result += "M";
        num -= 1000;
    }

    for(var i = arabic.length - 1; num > 0; i--) {
        while(num >= arabic[i]) {
            result += roman[i];
            num -= arabic[i];
        }
    }

    return result;
}


texts:
I am carrying out unit testing for my project but i am not sure i am doing it correctly. The example below calculates the difference between 2 time duration's.

public void diffTime2() throws Exception {

        //Calculsates the difference
        String ExpectedResult = "1:0:0";
        String str_time1 = "04 13, 2018 09:00:00";
        String str_time2 = "04 13, 2018 08:00:00";
        DateFormat simpleDateFormat3 = new SimpleDateFormat("MM dd, yyyy HH:mm:ss");
        Date date1 = simpleDateFormat3.parse(str_time1);
        Date date2 = simpleDateFormat3.parse(str_time2);
        DateTime dt1 = new DateTime(date2);
        DateTime dt2 = new DateTime(date1);
        long hours = (Hours.hoursBetween(dt1, dt2).getHours() % 24);
        long mins = (Minutes.minutesBetween(dt1, dt2).getMinutes() % 60);
        long secs = (Seconds.secondsBetween(dt1, dt2).getSeconds() % 60);
        String result = (hours+":"+mins+":"+secs);
        //System.out.println(hours+":"+mins+":"+secs);

        assertEquals(ExpectedResult, result);
}

It successfully runs and seems to be OKbut i am not sure that i am completing the unit testing exactly how i should.

Any observation about this is greatly appreciated


texts:
I saw a question about prime factorization on Stack Overflow and realized I had never attempted it before. This was what I ended up with after some playing around and tweaking.

I'd like improvements on anything here.

I know I could use a sieve instead of the naive method (I may switch later), but it was sufficient here. Is there a better way though to handle 2 in prime?? I feel like it being a special case is off.
Is there a better way than a full loop for the main function?
Whatever else

(find-prime-factors 993061001)
=> [17 173 337661]

Verified against CalculatorSoup.

(ns irrelevant.prime-factorization)

(defn is-factor-of? [n multiple]
  (zero? (rem n multiple)))

(defn prime? [n]
  (or (= n 2) ; TODO: Eww
      (->> (range 2 (inc (Math/sqrt ^double n)))
           (some #(is-factor-of? n %))
           (not))))

(defn primes []
  (->> (range)
       (drop 2) ; Lower bound of 2 for the range
       (filter prime?)))

(defn smallest-factor-of? [n possible-multiples]
  (some #(when (is-factor-of? n %) %)
        possible-multiples))

(defn find-prime-factors [n]
  (loop [remaining n
         remaining-primes (primes)
         prime-factors []]

    (if-let [small-prime (and (> remaining 1) (smallest-factor-of? remaining remaining-primes))]
      (let [rest-primes (drop-while #(not= % small-prime) remaining-primes)]
        (recur (long (/ remaining small-prime))
               rest-primes
               (conj prime-factors small-prime)))

      prime-factors)))


texts: Is this a good way to syncronize my Threads?

texts:
After getting much improvement, it´s still one issue that concerns me.
And that is the sync between my 2 threads.

I use AutoResetEvent, but sadly, it has some delay with it, and would love to use something else if possible. Would be great if something could be connected to a Bool or the Queue i am using. Here is the Codes:

    SharpDX.Windows.RenderLoop.Run(form, () =>
    {

    if (Queue.TryDequeue(out TextureData))
    {
        ........
    }
    else
    {
        AutoReset.WaitOne(100);
    }
});

So there it does it´s thing, if there is something in a Queue, else it will wait on AutoReset Up till 100ms (this is to prevent the Form to totally freeze).

while (ReceiveCheck.Checked && tt1.Connected)
{
    ...........
    AutoReset.Set();
    Queue.Enqueue(tempBytes);
}

And there i simply do my work, and then tell the other thread to start, and right after i Queue my item. (why i AutoReset Before that is because of the delay, to help minimize it a bit).

Is there a way to improve this?
Would be great if the other thread could just wait until there is something in the Queue and then run.


texts:
I wanted to get feedback on the correctness and efficiency of this post order traversal routine that my wife and I find really easy to grasp.

def postOrderTraversal(root: TreeNode):
  curr = root
  stack = []

  while stack or curr:
    if curr is None:
      if stack[-1].right is None or popped == stack[-1].right:
        popped = stack.pop()
        print(popped.val)
      else:
        curr = stack[-1].right
    else:
      stack.append(curr)
      curr = curr.left


texts:
I decided to write a tiny class to automatically write and delete a file given filename and content. It is intended to make testing IO less verbose. I include a small example usage.

temporary.py

import os

class Temporary:
    def __init__(self, name, content):
        self.name = name
        self.content = content

    def __enter__(self):
        with open(self.name, 'w+') as f:
            f.write(self.content)

    def __exit__(self,_,__,___):
        os.remove(self.name)

first_word.py

import doctest
from temporary import Temporary

def first_word_of_each_line(filename):
    """
    >>> txt = '\\n'.join(['first line', 'second line', 'bar bar'])
    >>> with Temporary('foo.txt', txt): first_word_of_each_line('foo.txt')
    ['first', 'second', 'bar']
    """
    with open(filename) as f:
        lines = f.read().splitlines()
        return [line.split()[0] for line in lines]

if __name__ == "__main__":
    doctest.testmod()


texts:
I spent the last two days getting a ribbon animation to work with divs so that I can later add li link elements to them to act as a menu. I used the progess bar animation code as inspiration from w3schools. The animation works great, only issue is that the code is very un-DRY. I tried to simplify the code by not repeating myself in the CSS and especially not in the javascript but I kept getting closure issues even after using self invoked functions. I would be greatful if anyone can give me some advice or even a solution that will greatly shorten my code to have the same animation effect. I know that I will have several ribbons on the page, each with different number of ribbon layers, so the code as it is can get very complicated very fast. N.B the code below is the working version.

function move1() {
  var width = 0;
  var elem = document.getElementById("ribbon-part-1");
  var id = setInterval(frame, 1);

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width + '%';
    }
  }
}

function move2() {
  var width = 0;
  var elem = document.getElementById("ribbon-part-2");
  var id = setInterval(frame, 1)

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width += 2;
      elem.style.width = width + '%';
    }
  }
}

function move3() {
  var width = 0;
  var elem = document.getElementById("ribbon-part-3");
  var id = setInterval(frame, 1)

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width += 2;
      elem.style.width = width + '%';
    }
  }
}

function move4() {
  var width = 0;
  var elem = document.getElementById("ribbon-part-4");
  var id = setInterval(frame, 1)

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width += 2;
      elem.style.width = width + '%';
    }
  }
}

function move5() {
  var width = 0;
  var elem = document.getElementById("end-ribbon");
  var id = setInterval(frame, 1)

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width += 2;
      elem.style.width = width + '%';
    }
  }
}

function move() {
  setTimeout(move1, 300);
  setTimeout(move2, 600);
  setTimeout(move3, 900);
  setTimeout(move4, 1200);
  setTimeout(move5, 1500);
}
* {
  box-sizing: border-box;
}

.front-ribbon {
  position: relative;
  /*background-color: grey;*/
  height: 23px;
  width: 160px;
  z-index: 1;
  transform: skewY(-11deg);
}

.back-ribbon {
  position: relative;
  /*background-color: grey;*/
  height: 23px;
  width: 160px;
  transform: skewY(4.7deg);
  z-index: -1;
}

#ribbon-part-1 {
  background-color: rgb(70, 125, 76);
  height: 23px;
  width: 0%;
}

#ribbon-part-2 {
  background-color: rgb(89, 166, 101);
  height: 23px;
  width: 0%;
}

/*Including the code below will allow for a reverse progressive bar*/
.front-ribbon #ribbon-part-2 {
  display: block;
  float: right;
}

#ribbon-part-3 {
  background-color: rgb(70, 125, 76);
  height: 23px;
  width: 0%;
}

#ribbon-part-4 {
  background-color: rgb(89, 166, 101);
  height: 23px;
  width: 0%;
}

/*Including the code below will allow for a reverse progressive bar*/
.front-ribbon #ribbon-part-4 {
  display: block;
  float: right;
}

#end-ribbon {
  fill: rgb(70, 125, 76);
  width: 0%;
}

JavaScript ribbon animation

<svg id="end-ribbon">
  <path d="M-6 17 L35 24 L24 10 Z" />
</svg>

<button onclick="move()">Click Me</button>


texts: Populating an array with times with half hour interval between them

texts:
So for example, getTimes("12:00", "15:30"); should return:
["12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30"]

The input parameters are always in :30 or :00 intervals(so 06:00, 06:30, 07:00, ...).
getTimes("06:00", "17:00"); -> should work

getTimes("06:30", "17:00"); -> should work

getTimes("06:25", "17:00"); -> doesn't have to work because the from or until time can never be "06:25"

It also only has to work for the range 00:00 - 23:30 the same day.

What I have right now is this:

function getTimes(from, until){
            //"01/01/2001" is just an arbitrary date
            var until = Date.parse("01/01/2001 " + until);
            var from = Date.parse("01/01/2001 " + from);
            //*2 because because we want every 30 minutes instead of every hour
            var max = (Math.abs(until-from) / (60*60*1000))*2;
            var time = new Date(from);
            var hours = [];
            for(var i = 0; i <= max; i++){
                //doubleZeros just adds a zero in front of the value if it's smaller than 10.
                var hour = this.doubleZeros(time.getHours());
                var minute = this.doubleZeros(time.getMinutes());
                hours.push(hour+":"+minute);
                time.setMinutes(time.getMinutes()+30);
            }
            return hours;
}

How can this be improved?


texts:
I've decided to write a common Makefile for Google benchmark library. You could say I could have taken generated Makefile, but it's not appropriate solution (or maybe I'm wrong?).

TARGET = libbenchmark.a

CXXFLAGS = -std=c++11 -Wall -Wextra -Wshadow -Werror -pedantic \
            -pedantic-errors -Wfloat-equal \
            -Wzero-as-null-pointer-constant -fstrict-aliasing \
            -DHAVE_STD_REGEX

LDFLAGS = -lpthread

# Define include files and directories
INCLUDES = -I./include -I./src

# Define the source files
SOURCE_FILES = src/colorprint.cc src/benchmark.cc src/commandlineflags.cc \
               src/console_reporter.cc src/csv_reporter.cc src/json_reporter.cc \
               src/log.cc src/reporter.cc src/sleep.cc src/string_util.cc \
               src/sysinfo.cc src/walltime.cc src/re_std.cc

OBJECT_FILES = $(SOURCE_FILES:.cc=.o)

CC = gcc
AR = gcc-ar

all: $(TARGET)

$(TARGET): $(OBJECT_FILES)
    $(AR) rcs $(TARGET) $(OBJECT_FILES)

%.o: %.cc
    $(CC) $(INCLUDES) $(CXXFLAGS) -c -o $@ $<

clean:
    $(RM) src/*.o $(TARGET)

install:
    mkdir -p $(DESTDIR)/usr/lib
    cp -p ./$(TARGET) $(DESTDIR)/usr/lib
    cp -r include $(DESTDIR)/usr


texts:
I'm a beginner as you can see and I would like to know how I can improve my code. Studying for 6 months now. Thank you.

roman_dict = {1: 'I', 4: 'IV',  5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD',
              500: 'D', 900: 'CM', 1000: 'M'}

divide_list = [1000, 100, 10, 1]

def not_in_dict(fixed_decimal, divide_num):
    sub_count = 0
    sub_roman_multi = roman_dict[divide_num]
    temp_decimal = fixed_decimal
    while temp_decimal not in roman_dict:
        temp_decimal -= divide_num
        sub_count += 1
    return roman_dict[temp_decimal]+(sub_count*sub_roman_multi)

def decimal_to_roman(decimal):
    original_decimal = decimal
    roman = ""
    for divide_num in divide_list:
        if decimal >= divide_num:
            reminder = decimal//divide_num
            if(reminder >= 1) and ((reminder*divide_num) in roman_dict):
                roman += roman_dict[(reminder*divide_num)]
                decimal -= reminder*divide_num
            else:
                roman += not_in_dict(reminder*divide_num, divide_num)
                decimal -= (reminder*divide_num)
    return str(original_decimal)+' = '+roman


texts: Finding the second-largest value in an array

texts:
The problem is stated as:

  You are given as input an unsorted array of n distinct numbers, where
  n is a power of 2. Give an algorithm that identifies the
  second-largest number in the array and that uses at most n+log(n)−2
  comparisons.

I've seen many references to the problem online but most focus on a recursive approach. I wonder why that is. Below is how I approached it. Is there an issue with this implementation? Why choose recurrence here?

testCase = [10, 9, 5, 4, 11, 100, 120, 110]
def getSecondHighest(a):
  hi = mid = lo = 0
  for i in range(0, len(a)):
    x = a[i]
    if ( x > hi):
      lo = mid
      mid = hi
      hi = x
    elif ( x < hi and x > mid):
      lo = mid
      mid = x
    elif ( x < lo):
      lo = x
  return mid

print(getSecondHighest(testCase))


texts: Reduce number of parameters of the same type

texts:
I'm looking at a class diagram and it shows a method like this:

SavePrintOptions(bool,bool,bool,bool,bool,bool,bool,bool,bool);

where each of the parameters match up with save options (checkboxes) in the UI.  How could I refactor this signature to reduce the number of parameters?


texts: Script to drop HTML part of multipart/mixed e-mails

texts:
I have a working script that I wrote in Python which for e-mail messages that consist only of a plain text part + an HTML part, discards the HTML and keeps only the plain text part.

The script is not exactly elegant and, as can be seen from the code, it smells like it is C (in particular, I simulate the use of bitmasks) and I am not exactly satisfied with some points of it.

I know that the script has some issues (like code duplication and the hack mentioned above), but I don't know the idiomatic Pythonic way of writing it and I would appreciate any kind of criticism to improve it in any way to make the code elegant.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author: Rogério Theodoro de Brito <rbrito@ime.usp.br>
License: GPL-2+
Copyright: 2010-2012 Rogério Theodoro de Brito

drop-alternatives is a simple Python script for those who hate emails in
HTML and who prefer their inbox to have as many messages in pure text as
feasible. This script is generally meant to be run as a filter with procmail
or some other mail delivery agent.

It tries to be moderately conservative and only act when things are
moderately safe:

* If the message is `multipart` and has a `text/plain` and a `text/html`
  part, keep the `text/plain` part only.

* In all other cases keep the message intact.
"""

import email
import email.message

def compose_message(orig, body):
    """
    Create new message with headers from `orig` and body from `body`.

    * `orig`: The original message.
    * `body`: The body that we want the new message to have.
    * Returns a new message.

    `compose_message` creates a new message with most of the fields from
    `orig`, with fields from `body` (if any) and with the payload of
    `body`. The fields excluded from `orig` are the following:

    * `content-length`
    * `content-type`
    * `lines`
    * `status`
    """
    wanted = email.message.Message()
    wanted.set_payload(body.get_payload())

    unwanted_fields = ["content-length", "content-type", "lines", "status"]

    # The dictionaries `orig` and `body` have only headers as their items.
    for field in unwanted_fields:
        del orig[field]

    for k, v in orig.items():
        wanted[k] = v
    for k, v in body.items():
        wanted[k] = v

    return wanted

def sanitize(msg):
    """
    Given an RFC-2822 message `msg`, generate its 'sanitized' version.

    * `msg`: The message to be sanitized.
    * Returns a sanitized version of `msg`.

    `sanitize` tries to be moderately conservative and only act when things
    are moderately safe:

    * If the message is multipart and has a `text/plain` and a `text/html`
      part, keep the `text/plain` part only.

    * In all other cases keep the message intact.
    """
    if not msg.is_multipart():
        return msg

    # 'composition' is a bitmask containing the kind of the parts
    TEXTPLAIN = 1  # text/plain
    TEXTHTML = 2  # text/html
    MISCPARTS = 4  # anything else

    composition = 0
    text_taken = False

    for part in msg.walk():
        if (part.get_content_maintype() == "multipart" or
            part.get_content_type() == "message/external-body" or
            part.get_payload() == ""):
            continue
        elif part.get_content_type() == "text/plain":
            if not text_taken:
                text_taken = True
                body = part
                composition |= TEXTPLAIN
            else:
                # if we are seeing a second text/plain part, stop throwing
                # things
                composition |= MISCPARTS
                break
        elif part.get_content_type() == "text/html":
            composition |= TEXTHTML
        else:
            composition |= MISCPARTS

    if composition == (TEXTPLAIN + TEXTHTML) or composition == TEXTPLAIN:
        return compose_message(msg, body)
    else:
        return msg

if __name__ == "__main__":
    import sys
    res = sanitize(email.message_from_file(sys.stdin))
    print res.as_string(unixfrom=False),


texts: Pouring water between two jugs to get a certain amount in one of the jugs (2)

texts:
I have been practicing recursion lately and I came up with this code to solve the water jug problem, given two jugs of volume jug1 and jug2, where jug1 < jug2, obtain a volume t, where t < jug2.

The algorithm below basically always pours from the smaller jug into the bigger jug, how would you improve the solution ?

I think I get the minimum number of steps this way... am I correct ?

jug1 = 5
jug2 = 7
t = 4

def jugSolver(amt1, amt2):

    print(amt1, amt2)

    if (amt1 == t and amt2 == 0) or (amt1 == 0 and amt2 == t):
        return

    elif amt2 == jug2:
        jugSolver(amt1, 0)

    elif amt1 != 0:
        if amt1 <= jug2-amt2:
            jugSolver(0, amt1+amt2)
        elif amt1 > jug2-amt2:
            jugSolver(amt1-(jug2-amt2),amt2+(jug2-amt2))

    else:
        jugSolver(jug1, amt2)

jugSolver(0,0)


texts:
I would like to simplify to following function as much as possible:

public string[] GetPowerSet(string input)
    {
        IEnumerable<IEnumerable<string>> seed = new List<IEnumerable<string>>() { Enumerable.Empty<string>() };

        return input.Split(',').ToList().Aggregate(seed, (a, b) =>
          a.Concat(a.Select(x => x.Concat(new List<string>() { b })))).Select(subset => string.Join(",", subset.ToArray())).Skip(1).ToArray();
    }


texts: Displaying a list of attributes and differentiate them from attributes already selected

texts:
attributes is an array with all attributes selected by the user.

attributeList is a Mongo collection declared in [root]/lib and contains all possible attributes.

I'm using two loops in order to match attributes. For those that match, new fields "operator" and "value" are added and will be used in the template.

Do you see a way how to improve these two loops in terms of speed?

var attibutes = attrInfo2.findOne({}, {"fields": {"metric": 1}, reactive: false});
var result = attributeList.find(query).map(function (attr) {
    if(attr.inputType) {
        if (attr.inputType === "int" || attr.inputType === "double") {
            _.map(attibutes.metric, function (m) {
                var operator;
                if (m.attrType === "filter" && attr.field === _.values(m.attrField)[0]) {
                    if (_.isObject(m.attrData)) {
                        operator = _.keys(m.attrData)[0];
                        if (operator !== "in") {
                            attr.operator = operator;
                        }
                        attr.value = _.values(m.attrData)[0];
                    } else {
                        attr.value = m.attrData;
                    }
                }
                return m;
            });
        } else if (attr.inputType === "string"){
            _.map(attibutes.metric, function (m) {
                if (m.attrType === "filter" && attr.field === _.values(m.attrField)[0]) {
                    if (_.isObject(m.attrData)) {
                        attr.value = _.values(m.attrData)[0];
                    } else{
                        attr.value = m.attrData;
                    }
                }
                return m;
            });
        }
    }
    return attr;
});


texts: Golang gRPC context to check if cancelled or if deadline is exceeded while running function code

texts:
I am writing a gRPC Golang application and am looking for the best way to check if the deadline is exceeded or if the client cancelled the call.

On the server side I created a channel called done. When done is called by either the go-routines the server returns with either the error or the success.

In the code I have two go-routines. The first one runs the actual program and if successful calls the done channel without and error, the second waits for the context.Done() and if called calls the done channel with the error.

I am wanting to know if there is a more efficient way to do this without two go-routines.

I don't want to check periodically ctx.Done() or ctx.Cancelled because I feel that would be a waste of time but the method below would use more CPU resources.

package main

import (
    "context"
    "log"

    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"

    pb "mygit/controller/pb"
)

// ping controller
func (s *server) PingController(ctx context.Context, in *pb.PingControllerRequest) (*pb.PingControllerResponse, error) {

    done := make(chan error) // make a done bool
    var retOut pb.PingControllerResponse

    // run function in go routine and call done when finished without being cancelled
    go func(i *pb.PingControllerRequest) {
        log.Println(in.Client)
        // other business logic would go here
        retOut = pb.PingControllerResponse{Pong: "PONG"}
        done <- nil
    }(in)

    // if context is done (due to error) return with done
    go func(c context.Context) {
        <-c.Done()
        done <- status.Error(codes.Canceled, c.Err().Error())
    }(ctx)

    // wait for done channel to be called
    var doneErr = <-done

    // if there was a context error return with error
    if doneErr != nil {
        return nil, doneErr
    }

    // no context error return with response
    return &retOut, nil
}


texts:
Here is my database:

Here is my viewModel:

public class groupsFoldersViewModel
    {
        private DAL.educationSocialNetworkEntities DB = new DAL.educationSocialNetworkEntities();
     public  List<DAL.sharedFolders_table> sharedFolders { get; set; }

     public groupsFoldersViewModel(int gid , int uid)
     {
         DAL.group_table group = DB.group_table.Find(gid);

         if (group != null)
         {

             sharedFolders = group.sharedFolders_table.ToList();
         }

     }
    }

Which way of joining table is better and faster?

One heavy query for joining tables in ViewModel constructor
Using something like this in a razor page:

@foreach (var f in Model.sharedFolders)
{
    <a> @f.folder_table.folderName </a>
}


texts: Basic string compression counting repeated characters

texts:
My task was to implement a method which performs basic string compression by counting sequences of repeating characters. Given "aaabbbccc" it should return "a3b3c3". I have included some sample tests I made up. Please let me know if I have missed any cases. I am looking for the fastest implementation possible with the most concise code. I'm looking to cut down on if else statements or give them simpler logic if possible.

public class StringCompression {
    public String compress(String str){
        int count = 1;
        StringBuilder builder = new StringBuilder();

        for(int i = 1; i<str.length(); i++){

            if(str.charAt(i) == str.charAt(i-1) && i < str.length()-1){
                count++;
            }
            // case when the last letter is in the sequence preceding it. Add that sequence to
            // the compressed string
            else if(i == str.length()-1 && str.charAt(i) == str.charAt(i-1)){
                count++;
                builder.append(str.charAt(i));
                builder.append(count);
            }

            // case where the last letter is NOT in the sequence preceding it. Add it to string.
            else if(i == str.length()-1 && str.charAt(i) != str.charAt(i-1)){
                builder.append(str.charAt(i-1));
                builder.append(count);
                count = 1;
                builder.append(str.charAt(i));
                builder.append(count);
            }
            else{
                // appending the character and THEN appending the count works.
                builder.append(str.charAt(i-1));
                builder.append(count);
                count = 1;
            }

        }

        str = builder.toString();
        System.out.println(str);

        return str;
    }

    public static void main(String[] args){
        StringCompression test = new StringCompression();

        test.compress("aabcccccaaa");
        test.compress("aaaaa");
        test.compress("aaaabbb");
        test.compress("aaabbbccc");
        test.compress("abc");
        test.compress("a");
        test.compress("");
    }
}


texts: Python print the sentences from the corpus containing the word

texts:
I'm asked to print the sentences from the corpus containing the word(s) with the greatest number of distinct tags. I already got the top 6 words with most distinct tags (5 tags). My questions are:

I don't know how to get the words without using "len(cfd[key])>4"? Because I've tried using max() function but it doesn't work.
I want to print the sentences that include these words. But it prints all sentences that include the non-exact words. For example, I just want to print sentences included only EXACT word: "round", but the code also print the sentences that included "around" (because "round" is part of "around"). What do I have to add?

This is my code:

import nltk
from nltk.probability import FreqDist
from nltk.probability import ConditionalFreqDist
from nltk.corpus import*
from nltk.book import*
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize

import string
import re
cfd = nltk.ConditionalFreqDist((word,tag) for (word, tag) in
brown.tagged_words(tagset='universal'))
homographs = [(key, len(cfd[key])) for key in cfd.keys() if len(cfd[key])>4]
words = [key for key in cfd.keys() if len(cfd[key])>4]
print("Word(s) with the greatest number of distinct tags:", homographs)
print("List of sentences containing the word: ")
txt = brown.sents()
for sentence in txt:
    if list(set(words) & set(sentence)):
        result = "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in sentence]).strip()
        print(result)

Anyone can help me, how to solve these problems? Thank you for your effort.


texts: Solution for Gophercises Quiz game in Haskell

texts:
Here is my solution for the Quiz game exercise from https://gophercises.com/. The goal is to write a program that will read questions and their correct answers from a CSV file, ask them from a user one by one, and print the number of correct answers. The interesting part is that a user has a limited amount of time for answering questions and the quiz should stop as soon as the time limit has exceeded.
I use MissingH and parsec to parse CSV files, optparse-applicative to parse CLI options.
From a code review, I expect some general advice and answers to the following specific questions:

Is there a way to rewrite play function without MVar's?
How to separate quiz logic from the concurrent implementation (forking, MVar manipulation) in the play function?
The first version of the solution was without a timer and to count the number of correct answers I used the following function:

Code for kinda beautiful count function:
count :: [IO Bool] -> IO Integer
count [] = return 0
count (act:xs) = do
  correct <- act
  fmap ((if correct then 1 else 0) +) (count xs)

With the presence of a timer, I have to use another MVar (which is an ugly solution IMHO) to hold the number of correct answers because the thread could be killed at any time. Is it possible to stop recursion somehow when the thread got killed to return the partial result?
Code for the final solution:
module Main where

import Lib

import System.IO
import Text.ParserCombinators.Parsec (parseFromFile)
import Data.CSV (csvFile)
import Control.Applicative (liftA2)
import Options.Applicative
import Data.Semigroup ((<>))
import Control.Concurrent.MVar
import Control.Exception
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad (when)

data Options = Options {inputFile :: String, time :: Int}
options :: Parser Options
options = Options
  <$> strOption
    (long "csv-file" <> value "problems.csv")
  <*> option auto
    (long "time" <> value 30)

main :: IO ()
main = do
  Options {inputFile = file, time = t} <- execParser $ info options briefDesc
  result <- parseFromFile csvFile file
  case result of
    Left e -> putStrLn ("CSV parse error: " ++ show e)
    Right lines -> play lines t

play :: [[String]] -> Int -> IO ()
play lines time = do
  putStrLn $ "Total number of questions is " ++ (show . length) lines
  waitAnyKey
  done <- newEmptyMVar
  correct <- newMVar 0
  questionsT <- forkIO $ do
    askQuestions (map (\[q, a] -> ask q a) lines) done correct
    putMVar done True
  timerT <- forkIO $ do
    threadDelay $ time * 10^6
    putStrLn "\nTimes is out"
    putMVar done True
  takeMVar done
  throwTo questionsT ThreadKilled
  throwTo timerT ThreadKilled

  c <- takeMVar correct
  putStrLn $ "\nNumber of correct answers is " ++ show c

waitAnyKey :: IO ()
waitAnyKey = do
  hSetBuffering stdin NoBuffering
  putStrLn "Hit any key when you get ready"
  getChar
  putChar '\b'
  hSetBuffering stdin LineBuffering

askQuestions :: [IO Bool] -> MVar Bool -> MVar Integer -> IO ()
askQuestions [] done correct = putMVar done True
askQuestions (act:xs) done correct = do
  c <- act
  when c $ modifyMVar_ correct $ \ v -> return (v + 1)
  askQuestions xs done correct

type Question = String
type Answer = String

ask :: Question -> Answer -> IO Bool
ask q a = do
  putStr (q ++ "? ")
  hFlush stdout
  userAnswer <- getLine
  return (userAnswer == a)