texts: Count Words in Quotes Fetched from Website

texts:
I have solved the following exercise and would like to get some feedback on my implementation.

  Create a function that uses futures to parallelize the task of downloading random quotes from https://www.braveclojure.com/random-quote using (slurp "http://www.braveclojure.com/random-quote"). The futures should update an atom that refers to a total word count for all quotes. The function will take the number of quotes to download as an argument and return the atom’s final value. Keep in mind that you’ll need to ensure that all futures have finished before returning the atom’s final value.

(defn quote-word-count
  [quote-count]
  (->> quote-count
      (range)
      (map (fn [_] (fetch-quote)))
      (pmap (comp count-words deref))
      (apply merge-with +)
      (atom)))

(defn fetch-quote
  []
  (future (slurp "https://www.braveclojure.com/random-quote")))

(defn update-word
  [word-counts word]
  (update word-counts word (comp inc zero)))

(defn zero
  [number]
  (if (= nil number) 0 number))

(defn count-words
  [quote]
  (let [cleaned-quote (clean-input quote)]
    (reduce update-word {} (clojure.string/split cleaned-quote #" "))))

(defn clean-input
  [input]
  ((comp remove-commas remove-author clojure.string/lower-case) input))

(defn remove-author
  [quote]
  (clojure.string/replace quote #".\n-- .*\n" ""))

(defn remove-commas
  [quote]
  (clojure.string/replace quote #"," ""))

Things I am not sure about:

the range then map to create the calls
the top-down order of functions
the atom. the exercise says to return an atom but I don't understand why I would need that

Any feedback is appreciated.


texts: Simple C# application that transfers new files (modified in the last 24 hours) from one directory to another

texts:
I'm new to C#, so I'm eager for any and all criticism/advice.

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

namespace FileTransfer
{
    class Program
    {
        private static string targetPath;
        public static bool running;

        static void Main(string[] args)
        {
            var function = new Functions();
            running = true;
            int num = 0;

            while (running)
            {

                Console.WriteLine("These files in Customer Orders are new:");
                ModifiedFiles newFiles = new ModifiedFiles();
                num = 0;

                foreach (var file in newFiles.modified())
                {
                    Console.WriteLine("\""+file+"\"");
                    num++;
                }

                Console.WriteLine("Transfer {0} file(s) to Home Office? y/n", num);
                string answer = Console.ReadLine();

                if (answer == "y")
                {
                    targetPath = @"C:\Users\Student\Desktop\Home Office";

                    num = 0;
                    foreach (var file in newFiles.modified())
                    {
                        File.Copy(file.FullName, Path.Combine(targetPath, file.Name), true);
                        num++;
                    }

                    Console.WriteLine("{0} file(s) transfered.", num);
                    function.exit();
                }

                else if (answer == "n")
                {
                    function.exit();
                }

                else
                {
                    function.wrong();
                }
            }
        }
    }
    class ModifiedFiles
    {
        public string sourceDir;
        public IEnumerable<FileInfo> modified()
        {
            sourceDir = @"C:\Users\Student\Desktop\Customer Orders";
            var directory = new DirectoryInfo(sourceDir);
            DateTime from_date = DateTime.Now.AddDays(-1);
            DateTime to_date = DateTime.Now;
            var files = directory.GetFiles()
              .Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);
            return files.ToList();
        }
    }
    class Functions
    {
        public void wrong() { Console.WriteLine("---Input must be 'y' or 'n'."); }

        public void exit()
        {
            Console.WriteLine("Would you like to exit the program? y/n");
            string answerExit = Console.ReadLine();
            if (answerExit == "y")
            {
                Console.WriteLine("See yah!");
                Environment.Exit(0);
            }
            else if (answerExit == "n")
            {
                // Loop back to beginning
            }
            else
            {
                this.wrong();
            }

        }
    }
}


texts:
I decided to implement the round robin algorithm in Python. My code takes a list of teams as input and prints the schedule.

This is my first try to write something by my own after taking some online courses, so I am absolutely sure that this code must be significantly improved.

Here it is:

import random

def simulate_draw(teams):
    if len(teams) % 2 == 0:
        simulate_even_draw(teams)
    else:
        simulate_odd_draw(teams)

def simulate_even_draw(teams):
    dic = {}
    for i in range(len(teams)):
        dic[i] = teams[i]

    games = []
    arr1 = [i+1 for i in range(int(len(teams)/2))]
    arr2 = [i+1 for i in range(int(len(teams)/2), len(teams))][::-1]

    for i in range(len(teams)-1):
        arr1.insert(1, arr2[0])
        arr2.append(arr1[-1])
        arr2.remove(arr2[0])
        arr1.remove(arr1[-1])
        zipped = list(zip(arr1, arr2))
        games.append(zipped)
        zipped = []

    for game in games:
        for gm in list(game):
            r = random.sample(gm, len(gm))
            print(dic[r[0]-1] + ' plays ' + dic[r[1]-1])

def simulate_odd_draw(teams):
    dic = {}
    for i in range(len(teams)):
        dic[i] = teams[i]
    dic[i+1] = ''
    games = []
    arr1 = [i+1 for i in range(int((len(teams)+1)/2))]
    arr2 = [i+1 for i in range(int((len(teams)+1)/2), len(teams)+1)][::-1]
    for i in range(len(teams)):
        arr1.insert(1, arr2[0])
        arr2.append(arr1[-1])
        arr2.remove(arr2[0])
        arr1.remove(arr1[-1])
        zipped = list(zip(arr1, arr2))
        games.append(zipped)
        zipped = []
    for game in games:
        for gm in list(game):
            r = random.sample(gm, len(gm))
            if len(teams)+1 not in r:
                print(dic[r[0]-1] + ' plays ' + dic[r[1]-1])

I think that big blocks of code that largely repeat themselves inside 2 functions may be united in one function, but not sure how to implement it.


texts:
I've recently began trying to put more error handling in to my code so I thought I'd post a use-case to check I'm on the right path. I feel like this is going to make my functions much larger and more indented/nested than before. Is this the right way to go about things or should I be utilising try? instead? Where do people generally put these Error enum definitions?

fileprivate enum LocationError: Error {
    case noAuthorization
    case noBeaconSupport
    case rangingUnavailable
}

class ViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var distanceReading: UILabel!
    var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()

    view.backgroundColor = UIColor.gray
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    do {
        guard status == .authorizedWhenInUse else {
            throw LocationError.noAuthorization
        }
        guard CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) else {
            throw LocationError.noBeaconSupport
        }
        guard CLLocationManager.isRangingAvailable() else {
            throw LocationError.rangingUnavailable
        }
        startScanning()
    }
    catch LocationError.noAuthorization {
        print("User has not authorized us to use location")
    }
    catch LocationError.noBeaconSupport {
        print("User's device does not support Beacons")
    }
    catch LocationError.rangingUnavailable {
        print("User's device does not support ranging")
    }
    catch {
        fatalError()
    }
}


texts: Program to print the multiple occurrence of numbers in a list

texts:
I wrote this program to print how many times each number occurs in a list:

class deleteduplicate:

    def __init__(self):
        a=[]
        num=int(input("Enter the number of elements"))
        for i in range(0,num):
            try:
                a.append(int(input("Enter the number {}".format(i))))
            except ValueError:
                print ("Wrong Input")
                i=i-1

        flagarray=[]
        countarray=[]
        j=0;
        for c in a:
            flagarray.append(False)
            countarray.append(1)

        for c in a:
            count=1
            flag=False
            ca=[]
            for i in range(j,len(a)):

                if a[i] == c and flagarray[i]==False:

                    flag=True
                    count=count+1
                    flagarray[i]=True
                    ca.append(i)
            if  len(ca)>0:
                print(str(c)+"ocuurs"+str(len(ca))+"times")

            j=j+1

deleteduplicate()


texts:
I am new to the code review area of Stack and welcome all positive criticism.

I would be grateful if someone could review my code below and let me know where I can improve or have gone wrong that I cannot see.

The only thing that I have left is to write the delete and would appreciate help in doing this is possible too please.

My code is

    CREATE TABLE CRM_PERS_CONTACT_INFORMAITON(
 SEQ_ID                     INT IDENTITY(1,1) not null primary key,
 PERS_ID                    INT NOT NULL,
 PREFERRED                  BIT DEFAULT (0),
 CEASED_DATE                DATETIME,
 COMMUNICATION_TYPE         VARCHAR(50),
 COMMUNICATION_VALUE        VARCHAR(255),
 DATE_ADDED                 DATETIME DEFAULT (GETDATE()),
 ADDED_BY                   VARCHAR(50),
 UPDATED_DATE               DATETIME DEFAULT(GETDATE()),
 UPDATED_BY                 VARCHAR(50)
)
GO

CREATE TABLE CRM_PERS_CONTACT_INFORMAITON_HISTORY(
 SEQ_ID                     INT IDENTITY(1,1) not null primary key,
 PERS_ID                    INT NOT NULL,
 PREFERRED                  BIT DEFAULT (0),
 CEASED_DATE                DATETIME,
 COMMUNICATION_TYPE         VARCHAR(50),
 COMMUNICATION_VALUE        VARCHAR(255),
 DATE_ADDED                 DATETIME DEFAULT (GETDATE()),
 ADDED_BY                   VARCHAR(50),
 ACTION_TYPE                VARCHAR(20)
 )
 GO

CREATE PROCEDURE MERGE_CRM_PERS_CONTACT_INFORMATION

@SEQ_ID                     INT,
@PERS_ID                    INT ,
@PREFERRED                  BIT ,
@CEASED_DATE                DATETIME,
@DATE_ADDED                 DATETIME,
@ADDED_BY                   VARCHAR,
@UPDATED_DATE               DATETIME,
@UPDATED_BY                 VARCHAR,
@COMMUNICATION_TYPE         VARCHAR,
@COMMUNICATION_TYPE_VALUE   VARCHAR,
@ACTION_TYPE                VARCHAR

AS
BEGIN

MERGE CRM_PERS_CONTACT_INFORMAITON as Target
USING (select
 @PERS_ID
,@PREFERRED
,@CEASED_DATE
,@DATE_ADDED
,@ADDED_BY
,@UPDATED_DATE
,@UPDATED_BY
,@COMMUNICATION_TYPE
,@COMMUNICATION_TYPE_VALUE
) AS Source(
PERS_ID
,PREFERRED
,CEASED_DATE
,DATE_ADDED
,ADDED_BY
,UPDATED_DATE
,UPDATED_BY
,COMMUNICATION_TYPE
,COMMUNICATION_TYPE_VALUE
)
ON (Source.PERS_ID = Target.PERS_ID
AND Source.COMMUNICATION_TYPE = Target.COMMUNICATION_TYPE)
WHEN MATCHED THEN

    update SET
     COMMUNICATION_TYPE         = @COMMUNICATION_TYPE
    ,COMMUNICATION_VALUE        = @COMMUNICATION_TYPE_VALUE
    ,UPDATED_DATE               = GETDATE()
    ,UPDATED_BY                 = @UPDATED_BY
    ,CEASED_DATE                = @CEASED_DATE
    ,PREFERRED                  = @PREFERRED

WHEN NOT MATCHED BY TARGET THEN
    INSERT (
     PERS_ID
    ,PREFERRED
    ,CEASED_DATE
    ,COMMUNICATION_TYPE
    ,COMMUNICATION_VALUE
    ,DATE_ADDED
    ,ADDED_BY
    ,UPDATED_DATE
    ,UPDATED_BY
    )
    VALUES (
     @PERS_ID
    ,@PREFERRED
    ,@CEASED_DATE
    ,@COMMUNICATION_TYPE
    ,@COMMUNICATION_TYPE_VALUE
    ,@DATE_ADDED
    ,@ADDED_BY
    ,GETDATE()
    ,@UPDATED_BY
    )
WHEN NOT MATCHED BY SOURCE THEN
DELETE;

SET @ACTION_TYPE = $action

INSERT INTO CRM_PERS_CONTACT_INFORMAITON_HISTORY(
 PERS_ID
,PREFERRED
,CEASED_DATE
,COMMUNICATION_TYPE
,COMMUNICATION_VALUE
,DATE_ADDED
,ADDED_BY
,ACTION_TYPE
)
VALUES (
 @PERS_ID
,@PREFERRED
,@CEASED_DATE
,@COMMUNICATION_TYPE
,@COMMUNICATION_TYPE_VALUE
,GETDATE()
,@ADDED_BY
,@ACTION_TYPE
);
END
GO


texts:
My code given below will produce the correct output but it tends to take way too much time with larger data thus timing out for some of the test cases. I've linked to the problem description here:

  It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride!

  There are n people queued up, and each person wears a sticker indicating their initial position in the queue (i.e. 1, 2, ..., n - 1, n: with the first number denoting the frontmost position).

  Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original place in line. One person can bribe at most two other persons.

  That is to say, if n = 8 and Person 5 bribes Person 4, the queue will look like this:
  1, 2, 3, 5, 4, 6, 7, 8.

  Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state!

  Note: Each Person X wears sticker X, meaning they were initially the Xth person in queue.

  Input Format

  The first line contains an integer, T, denoting the number of test cases.
  Each test case is comprised of two lines; the first line has n (an integer indicating the number of people in the queue), and the second line has n space-separated integers describing the final state of the queue.

  Constraints

  $$ 1 \leq T \leq 10 $$
  $$ 1 \leq n \leq 10^5 $$

  Subtasks

  For 60% score $$1 \leq n \leq 10^3$$
  For 100% score $$1 \leq n \leq 10^5$$

  Output Format

  Print an integer denoting the minimum number of bribes needed to get the queue into its final state; print Too chaotic if the state is invalid (requires Person X to bribe more than 2 people).

  Sample Input

  2
5
2 1 5 3 4
5
2 5 1 3 4

  Sample Output

  3
Too chaotic

Any help/advice/suggestion is welcome.

#!/bin/python3

import sys

inp0 = sys.stdin.read()
inp1 = inp0.split('\n')
T = int(inp1[0])
del inp1[0]

# Swaps the i'th and (i-1)'th elements and returns the list
def swap(intermediate_q,i):
    intermediate_q[i],intermediate_q[i-1] = intermediate_q[i-1],intermediate_q[i]
    return(intermediate_q)

# Increment bribes and total_bribes
def compute_bribes(bribes,total_bribes):
    if(bribes+1==3):
        return (-1,-1)
    return (bribes+1,total_bribes+1)

for i in range(0,(2*T)-1,2):
    n = int(inp1[i])
    final_q = list(int(i) for i in inp1[i+1].split(' '))
    initial_q = list(i+1 for i in range(n))
    total_bribes,chaos_flag=0,0
    for i in range(n):
        bribes = 0
        # If the position in the initial/transition queue is not equal to the position in the final queue
        # final_q is the input against which swaps are made in my initial_q.
        if(final_q.index(initial_q[i]) != initial_q.index(initial_q[i])):
            index_in_initial_q = initial_q.index(final_q[i])
            index_in_final_q = final_q.index(final_q[i])
            while(index_in_initial_q != index_in_final_q):
                initial_q = swap(initial_q,index_in_initial_q)
                bribes,total_bribes = compute_bribes(bribes,total_bribes)
                if(bribes == -1):
                    print("Too chaotic")
                    chaos_flag=1
                    break
                index_in_initial_q-=1
        if(chaos_flag == 1):
            break
    if (chaos_flag == 1):
        continue
    print(total_bribes)


texts:
I'm trying to design a Shader class.  For now, I'm just trying to get basic outline for handling uniforms. Some design goals I aimed for is to avoid passing a string to a function as this is error prone and has no type checking. There's really only one place this can go wrong:  if you mistype the name of the uniform when defining it.

There is a lot of potential for code bloat.  I could potentially move the Name out of the template parameters for Parameter and store it as a member variable, which would get assigned in the default constructor.

template<typename ParamType>
class Shader
{
public:
    template<typename Type, const char* (*Name)()>
    class Parameter
    {
        static const char* name;
        static GLuint location;
        static GLuint program;

        template<typename> friend class Shader;
    };

    template<typename Type, const char* (*Name)()>
    void SetParameter(const Parameter<Type,Name>&, const Type& value )
    {
        // static_assert(!std::is_same<Type,Type>::value, "Unsupported type, needs specialization.");
        typedef Parameter<Type,Name> Param;

        if(program != -1 && Param::program != program)
        {
            // set Param::location
            Param::program = program;
        }

        std::cout << Param::name << std::endl;
    }

private:

    GLuint program;

};

template<typename ParamType>
template<typename Type, const char* (*Name)()>
const char* Shader<ParamType>::Parameter<Type, Name>::name = Name();

template<typename ParamType>
template<typename Type, const char* (*Name)()>
GLuint Shader<ParamType>::Parameter<Type, Name>::program = -1;

#include "shaderparameters.inl"

shaderparameters.inl:

#define MY_PARAMETER(shader, type, name) \
    private: static const char* ShaderParameterStr##shader##type##name##() { return #name ; }  \
    public:  typedef Shader< shader >::Parameter< type, &ShaderParameterStr##shader##type##name > name;

struct ShaderParam
{
    struct Generic
    {
        MY_PARAMETER( Generic, Vec4, position )
        MY_PARAMETER( Generic, Mat4, projection )
    };

};
#undef MY_PARAMETER

Usage:

Shader<ShaderParam::Generic> s;

s.SetParameter(ShaderParam::Generic::projection(), Mat4());
s.SetParameter(ShaderParam::Generic::position(), Vec4());

What are you thoughts on this implementation? Do you have suggestions for improvements or perhaps an entirely different system?

I know I've seen people use hash maps and such, but there's still the problem of continuously using a string literal to set the uniforms and such (I don't really like the thought of using a Macro to define the string, either).


texts: Convert Ternary Expression to a Binary Tree

texts:
This is programming question I came across (geeksforgeeks) :
Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree.Any feedback appreciated.

All the required classes are added as members.
I am using a simple recursive approach to build the tree.
Each time  a '?' expression is encountered then the next element is added as the left node.Similarly, each time a ':' expression is encountered then the next element is added as the right node.

 Input :  string expression =   a?b:c
    Output :        a
                  /  \
                 b    c

    Input : expression =  a?b?c:d:e
    Output :     a
               /  \
              b    e
            /  \
           c    d

The Code:

public class TernaryExpressionToBinaryTree {

    public class Node {
        private Character data;
        private Node left;
        private Node right;

        public Node(Character data) {
            this.data = data;
        }
    }

    public class BST {
        public Node getRoot() {
            return root;
        }

        public void setRoot(Node root) {
            this.root = root;
        }

        public Node root;

        public void addNode(Character data) {
            root = addNode(root, data);
        }

        private Node addNode(Node node, Character data) {
            if (node == null) {
                return new Node(data);
            }
            if (data < node.data) {
                node.left = addNode(node.left, data);
            } else {
                node.right = addNode(node.right, data);
            }
            return node;
        }
    }

    /*
    Preorder traversal
     */
    public void displayTree(Node node) {
        if (node != null) {
            System.out.print(node.data + " | ");
            displayTree(node.left);
            displayTree(node.right);
        }
    }
    public Node buildTreeFromTernaryExpression(Node node, String expression, int index) {

        // check corner cases
        if (expression == null || expression.trim().isEmpty() || index < 0 || index > expression.length()) {
            return null;
        }
       // if its is a valid character
        if (node == null || index == 0 || expression.charAt(index) != '?' || expression.charAt(index) != ':') {
            node = new Node(expression.charAt(index));
        }
      //if it is a valid expression ? or :
        if ((index + 1) < expression.length()-1 && expression.charAt(index + 1) == '?') {
            node.left = buildTreeFromTernaryExpression(node.left, expression, index + 2);
        }

        if ((index + 1) < expression.length()-1 && expression.charAt(index + 1) == ':') {
            node.right = buildTreeFromTernaryExpression(node.right, expression, index + 2);
        }
        return node;
    }

    public static void main(String args[]) {
        TernaryExpressionToBinaryTree ternaryExpressionToBinaryTree = new TernaryExpressionToBinaryTree();
        Node root = ternaryExpressionToBinaryTree.buildTreeFromTernaryExpression(null, "a?b?c:d:e", 0);
        ternaryExpressionToBinaryTree.displayTree(root);
    }
}


texts:
I'm trying to speed up my union-find disjoint set data structure. The idea is that initially n sets of single element sets are made, and put into a vector nodes. Each node has a parent node, and the highest parent of any particular index in the vector is the highest ranking member of set. Two concepts, union by rank and path compression, are used to achieve faster merging and finding times.

There are two querying types: Union of two values (and thus their sets), and checking if 2 members are in the same set.

Nevertheless, when using very large values for n (such as 100,000,000) and and m (such as 1,000,000), the program takes a bit of time to run. Generally around 30 seconds for my machine.

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

using namespace std;

int n; //number of total elements
int q; //number of queries

struct node
{
    int data;
    node* parent;
    int rank;
    node(int d);
};

node::node(int d)
{
    data = d;
    rank = 0;
    parent = nullptr;
}

node* find(node* root)
{
    if (root != root->parent)
        root->parent = find(root->parent);
    return root->parent;
}

void merge(node* one, node* two)
{
    node* i = find(one);
    node* j = find(two);
    if (i->rank > j->rank)
        j->parent = i;
    else
        i->parent = j;

    if (i->rank == j->rank)
    {
        i->parent = j;
        j->rank++;
    }
}

int sameSet(int i, int j, vector<node*> v)
{
    if (find(v.at(i - 1))->data == find(v.at(j - 1))->data)
        return 1;
    return 0;
}

int main(int argc, char** argv) {

    cin >> n >> q;

    vector<node*> v (n); //vector holding all pointers to sets of nodes

    for (int i = 0; i < n; i++) //make n sets of 1 element each
    {
        node* n = new node(i);
        n->parent = n;
        v[i] = n;
    }
}

Would using a map instead of a vector, for example, be faster? Am I not compressing the path correctly (so that every member of a sets immediate parent is the highest ranking member) or unionizing by rank? As far as I'm aware, both merge and find should take O(log n) if implemented in the most efficient way, making me think this should be faster than it is.


texts:
I've asked a question about this particular code before, although it was a little different back then. I took the suggestions from people who replied to my question and decided to post a follow up to that question, in attempt to improve the class even more.

Simple console logger used instead of packages like log4net and nlog for minimalism.

public class ConsoleLogger <TClass> : ILogger
{
    private static readonly string FilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location + "/resources/logging/");

    private readonly Type _className;

    public ConsoleLogger()
    {
        _className = typeof(TClass);
    }

    public void Trace(string message, bool logToFile = false)
    {
        Log(message, ConsoleColor.White, logToFile);
    }

    public void Warn(string message, bool logToFile = false)
    {
        Log(message, ConsoleColor.Yellow, logToFile);
    }

    public void Debug(string message, bool logToFile = false)
    {
        Log(message, ConsoleColor.Cyan, logToFile);
    }

    public void Success(string message, bool logToFile = false)
    {
        Log(message, ConsoleColor.Green, logToFile);
    }

    public void Error(string message, bool logToFile = false)
    {
        Log(message, ConsoleColor.Red, logToFile);
    }

    public void Error(Exception e, bool logToFile = true)
    {
        Log("An error occurred: " + Environment.NewLine + e, ConsoleColor.Red, logToFile);
    }

    private void Log(string message, ConsoleColor color, bool logToFile = false)
    {
        var oldColor = Console.ForegroundColor;
        Console.ForegroundColor = color;
        Console.WriteLine($"[{DateTime.Now:MM/dd HH:mm:ss}] " + message);
        Console.ForegroundColor = oldColor;

        string logFile;

        switch (color)
        {
            case ConsoleColor.Yellow:
                logFile = "error.log";
                break;
            case ConsoleColor.Cyan:
                logFile = "debug.log";
                break;
            case ConsoleColor.Red:
                logFile = "error.log";
                break;
            default:
                logFile = "trace.log";
                break;
        }

        if (logToFile)
        {
            LogToFile(logFile, $"Occurred at [{DateTime.Now:MM/dd HH:mm:ss}] in [{_className.FullName}]: " + message);
        }
    }

    private static void LogToFile(string file, string content)
    {
        try
        {
            using (var fileWriter = new StreamWriter(FilePath + file, true))
            {
                fileWriter.WriteLine(content);
                fileWriter.Close();
            }
        }
        catch (DirectoryNotFoundException)
        {
            Directory.CreateDirectory(FilePath);
        }
        catch (FileNotFoundException)
        {
            File.Create(file);
        }
    }
}

ILogger interface:

public interface ILogger
{
    void Trace(string message, bool logToFile = false);
    void Warn(string message, bool logToFile = false);
    void Debug(string message, bool logToFile = false);
    void Success(string message, bool logToFile = false);
    void Error(string message, bool logToFile = false);
    void Error(Exception e, bool logToFile = true);
}


texts: WordPress hook to add URL-rewriting rules for articles with language variants

texts:
Please look at this working WordPress code:

add_action('init', 'add_custom_rewrites');
function add_custom_rewrites(){
  add_rewrite_rule(
    '^(en|fr|es|de)/inspiration/testimonial/([^/]*)?',
    'index.php?post_type=testimonial&lang=$matches[1]&name=$matches[2]',
    'top'
  );

  add_rewrite_rule(
    '^inspiration/testimonial/([^/]*)?',
    'index.php?post_type=testimonial&lang=it&name=$matches[1]',
    'top'
  );
}

The first rule matches a post under an url like this:

example.com/en/inspiration/testimonial/test-post

The second matches this:

example.com/inspiration/testimonial/test-post

Which is for the default language (it). Since the default lang is implicit, it's not written in the url, but under the hood it's like example.com/it/inspiration/testimonial/test-post.

Well, the question: is there any better way of achieving this result? Particularly, is there any way of doing it with only one single rule?


texts: Can calculation of word wrapping be made notably faster?

texts:
I need to re-wrap a text so that it fits a given width, font and DC. The result needs to be an array of lines. I use the following code:

private struct SplitInfo
{
    public string Word;

    public string SplitChar;

    public override string ToString()
    {
        return Word;
    }
}

private static float GetWidth(Graphics gr, string text, Font font)
{
    SizeF size = gr.MeasureString(text, font, 10000, StringFormat.GenericTypographic);
    return size.Width;
}

public static string[] WrapText(string text, IntPtr hdc, Font font, int textWidthInLoMetric)
{
    // Split words at space (functionality for splitting at multiple different chars omitted for simplicity).
    // This is also why it needs SplitInfo to store the words.
    List<SplitInfo> words = new List<SplitInfo>(text.Split(' ').Select(x => new SplitInfo { SplitChar = " ", Word = x }));

    StringBuilder resultText = new StringBuilder();
    string currentLine = string.Empty;
    SplitInfo lastWord = new SplitInfo { Word = string.Empty, SplitChar = string.Empty };

    using (Graphics gr = Graphics.FromHdc(hdc))
    {
        while (true)
        {
            string newString = (currentLine + lastWord.SplitChar).TrimStart(' ') + words[0].Word;

            if (currentLine != string.Empty && GetWidth(gr, newString, font) > textWidthInLoMetric)
            {
                // Word no longer fits in line.
                resultText.Append(currentLine.TrimEnd() + "\n");
                currentLine = string.Empty;
            }
            else
            {
                lastWord = words[0];
                words.RemoveAt(0);
                currentLine = newString;
            }

            if (words.Count == 0)
            {
                resultText.Append(currentLine.TrimEnd() + "\n");
                break;
            }
        }
    }

    return resultText.ToString().TrimEnd().Split('\n');
}

Performance measurement shows that MeasureString is the main time consumer here (~90%). Is there any clever way to reduce the number of MeasureString calls? Other than that, I don't see opportunities to make word wrapping significantly faster.


texts: Separating paging, sorting and filtering

texts:
in my ASP.NET MVC application I have a service that had a method for paging, sorting and filtering of Vehicle Makes:

public class VehicleService : IVehicleService
{
    private readonly DbContext _context;

    public VehicleService(DbContext context)
    {
        _context = context;
    }

    public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        switch (sort)
        {
            case "Name desc":
                makes = makes.OrderByDescending(x => x.Name);
                break;
            default:
                makes = makes.OrderBy(x => x.Name);
                break;
        }

        return await makes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
    }
}

VehicleService interface:

public interface IVehicleService{
Task<X.PagedList.IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort);
}

After the review of my code, I was told that sorting, filtering and paging should be in separate classes that have interfaces. I implemented that in following way:

Sorting:

internal class Sorting : ISorting
{
    private readonly DbContext _context;

    public Sorting(DbContext context)
    {
        _context = context;
    }

    public IEnumerable<VehicleMake> SortMakes(string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        makes = sort == "Name desc" ? makes.OrderByDescending(x => x.Name) : makes.OrderBy(x => x.Name);
        return makes;
    }
}

Sorting interface:

interface ISorting
{
 IEnumerable<VehicleMake> SortMakes(string sort);
}

Paging:

class Paging : IPaging
{
    private readonly ISorting _sorting;

    public Paging(DbContext context)
    {
        _sorting = new Sorting(context);
    }

    public async Task<IPagedList<VehicleMake>> GetPagedListOfSortedMakes(string search, int? page, string sort)
    {
        var sortedMakes = _sorting.SortMakes(sort).AsQueryable();
        return await sortedMakes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
    }
}

Paging interface:

interface IPaging
   {
    Task<IPagedList<VehicleMake>> GetPagedListOfSortedMakes(string search, int? page, string sort);
   }

And then in my service:

public class VehicleMakeService : IVehicleMakeService
{
    private readonly DbContext _context;
    private readonly IPaging _paging;

    public VehicleMakeService(DbContext context)
    {
        _context = context;
        _paging = new Paging(context);
    }

    public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        return await _paging.GetPagedListOfSortedMakes(search, page, sort);
    }
}

This works well, but I'm not sure if I implemented this correctly. Is there a better (cleaner) way to do this?


texts: Speeding up evaluation of power series, Python

texts:
I want to plot (on the complex plane, with mpmath) the power series whose general term is the number of partitions of an integer.

The more points I want (and the larger the degree is), the longer the plot takes.

I first wrote a naive version, added memoization of the sequence, changed the naive evaluation of the polynomial with the Horner algorithm. All these modifications led to speed ups, and I want to know if there are more optimizations I could do.

import mpmath

MAX_DEGREE = 250
NB_POINTS = 40000

def memoize(function):
    memo = {}

    def wrapper(*args):
        if args in memo:
            return memo[args]
        else:
            rv = function(*args)
            memo[args] = rv
            return rv

    return wrapper

@memoize
def p_k(k, n):
    if k == 1 or k == n:
        return 1
    if k > n:
        return 0

    return p_k(k - 1, n - 1) + p_k(k, n - k)

@memoize
def p(n):
    res = 1
    for k in range(1, n):
        res = res + p_k(k, n)
    return res

def mgf(x):
    if abs(x) >= 1:
        return 0
    res = 0
    x_i = x
    for i in range(1, MAX_DEGREE):
        res = res + p(i) * x_i
        x_i = x_i * x
    return res

def mgf_horner(x):
    if abs(x) >= 1:
        return 0
    res = p(MAX_DEGREE)
    for i in reversed(range(1, MAX_DEGREE)):
        res = res * x + p(i)
    return res * x

if __name__ == "__main__":
    assert(p(1) == 1)
    assert(p(2) == 2)
    assert(p(5) == 7)
    assert(p(7) == 15)
    assert(round(mgf_horner(0.3), 8) == round(mgf(0.3), 8))
    assert(round(mgf_horner(0.5), 8) == round(mgf(0.5), 8))

    print("Tests passed!")

    mpmath.cplot(mgf_horner, points=NB_POINTS, re=[-1, 1], im=[-1, 1])


texts:
I am new to Java and have written a custom matcher to compare two maps because the error message from either JUnit or Hamcrest is not detailed enough. The code I wrote works, but I welcome critiques or comments to make it better.

One question:

Right now, I hard-coded my map to <String, String> but would like to be more generic. My first attempt was to use <Object, Object>, which resulted in a compiler error.

Here is my matcher:

package net.southeastwind.test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;

public class MapEquivalent extends TypeSafeDiagnosingMatcher<Map<String, String>> {
    private Map<String, String> m_expected;

    public MapEquivalent(Map<String, String> expected) {
        m_expected = expected;
    }

    public static MapEquivalent mapEquivalent(Map<String, String> expected) {
        return new MapEquivalent(expected);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("Maps are equivalent");
    }

    @Override
    protected boolean matchesSafely(Map<String, String> actual, Description description) {
        boolean matched = true;

        Set<String> keys = new HashSet<>();
        keys.addAll(actual.keySet());
        keys.addAll(m_expected.keySet());

        for (String key: keys) {
            String expectedValue = m_expected.get(key);
            String actualValue = actual.get(key);

            if (null == expectedValue) {
                matched = false;
                description
                    .appendText("\n\t\tOnly in actual: {").appendValue(key)
                    .appendText(": ").appendValue(actualValue).appendText("}");
            } else if (null == actualValue) {
                matched = false;
                description
                    .appendText("\n\t\tOnly in expected: {").appendValue(key)
                    .appendText(": ").appendValue(expectedValue).appendText("}");
            } else if (!actualValue.equals(expectedValue)) {
                matched = false;
                description
                    .appendText("\n\t\tValues differ: ")
                    .appendText("actual={").appendValue(key).appendText(": ").appendValue(actualValue).appendText("}")
                    .appendText(", expected={").appendValue(key).appendText(": ").appendValue(expectedValue).appendText("}");

            }
        }

        return matched;
    }
}

Sample test and output:

@Test
public void compareMaps() {
    Map<String, String> expected = new HashMap<String, String>() {{
        put("alias", "haiv");
        put("uid", "501");
        put("admin", "no");
    }};

    Map<String, String> actual = new HashMap<String, String>() {{
        put("alias", "haiv");
        put("uid", "502");
        put("shell", "bash");
    }};

    assertThat("Error 6a3429f7", actual, is(mapEquivalent(expected)));
    // CustomMatchersTest > compareMaps FAILED
    //     java.lang.AssertionError: Error 6a3429f7
    //     Expected: Maps are equivalent
    //          but:
    //                 Values differ: actual={"uid": "502"}, expected={"uid": "501"}
    //                 Only in actual: {"shell": "bash"}
    //                 Only in expected: {"admin": "no"}
}


texts: Set an image sprite depending on the lowest common number in a set

texts:
In my game you can earn either a bronze, silver or gold medal. There is 4 difficulties which you can earn a medal on.

I want to display a medal depending on the lowest common medal earnt if that makes sense.

So if the user has bronze in 3 and gold in the other, it will display bronze.

Gold in 3 of them but no medal in 1. it wont display anything.

2 silver and 2 gold will display silver.

    int easyMedal = PlayerPrefs.GetInt("EasyModeMedal");
    int mediumMedal = PlayerPrefs.GetInt("MediumModeMedal");
    int hardMedal = PlayerPrefs.GetInt("HardModeMedal");
    int insaneMedal = PlayerPrefs.GetInt("InsaneModeMedal");

    if (easyMedal != 0 && mediumMedal != 0 && hardMedal != 0 && insaneMedal !=0)
    {
        enduranceMedal.SetActive(true);
        Image enduranceImage = enduranceMedal.GetComponent<Image>();

        if (easyMedal == 1)
        {
             enduranceImage.sprite = bronzeSprite;

        } else if (easyMedal == 2)
        {
            if (mediumMedal < 2 || hardMedal < 2 || insaneMedal < 2)
            {
                enduranceImage.sprite = bronzeSprite;
            } else {
                enduranceImage.sprite = silverSprite;
            }
        } else
        {
            if (mediumMedal < 3 || hardMedal < 3 || insaneMedal < 3)
            {
                if (mediumMedal == 1 || hardMedal == 1 || insaneMedal == 1)
                {
                    enduranceImage.sprite = bronzeSprite;
                } else
                {
                    enduranceImage.sprite = silverSprite;
                }
            }
            else
            {
                enduranceImage.sprite = goldSprite;
            }
        }
    }

So the first 4 variables get each difficulties medal. 0 = no medal, 1 = bronze, 2 = silver and 3 = gold.

I then have a long and confusing if-statement to determine what medal should be shown. I'm sure there must be a way to clean this up.


texts:
I'm trying to get a certain number of date ranges given a start date. Here's my code:

var startDate = new DateTime(2014, 1, 1);
var dates = new List<DateBlock>();
int counter = 0;
while(counter < 6)
{
    if (startDate >= DateTime.UtcNow)
    {
        dates.Add(new DateBlock
        {
            StartDate = startDate,
            EndDate = startDate.AddDays(30)
        });

        counter++;
    }

    startDate = startDate.AddDays(30);
}

var first =  dates.First();
dates.Insert(0, new DateBlock
{
    StartDate = first.StartDate.AddDays(-30),
    EndDate = first.StartDate
});

I'm wondering if there is a better way of doing this?

EDIT:
If the start date is 1/1/1 it should loop through and increment by 30 days and only add to the list if the current date is greater than or equal to UtcNow. Also it should keep going into the future until 6 more DateBlock's are added to the list.


texts: Processing a company list in which every element is an employee list

texts:
Now, there is a company list in which an element is an employee list in every company. I calculate the salary of employees in every company with a RESTful API one by one,. This is very slow, so I join 1000 elements to one list and post it to the service.

import requests

def _calculate_employee_salaries(employees):
    response = requests.post(url, json={"input": employees})
    salaries = parse_response(response)
    return salaries

def get_calculate_employee_salaries(company_employees_lis):
    begin, step = 0, 1000
    company_employee_salaries_lis = []
    while begin < len(company_employees_lis):
        employees = []
        employee_num_lis = []
        for comp_employees in company_employees_lis[begin:(begin+step)]:
            employees.extend(comp_employees)
            employee_num_lis.append(len(comp_employees))
        salaries = _calculate_employee_salaries(employees)

        idx = 0
        for num in employee_num_lis:
            company_employee_salaries_lis.append(salaries[idx:(idx + num)])
            idx += num
        begin += step
    return company_employee_salaries_lis

if __name__ == "__main__":
    company_employees_lis = [["employees_id_1", "employees_id_2", "employees_id_3"], ["employees_id_4"], ["employees_id_5", "employees_id_6"]]
    company_employee_salaries_lis = get_calculate_employee_salaries(company_employees_lis)

I think my code is bad, because I use a variable employee_num_lis to remember the number of employees in every company. And there must be clean, artful and pythonic code. This code is just a sample, not what I should do.


texts: Optimizing performance of hashing array algorithm's implementation

texts:
I wrote the following C++ code and since I am a novice in C++ and do not really have anybody who can give me advice, I think this site would be a good place to ask.

The algorithm takes the first two elements a1 and a2 of an array, calculate the difference a2 - a1. Then the first two elements a1 and a2 will be removed from the array and the calculated difference will be inserted in front of the array. This will be repeated until there is only one element left. The last element of the array will be the hash value of the array.

The initial array will be mutated q times with the following formula: increase all elements in the segment [lj,rj] by vj, after each mutation the hash value should be printed.

The input will look something like following

7
4 2 -5 10 4 -2 6
4
2 4 -8
5 7 2
3 3 -1
3 7 3

where the first line indicates the length of the array. The next line will be the content of the array, the third line would be q and every following line is lj, rj, vj.

This is how my code looks like at the moment. I would appreciate every critic.

#include <vector>
#include <iostream>

#define ll long long

ll __hash__(const std::vector<int> &arr) {
    ll front = arr[0];
    for(ll i = 1; i < arr.size(); i++){
        front = arr[i] - front;
    }
    return front;
}

int main() {
    std::vector<int> arr;
    ll size;
    std::cin >> size;
    for (ll i = 0; i < size; ++i) {
        ll c;
        std::cin >> c;
        arr.push_back(c);
    }
    ll q;
    std::cin >> q;
    for (ll i = 0; i < q; ++i) {
        ll l, r, v;
        std::cin >> l >> r >> v;
        for(ll j = l - 1; j < r; ++j){
            arr[j] += v;
        }
        std::cout << __hash__(arr) << std::endl;
    }
    return 0;
}


texts:
I have the following task:

  Create a simple treasure hunt game.

  Create a two-dimensional array of integers 10 by 10.  In a random
  position in the array store the number 1.  repeat  Get the user to
  enter coordinates where they think the treasure is.  If there is a 1
  at this position display ‘success’.  Until they find the treasure

Instead of using arrays I used lists:

-module(hunt).
-export([start/0]).
start() ->
    X = [[12,1,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5],[12,13,14,15,16,22,11,11,2,5]],
    loop(X).
loop(X) ->
    Inputs = io:get_line("Enter the coordinates"),
    {A,_} = string:to_integer(string:substr(Inputs,1,2)),
    {B,_} = string:to_integer(string:substr(Inputs,3,2)),
    erlang:display(A),
    erlang:display(B),
    case get(X,A,B) of
        1 -> io:format("You did it!");
        _ -> io:format("Try again"), loop(X)
    end.
get(List,A,B) ->
    ghelper(List,A,B).
ghelper(List,A,B) -> ghelper(List,A,B,0,0).
ghelper([H|Tail],A,B,N,M) ->
    case N == A of
        true -> ghelper(second,H,B,M);
        false -> ghelper(Tail,A,B,N+1,M)
    end.
ghelper(second,[H|Tail],B,M) ->
    case M == B of
        true -> H;
        false -> ghelper(second,Tail,B,M+1)
    end.

Is there a way to improve this further? I know I could probably make a function to randomly generate a 2D array (represented by lists here), but apart from that, is there anything I could improve?


texts:
I have a table that reads every minute, but the data on one meter only changes once every 60 minutes. It will then repeat that value for 60 minutes before changing again.

I need to take the sum of these values and add them up for the day. But if I grab it by the hour, I will get duplicates. So what I decided to do was count the number of records, and if is over 30 minutes use that record.

This is currently working good and is not a big issue, but I am curious if there is an easier way to do this.

WITH A AS
(SELECT DISTINCT
  CONVERT(CHAR(12), TIME, 101) AS [ DAY ],
  DatePart (HOUR, TIME) AS [ HOUR ],
  [ B100 Pulse LAST HOUR ],
  [ RESET Counter ],
  [ B700 Pulse LAST HOUR ],
  [ B800 Pulse LAST HOUR ],
  [ B1300 Pulse LAST HOUR ],
  [ B900 Pulse LAST HOUR ],
  COUNT([ RESET Counter ]) AS Records
FROM
  (SELECT
    TOP (100) PERCENT KPI $.[ B100 Pulse LAST HOUR ],
    Main $.Time,
    KPI $.[ RESET Counter ],
    KPI $.[ B700 Pulse LAST HOUR ],
    KPI $.[ B800 Pulse LAST HOUR ],
    KPI $.[ B900 Pulse LAST HOUR ],
    KPI $.[ B1300 Pulse LAST HOUR ]
  FROM
    Main $
    INNER JOIN KPI $
      ON Main $.[LOOP INDEX ] = KPI $.[LOOP INDEX ]
  ORDER BY Main $.Time DESC) AS t1
GROUP BY CONVERT(CHAR(12), TIME, 101),
  DatePart (HOUR, TIME),
  [ B100 Pulse LAST HOUR ],
  [ RESET Counter ],
  [ B700 Pulse LAST HOUR ],
  [ B800 Pulse LAST HOUR ],
  [ B1300 Pulse LAST HOUR ],
  [ B900 Pulse LAST HOUR ])
SELECT
  Top 120 [ DAY ],
  COUNT(*) AS [ # of Records], SUM([B100 Pulse Last Hour]) * 100 AS [Building 100 Gal Discharged], SUM([B700 Pulse Last Hour]) * 100 AS [Building 700 Gal Discharged], (SUM([B800 Pulse Last Hour])
  - SUM([ B1300 Pulse LAST HOUR ])) * 100 AS [ Building 800 Gal Discharged ],
  SUM([ B900 Pulse LAST HOUR ]) * 100 AS [ Building 900 Gal Discharged ],
  SUM([ B1300 Pulse LAST HOUR ]) * 100 AS [ Building 1300 Gal Discharged ],
  SUM(
    (
      [ B100 Pulse LAST HOUR ] + [ B700 Pulse LAST HOUR ] + [ B800 Pulse LAST HOUR ] + [ B900 Pulse LAST HOUR ]
    ) * 100
  ) AS [ Daily Total ],
  [ STARTING LEVEL ] AS [ LEVEL IN B1800 AT Midnight ],
  [ Difference ]
FROM
  (SELECT
    *,
    ROW_NUMBER () Over (
      PARTITION BY Records
  ORDER BY Records ASC
  ) AS ROW
  FROM
    A
    INNER JOIN B1800_Totals
      ON A.[ DAY ] = B1800_Totals.[ DATE ]) AS A2
WHERE Records >= 30
  AND ([ DAY ] = @date)
GROUP BY DAY,
  [ STARTING LEVEL ],
  [ Difference ]
ORDER BY DAY ASC


texts: Tail-recursive call vs looping for a Poker app

texts:
I'm developing a Poker app. It is almost done, and I'm looking for improvement. One of the things I wonder is whether I should change how I perform iterations. I currently iterate by using tail-recursive calls. However, a friend of mine suggested that I use a while loop instead because loops don't require stack space.

private async Task Turns()
    {
        _turns = ReturnTurns();
        GC.KeepAlive(Updates);
        if (!Player.FoldTurn && Player.Chips > 0)
        {
            if (Player.Turn)
            {
                SetPlayerStuff(true);
                Call -= Player.PreviousCall;
                _up = int.MaxValue;
                _turnCount++;
                Bot1.Turn = true;
                _restart = true;
            }
        }
        if (!Player.Turn)
        {
            await Flip(0);
        }
        if (Player.FoldTurn || !Player.Turn || Player.Chips <= 0)
        {
            Call = TempCall;
            if (StatusLabels[Player.EnumCasted].Contains(RepetitiveVariables.Fold))
            {
                Bot1.Turn = true;
            }
            SetPlayerStuff(false);
            Bot1 = (Bot)await RotateTurns(Bot1, Bot1.EnumCasted);
            Bot2 = (Bot)await RotateTurns(Bot2, Bot2.EnumCasted);
            Bot3 = (Bot)await RotateTurns(Bot3, Bot3.EnumCasted);
            Bot4 = (Bot)await RotateTurns(Bot4, Bot4.EnumCasted);
            Bot5 = (Bot)await RotateTurns(Bot5, Bot5.EnumCasted);
            _restart = false;
        }
        if (!_restart)
        {
            await Turns();
        }
    }

That's how I think it should look like with a while loop:

    private async Task Turns()
    {
        while (true)
        {
            _turns = ReturnTurns();
            GC.KeepAlive(Updates);
            if (!Player.FoldTurn && Player.Chips > 0)
            {
                if (Player.Turn)
                {
                    SetPlayerStuff(true);
                    Call -= Player.PreviousCall;
                    _up = int.MaxValue;
                    _turnCount++;
                    Bot1.Turn = true;
                    _restart = true;
                }
            }
            if (!Player.Turn)
            {
                await Flip(0);
            }
            if (Player.FoldTurn || !Player.Turn || Player.Chips <= 0)
            {
                Call = TempCall;
                if (StatusLabels[Player.EnumCasted].Contains(RepetitiveVariables.Fold))
                {
                    Bot1.Turn = true;
                }
                SetPlayerStuff(false);
                Bot1 = (Bot) await RotateTurns(Bot1, Bot1.EnumCasted);
                Bot2 = (Bot) await RotateTurns(Bot2, Bot2.EnumCasted);
                Bot3 = (Bot) await RotateTurns(Bot3, Bot3.EnumCasted);
                Bot4 = (Bot) await RotateTurns(Bot4, Bot4.EnumCasted);
                Bot5 = (Bot) await RotateTurns(Bot5, Bot5.EnumCasted);
                _restart = false;
            }
            if (!_restart)
            {
                continue;
            }
            break;
        }
    }


texts: Changing the ACL on a folder through Wscript.Shell within VBA

texts:
I have working VBA code in excel that changes a network folders permissions.

The code uses Wscript.Shell to run icacls commands but there are multiple instances of this command and each time it runs, it opens up a new shell window.

It would be interesting to see if there is a way of making the code more efficient by opening a single shell instance then go on to run each of the icacls commands.

Private Sub TestingPermissions()

Dim FSO
Dim MyFolder
Dim objShell

Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFolder = FSO.GetFolder(Worksheets("Config").Range("D4").Value & ActiveSheet.Range("C21").Value)

Set objShell = CreateObject("Wscript.Shell")

' Take ownership and modify permission of folder
objShell.Run ("takeown /f " & """" & MyFolder & "\My Music""" & " /r /d y")
objShell.Run ("icacls " & """" & MyFolder & "\My Music""" & " /setowner mydomain\admin")
objShell.Run ("icacls " & """" & MyFolder & "\My Music""" & " /grant mydomain\StudentExam101:(OI)(CI)F /T")
objShell.Run ("icacls " & """" & MyFolder & "\My Music""" & " /grant mydomain\DAdmins:(OI)(CI)F /T")
objShell.Run ("icacls " & """" & MyFolder & "\My Music""" & " /grant mydomain\admin:(OI)(CI)F /T")
objShell.Run ("icacls " & """" & MyFolder & "\My Music""" & " /grant SYSTEM:(OI)(CI)F /T")
objShell.Run ("icacls " & """" & MyFolder & "\My Music""" & " /grant CREATOR OWNER:(OI)(CI)F /T")

End Sub

I thought I had found a part solution by combining the icalcs permissions all into one command but further testing and I realised it had not worked, but I will investigate this further anyway.


texts: Maintain the ordering of the original array, but group either negative or positive numbers into sub arrays

texts:
For a code challenge I thought it'd be useful to have a helper function to group positives and negatives into their own sub arrays while maintaining the ordering of the original array. I'm sure there's a better way to do this but wanted to take a crack at it before researching.

This idea came to mind, to track the state of the numbers, either positive or negative, and group them according to state. This is just MVP and I didn't account for 0.

Despite being verbose, does the code make sense> Do you have recommendations for improvement?

(code playground)

//compare two numbers state
function negAndPosCompare(numA: number, numB: number) {
    if (numA > 0 && numB > 0) {
        // we'll call 1 our positive state
        return 1;
    }
    else if (numA < 0 && numB < 0) {
        // we'll call -1 our negative state
        return -1
    }
    else {
        // false is if two numbers are not the same state
        return false;
    }
}

//simply return the state of a single number
function getState (num : number) {
    if (num > 0){
        return 1;
    }
    else if (num < 0) {
        return -1;
    }
}

function subArray_pos_and_neg(arr: number[]) {
    // our final return
    const output: number[][] = [];

    //where we'll hold numbers of the same state, it'll be exclusive, either pos, or neg.
    // we can default it to the very first number. It's a temp because we'll keep recycling it whenever state changes.
    let temp_sameKind = [arr[0]];

    // grab the state right away, are we starting with pos or neg?
    let currentState = getState(arr[0]);

    for (let i = 0; i < arr.length; i++) {
        // check that i is gte -> 1 so we can safely check arr[i-1]
        if (i >= 1) {

            //if the current number compared to the last number are not the same state, then that means the streak of a given state is over
            if (negAndPosCompare(arr[i], arr[i - 1]) === false) {

               //grab the new state.
                currentState = getState(arr[i]);

                //push the numbers of the same state that we've accumulated so far, they belong together and we'll reset our temp holder
                //to accomodate our new state of numbers
                output.push(temp_sameKind);
                temp_sameKind = [];

                //push the current number right away, it is the first number of our new state. this operation is similiar to how we defaulted our
                // temp_sameKind array right off the bat (before the for loop). if we don't push it now it'll go missing.
                temp_sameKind.push(arr[i]);
            }

            // the current number is of the same state as our current streak, therefore we want to include it in our accumulation.
            if (negAndPosCompare(arr[i], arr[i - 1]) === currentState) {
                temp_sameKind.push(arr[i]);
            }
        }
    }
    // this check outside of the for loop is the final push of our accumulated numbers... if we don't accomodate the last state of numbers,
    // they'll be excluded by our previous logic (since the state doesn't change again in the for loop)
    if (temp_sameKind){
        output.push(temp_sameKind);
    }
    return output;
}

subArray_pos_and_neg([1,2,-4,2,5,-6,-3,3,-6,8,9]); //?


texts: Reverse the character order of the words in a string

texts:
I've been trying to learn Java and one way I've been teaching myself is by tackling "programming challenge questions".

One such question is "reverse the character order of words in a string".

For example, " I   have a hat   " => " I   evah a tah   " (note the spaces). In my implementation, I don't deal with punctuation, so "I have a hat!" => "I evah a !tah".

I've written an implementation and I'd like some feedback, particularly regarding the readability and efficiency of the code (basically, is there a slicker implementation of what I'm trying to accomplish - to me, the answer is yes, especially the last part of my implementation).

The implementation is basically doing the following:

Create a one element-sized String array called candidateReversedWordsString and initialize it with the input String
Create a StringBuilder that will build all the reversed words.
Iterate through the characters in the string
If the character is not a space and the StringBuilder is empty, note the character index value in the wordStartIndex variable and add the character to the StringBuilder.
If the character is not a space and the StringBuilder is not empty, add the character to the StringBuilder
If the character is a space and the StringBuilder is not empty, take the only element in the candidateReversedWordsString array and basically concatenate the element with the reversed word from the StringBuilder using substrings.
If at the final character and the StringBuilder is not empty, slight adjustment to the concatenation

public String reverseWordsInString(final String string) {
    final String[] candidateReversedWordsString = new String[1];
    candidateReversedWordsString[0] = string;
    int stringCharacterIndex = 0;
    int wordStartIndex = 0;
    final StringBuilder reverseWordStringBuilder = new StringBuilder();
    while (stringCharacterIndex < string.length()) {
        if (' ' != string.charAt(stringCharacterIndex)) {
            if (reverseWordStringBuilder.length() == 0) {
                wordStartIndex = stringCharacterIndex;
            }
            reverseWordStringBuilder.append(string.charAt(stringCharacterIndex));
        }

        if (' ' == string.charAt(stringCharacterIndex) && reverseWordStringBuilder.length() > 0) {
            candidateReversedWordsString[0] = new StringBuilder().
                    append(candidateReversedWordsString[0].substring(0, wordStartIndex)).
                    append(reverseWordStringBuilder.reverse().toString()).
                    append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString();
            reverseWordStringBuilder.setLength(0);
        }

        if (stringCharacterIndex == string.length() - 1 && reverseWordStringBuilder.length() > 0) {
            candidateReversedWordsString[0] = new StringBuilder().
                    append(candidateReversedWordsString[0].substring(0, wordStartIndex)).
                    append(reverseWordStringBuilder.reverse().toString()).toString();
        }
        stringCharacterIndex++;
    }

    return candidateReversedWordsString[0];
}


texts: Produce a nearly sorted (or K sorted) array

texts:
Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time.
For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. I'm looking for code review, best practices, optimizations etc. Also for some reason I could not get assertarrayequals hooked up so tested arrays unconventionally. Please ignore that as part of feedback

public final class KSortedArray {

    private KSortedArray() { }

    /**
     * Returns the sorted array provided the input array is k-sorted.
     * If input array is not k-sorted, then results are unpredictable.
     *
     * @param arr   The k-sorted array
     * @param k     the value of k, the deviation of placement.
     * @return      the sorted array
     */
    public static int[] kSortDontModifyInput(int[] arr, int k) {
        int[] n = new int[arr.length];

        final Queue<Integer> queue = new PriorityQueue<Integer>(k + 1);
        for (int  i = 0; i <= k; i++) {
            queue.add(arr[i]);
        }

        int ctr = 0;
        for (int i = k + 1; i < arr.length; i++) {
            n[ctr++] = queue.poll();
            queue.add(arr[i]);
        }
        while (!queue.isEmpty()) {
            n[ctr++] = queue.poll();
        }
        return n;
    }

    /**
     * Sorted array provided the input array is k-sorted.
     * If input array is not k-sorted, then results are unpredictable.
     *
     * @param arr   The k-sorted array
     * @param k     the value of k, the deviation of placement.
     */
    public static void kSortMoidifyInput(int[] arr, int k) {
        Queue<Integer> queue = new PriorityQueue<Integer>(k + 1);
        for (int  i = 0; i <= k; i++) {
            queue.add(arr[i]);
        }
        int ctr = 0;
        for (int i = k + 1; i < arr.length; i++) {
            arr[ctr++] = queue.poll();
            queue.add(arr[i]);
        }

        while (!queue.isEmpty()) {
            arr[ctr++] = queue.poll();
        }
    }

    public static void main(String[] args) {
        int arr[] = {2, 6, 3, 12, 56, 8};

        int[] expected = {2, 3, 6, 8, 12, 56};
        int[] actual = kSortDontModifyInput(arr, 3);
        kSortMoidifyInput(arr, 3);
        for (int i = 0; i < expected.length; i++) {
            Assert.assertEquals(expected[i], actual[i]);
            Assert.assertEquals(expected[i], arr[i]);
        }
    }
}


texts:
I am learning design patterns and I have implemented the abstract factory using generics C#.NET. Is this implementation correct or not? Or is there any SOLID principle violation?

using System;
namespace GenericAbstractFactory
{
    public enum vehicles { car, bicycle, truck }

    interface IFourWheeler
    {
        void DriveFourWheeler();
    }

    interface ITwoWheeler
    {
        void DriveTwoWheeler();
    }

    interface IVehcileAbstractFactory<VehicleTypeFactory> //Abstract Factory
    {
        VehicleTypeFactory GetVehicleType();
    }

    class FourWheeler<VehicleType> : IVehcileAbstractFactory<IFourWheeler>
        where VehicleType : IFourWheeler, new() // ConcreteFactory
    {
        public IFourWheeler GetVehicleType()
        {
            return new VehicleType();
        }
    }

    class TwoWheeler<VehicleType> : IVehcileAbstractFactory<ITwoWheeler>
        where VehicleType : ITwoWheeler, new() // ConcreteFactory
    {
        public ITwoWheeler GetVehicleType()
        {
            return new VehicleType();
        }
    }

    class Car : IFourWheeler
    {
        public void DriveFourWheeler()
        {
            Console.WriteLine("Drive Car");
        }
    }

    class Truck : IFourWheeler
    {
        public void DriveFourWheeler()
        {
            Console.WriteLine("Drive Truck");
        }
    }

    class Bicycle : ITwoWheeler
    {
        public void DriveTwoWheeler()
        {
            Console.WriteLine("Drive Bicycle");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            vehicles veh = vehicles.bicycle;
            IVehcileAbstractFactory<IFourWheeler> getFourWheeler = null;
            IVehcileAbstractFactory<ITwoWheeler> getTwoWheeler = null;
            IFourWheeler actionFourWheeler = null;
            ITwoWheeler actionTwoWheeler = null;
            if (veh == vehicles.car)
            {
                getFourWheeler = new FourWheeler<Car>();
                actionFourWheeler = getFourWheeler.GetVehicleType();
            }
            else if (veh == vehicles.bicycle)
            {
                getTwoWheeler = new TwoWheeler<Bicycle>();
                actionTwoWheeler = getTwoWheeler.GetVehicleType();
            }
            else if (veh == vehicles.truck)
            {
                getFourWheeler = new FourWheeler<Truck>();
                actionFourWheeler = getFourWheeler.GetVehicleType();
            }
            else
            {
                throw new Exception("vehicle type not supported");
            }

            if (actionFourWheeler != null)
            {
                actionFourWheeler.DriveFourWheeler();
            }
            else if (actionTwoWheeler != null)
            {
                actionTwoWheeler.DriveTwoWheeler();
            }
            Console.Read();
        }
    }
}


texts: Path finding algorithm using recursion in Python

texts:
Here is a code I developed some time ago. I wonder if there is anything I can do to improve it. It works for non-loopy mazes which was already my goal.

In the maze defined, True are the open ways and False are the walls.

The main subjects that I gladly accept suggestions can be listed like this:

Is the solution pythonic, if not what can be done to improve?
Because of the recursion, after I reach the ending point, I cannot directly return the true_path because the dead ends encountered by the player makes the function return  None. So I have to save it in another variable and let the recursion end after that. It is not directly an issue but I am eager to hear suggestions about it.(That is the reason i didn't return the recursions done in the function. They are just called.)
Is a while loop a better solution to this kind of problem?
Even if the solution is pythonic, are there any better ways to implement this path finding algorithm.

def possible_paths(maze, coor):
    # This function checks the 4 available routes around the current point.

    paths = [
    (coor[0]- 1, coor[1]),
    (coor[0],coor[1]-1),
    (coor[0], coor[1] + 1),
    (coor[0] + 1, coor[1])
        ]
    possible_paths = []

    for path in paths:
        if path[0] >= 0 and path[1] >= 0 and path[0] < len(maze[0]) \
        and path[1] < len(maze):
            if maze[path[1]][path[0]]:
                possible_paths.append(path)
    return possible_paths

answer = []
def solve(maze, pos, exit, true_path = []):
    global answer
    paths = [path for path in possible_paths(maze, pos) if path not in true_path]

    if pos == exit:
        answer = true_path
    elif len(paths) == 1:

        pos = paths[0]
        true_path.append(pos)
        solve(maze, pos, exit, true_path)

    else:
        for path in paths:
            temp_path = true_path[:] + [path]
            solve(maze, path, exit, temp_path)

maze = [[True, False, True,  False],
        [True, False, True,  False],
        [True, True , True,  False],
        [True, False, False, False],
        [True, True,  True, True],
        [True, False, False, False]]

solve(maze, (0,0), (2,0), [(0,0)])
print answer
# Gives [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0)]

Note: Please notice that (2,0) is a coordinate, so it is actually equivalent to maze[0][2].


texts: K&R (C): generate histogram of word-lengths

texts:
From "The C Programming Language" (K&R):

  Exercise 1-13. Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

I wrote a program to generate a vertically-oriented histogram. It doesn't accurately handle punctuation (punctuation characters get counted as word characters), but given the limited tools covered in chapter 1 of the book, I felt this was reasonable. I've tried to limit myself to tools covered up until this point in the book (I had to resist the urge to use ternaries in a couple spots).

#include <stdio.h>

#define IN_WORD     1   /* point in word */
#define OUT_WORD    0   /* point out of word */
#define MAX_LEN     20  /* max word length to consider */

int main()
{
    int i, j;       /* iterators */
    int c;          /* character */
    int len;        /* word length */
    int state;      /* in/out of word */
    int top_count;
    int histogram[MAX_LEN];

    i = j = c = len = top_count = 0;
    state = OUT_WORD;

    for (i = 0; i < MAX_LEN; ++i)
        histogram[i] = 0;

    /* process input */
    while ((c = getchar()) != EOF) {

        if (c == ' ' || c == '\t' || c == '\n') {
            if (state == IN_WORD) {
                /* increment histogram entry for current word length */
                if (len < MAX_LEN)
                    j = len;
                else
                    j = MAX_LEN;
                ++histogram[j - 1];

                /* keep a record of the highest count */
                if (histogram[j-1] > top_count)
                    top_count = histogram[j-1];
            }
            /* reset state */
            len = 0;
            state = OUT_WORD;

        } else {
            /* keep track of current word length */
            ++len;
            state = IN_WORD;
        }
    }

    /* print histogram from top to bottom */
    for (i = top_count; i > 0; --i) {
        /* print Y-axis */
        printf("%3d|", i);

        /* print entries for each word length */
        for (j = 0; j < MAX_LEN; ++j) {
            if (histogram[j] < i)
                printf("  ");
            else
                printf(" .");
        }
        putchar('\n');
    }

    printf("    ");
    /* print X-axis */
    for (i = 0; i < MAX_LEN; ++i)
        printf("--");
    putchar('\n');

    return 0;
}

A small sample run against a quote by Benjamin Franklin:

  In wine there is wisdom, in beer there is Freedom, in water there is bacteria.

  6|   .
  5|   .
  4|   .     .
  3|   .     .
  2|   .   . .
  1|   .   . .   . . .
    ----------------------------------------


texts: Long function as a lambda, right or wrong?

texts:
I have been reviewing the code of a new co-worker and, although in general I think it's OK, there's a thing that causes me mixed feelings:

  private void Method(...)
  {
       Thread t = new Thread(() =>
       {
           // Some ~50 lines of code here
       });
       t.Start();
  }

This is no big deal, but I'm curious about what you guys think of it.
Is this exactly what lambdas are for? Or just the opposite? I try to avoid any lambda which doesn't fit on a couple lines at most...


texts: Formatting a possibly nil value as hours and minutes

texts:
This might be a bit silly because there are like a thousand ways to do this, but I'm struggling to come up with one that I like. I feel like this should fit in one line, but I don't like re-using read_attribute(:length) lots and I don't like the below because it's not that clear.

# returns a human-readable string in the format Xh Ym
def length
  # length stored in seconds
  len = read_attribute(:length)
  "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m" unless len.nil?
end


texts:
I started doing hackerrank problems only recently and here's my attempt to solve this problem.

Basically, you're given two integers N and K, so you need to find the sum of all 1 <= n <= N such that the sum is at most K away from a perfect square.

For example, for N = 65 and K = 0, we calculate the sum of squares of factors for all numbers from 1 to 65, i.e. 1, 5, 10, ... and see which of these sums is a perfect square (or more precisely 0 away from a perfect square). For 65, that happens to be 1 and 42, so the answer would be 43.

#include <cmath>
#include <vector>
#include <unordered_map>
#include <iostream>

using namespace std;

// Lookup table
unordered_map<uint_fast16_t, uint_fast16_t> fac_sq_diff;

auto sum_fac_sq(uint_fast16_t n) {
    uint_fast16_t sum = 0;
    // Calculate factors in pairs,
    // eg. 20 => (1, 20), (2, 10), (4, 5)
    auto sqrtn = sqrt(n);
    for (auto i = 1; i <= sqrtn; ++i) {
        if (n % i == 0) {
            sum += (i * i);
            auto j = n / i;
            if (i != j) {
                sum += (j * j);
            }
        }
    }
    return sum;
}

uint_fast32_t solve(uint_fast16_t n, uint_fast16_t k) {
    uint_fast32_t result = 0;
    int_fast32_t diff = 0;
    for (uint_fast16_t j = 1; j <= n; ++j) {
        auto idiff = fac_sq_diff.find(j);
        if (idiff == fac_sq_diff.end()) {
            auto sum = sum_fac_sq(j);
            // Closest perfect square:
            // https://stackoverflow.com/questions/6054909
            auto sqrtsum = static_cast<uint_fast16_t>(sqrt(static_cast<float>(sum)) + .5f);
            diff = sum - (sqrtsum * sqrtsum);
            diff = abs(diff);
            idiff = fac_sq_diff.emplace(j, diff).first;
        }

        if (idiff->second <= k) {
            result += j;
        }
    }
    return result;
}

int main() {
    // Expected input:
    // 11
    // 65 0
    // 269 1
    // 312 2
    // 745 3
    // 1457 4
    uint_fast16_t q = 1;
    cin >> q;

    // Find max N and reserve lookup table mem
    vector<pair<uint_fast16_t, uint_fast16_t>> NK;
    uint_fast16_t max_N = 0;
    for (auto i = 0; i < q; ++i) {
        uint_fast16_t N = 0, K = 0;
        cin >> N >> K;
        NK.emplace_back(N, K);
        max_N = max(N, max_N);
    }
    fac_sq_diff.reserve(max_N);

    for (auto &nk: NK) {
        cout << solve(nk.first, nk.second) << endl;
    }
    return 0;
}

No matter what I try, I am not able to get past the first test (in terms of speed). :(

I also tried the geometric summation formula to calculate the sum of factors squared, but my implementation turned out to be slower than this one.


texts:
Is there a more cleaner approach to this? I'm doing the String calculator Kata posted by Roy Osherove. I realized that my calculator has no way of clearing out a previous expression after calling add. How can I handle this, and also how can I cut down the number of methods?

Here's a valid string: calc.add("//+\n1+2")

Here's an invalid string: calc.add("//b\n1b2")

class StringCalculator
  attr_reader :numbers

  def initialize(numbers = '')
    @numbers = numbers
  end

  def add(expression)
    @numbers << expression
    return nil if @numbers.end_with("\n")
    @numbers.gsub!(/\n/, delimiter)
    @numbers.empty? ? 0 : solution
  end

  private

  def valid_delimiters
    [*(33..46), *(58..64)].map(&:chr).join
  end

  def solution
    numerics = @numbers.split(delimiter).map(&:to_i)
    find_negatives(numerics)
    numerics.reduce(:+)
  end

  def find_negatives(numerics)
    negatives = numerics.select { |n| n < 0 }
    fail "negatives not allowed: #{negatives.join(', ')}" if negatives.any?
  end

  def supports?
    valid_delimiters.include?(@numbers[2, 1])
  end

  def delimiter
    return ',' unless @numbers.match(%r{^//})
    supports? ? @numbers[2, 1] : fail('Unsupported delimiter')
  end
end


texts: Small Markov chain Monte Carlo implementation

texts:
I've written a small markov chain monte carlo function that takes samples from a posterior distribution, based on a prior and a binomial (Bin(N, Z)) distribution.

I'd be happy to have it reviewed, especially perhaps, regarding how to properly pass functions as arguments to functions (as the function prior_dist() in my code). In this case, I'm passing the function uniform_prior_distribution() showed below, but it's quite likely I'd like to pass other functions, that accept slightly different arguments, in the future. This would require me to rewrite mcmc(), unless there's some smart way around it...

def mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10):
    import random
    from scipy.stats import binom
    #Make Markov chain (Monte Carlo)
    mc = [0] #Initialize markov chain
    while len(mc) < thin*size + burn:
        cand = random.gauss(mc[-1], 1) #Propose candidate
        ratio = (binom.pmf(Z, N, cand)*prior_dist(cand, size)) / (binom.pmf(Z, N, mc[-1])*prior_dist(mc[-1], size))
        if ratio > random.random(): #Acceptence criteria
        mc.append(cand)
    else:
        mc.append(mc[-1])
    #Take sample
    sample = []
    for i in range(len(mc)):
        if i >= burn and (i-burn)%thin == 0:
            sample.append(mc[i])
    sample = sorted(sample)
    #Estimate posterior probability
    post = []
    for p in sample:
        post.append(binom.pmf(Z, N, p) * prior_dist(p, size))
    return sample, post, mc

def uniform_prior_distribution(p, size):
    prior = 1.0/size
    return prior


texts: SQL design for representing a two-level hierarchy of objects with containment

texts:
I am trying to represent questions in quizzes.
The database is Mysql but I am using fairly generic sql.  The assumption is that varchar cannot handle more than 255 though, so I am supporting longer text by having multiple text components.

There are four primitive kinds of questions: multiple choice, multiple answer, fill in the blank, and editText.  Multiple choice have multiple answers, with one being right.  Multiple anwer have multiple answers, with some being wrong and some being right.  The student is expected to pick multiple answers and avoid getting incorrect ones.  Fill in the blank allows a string answer which is compared against the answer (or answers).  For editText, a block of text is loaded and must be modified by the student.  An edittext can exceed 255 characters, so cannot use a single varchar.

In addition to the base types, there are also multi-part questions where each part can be a question.

My approach is as follows:

A Quiz is a collection of CompoundQuestions in a particular order.  This table is not included because it is not relevant to the rest of the question.

A CompoundQuestion is a sequence of text, graphics, and questions.  Some compound questions could have zero questions (text only) while other CompoundQuestions could have many.  Most will have just one.

CREATE TABLE CompoundQuestion(
  cqid integer(8) primary key
);

CREATE TABLE CompoundQuestionText(
  cqid integer(8),
  seq  integer(4),
  primary key (cqid, seq),
  text varchar(255),
  imgname varchar(255)
);

CREATE TABLE Questions (
  qid integer(8) primary key,
  qtype integer(4),
  cqid integer(8),
  seq  integer(4)
);

CREATE TABLE QuestionText (
  qid integer(8),
  seq integer(4),
  primary key(qid,seq),
  text varchar(255)
);

CREATE TABLE Answers (
  qid integer(8),
  aid integer(4),
  primary key (qid,aid),
  text varchar(255),
  img varchar(255)
);

Is this a reasonable approach?
Is there a better way to handle columns larger than 255 characters?  Blobs add complication and can't be searched, right?

Suppose more types are added.  Do extra fields just get added in new tables and joined to the base question table?  If so, every kind of question then requires a different query.  Is there any better way to do that?

Ideally, I would like to be able to write a stored procedure that loads all questions in a particular quiz.

The two approaches that occur to me are selecting each question and based on the type, creating the object, or selected all the objects of each type.  If the system expands to 10-20 different types of questions, what would be the best way to implement this query?


texts:
Hello guys could you help me please how to render this code as OOP?
I want to improve this code and follow the OOP anyone could help me, please
thank you in advance
this is class Expression
class Expression {
        public int type;
        public int value;
        public Expression leftOp;
        public Expression rightOp;

        public Expression(int type, int value, Expression leftOp, Expression rightOp) {
            this.type = type;
            this.value = value;
            this.leftOp = leftOp;
            this.rightOp = rightOp;
        }
    }

    class Arith {

/** Constantes pour representer les types */
        public static final int TYPE_NUMBER = 1;
        public static final int TYPE_SUM = 2;
        public static final int TYPE_PROD = 3;

    public static void main(String[] args) {

            Expression term = new Expression(TYPE_SUM, 0, new Expression(TYPE_NUMBER, 3, null, null), new Expression(
                    TYPE_PROD, 0, new Expression(TYPE_NUMBER, 2, null, null), new Expression(TYPE_NUMBER, 5, null, null)));
            System.out.println(evaluate(term));
        }

        /** Evalue recursivement the expression */
        public static int evaluate(Expression term) {
            switch (term.type) {
            case TYPE_NUMBER:
                return term.value;
            case TYPE_SUM:
                return evaluate(term.leftOp) + evaluate(term.rightOp);
            case TYPE_PROD:
                return evaluate(term.leftOp) * evaluate(term.rightOp);
            default:
                return 0;
            }
        }
    }


texts: Finding largest prime factor from inputted number

texts:
This is my first C# console application. This program asks for an input of a number, and finds the highest prime factor of that number. Please review my code.

Have I used things right?
Is my code efficient?
Is there a better way to achieve this?

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

namespace Problems
{
    class Program
    {
        static int FindFactor(Int64 UserInput)
        {
            int LargestFactor = 0;
            Int64 Number = UserInput;

            for (int i = 2; i < Number; i++)
            {
                if (Number % i == 0)
                {
                    if (PrimeFactorCheck(i) == true)
                    {
                        LargestFactor = i;
                    }
                }
            }
            return LargestFactor;
        }
        static bool PrimeFactorCheck(int Number)
        {
            bool PrimeNumberValidity = true;

            for(int i = 2; i < Number; i++)
            {
                if (PrimeNumberValidity == true)
                {
                    if (Number % i == 0)
                    {
                        PrimeNumberValidity = false;
                    }
                }
                else
                {
                    i = Number;
                }
            }

            return PrimeNumberValidity;
        }
        static void Main(string[] args)
        {
            Console.Write("Hello, please enter a number to find the biggest prime factor of it: ");
             Int64 UserInput = Convert.ToInt64(Console.ReadLine());

            int Answer = FindFactor(UserInput);
            Console.WriteLine(Answer);
            Console.ReadKey();
        }
    }
}


texts:
I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.

Example:

Input String: The quick brown fox jumped over the fence, K: 11

Output: The quick

Here is what I have tried:

  function crop(message, K) {
  var originalLen = message.length;
  if(originalLen<K)
  {
      return message;
  }
  else
  {
      var words = message.split(' '),substr;

      for(var i=words.length;i > 0;i--)
       {

           words.pop();

            if(words.join(' ').length<=K)
            {
              return words.join(' ');
            }
       }

  }
}

This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?


texts: How to improve this algorithm for building a graphs closures

texts:
We have a large directed acyclic graph and a requirement to filter it by allowing a user to select certain nodes and then we remove all nodes that are not selected nodes, ancestors of those nodes, or descendants of those nodes.

As you can see in the above image nodes 6 and 9 have been selected and so nodes which do not route to those nodes are removed.

We are trying to build the closures (transitive closures?) of the graph so we can quickly filter it. We used the below code which was very slow. Profiling it shows around half of the time is spent in garbage collection.

public static class NodeClosureAnalyser
    {
        public static NodeClosures Analyse(Node root)
        {
            var results = new NodeClosures
                              {
                                  AncestorClosures = new Dictionary<int, HashSet<int>>(),
                                  DescendantClosures = new Dictionary<int, HashSet<int>>()
                              };
            //walk the tree and build the closures lists
            var stack = new Stack<Node>();
            stack.Push(root);

            var route = new Stack<Node>();

            while (stack.Count != 0)
            {
                var current = stack.Pop();
                //keep track of the route to root
                while (route.Any() && !route.Peek().Children.Any(n => n.Id == current.Id))
                {
                    route.Pop();
                }
                route.Push(current);

                AddNodeRelationships(results, current, route);
                foreach (var child in current.Children)
                {
                    stack.Push(child);
                }
            }
            return results;
        }

        private static void AddNodeRelationships(NodeClosures results, Node current, IEnumerable<Node> route)
        {
            foreach (var node in route)
            {
                results.AncestorClosures.GetOrCreateValuesList(current.Id).Add(node.Id);
                results.DescendantClosures.GetOrCreateValuesList(node.Id).Add(current.Id);
            }
        }
    }

    public struct NodeClosures
    {
        public Dictionary<int, HashSet<int>> AncestorClosures { get; set; }
        public Dictionary<int, HashSet<int>> DescendantClosures { get; set; }
    }

    public static class DictionaryExtension
    {
        public static HashSet<int> GetOrCreateValuesList(
            this IDictionary<int, HashSet<int>> dictionary, int key)
        {
            HashSet<int> ret;
            if (!dictionary.TryGetValue(key, out ret))
            {
                ret = new HashSet<int>(new List<int>());
                dictionary[key] = ret;
            }
            return ret;
        }
    }

A program with tests to demonstrate the issue is available on Github

Many thanks for any input!


texts:
Problem description.
I have JSON which comes in bad shape:
data = [
    {"ids": [1]},
    {"ids": [3, 4]},
    {"ids": [1, 2]},
    {"ids": [4]},
    {"ids": [3]},
    {"ids": [2]},
] # LD. List of dictionaries.

I want it to get in shape, like this:
expected = [
  [{"ids": [1]}, {"ids": [2]}],        # Length = 1
  [{"ids": [3, 4]}, {"ids": [1, 2]}],  # Length = 2
]  # LOLD. List is now list-of-lists of dictionaries.

To simplify the problem, we can remove the dictionaries of a single kv-pair, keeping in mind that we must reconstruct it later:
# in
[
    [3, 4], [1, 2],
    [1], [4], [3], [2]
]

# out
[
    [[3, 4], [1, 2]]
    [[1], [4], [3], [2]]
]

This is very easy. assemble . op . disassemble $ data:
def main(ids):
    return [list(x) for x in assemble(cardinality_groups(disassemble(ids)))]

def cardinality_groups(lol):
    return [list(group) for _, group in groupby(sorted(lol, key=len), key=len)]

def assemble(data):
    return [tag_datum(x) for x in data]

def tag_datum(datum):
    return [{"ids": x} for x in datum]

def disassemble(ids):
    return [x['ids'] for x in ids]

but
I insist, it must be simpler, purer! Although, I am not sure if Python sports the amenities to make things prettier. So please suggest functionality present in other languages.
I am curious about two ways the program can expand here, and some other things:

By the complexity and nesting of the data. Data can take the form of any JSON found in the wild. Here we simply descend a few levels down.
By the operation performed: Here grouping by cardinality solved the issue. In another world we want no two sets to intersect. Is there any more complex operations, what are they, and do they break anything?
Assembly-disassembly symmetry. The two should be each other's inverse, so can I deduce one from the other, thus not having to code it. Does any language provide such tools?
Beyond typing, are there any languages that support describing how data looks when it comes in, and how it will look when it comes out? Not just the top-level type, but the shape of the data the code works with at that level of abstraction. My presumption is that many programs lend well to this type of reasoning.
I don't like f(g(h(x))). I like f . g . h $ x--it's purer. It really bothers that I can't do something like this in Python, or JavaScript--two of the most popular languages! Consequently, I frequently find myself doing either:

someValue = dostuff(someInput)
valueIsNowSlightlyChanged = doMoreStuff(someValue)
iAmLosingTrack = doStuffMoreNow(valueIsNowSlightlyChanged)
final = wtf(iAmLosingTrack)

return final

Or variations thereof. At this point I don't feel like using either language. Doing things this way isn't, of course, isn't always going to be possible, but I don't even get the opportunity. Am I confused, or do I have a point, and you possibly a solution to my supposed confusion?
\0.
This code was originally written for a question on StackOverflow. I believe that I found a neat way to do it in comparison to the rest. Regardless, I must assume that I don't have the only good solution. Do you have an example?
Feel free to interpret my questions liberally. Apologies if some is beyond the scope of this forum. I appreciate any pointers to literature on these topics, as well as all your impressions.
Please also let me know if I am unclear. Thank you!


texts: Project Euler #10 in C++ (sum of all primes below two million)

texts:
Project Euler Problem 10 asks for the sum of all the primes below two million.

I'm creating a list of primes and keep checking any new number for divisibility with only prime numbers. I thought it should take less time but it is going over 4 minutes. How should I approach such a problem?

#include<iostream>
#include<list>

#define X 2000000

using namespace std;

list<long long> lst={2ll,3ll};

bool divideByAnyPrime(long long a)// checks if the number a is divisible by any prime in the list (lst)
{

    for( auto x:lst )
        if( a%x == 0 )
            return true;
    return false;
}

long long getNextPrime()//adds next prime number to list
{

    long long a=lst.back()+2;
    for( ; divideByAnyPrime(a); a+=2);
    lst.push_back(a);

    return a;

}

int main()
{
    long long sum=5ll;//sum of already existing elements 2 and 3
    while(lst.back()<=X)
    {
        sum+=getNextPrime();
    }
    sum-=lst.back();
    lst.pop_back();//as our list will contain one element at the last which we don't want

    cout<<"\nSum is "<<sum;

}


texts: Scraping HTML via async controller & classes + HTML agility pack

texts:
I've developed a simple application to grab golfer index scores from a website that has no API. The application works but is very slow, with 6 users that require updating takes 60 seconds. I've tried to make my web requests asyncronous to offset some of this lag but it only resulted in a 15% increase in performance.

Description of the code:

On my view I have anchor tag that when clicked hides all the elements in the DOM and loads a preloader, after the preloader is appended to the DOM a AJAX call is executed that calls the UpdatedHandicap method on a controller in my project. From there we await a static method GrabIndexValue. All the code works, it's just very slow.

Possible solution:

This website allows me to input multiple GHIN #s however the result set is in a table with strangely generated xpaths:

//*[@id="ctl00_bodyMP_gvLookupResults_ctl02_lblHI"] which returns index of: 10.5
//*[@id="ctl00_bodyMP_gvLookupResults_ctl03_lblHI"] which returns index of: 9
//*[@id="ctl00_bodyMP_gvLookupResults_ctl04_lblHI"] which returns index of: 13.5

I don't know how to dynamically grab those result sets and parse them properly. So I feel like I'm stuck doing 1 web request per index value.

Async controller method:

public async Task<ActionResult> UpdateHandicap()
{
    //Fetch all the golfers
    var results = db.Users.ToList();
    //Iterate through the golfers and update their index value based off their GHIN #. We store this
    //value in the database to make our handicap calculation
    foreach (Users user in results)
    {
        user.Index = await Calculations.GrabIndexValue(user.GHID);
        db.Entry(user).State = EntityState.Modified;
        db.SaveChanges();
    }
    return RedirectToAction("Index", "Users");
}

Method to actually grab the data:

public static async Task<double?> GrabIndexValue(int ghin)
{
    string url = $"http://xxxxxxxxx/Widgets/HandicapLookupResults.aspx?entry=1&ghinno="+ghin+"&css=default&dynamic=&small=0&mode=&tab=0";
    HtmlWeb web = new HtmlWeb();
    HtmlDocument htmlDoc  = await Task.Run(()=>web.Load(url));

    string index = null;
    try
    {
        index = htmlDoc.DocumentNode.SelectNodes("//*[@id=\"ctl00_bodyMP_grdClubs\"]/tbody/tr/td[2]")[0].InnerText;
    }
    catch
    { }

    if (index != null)
    {
        var indexResult = Convert.ToDouble(index);
        return indexResult;
    }
    else
    {
        return null;
    }
}

Any insight into this predicament is greatly appreciated

Thank you


texts:
I'm having trouble structuring the logic of OAuth integration into my web app. In the app, a user creates a Report that consists of data from their Google Analytics account.

User steps:

User clicks 'New Report'
Google presents the 'Allow Access' page for OAuth access
User is presented with a list of their GA web properties and selects one
A report is created using data from the selected web property

My issue is in structuring the code below.

When the user clicks "New Report", they are actually redirected to google_analytics#ga_session to begin the authorization process. The code to retrieve the user's web properties succeeds, but the code at the bottom needs to be refactored so it is reusable when retrieving web property data. The main two issues I can't figure out is how to make the Google Analytics instance reusable and how to structure the OAuth redirects.

Retrieve web properties:

GoogleAnalyticsController

def ga_session
    client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
        :token_url => 'https://accounts.google.com/o/oauth2/token'
    })
    redirect_to client.auth_code.authorize_url({
         :scope => 'https://www.googleapis.com/auth/analytics.readonly',
         :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'],
         :access_type => 'offline'
     })
  end

  def oauth_callback
    session[:oauth_code] = params[:code]
    redirect_to new_report_path
  end

ReportsController

def new
     @report = Report.new
     ga_obj = GoogleAnalytics.new
     ga_obj.initialize_ga_session(session[:oauth_code])
     @ga_web_properties = ga_obj.fetch_web_properties
end

GoogleAnalytics model

def initialize_ga_session(oauth_code)
    client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
        :token_url => 'https://accounts.google.com/o/oauth2/token'
    })
    access_token_obj = client.auth_code.get_token(oauth_code, :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'])
    self.user = Legato::User.new(access_token_obj)
  end

  def fetch_web_properties
    self.user.web_properties
  end

Retrieve web property data: when creating the report

ReportsController

def create
    @report = Report.new(params[:report])
    @report.get_top_traffic_keywords(session[:oauth_code])
    create!
end

Report Model

def get_keywords(oauth_code)
    ga = GoogleAnalytics.new
    ga.initialize_ga_session(oauth_code) # this is a problem b/c the user will be redirected the new_report_path after the callack
    self.url = ga.fetch_url(self.web_property_id)
    self.keywords = # Get keywords for self.url from another service
    keyword_revenue_data(oauth_code)
end

def keyword_revenue_data(oauth_code)
    ga = GoogleAnalytics.new
    ga.initialize_ga_session(oauth_code)
    revenue_data = # Get revenue data
end


texts:
I have these relevant tables in an MVC website:

Server
ServerPlayer
ServerPlayerChat

Servers have serverPlayers and ServerPlayers have ServerPlayerChats. Simple enough and expectable.

I have a feeling my code could be drastically condensed (particularly the GetServerPlayer method) and that the GetServerPlayer method is named wrong, although I couldn't think of a better name other than GetOrCreateServerPlayer, which is really long-winded. Also, this is in the Server model. I think I could move the add chat to the server player model, but my concern is that this might be more appropriate in a controller.

Is it good practice to do what I'm doing where I'm not only adding the new chat to the ServerUserChats collection, but also setting ServerPlayer = player inside the new chat? I'm aware that LINQ/EF/... is capable of figuring out relations like this from just one variable but it felt right to do this, so feedback on that is accepted too.

public void AddChat(string playername, string chat, int time)
{
    LastChat = time;
    ServerPlayer player = GetServerPlayer(playername);
    player.ServerUserChats.Add(new ServerPlayerChat() {
        Content = chat,
        Time = time,
        ServerPlayer = player
    });
}

public ServerPlayer GetServerPlayer(string playername)
{
    ServerPlayer player = GetPlayer(playername);
    if (player == null)
    {
        player = new ServerPlayer() {
            Server = this,
            UserName = playername,
        };

        Players.Add(player);
    }

    return player;
}

public ServerPlayer GetPlayer(string playername)
{
    return Players.Where(x => x.UserName == playername).FirstOrDefault();
}