texts: Change random methods without losing too much performance

texts:
I have a class in C# that uses a Random object to get a list of numbers randomized from an array of 1-25. Now what I need is improve this method to use RNGCryptoServiceProvider because it is not random enough for the application.

I know that RNGCryptoServiceProvider is slower than Random, but I need to change it and I don't know anything about this class.  How big should the Buffer storage be so as to not slow down the client PC too much?

What I'm passing to the method is this array:

string[] num25 = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25" };

This is the actual code:

public static class RandomStringArrayTool
{
    /// <summary>
    /// Stores the current random number
    /// </summary>
    static Random _random = new Random();

    /// <summary>
    /// Return randomized version of the string array
    /// </summary>
    public static string[] RandomizeStrings(string[] arr)
    {
        List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
        // Add all strings from array
        // Add new random int each time
        foreach (string s in arr)
        {
            list.Add(new KeyValuePair<int, string>(_random.Next(), s));
        }
        // Sort the list by the random number
        var sorted = from item in list
                     orderby item.Key
                     select item;
        // Allocate new string array
        string[] result = new string[arr.Length];
        // Copy values to array
        int index = 0;
        foreach (KeyValuePair<int, string> pair in sorted)
        {
            result[index] = pair.Value;
            index++;
        }
        // Return copied array
        return result;
    }
}


texts: Longest common subsequence (LCS) for multiple strings

texts:
How would you improve this code? Particularly the check and check_all functions?

The time complexity of the algorithm of mlcs is \$O(|\Sigma|MN)\$, where \$\Sigma\$ is the alphabet, M is the number of strings and N is the length of the strings.
Is that right?

My analysis: candidates() performs \$O(|\Sigma|M)\$ operations and is called \$O(N)\$ times.

Based on the reviewed code posted before at
Multiple longest common subsequence (another algorithm)

def check(string, seq):
    i = 0
    j = 0
    while i < len(string) and j < len(seq):
        if string[i] == seq[j]:
            j += 1
        i += 1
    return len(seq) - j

def checkall(strings, seq):
    for x in strings:
        a = check(x, seq)
        if not a == 0:
            print(x, seq, a)
            return False
    return True

def mlcs(strings):
    """Return a long common subsequence of the strings.
    """
    if not strings:
        raise ValueError("mlcs() argument is an empty sequence")
    strings = list(set(strings)) # deduplicate
    alphabet = set.intersection(*(set(s) for s in strings))

    # indexes[letter][i] is list of indexes of letter in strings[i].
    indexes = {letter:[[] for _ in strings] for letter in alphabet}
    for i, s in enumerate(strings):
        for j, letter in enumerate(s):
            if letter in alphabet:
                indexes[letter][i].append(j)

    # Generate candidate positions for next step in search.
    def candidates():
        for letter, letter_indexes in indexes.items():
            candidate = []
            for ind in letter_indexes:
                if len(ind) < 1:
                    break
                q = ind[0]
                candidate.append(q)
            else:
                yield candidate

    result = []
    while True:
        try:
            # Choose the closest candidate position, if any.
            pos = None
            for c in candidates():
                if not pos or sum(c) < sum(pos):
                    pos = c
            letter = strings[0][pos[0]]
        except TypeError:
            return ''.join(result)
        for let, letter_indexes in indexes.items():
            for k, ind in enumerate(letter_indexes):
                ind = [i for i in ind if i > pos[k]]
                letter_indexes[k] = ind
        result.append(letter)

strings = []
# Alphabet for the strings.
sigma = ["a", "b", "c", "d"]
# Alphabet for the LCS.
sigmax = ["e", "f", "g"]
import random
Nx = 67 # Length of LCS.
N = 128 # Length of strings. N >= Nx.
M = 128 # Number of strings.
x = ""
for _ in range(Nx):
    x += random.choice(sigmax)
for _ in range(M):
    string = ""
    for _ in range(N):
        string += random.choice(sigma)
    indexes = list(range(N))
    random.shuffle(indexes)
    indexes = sorted(indexes[:len(x)])
    for j in range(len(x)):
        string = string[:indexes[j]]+x[j]+string[indexes[j]+1:]
    strings += [string]

#strings = ["abbab", "ababa", "abbba"]
#strings = ["abab", "baba", "abaa"]
#strings = ["bacda", "abcde", "decac"]
#strings = ["babbabbb", "bbbaabaa", "abbbabab", "abbababa"]
#strings = ["ab", "aba"]
#print("Strings:")
#print(strings)
l = mlcs(strings)
print("LCS:")
print(l, len(l), checkall(strings, l))


texts: Blackjack simulator for Probability of a dealer bust for each starting card

texts:
I came up with this solution to another exercise out of John Zelle's Programming book.

#bust.py --- Simulates multiple games of blackjack with each possible dealer starting card and estimates
#   the probability that the dealer will bust

import random

def intro():
    pass

def takecard():
    card = random.randint(1, 10)
    has_ace = False
    #Randomly choose if the 1 is an ace
    if card == 1:
        has_ace = random.choice([True, False])
    return card, has_ace

def sim_one_game(starter):
    #For simulating the ace
    if starter == 12:
        starter = 1
        has_ace = True

    total = starter

    while total <= 17:
        card, has_ace = takecard()
        total += card

        #Ace is valued at 11 when it would produce a stopping total
        if has_ace == True and total + 10 >= 17 and total + 10 <= 21:
            total += 10

    return total

def sim_n_games(starter, game_count):
    busts = 0
    for i in range(game_count):
        score = sim_one_game(starter)
        if score > 21:
            busts += 1
    return busts

def sim_each_card(game_count):
    bustsls = []
    for i in range(1, 12):
        bustsls.append(sim_n_games(i, game_count))

    return bustsls

def output(bustsls, game_count):
    print("Busts for Starting Card A: {} out of {} games. ({:0.1%})".format(bustsls[10], game_count, bustsls[10] / game_count))
    for card in range(1, 11):
        print("Busts for Starting Card {}: {} out of {} games. ({:0.1%})".format(card, bustsls[card - 1], game_count, bustsls[card - 1] / game_count))

def main():
    intro()
    game_count = int(input("\nHow many rounds to simulate? "))
    bustsls = sim_each_card(game_count)
    output(bustsls, game_count)

if __name__ == "__main__": main()

It works pretty well, although when profiling it with 100.000 iterations it takes ~5 seconds to finish. When profiling I noticed that all the calls to random take up quite some time.

Anyone know a better way to solve this? Please note that I am a beginner and there are a lot of things I haven't learned anything about yet, but I'll read into all of your suggestions!


texts:
Write a method mirror that doubles the size of a list of integers by
  appending the mirror image of the original sequence to the end of the
  list. The mirror image is the same sequence of values in reverse
  order. For example, if a variable called list stores this sequence of
  values:

  [1, 3, 2, 7]

  and we make the following call:

  list.mirror();

  then it should store the following values after the
  call:

  [1, 3, 2, 7, 7, 2, 3, 1]

  Notice that it has been doubled in size by
  having the original sequence appearing in reverse order at the end of
  the list. You may not make assumptions about how many elements are in
  the list. Because adding these elements might overrun the capacity of
  the underlying array, you may need to call ensureCapacity to enlarge
  this array.

  Assume you are adding to the ArrayIntList class with following fields:

public class ArrayIntList {
    private int[] elementData;
    private int size;

    public void add(int value) { ... }
    public void add(int index, int value) { ... }
    public void ensureCapacity(int capacity) { ... }
    ...

    // your code goes here
}

What improvements can I make to help on my future coding? Interested in knowing if there are other ways to tackle this question, and if the way I solved the problem is safe? This code interacts with the ArrayIntList.java class.

public void mirror() {
    if (size != 0) {
        int limit = size * 2;
        this.ensureCapacity(limit);
        size = limit;
        for (int i = 0; i < size; i++) {
           elementData[(limit - 1) - i] = elementData[i];
        }
    }
}


texts:
Problem from hackerrank:

You’re given the pointer to the head nodes of two sorted linked lists.
The data in both lists will be sorted in ascending order. Change the
next pointers to obtain a single, merged linked list which also has
data in ascending order. Either head pointer given may be null meaning
that the corresponding list is empty.
Input Format
You have to complete the Node* MergeLists(Node* headA,
Node* headB) method which takes two arguments - the heads of the two
sorted linked lists to merge. You should NOT read any input from
stdin/console.
Output Format
Change the next pointer of individual nodes so that
nodes from both lists are merged into a single list. Then return the
head of this merged list. Do NOT print anything to stdout/console.
Sample Input
1 -> 3 -> 5 -> 6 -> NULL
2 -> 4 -> 7 -> NULL

15 -> NULL
12 -> NULL

NULL
1 -> 2 -> NULL

Sample Output
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
12 -> 15 -> NULL
1 -> 2 -> NULL

/*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
 int data;
 struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
if(headA == NULL)
  return headB;
if(headB == NULL)
  return headA;

Node* temp1;
Node* temp2;
Node* originalHead;
Node* head = new Node;
head->data = 0;
head->next = 0;
//temp1 should always point to head with smaller value
if(headA->data <= headB->data)
{
  temp1 = headA;
  originalHead = headA;
  temp2 = headB;
}
else
{
  originalHead = headB;
  temp1 = headB;
  temp2 = headA;
}
while(temp1 != 0 && temp2 != 0)
{
    if(temp1->data <= temp2->data){
        head->next = temp1;
        head = temp1;
        if(temp1->next != NULL)
            temp1 = temp1->next;
        else{
            head->next = temp2;
            break;
        }
    }
    else{
        head->next = temp2;
        head = temp2;
        if(temp2->next != NULL)
            temp2 = temp2->next;
        else{
            head->next = temp1;
            break;
        }
    }
}
return originalHead;
}


texts: jQuery animations with only one callback

texts:
I'm aware of doing that 'magic' inside $.when(). How should I achieve same effect writing code more readable ? I read something about a $.Defferer() that I think should help but I don't know how to use it.

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

Element 1

Element 2

Element 3

What I want is to run multiple animations and at the end of them to show a message, to do something. I know that I can use $(".elm").animate() and all elm divs will be animated by I use that .each() to set the delay between them (maybe there's another posibility using animation step or progress handlers), but I can't get it to do something at the end of all animations. What I ask is if there's any other implementation that will to same thing and be more code readeable.


texts: Generic dataloader for redux-thunk using axios

texts:
I am developing an application where there are lots of async actions. I wanted to go with redux-saga but most have insisted to continue with redux-thunk. In redux-thunk, inside each action we have to work with async operation using then, dispatch, catch, etc. This makes looks actions so messy and lots of code will be repeated. I wanted to create a generic dataLoader for the use of redux-thunk and axios.

Here is my attempt:

export class Company {
/**
* Generic api data loader
*/
static dataLoader(apiUri, onSuccess, onError, data, ...actionArguments) {
  const requestURL = `${API_BASE}${apiuri}`;
  try {
    let options;
    if (data !== undefined) {
      // if we have data to post
      options = {
      method: 'POST',
      url: requestURL,
      body: JSON.stringify(data),
      headers: {
         'Content-Type': 'application/json',
         'X-Requested-With': 'XMLHttpRequest',
      },
      };
    }
  }
  return function(dispatch) {
    axios(options)
    .then(response => {
      dispatch({
        type: onSucess,
        payload: response.data
      });
    })
    .catch(error => {
      dispatch({ type: onError, payload: err});
    });
  }
}

static get(apiUri, onSuccess, onError, ...actionArguments) {
    return this.dataLoader(apiUri, onSuccess, onError, undefined, ...actionArguments);
  }

  /*
   * Shorthand POST function
   */
  static post(apiUri, onSuccess, onError, data, ...actionArguments) {
    return this.dataLoader(apiUri, onSuccess, onError, data, ...actionArguments);
  }

}

I want to convert the following code to further this one:

export function showResultofApartment() {
  return (dispatch) => {
    dispatch({ type: 'APARTMENT_FETCH_START' });
    const token = localStorage.getItem('token');
    return axios.get(`${API_URL}/newoffers/apartment/`)
    .then((response) => {
      console.log('response apart', response.data);
        dispatch({ type: 'APARTMENT_FETCH_SUCCESS', payload: response.data });
    })
    .catch((err) => {
      dispatch({ type: 'APARTMENT_FETCH_FAILURE', payload: err });
    });
  };
}

to such or more efficient than this:

export function showResultofApartment() {
  return(dispatch) => {
    dispatch({ type: APARTMENT_FETCH_START });
    const token = localStorage.getItem('token');
    return Company.get('/apartments', APARTMENT_FETCH_SUCCESS, APARTMENT_FETCH_ERROR);
    // if post then Company.post('/apartment', APARTMENT_POST_SUCCESS, APARTMENT_POST_ERROR, data)
  }
}

I have not tested this. I am just throwing my idea through code to get other experts idea on how I should handle such case for a more efficient technique without using other more external libraries.


texts: Checking if a Stack is sorted in ascending order

texts:
Write a method isSorted that accepts a stack of integers as a parameter and returns true if the elements in the stack occur in
  ascending (non-decreasing) order from top to bottom, and false
  otherwise. That is, the smallest element should be on top, growing
  larger toward the bottom. For example, passing the following stack to
  your method should cause it to return true:

  bottom [20, 20, 17, 11, 8, 8, 3, 2] top

  The following stack is not sorted (the 15 is out of place), so passing it to your method should return a result of false:

  bottom [18, 12, 15, 6, 1] top

  An empty or one-element stack is considered to be sorted. When your method returns, the stack should be in the same state as when it
  was passed in. In other words, if your method modifies the stack, you
  must restore it before returning.

Obey the following restrictions in your solution:

You may use one queue or stack (but not both) as auxiliary storage.
You may not use other structures (arrays, lists, etc.), but you can have as many simple variables as you like.
Use the Queue interface and Stack/LinkedList classes discussed in the textbook.
Use stacks/queues in stack/queue-like ways only. Do not call index-based methods such as get, search, or set (or use a for-each loop or iterator) on a stack/queue. You may call only add, remove, push, pop, peek, isEmpty, and size.
Your solution should run in O(N) time, where N is the number of elements of the stack.
You have access to the following two methods and may call them as needed to help you solve the problem:

public static void s2q(Stack s, Queue q) { ... }

public static void q2s(Queue q, Stack s) { ... }

I'm looking for general feedback that will make my future code better. Are there any glaring issues that you can find that make it harder for you to read my code? Is there a better way you can think of to accomplish this task?

public boolean isSorted(Stack<Integer> s) {
    boolean isSorted = true;
    if (s.size() == 1 || s.isEmpty()) {
        return isSorted;
    }

    Queue<Integer> q = new LinkedList<Integer>();
    while(!s.isEmpty()){
        int s1 = s.pop();
        if (!s.isEmpty()) {
            int s2 = s.peek();
            isSorted &= s2 >= s1;
        }
        q.add(s1);
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }

    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }

    return isSorted;
}


texts: Simple networking layer in Swift using Strategy design pattern

texts:
Does the following code demonstrate proper use of Strategy design pattern for a simple networking layer in swift 3?

Some code smells I'm unsure about:

violates Single responsibiility principle. Each strategy class such as Find, has a method for a different type of implementation. This is because I could want to find an image, or a user, or a chatroom. which are stored at different nodes in Firebase. all these different find methods are clumped together in Find class.
At the call sight of a request, if I need to make multiple async request, I nest the next request call inside the closure of the call back. Is this Ok?
The request object allows access to every type of insert, and find method. so in my signup VC I could i have the option to download a chatroom. Is even having access to that kind of implementation bad?

I have posted the code below, and left out all the actual implementation for brevity.

Any tips or guidance is much appreciated!

// USE CASE: Would go in viewDidLoad of ViewController
func testMyRequest () {

    let myRequest = Request(insert: Insert(), find: Find())

    myRequest.find?.user(with: "id", handler: { (user) in

        myRequest.find?.nearbyUsers(user: user, handler: { (users) in

            // update collectionView datasource
        })
    })
}

// Is this protocol necessary?
protocol RequestProtocol {
    // - Family of algorithms, related actions.
    var insert: Insert? { get set }
    var find: Find? { get set }
}

// ---------------------------

class Request: RequestProtocol {

    var insert: Insert?
    var find: Find?

    init(insert: Insert?, find: Find?) {
        self.insert = insert
        self.find = find
    }
}

// Use a singleton maybe for the classes below? Why wouldn't I?

class Insert {

    init() { }

    func user(_ user: User) {
        // insert user to firebase implementation
    }

    func message(_ message: Message) -> Void  {
        // insert message to firebase impelmentation
    }

    func image(data: Data, user: User)  {
        // insert image to firebase impelmentation
    }
}

class Find {

    init() { }

    func user(with id: String, handler: @escaping (_ user: User) -> Void ) {
        // find user implementation
    }

    func allChatrooms(handler: @escaping ([Chatroom]) -> Void) {
        // find all chatrooms implementation
    }

    func nearbyUsers(user: User, handler: @escaping ([User]) -> Void ) {
        // find nearby Users relative to current User location implementation
    }

    // Private helper method
    private func findChatPartners (currentUser: User, chatrooms: [Chatroom] ) -> Set<String> {
    }

}


texts:
Here a string is taken as input and the program suppose to check whether the string is palindrome or not.
Is there any way the code can be improved? Is it okay to use foreach to break the string into character.

class Program
{
    static void Main(string[] args)
    {
        //input a string
        string orginalStr = Console.ReadLine().ToLower(); ;

        //call the palindrome method

        Console.WriteLine(CheckPalindrome(orginalStr)
            ? "This is palindrome"
            : "This is not palindrome");

        Console.ReadKey();
    }

    static bool CheckPalindrome(string orginalStr)
    {
        //call the string reverse method
        var reversedStr = ReverseString(orginalStr);

        if (reversedStr.Equals(orginalStr))
            return true;

        return false;
    }

    static string ReverseString(string orginalStr)
    {
        string reversedStr = "";

        foreach (char ch in orginalStr)
        {
            reversedStr = ch + reversedStr;
        }

        return reversedStr;
    }
}


texts: Launch and place application depending on screen resolution

texts:
I got fed up off opening a set of applications when I wanted to code. So I decided to read up on AppleScript and came up with the following task for myself.

  Open a application of choice on a given page/directory. Arrange that
  application depending on your monitor width/height by setting the
  application display size and position on the screen.

I came up with the following:

global _browserList
set _browserList to {"Safari", "Google Chrome"}
--------------------------------------
on reSizeLoc(_app, _posL, _posT, _appWidth, _appHeight) --Resize and Place application on screen
    tell application "System Events" to tell application process _app
        try
            repeat with x from 1 to (count windows)
                get properties of window x
                set position of window x to {_posL, _posT}
                set size of window x to {_appWidth, _appHeight}
            end repeat
        end try
    end tell
end reSizeLoc
--------------------------------------
on bringToFront(_app) --Bring the application to the front (Focus)
    try
        tell application "System Events"
            tell process _app
                set frontmost to true
                perform action "AXRaise" of (windows whose title is _app)
            end tell
        end tell
    end try
end bringToFront
--------------------------------------
on openDir(_app, _dir) --Open application on a specific page/directory
    if _dir is not "" then
        if application _app is running and _app is not "Finder" then
            tell application _app
                if _browserList contains _app then
                    open location _dir
                else
                    open _dir
                end if
            end tell
        else
            tell application _app
                open alias _dir
            end tell
        end if
    end if
end openDir
--------------------------------------
on openApp(_app, _dir, _posL, _posT, _appWidth, _appHeight) --Main function
    if application _app is running and _app is not "Finder" then
        bringToFront(_app)
        openDir(_app, _dir)
        reSizeLoc(_app, _posL, _posT, _appWidth, _appHeight)
    else
        tell application _app to activate --Bring to front
        delay 0.5
        openDir(_app, _dir)
        delay 0.5
        reSizeLoc(_app, _posL, _posT, _appWidth, _appHeight)
    end if
end openApp
--------------------------------------------------
tell application "Finder" --Get monitor details
    set _dim to bounds of window of desktop
    set _item1 to item 1 of _dim
    set _item2 to item 2 of _dim
    set _width to item 3 of _dim
    set _height to item 4 of _dim
end tell

--Ultrawide
if _item1 = 0 and _item2 = 0 and _width = 3440 and _height = 1440 then
    openApp("Safari", "http://www.google.co.uk", 2292, 0, 1146, 1353)
    openApp("Atom", "Macintosh HD:Users:jjpro:Desktop:Github", 1146, 0, 1146, 1353)
    openApp("Google Chrome", "http://localhost:8888", 0, 0, 1146, 1353)
    openApp("MAMP", "", 0, 0, 400, 200)
    openApp("Finder", "Macintosh HD:Users:jjpro:Desktop:Github", 600, 1, 700, 400)
    return "Complete - Ultrawide mode ONLY"
end if

Just wanted a second pair of eyes to suggest possible improvements?
It works perfectly and does exactly what I want it to do; but there is always room for improvement.


texts:
The task is to implement a solveEquation function, which solves the Quadratic equation. Each equality has exact 2 integer solutions. Return those numbers as an ordered array.

Example:

const solutions = solveEquation('2 * x^2 - 10 * x + 12');
console.log(solutions); // [2, 3]

Solution:

function solveEquation(equation) {
    // Your solution here
    let a, b, c;
    // Using ES6 destructuring
    [a, b, c] = getValues(equation);
    return getXList(a, b, c);
}

// Determine a,b,c and return in an array
function getValues(equation) {
    // ax^2 + bx + c
    let a = equation.split(' * x^2')[0];
    let aSign = equation.split(a + ' * x^2')[0];
    // Assigns +- a
    a = parseInt(aSign + a);
    let bSign = equation.split(a + ' * x^2 ')[1].charAt(0);
    let b = equation.split(' * x^2 ' + bSign + ' ')[1].split(' * x ')[0];
    // Assigns +- b
    b = parseInt(bSign + b);
    // Assigns +- b
    let cSign = equation.split(' * x ')[1].charAt(0);
    let c = equation.split(' * x ' + cSign + ' ')[1];
    // Assigns +- c
    c = parseInt(cSign + c);
    return [a, b, c];
}
// Returns ordered Array
function getXList(a, b, c) {
    let list = [];
    list.push(getX('+', a, b, c));
    list.push(getX('-', a, b, c));
    list.sort((a, b) => a - b);
    return list;
}
// Returns X
function getX(sign, a, b, c) {
    // represent x = (- b +- √b^2-4ac)/2a as x = (b1 +- c1)/a1
    let x, b1, a1, c1;
    b1 = parseInt(- + b);
    a1 = 2 * a;
    c1 = Math.sqrt((b * b) - 4 * a * c);
    return x = Math.round((sign === '+') ? ((b1 + c1) / a1) : ((b1 - c1) / a1));
}

console.log(solveEquation('2 * x^2 - 10 * x + 12'));// [2, 3]
console.log(solveEquation('-20 * x^2 - 108797540 * x - 130011773690520'));// [-3667291, -1772586]
console.log(solveEquation('294 * x^2 - 141195558 * x - 1600964090384736'));// [-2105744, 2586001]
console.log(solveEquation('-267 * x^2 + 296412186 * x + 4722715166392080'));// [-3687112, 4797270]
console.log(solveEquation('-381 * x^2 + 2871374115 * x - 5385906614046864'));// [3516911, 4019504]
console.log(solveEquation('-154 * x^2 + 645219652 * x - 602658645850800'));// [1405588, 2784150]

The main reason I post this program is to get critical feedback and perhaps improve my coding style.


texts: Checking consecutive characters in a string

texts:
First of all, this code will ask for a number (first) on how many test the user would like to have. Then the user will input the strings depending on how the number entered.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim input As String = txtInput.Text
    Dim inputArr As String() = input.Split(New Char() {Environment.NewLine})
    Dim count As Integer = Convert.ToInt32(inputArr(0))
    If count >= 1 And count <= 10 Then
        If txtInput.Lines.Length() - 1 <= count Then
            For x As Integer = 1 To count
                If inputArr(x).Length - 1 >= 1 And inputArr(x).Length - 1 <= 10 Then
                    Dim numDeletes = CountConsecutiveDuplicates(inputArr(x))
                    txtResult.AppendText(numDeletes & Environment.NewLine)
                Else
                    MessageBox.Show("Hell no!")
                End If
            Next x
        Else
            MessageBox.Show("Max test reached!")
        End If

    Else
        MessageBox.Show("Number of cases is limited only from 1 - 10")
    End If
End Sub

Shared Function CountConsecutiveDuplicates(Of T)(input As IEnumerable(Of T)) As Int32
    Dim count As Int32 = 0
    Dim comparer = EqualityComparer(Of T).Default

    ' optimization for lists and arrays: '
    Dim listT = TryCast(input, IList(Of T))
    If listT IsNot Nothing Then
        If listT.Count <= 1 Then Return 0
        For i As Int32 = 0 To listT.Count - 2
            If comparer.Equals(listT(i), listT(i + 1)) Then
                count += 1
            End If
        Next
        Return count
    End If

    If Not input.Any() Then Return 0
    Dim this As T = input.First()
    For Each item As T In input.Skip(1)
        If comparer.Equals(this, item) Then
            count += 1
        End If
        this = item
    Next
    Return count
End Function

Here are the constraints:

tests >= 1 and tests <= 10
charofstring >= 1 and charofstring <= 10

This code will check the string that user input in a multiline textbox. For example, the input is 4 (as the test counter)(\n) AABBCCC (first string to check)(\n) AAAABBBC (2nd string to check)(\n) ... (4th string)

I need to check on the number of consecutive characters that are needed to delete until no characters are consecutive. This will be the result of the user input.

4 (first string because 1A 1B and 2C) - text in the parentheses not included in output
5 (2nd string because 3A 2B)
...

Is there any code that I do not need? Someone told me that I can still shorten the code I have. How can I modify this code?

"txtInput = name of input textbox"
"txtResult = name of output textbox"
"Button1 = name of button to execute the code."


texts:
I use the following script to download the result of a SEDE query and scrape a specific column from it using BeautifulSoup:

import json

def extract_column(soup, colname):
    """
    Returns a generator of cell values in selected column.

    For simple columns like timestamp, a cell value can be simple,
    for example: 1414433013197

    For more complex columns like Post Link, a cell value can be an object,
    for example:

      {
        "id": 68102,
        "title": "Bash Script - File Comment out & Notate"
      }

    :param soup: a bs4 (BeautifulSoup) object
    :param colname: name of the SEDE column to extract
    :return: generator of cell values in selected column
    """
    def get_column_index():
        for index, info in enumerate(columns):
            if info['name'] == colname:
                return index
        return -1

    for script in soup.findAll('script'):
        result_sets_col = 'resultSets'
        if result_sets_col in script.text:
            start = script.text.rindex('{', 0, script.text.index(result_sets_col))
            end = script.text.index('}', script.text.index('querySetId')) + 1
            data = json.loads(script.text[start:end])

            results = data[result_sets_col][0]
            columns = results['columns']
            rows = results['rows']

            column_index = get_column_index()
            if column_index > -1:
                for row in rows:
                    yield row[column_index]

Unit tests:

import os
import unittest

from bs4 import BeautifulSoup
from robosanta.stackexchange.sede import extract_column

BASE_DIR = os.path.dirname(__file__)

SEDE_OUTPUT_HTML = os.path.join(BASE_DIR, 'sede-output.html')
POST_ID_COLUMN = 'Post Link'
DATE_COLUMN = 'CreationDate'
ROW_COUNT = 49

def new_soup():
    with open(SEDE_OUTPUT_HTML) as fh:
        return BeautifulSoup(fh)

class TestGetColumn(unittest.TestCase):
    def extract_column(self, colname):
        return extract_column(new_soup(), colname)

    def extract_post_link(self):
        return self.extract_column(POST_ID_COLUMN)

    def extract_date(self):
        return self.extract_column(DATE_COLUMN)

    def test_row_count_of_post_link(self):
        self.assertEqual(ROW_COUNT, len(list(self.extract_post_link())))

    def test_first_post_link(self):
        expected = {
            'title': 'TinyMVC Model / Plugin how to implement?',
            'id': 12144,
        }
        self.assertEqual(expected, next(self.extract_post_link()))

    def test_row_count_of_date(self):
        self.assertEqual(ROW_COUNT, len(list(self.extract_date())))

    def test_first_date(self):
        self.assertEqual(1338304381360, next(self.extract_date()))

    def test_nonexistent_column(self):
        with self.assertRaises(StopIteration):
            next(self.extract_column('nonexistent'))

if __name__ == '__main__':
    unittest.main()

You can find the content of sede-output.html (the test data) here.

I'm looking for any and all suggestions, especially concerning:

Improving the main implementation (the scraping)
Improving the way to test this


texts:
I am new to Java's Swing and built a test client that connects to a server. I was wondering if my use of a Controller class as a link between the classes ClientWindow and WebsocketService made sense and would be thankful for comments. (I can take it, so the more my code is criticized the happier I am.)

For the sake of brevity, I have omitted most methods and fields.

ClientWindow

public class ClientWindow implements ActionListener {
    private static final String USER_ID = "19";
    private final IController controller;

    @Override
    public void actionPerformed(ActionEvent e) {
        controller.connectAs(USER_ID);
    }

    public void addMessage(String line) {
        responseArea.setText( responseArea.getText() + line );
    }
}

DefaultController (implements IController)

public class DefaultController implements IController {

    protected WebsocketService wsService;
    protected ClientWindow display;

    public DefaultController() {
        wsService = new WebsocketService(this);
    }

    public void setDisplay(IClientDisplay display) {
        this.display = display;
    }

    // ------------------
    // IController methods
    @Override
    public void updateMessage(String message) {
        if (display != null) {
            display.addMessage(message);
        }
    }

    @Override
    public void connectAs(String userId) {
        wsService.connectToServer(userId);
    }
}

WebsocketService

@ClientEndpoint
public class WebsocketService {
    private final IController controller;
    private String userId;

    public WebsocketService(IController controller) {
        this.controller = controller;
    }

    /**
     * On open: register the session and signal
     * the user ID and to the Node.js server.
     * @param session The WebSocket session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        controller.updateMessage("Connected to server");
        send( "c:" + userId);
    }

    /**
     * On message: handle incoming message by
     * invoking methods of the controller.
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        controller.updateMessage(message);
    }

    /**
     * Open a WebSocket to connect to the Node.js server.
     */
    public void connectToServer(String userId) {
        this.userId = userId;
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            container.connectToServer(this, new URI(Commons.SERVER_ADDR));
        }
        // catch blocks
    }
}

Finally, Client

public class Client {
    public static void main(String[] args) {
        DefaultController controller = new DefaultController();
        controller.setDisplay(new ClientWindow(controller));
    }
}

Client definitely looks bad, especially that second line. I might as well skip the DefaultController and just have a field for ClientWindow in WebsocketService and vice versa but that's obviously a big no-no. I have looked into MVC but I don't really have much to model (or am I wrong?).

After all, I need to be able to give commands to my Service but also to display output from it at any given time (onMessage) and so this was the most elegant solution I could think of.


texts: Is this a good algorithm to unflat js objects?

texts:
I am dealing with a scenario where I get data in the following form:

var data = {
    'user.name': 'renatoargh',
    'user.age': 27,
    'user.interests.0.description': 'coding',
    'user.interests.0.receiveNotifications': true,
    'user.interests.1.description': 'bungee jumping',
    'user.interests.1.receiveNotifications': false
};

So in order to validate and persist this data I decided to create a way to unflat these strings into regular JS objects, and send them to MongoDb (since it is schema-less).

I coded an algorithm that I am unsure that works for most cases so I created a fiddle that seems to be able to deal with an extreme case, full of nested arrays.

Can someone point any week point or case in which my algorithm would fail? Any kind of advice will be appreciated.

Link to the fiddle here!

Heres the code, where messageObject is the array and the output is in messageTree

function forEachOwnProperty(object, iterator) {
    for(var property in object){
        if(object.hasOwnProperty(property)) {
            iterator(property, object[property]);
        }
    }
}

forEachOwnProperty(messageObject, function(property, messages) {
    property = property.split('.');

    var currentNode = messageTree;

    for(var i = 0; i < property.length; i++) {
        var currentProperty = property[i];

        if(typeof currentNode[currentProperty] === 'undefined') {
            if(i === property.length - 1) {
                currentNode[currentProperty] = messages
            } else {
                if(/^\+?(0|[1-9]\d*)$/.test(property[i + 1])) {
                    currentNode[currentProperty] = [];
                } else {
                    currentNode[currentProperty] = {};
                }
            }
        }

        currentNode = currentNode[currentProperty];
    }
});


texts:
I'm currently building a small plane with Raspberry Pi Zero W. I wrote a small code which uses UDP to control it.

Here I'm resending packets regularly in a thread because of the joystick input (it gives a lot of values when used and time.sleep() in a pygame event loop does bad things). Am I doing it the right way?

I'm also sending three bytes only per packets (which is enough for the control), but should I use power of 2 packet size? And why?

import socket
import struct
import time
import threading

S_TYPE = "BBB"

class Server:
    def __init__(self, ip="", port=8080, timeout=-1):
        self.ip = ip
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind((ip, port))
        if (timeout > 0):
            self.sock.settimeout(timeout)

    def recv(self):
        data = self.sock.recv(struct.calcsize(S_TYPE))
        res = struct.unpack("BBB", data)
        return (res)

class Client:
    def __init__(self, ip, port=8080, interval=100):
        self.ip = ip
        self.port = port
        self.data = (0, 0, 0)
        self.interval = interval
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.thread = threading.Thread(target=self.send_loop)
        self.thread.daemon = True
        self.lock = threading.Lock()
        self.running = True

    def send(self, data_bytes):
        self.sock.sendto(data_bytes, (self.ip, self.port))

    def send_loop(self):
        '''Send loop is used to regulary send data in a thread'''
        while (self.running):
            self.lock.acquire()
            data_bytes = struct.pack(S_TYPE, *self.data)
            self.lock.release()
            self.send(data_bytes)
            time.sleep(self.interval / 1000.0)

    def update(self, a, b, c):
        '''Update data which is sent'''
        self.lock.acquire()
        self.data = (a, b, c)
        self.lock.release()

    def start(self):
        self.thread.start()

    def stop(self):
        # __del__ wouldn't be called with a thread running
        self.running = False

EDIT: do you see any problem not using a lock for self.running?


texts:
This library management program can do following functions:

Add a book to the library
Display all available books
Lend books to students
Return books to the library
Display students who have yet to return a book

Question: How do you refactor this code so that it follows OOP, reads better, is manageable and is pythonic? How can I write name functions and classes better? How do you know which data structure you need to use so as to manage data effectively?

Library class that contains a list of books

class Library:
    def __init__(self):
        self._books = []

    def add_book(self, new_book):
        self._books.append(new_book)

    def display_books(self):
        if self._books:  # if list of books is not empty
            print("The books we have made available in our library are:\n")
            for book in self._books:
                print(book)
        else:
            print("Sorry, we have no books available in the library at the moment")

    def lend_book(self, requested_book):
        if requested_book in self._books:
            print("You have now borrowed \"%s\" " % requested_book)
            self._books.remove(requested_book)

        else:
            print("Sorry, \"%s\" is not there in our library at the moment" % requested_book)

StudentDatabase class (container for all students)

class StudentDatabase:
    def __init__(self):
        self._books = {}

    def get_student(self, name):
        if name not in self._books:
            return "Not Found"

        return self._books[name]

    def borrow_book(self, name, book):
        if name not in self._books:
            self._books[name] = list(book)
        else:
            self._books[name].append(book)

    def return_book(self, name, book):
        if book not in self._books[name]:
            print("You don't seem to have borrowed \"%s\"" % book)
        else:
            self._books[name].remove(book)

    def display_students_with_books(self):
        for name, books in self._books.items():
            if books:
                print("%s: %s" % (name, books))

Follow-up : Object-oriented student library


texts:
I have the below code which increases the code complexity. Any way to refactor it?

I am trying to refactor the below code so that the CCM can be reduced for the code. i.e code complexity matrix.

//// TODO: Needs refactoring
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var memberNames = new List<string>();

        if (this.DateOfBirth == DateTime.MaxValue)
        {
            memberNames.Add("DateOfBirth");
            yield return new ValidationResult("Invalid date, please enter your date of birth", memberNames);
        }
        else if (this.DateOfBirth == DateTime.MinValue)
        {
            memberNames.Add("DateOfBirth");
            yield return new ValidationResult("Invalid date, please enter your date of birth", memberNames);
        }

        if (!this.Age.HasValue)
        {
            memberNames.Add("DateOfBirth");
            yield return new ValidationResult("Invalid date, please enter your date of birth", memberNames);
        }
        else
        {
            if (this.Age < 18 || this.Age > 75)
            {
                memberNames.Add("DateOfBirth");
                yield return new ValidationResult("Age must be between 18 and 75 years", memberNames);
            }
        }

        if (!this.Gender.HasValue)
        {
            memberNames.Add("Gender");
            yield return new ValidationResult("This field is required", memberNames);
        }

        if (!(this.Age >= 60))
        {
            yield break;
        }

        // similarly many more validation checks - if-else conditions
    }


texts: Loading objects for users, roles, and groups from a query with LEFT OUTER JOINs

texts:
I have this function that returns me a list of users with their roles and groups. As you can see, this is how I fetch and create list of objects. I'm wondering whether this is a good approach and what parts should be improved. I'm not that experienced with PHP so I would appreciate code samples.

I'm also wondering how good an approach it is to first get all users and then make another prepared statement to get user roles and groups. That would mean I will have big number of database calls, so I think it's a bad idea.

    $stmt = $mysqli->prepare("SELECT u.id, u.firstName, u.lastName, u.email,
        u.phoneNumber, u.address, u.birthDate, ur.roleName, cg.id, cg.name FROM users as u
        LEFT OUTER JOIN user_role as ur ON u.id = ur.userId
        LEFT OUTER JOIN user_group as ug on ug.userId = u.id
        LEFT OUTER JOIN control_group as cg on cg.id = ug.groupId WHERE u.id != ?");
    $stmt->bind_param("i", $_SESSION["id"]);
    $stmt->execute();
    $stmt->bind_result($id, $firstName, $lastName, $email, $phoneNumber,
        $address, $birthDate, $roleName, $groupId, $groupName);
    $users = array();

    while ($stmt->fetch()) {
        if (empty($users[$id])) {
            $users[$id] = array(
                'id' => $id,
                'firstName' => $firstName,
                'lastName' => $lastName,
                'email' => $email,
                'phoneNumber' => $phoneNumber,
                'address' => $address,
                'birthDate' => $birthDate,
                'roles' => array(),
                'groups' => array()
            );
        }
        if ($roleName) {
            $found = false;
            foreach ($users[$id]['roles'] as $role) {
                if($role['roleName'] == $roleName){
                    $found = true;
                    break;
                }
            }
            if($found == false)
                $users[$id]['roles'][] = array(
                    'roleName' => $roleName
                );
         }

        if ($groupId) {
            $found = false;
            foreach ($users[$id]['groups'] as $group) {
                if($group['groupName'] == $groupName){
                    $found = true;
                    break;
                }
            }
            if($found == false)
                $users[$id]['groups'][] = array(
                    'groupName' => $groupName
                );
         }
    }

    $stmt->close();
    $mysqli->close();
    echo json_encode($users);

This is the response I get, only thing that I want improve is item index, as you can see in my example as index I have item id, I would like to get correct index starting from 0.


texts: Shorten dict comprehension with repeated operation

texts:
dc = {line.split('=')[0]: line.split('=')[1] for line in txt}

Below avoids duplication but is even longer:
dc = {k: v for line in txt for k, v in
      zip(*map(lambda x: [x], line.split('=')))}

Any better way? Just without any imports.

Context: with open('config.txt', 'r') as f: txt = f.read().split('\n')
a=1
bc=sea

>>> {'a': '1', 'bc': 'sea'}  # desired output; values should be string


texts: LeetCode: Queue Reconstruction by Height C#

texts:
https://leetcode.com/problems/queue-reconstruction-by-height/

  Suppose you have a random list of people standing in a queue. Each
  person is described by a pair of integers \$(h, k)\$, where \$h\$ is the
  height of the person and \$k\$ is the number of people in front of this
  person who have a height greater than or equal to \$h\$. Write an
  algorithm to reconstruct the queue.

  Note: The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

Please review for performance

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace SortingQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/queue-reconstruction-by-height/
    /// </summary>
    [TestClass]
    public class ReconstructQueueTest
    {
        [TestMethod]
        public void ReconstructQueueExampleTest()
        {
            int[][] people = new int[6][];
            people[0] = new[] { 7, 0 };
            people[1] = new[] { 4, 4 };
            people[2] = new[] { 7, 1 };
            people[3] = new[] { 5, 0 };
            people[4] = new[] { 6, 1 };
            people[5] = new[] { 5, 2 };

            int[][] expected = new int[6][];
            expected[0] = new[] { 5, 0 };
            expected[1] = new[] { 7, 0 };
            expected[2] = new[] { 5, 2 };
            expected[3] = new[] { 6, 1 };
            expected[4] = new[] { 4, 4 };
            expected[5] = new[] { 7, 1 };
            int[][] res = ReconstructQueueClass.ReconstructQueue(people);
            for (var index = 0; index < res.Length; index++)
            {
                CollectionAssert.AreEqual(expected[index], res[index]);
            }
        }
    }

    public class ReconstructQueueClass
    {
        public static int[][] ReconstructQueue(int[][] people)
        {
            int[][] res = new int[people.Length][];
            Array.Sort(people, new PairComparer());

            List<int> list = new List<int>();

            for (int i = 0; i < people.Length; i++)
            {
                list.Add(i); //a list of indices 0,1,2,3,4...
                res[i] = new int[2];
            }

            for (int i = 0; i < people.Length; i++)
            {
                int index = list[people[i][1]]; //the index in the result is the number of people before you
                res[index][0] = people[i][0];
                res[index][1] = people[i][1];
                list.RemoveAt(people[i][1]); // we remove the index from the list so we keep only the un used ones
            }
            return res;
        }
    }

    /// <summary>
    /// sort the people, have min height first
    /// for the same height for example 5,0 and 5,2
    /// 5,2 is before 5,0
    /// </summary>
    public class PairComparer : IComparer<int[]>
    {
        public int Compare(int[] x, int[] y)
        {
            if (x[0] != y[0])
            {
                return x[0] - y[0];// we want min value first
            }
            return y[1] - x[1];
        }
    }
}


texts: Send Response To Browser without DB save confirmation

texts:
Just reviewing my own code and noticed that I'm saving info in the DB and WAITING for that to respond before I send info to the browser, although I'm wondering if it would be more performant to not wait...

For example, let's update a user's email address.

Currently, I get a user, update their info, save and wait for confirmation, then send the browser the data:

UserModel.findById(user._id)
  .then(function(user){
    user.email = 'newemail@google.com';
    return user.save();
  })
  .then(function(user){
    res.send(user.email)
  })

But the user data is already edited, and I already have it, so can't I send the browser the data and save to MongoDB at the same time...?

UserModel.findById(user._id)
  .then(function(user){
    user.email = 'newemail@google.com';
    user.save();
    res.send(user.email)
  })

I guess, now that I'm typing it out, the only issue (I can imagine) would be if there was an error with the saving operation at the DB level... How often does that even happen? It's really only a matter of milliseconds, but just wondering if anyone has done this or can share a horror store of why I definitely should not do this.


texts:
I'm pretty new to C# and have decided that I wanted to make a program that calculate the multiplication table of a selected number to practice on loops etc. I'm pretty satisfied, but I wondered if there is anything I can do to make the code better and more concise.

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

namespace Multiplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Write a number and I'll calculate the multiplication table of the number");
            int userValue_number = int.Parse(Console.ReadLine());

            Console.WriteLine("How far do you want to go? E.g. 12, then {0} x 12 is the highest I will go ", userValue_number);
            int userValue_length = int.Parse(Console.ReadLine());

            int n = userValue_number;
            int i = 1;
            while (n <= (userValue_number * userValue_length))
            {
                Console.WriteLine("{0} x {1} = {2}", i, userValue_number, n);
                n=n+userValue_number;
                i++;
            }
            Console.ReadLine();
        }
    }
}


texts:
I'm trying to improve my Color Picker code.  It works like Photoshop and I don't want to use a library.

    for(var yColor = 0; yColor < 255; yColor++)
    {
        var r = 255,
            g = 0,
            b = 0;
        for(var xColor = 0; xColor < 255; xColor++)
        {
            if(r == 255 && g < 255 && b == 0) g += 6;
            else if(r > 0 && g == 255 && b == 0) r -= 6;
            else if(r == 0 && g == 255 && b < 255) b += 6;
            else if(r == 0 && g > 0 && b == 255) g -= 6;
            else if(r < 255 && g == 0 && b == 255) r += 6;
            else if(r == 255 && g == 0 && b > 0) b -= 6;

            if(r > 255) r = 255;
            else if(r < 0) r = 0;
            else if(g > 255) g = 255;
            else if(g < 0) g = 0;
            else if(b > 255) b = 255;
            else if(b < 0) b = 0;

            var rG = r + yColor > 255 ? 255 : r + yColor;
            var gG = g + yColor > 255 ? 255 : g + yColor;
            var bG = b + yColor > 255 ? 255 : b + yColor;

            GAContext.beginPath();
            GAContext.fillStyle = "rgb(" + rG + ", " + gG + ", " + bG + ")";
            GAContext.rect(xColor, yColor, 1, 1);
            GAContext.fill();
        }
    }


texts: Simple Deferred / Promise pattern in JavaScript

texts:
I've wrote a very simple implementation of Deferred / Promise pattern (inspired by jQuery's $.deferred) for my tiny project (which does not use jQuery)

It can handle multiply onSuccess an onFail callbacks with result caching. Example in comments above the code.

/**
 * defer() returns methods:
 *      resolve(data) - request is successfully resolved (returns nothing)
 *      reject(msg) - request if failed (returns nothing)
 *      promise() - returns promise function
 *
 * promise() returns methods:
 *      done(successfulCallback) - add on successful callback (returns nothing)
 *      fail(failCallback) - add on fail callback (returns nothing)
 *
 * Example:
 *
 * function someHeavyRequest(url) {
 *      var d = defer();
 *      doHeavyRequest(url,
 *          function (data) {
 *              // on success
 *              // ...do something
 *              d.resolve(data);
 *          },
 *          function (data) {
 *              // on fail
 *              // ...do something
 *              d.reject(data);
 *          });
 *      return d.promise();
 * }
 *
 * var req = someHeavyRequest("http://some.url/of/request/");
 *
 * req.done(function (data) {
 *      console.log("We got it!");
 *      console.log(data);
 * });
 *
 * req.done(function (data) {
 *      console.log("We got it again without new request!");
 *      console.log(data);
 * });
 *
 * req.fail(function (data) {
 *      console.error("Something wrong");
 *      console.error(data);
 * });
 *
 */
function defer () {
    var status = 0, // 0 = in progress / 1 = successful / -1 = fail
        callbacks = { done: [], fail: [] },
        args = { resolve: [], reject: [] },
        execute = function (callbacks, args) {
            var f;
            while (callbacks.length) {
                f = callbacks.shift();
                if (f) f.apply(this, args);
            }
        };

    return {
        promise: function () {
            return {
                done: function (callback) {
                    callbacks.done.push(callback);
                    if (status === 1) {
                        execute(callbacks.done, args.resolve);
                    }
                },

                fail: function (callback) {
                    callbacks.fail.push(callback);
                    if (status === -1) {
                        execute(callbacks.fail,args.reject);
                    }
                }
            };
        },

        resolve: function () {
            status = 1;
            args.resolve = arguments;
            execute(callbacks.done, args.resolve);
        },

        reject: function () {
            status = -1;
            args.reject = arguments;
            execute(callbacks.fail, args.reject);
        }
    };
}


texts: Constructing query conditions from answers that may be null

texts:
I was thinking about this after recently reading about the new Null Conditional Operators in C# 6.0. So here is my code that I am currently working on...

    if (!string.IsNullOrWhiteSpace(question2Answer))
    {
        stringbuild.Append($" and ProdUsers = {Regex.Match(question2Answer, @"\d+").Value}");
    }
    if (!string.IsNullOrWhiteSpace(question3Answer))
    {
        stringbuild.Append($" and ProdFullyOnline = '{(int)Enum.Parse(typeof(YesNo), question3Answer, true)}'");
    }
    if (!string.IsNullOrWhiteSpace(question4Answer))
    {
        stringbuild.Append($" and ProdMultiCurrency = '{(int)Enum.Parse(typeof(YesNo), question4Answer, true)}'");
    }
    if (!string.IsNullOrWhiteSpace(question5Answer))
    {
        stringbuild.Append($" and ProdPrice <= {question5Answer}");
    }

As you can see, it is fairly repetitive. So my question, is would there be a better way of checking whether questionXAnswer is null or not and then using the not null value on the string builder. And it would be nice to use the new null conditional operators with C# 6.0, if possible.

The main reason for me posting this however, is to solve the repetition problem if possible. And obviously, any other ways I could improve this would be appreciated too!


texts:
I'm practicing SOLID principles and the concept of making a clear distinction between an object's private and public interfaces.

I made the conscious choice to extract complex logic into private methods to hide the implementation details from the public interface. I did this because I heard that it's best for public methods to clearly indicate what they're doing so that others have an easier time figuring out what the program is doing.

I watched a talk by Ben Orenstein, during which he revealed that he does not test private methods very often. I don't know if this is a good idea or not, but I trust his practices. How do you all feel about this? For those of you who agree with him, under what circumstances DO you test your private methods? How do you decide it's important enough to test?

The specs:

require_relative '../lib/oranges'
require 'spec_helper'

describe OrangeTree do
  let(:orange_tree) { OrangeTree.new }

  it 'starts with an age of 0' do
    expect(orange_tree.age).to eq 0
  end

  it 'starts with an height of 0' do
    expect(orange_tree.height).to eq 0
  end

  it 'increases age by one when we call age!' do
    orange_tree.age!

    expect(orange_tree.age).to eq 1
  end

  it 'can be aged twice' do
    age_by_years(2)

    expect(orange_tree.age).to eq 2
  end

  it 'grows 2 feet each year' do
    orange_tree.age!

    expect(orange_tree.height).to eq 2
  end

  it 'dies after it reaches its lifespan' do
    age_by_years(15)

    expect(orange_tree.send(:dead?)).to eq true
  end

  it 'only has oranges' do
    expect(orange_tree.oranges).to eq []
  end

  it 'only grows oranges after reaches 3 years old' do
    assert_emptiness_when_young
    orange_tree.age!

    all_oranges?(orange_tree)
  end

  it 'can be picked' do
    age_by_years(3)
    orange_tree.oranges.pick!

    expect(orange_tree.oranges.count).to eq 2
  end

  private

  def all_oranges?(orange_tree)
    orange_tree.oranges.each do |orange|
      expect(orange).to be_an_instance_of(Orange)
    end
  end

  def assert_emptiness_when_young
    orange_tree.age!

    expect(orange_tree.oranges).to eq []

    orange_tree.age!

    expect(orange_tree.oranges).to eq []
  end

  def age_by_years(number_of_years)
    number_of_years.times { orange_tree.age! }
  end
end

The main program:

class Orange
end

class OrangeTree
  attr_reader :age, :height, :oranges

  LIFESPAN = 15
  FRUIT_BEARING_AGE = 3

  def initialize
    @age = 0
    @height = 0
    @oranges = []
  end

  def age!
    increase_age_by_one_year
    increase_height_by_two_feet
    add_three_oranges_to_tree if reached_age?(FRUIT_BEARING_AGE)
  end

  def dead?
    reached_age?(LIFESPAN)
  end

  private

  def reached_age?(requirement)
    age >= requirement
  end

  def increase_age_by_one_year
    @age += 1
  end

  def increase_height_by_two_feet
    @height += 2
  end

  def add_three_oranges_to_tree
    3.times { oranges << Orange.new }
  end
end

class Array
  def pick!
    pop
  end
end

Any suggestions?


texts:
Below is the code I have for a RandomForest multiclass-classification model. I am reading from a CSV file and doing various transformations as seen in the code. I am planning to run this in a Spark cluster with lots of data (at least 6 million rows of data with 50 features). I can get sufficient amount of RAM and cores so that is not a problem.

What parts of my code can be improved for scalability/efficiency in terms of spark?

def main(args: Array[String]): Unit = {

  val conf = new SparkConf().setAppName("MLApp").setMaster("local")
  val sc = new SparkContext(conf)
  val sqlContext = new SQLContext(sc)
  println(s"Running Spark Version ${sc.version}")

  // Need to predict 2 classes
  val cols_to_predict=Array("Label1","Label2")

  // ID col
  val omit_cols=Array("Key")

  // reading the csv file
  val data = sqlContext.read
.format("com.databricks.spark.csv")
.option("header", "true") // Use first line of all files as header
.option("inferSchema", "true") // Automatically infer data types
.load("abc.csv")
    .cache()
  println(data.printSchema())

  // creating a features DF by droppping the labels so that I can run all
  // the cols through String Indexer
  val features=data.drop("Label1").drop("Label2").drop("Key")

  // Since I do not know my max categories possible, I find it out
  // and use it for maxBins parameter in RF
  val distinct_col_counts=features.columns.map(x => data.select(x).distinct().count ).max

  val transformers: Array[org.apache.spark.ml.PipelineStage] = features.columns.map(
    cname => new StringIndexer().setInputCol(cname).setOutputCol(s"${cname}_index").fit(features)
  )
  val assembler  = new VectorAssembler()
    .setInputCols(features.columns.map(cname => s"${cname}_index"))
    .setOutputCol("features")

  val labelIndexer2 = new StringIndexer()
    .setInputCol("prog_label2")
    .setOutputCol("Label2")
    .fit(data)

  val labelIndexer1 = new StringIndexer()
    .setInputCol("orig_label1")
    .setOutputCol("Label1")
    .fit(data)

  val rf = new RandomForestClassifier()
    .setLabelCol("Label1")
    .setFeaturesCol("features")
    .setNumTrees(100)
    .setMaxBins(distinct_col_counts.toInt)

  val labelConverter = new IndexToString()
    .setInputCol("prediction")
    .setOutputCol("predictedLabel")
    .setLabels(labelIndexer1.labels)

  // Split into train and test
  val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))
  trainingData.cache()
  testData.cache()

  // Running only for one label for now Label1
  val stages: Array[org.apache.spark.ml.PipelineStage] =transformers :+ labelIndexer1 :+ assembler :+ rf :+ labelConverter //:+ labelIndexer2

  val pipeline=new Pipeline().setStages(stages)
  val model=pipeline.fit(trainingData)
  val predictions = model.transform(testData)

  val evaluator = new MulticlassClassificationEvaluator()
    .setLabelCol("Label1")
    .setPredictionCol("prediction")
    .setMetricName("precision")
  val accuracy = evaluator.evaluate(predictions)
  println("Accuracy  = " + (accuracy))
  println("Test Error = " + (1.0 - accuracy))

  }

}


texts: Unit Test case for services method in angular

texts:
I want to write the test case for Service class.
My Service Class dynamic-form.service.ts
import { HttpClient, HttpBackend } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class DynamicFormService {

  private http: HttpClient;

  constructor(private handler: HttpBackend
  ) {
    this.http = new HttpClient(handler);
  }

  async getDynamicFormData(paramName: any, data?: any): Promise<any> {
    return await this.http.get(this.HostUrl + paramName).toPromise();
  }

  async getTaskByWorkflowId(paramNameWithId): Promise<any> {
    return await this.http.get(this.HostUrl + paramNameWithId).toPromise();
  }

  async getAccontType(paramNameWithId): Promise<any> {
    return await this.http.get(this.HostUrl + paramNameWithId).toPromise();
  }
}

My dynamic-form.spec.ts are as follows
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed} from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';

import { DynamicFormServiceService } from './dynamic-form-service.service';

describe('DynamicFormServiceService', () => {
  let service: DynamicFormServiceService;
  let httpMock: HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])]
    });
    service = TestBed.inject(DynamicFormServiceService);
    httpMock= TestBed.inject(HttpTestingController);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

I have written one of service method test case as follows
it('should call getAccontType', ()=>{
    const data = [
      {
        "id": 4,
        "name": "24hrs"
      },
      {
        "id": 5,
        "name": "48hrs"
      }];
    service.getAccontType(`account-type`).then(res=> expect(res.length).toBeGreaterThan(0));
    const request = httpMock.expectOne(`http://localhost:8080/account-type`);
    expect(request.request.method).toBe('GET');
    request.flush(data);
    httpMock.verify();
  });

I want to know it is good way to write test-case this way or I can do better. Any suggestion.


texts:
I've got a solution for Project Euler's problem 45.

  Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

  $$\begin{array}{lll}
\textrm{Triangle}   & T_n=n(n+1)/2   & 1, 3, 6, 10, 15, \ldots \\
\textrm{Pentagonal}   & P_n=n(3n−1)/2   & 1, 5, 12, 22, 35, \ldots \\
\textrm{Hexagonal}   & H_n=n(2n−1)   & 1, 6, 15, 28, 45, \ldots \\
\end{array}$$

  It can be verified that \$T_{285} = P_{165} = H_{143} = 40755\$.

  Find the next triangle number that is also pentagonal and hexagonal.

It runs in under a second (so performance isn't an issue), but I can't help but feel that I'm doing it in an ugly way; I feel like I'm missing some sort of builtin like zipWith3.

Here's my current code:

tris  = scanl (+) 1 [2..]
pents = scanl (+) 1 [4,7..]
hexes = scanl (+) 1 [5,9..]

These are just the infinite lists of triangle, pentagonal, and hexagonal numbers.

findSame :: [Int] -> [Int] -> [Int] -> [Int]
findSame (x:xs) (y:ys) (z:zs)
    | (x==y) && (x==z) = x:(findSame xs ys zs)
    | (x<=y) && (x<=z) = findSame xs (y:ys) (z:zs)
    | (y<=x) && (y<=z) = findSame (x:xs) ys (z:zs)
    | (z<=x) && (z<=y) = findSame (x:xs) (y:ys) zs

This goes through the 3 lists at the same time and puts the numbers in a new list if they're equal (this also creates an infinite list).

This is the part where I think I could improve - this ended up looking relatively ugly.

main = do
    print $ last $ take 3 $ findSame tris pents hexes

This is just the main method and is pretty straightforward.

Any feedback on this code, especially the middle portion, would be very appreciated.  Creating code that looks clean is what motivates me to keep doing these, so ending up with this more brute-force approach leaves me hanging a bit.


texts:
I'm learning Python and have found this problem from Google Code Jam:

How many mkdir commands does it take to construct a given directory tree:
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each case begins with a line containing two integers N and M, separated by a space.
The next N lines each give the path of one directory that already exists on your computer. This list will include every directory already on your computer other than the root directory. (The root directory is on every computer, so there is no need to list it explicitly.)
The next M lines each give the path of one directory that you want to create.
Each of the paths in the input is formatted as in the problem statement above. Specifically, a path consists of one or more lower-case alpha-numeric strings (i.e., strings containing only the symbols 'a'-'z' and '0'-'9'), each preceded by a single forward slash. These alpha-numeric strings are never empty.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of mkdir you need.

I've solved it by writing code shown below, and it works correctly, but how can I make it faster?
import sys

def split_path(path_file,line_count_to_be_read):
    for i in range(line_count_to_be_read):
        # Get the Path line
        line = path_file.readline()
        # Skip the first slash
        line = line[1:]
        line = line.strip()
        splited = line.split('/')
        # make each subpaths from the source path
        for j in range(1,len(splited)+1):
            joined = "/".join(splited[:j])
            yield joined

def main():

    file_name = ""

    try:
        file_name = sys.argv[1]
    except IndexError:
        file_name = "A-small-practice.in"

    with open(file_name) as path_file:

        # skip the first line
        line = path_file.readline()
        total_testcases = int(line) # Number of Test Cases - Unused

        case_no = 0

        while True:
            line = path_file.readline()

            if not line:
                break

            # Get Existing path and New path count
            existing_count,new_count = line.split()
            existing_count = int(existing_count)
            new_count = int(new_count)

            # Split Every Path and Make all Subpaths
            existing_paths = list(split_path(path_file,existing_count)) # Existing Subpaths
            new_paths = list(split_path(path_file,new_count)) # New Subpaths

            # Remove all paths that is in Existing list from the New list
            new_mkdir_set = set(new_paths) - set(existing_paths)

            case_no += 1

            # length of new_set contains number of needed mkdir(s)
            print "Case #{0}: {1}".format(case_no,len(new_mkdir_set))

if __name__ == '__main__':
    main()


texts:
I'm trying to use JOGL and Java to draw a hexagonal based game.  I currently have it so that it displays correctly, however it seems to run poorly and needs optimization.

Currently I create a glList that has objects for the cells, the cell walls and the player.  When I draw one these objects, I push a new matrix, translate to the position of the object, rotate (if necessary), call the object from the list and then pop the matrix.

Method to create glList:

    private void HexList(GLAutoDrawable drawable){
       final GL2 gl = drawable.getGL().getGL2();

       floor = gl.glGenLists(3);
       gl.glNewList(floor, GL2.GL_COMPILE);

       gl.glBegin(GL2.GL_POLYGON);
       //gl.glNormal3f(0f, 0f, -1f);
       for(int i = 0; i < 6; i++){
            float[] vert = ToolBox.GetCorner(i, new float[]{0f, 0f}, board.width, board.height);
           gl.glVertex3f(vert[0], vert[1], 0f);
       }
       gl.glEnd();
       gl.glEndList();

       wall = floor + 1;
       gl.glNewList(wall, GL2.GL_COMPILE);

       float[] j = ToolBox.GetCorner(0, new float[]{0f, 0f}, board.width, board.height);
       float[] i = ToolBox.GetCorner(1, new float[]{0f, 0f}, board.width, board.height);
       float wallHeight = board.height / 2;
       gl.glBegin(GL2.GL_TRIANGLES);

       gl.glVertex3f(j[0], j[1], wallHeight);
       gl.glVertex3f(j[0], j[1], 0);
       gl.glVertex3f(i[0], i[1], 0);

       gl.glVertex3f(i[0], i[1], wallHeight);
       gl.glVertex3f(j[0], j[1], wallHeight);
       gl.glVertex3f(i[0], i[1], 0);

       gl.glEnd();
       gl.glEndList();

       player = wall + 1;
       gl.glNewList(player, GL2.GL_COMPILE);

       float[] top = new float[]{0, board.height / 4};
       float[] right = new float[]{board.height / 4, -board.height / 4};
       float[] left = new float[]{-board.height / 4, -board.height / 4};
       float playerHeight = 3 * board.height / 4;
       gl.glBegin(GL2.GL_TRIANGLES);

       //front side
       gl.glVertex3f(left[0], left[1], 0);
       gl.glVertex3f(right[0], right[1], 0);
       gl.glVertex3f(right[0], right[1], playerHeight);

       gl.glVertex3f(right[0], right[1], playerHeight);
       gl.glVertex3f(left[0], left[1], playerHeight);
       gl.glVertex3f(left[0], left[1], 0);

       //right side
       gl.glVertex3f(right[0], right[1], 0);
       gl.glVertex3f(top[0], top[1], 0);
       gl.glVertex3f(top[0], top[1], playerHeight);

       gl.glVertex3f(top[0], top[1], playerHeight);
       gl.glVertex3f(right[0], right[1], playerHeight);
       gl.glVertex3f(right[0], right[1], 0);

       //left side
       gl.glVertex3f(top[0], top[1], 0);
       gl.glVertex3f(left[0], left[1], 0);
       gl.glVertex3f(left[0], left[1], playerHeight);

       gl.glVertex3f(left[0], left[1], playerHeight);
       gl.glVertex3f(top[0], top[1], playerHeight);
       gl.glVertex3f(top[0], top[1], 0);

       gl.glEnd();
       gl.glEndList();

   }

Display Method:

    public void display(GLAutoDrawable drawable) {

       GameLogic(drawable);

       final GL2 gl = drawable.getGL().getGL2();

       CreateCameraView(gl);

        gl.glClearDepthf(1.0f);
       gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);

       gl.glEnable(GL2.GL_VERTEX_PROGRAM_POINT_SIZE);

       gl.glPushMatrix();

       for(int i = 0; i < board.size; i++){
           for(int j = 0; j < board.size; j++){
               Hexagon hex = board.testBoard[i][j];

               if(hex.path){
                   gl.glColor3d((hex.path ? (.5 + .0 * Math.random()) : .25), .75, .5);

                   gl.glPushMatrix();
                   gl.glTranslatef(hex.center[0], hex.center[1], 0f);
                   gl.glCallList(floor);
                   gl.glPopMatrix();

                  DrawWalls(hex, gl);
               }
           }
       }

       DrawPlayer(gl);

       gl.glPopMatrix();
       gl.glFlush();

Thanks for you help!


texts: Is there any more efficient way to code this “2 Sum” Questions

texts:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based. Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.

If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.

twoSum : function(A, B){
        var tempA = A;
        var index1 = [];
        var index2 = [];
        var Results = [];

        for(var i = 0; i < A.length - 1; i++){
            var temp = B - A[i];
            for(var j = i; j < A.length - 1; j++){
                if(temp == A[j]){
                    if(j - i > 0){
                        if(j < Results[1] || Results.length == 0){
                            if(A[j] != A[Results[1]-1] && A[i] != A[Results[0]-1]){
                                Results[0] = i + 1;
                                Results[1] = j + 1;
                            }
                        }
                    }
                }
            }
        }
        return Results;
    }```


texts:
I wrote a simple sort algorithm in JavaScript, but code climate is complaining its complexity being too high (currently sitting on 6 instead of 5, which is code climate wants).

I personally cannot see how it can be further simplified.

Can anyone help? The following algorithm sorts an array of numbers from largest to smallest.

function selectionSort(array) {
    let index = 0;
    let terminatingIndex = array.length - 1;
    let nextElementIndex = null;

    while (index < terminatingIndex) {
        nextElementIndex = index + 1;
        while (nextElementIndex <= terminatingIndex) {
            if (array[index] < array[nextElementIndex]) {
                [array[index], array[nextElementIndex]] = [array[nextElementIndex], array[index]];
            }
            nextElementIndex++;
        }
        index++;
    }
    console.log(`The sorted array is: ${array}`);
}


texts: A method for events callback with the correct "this"

texts:
What do you think of the following "utility" :

/**
 * Contextualize a method for callback
 *
 * @param    methodName      String Method name
 * @param    context         Object Context (this)
 * @param    mixed  OPTIONAL Argument to place at first
 * @param    mixed  OPTIONAL Argument to place at second (etc...)
 */
contextualize: function(methodName, context) {
    var otherArgs;
    if (
            (typeof context[methodName] === "undefined") ||
            !!!(context[methodName].constructor &&
                    context[methodName].call &&
                    context[methodName].apply)) {
        error("No " + methodName + " function defined");
    }
    otherArgs = $.makeArray(arguments).slice(2);
    return (function(obj, otherArgs) {
        return (function() {
            var args = [];
            $.merge(args, otherArgs);
            $.merge(args, $.makeArray(arguments));
            return (obj[methodName].apply(obj, args));
        });
    }(context, otherArgs));
},

For example, I use it to use the "fooBar" method of current object as callback of a click event, forcing a true as first argument :

$('#button').click(Utils.contextualize('fooBar', this, true));

That will use correctly the following method :

//....
fooBar: function(fromButton, event) {
    event.preventTarget();
    if (fromButton) {
      this.anotherMethod();
    }
    ...
},
//....


texts:
I have this sorting algorithm which takes an array of dictionary values:

guard var imageUrlString = anyImage.value as? [String:AnyObject] else { return }

I then loop through it, adding the values with the smallest Int key to a new array to be used afterward. Thus the values in this array of AnyObjects would go from 1 to n.

I was wondering if I could make it more concise.

var values = [AnyObject]()
var keys = [String]()
var Done = false
var j = 1

 while !Done {
    for i in imageUrlString {
        let key = Int(String(i.key.last!))

        if j == key {
            values.append(i.value)
            keys.append(i.key)
            print(i, " This is the i for in if ")
            if imageUrlString.count == j {
                print("Done yet: yes", values[0], " ", values[3])
                Done = true
                break;
            }
            j+=1
        } else {
            print("No,,.")
        }
    }
}


texts: Iter 2: Reusable, robust c++ std::hash for GMP's big integer type

texts:
This is the 2nd iteration of a code review. The 1st iteration (completed) is at
Iter 1: Reusable, robust c++ std::hash<mpz_class> for GMP's big integer type
1. Goal
My intention is to provide a fast hashing algorithm to hash GMP's big integer type mpz_class and mpz_t so I can use these types as keys for an unordered_map. The code shall be reusable for others.
2. Current Approach
Since C++17, the standard library provides the specialization hash<string_view> which is used to produce the initial hash value.
First, the magnitude data of the big integer is wrapped into a string_view and then its hash value is calculated using hash<string_view>. This produces an initial hash value which only depends on the magnitude, but not on the sign, of the big integer.
To keep the hashes of positive and negative big integers different, the initial hash value is scrambled once for negative big integers only.
3. Code
File hash_mpz.h:
#ifndef HASH_MPZ_H_
#define HASH_MPZ_H_

#include <gmpxx.h>

namespace std {

template<> struct hash<mpz_srcptr> {
    size_t operator()(const mpz_srcptr x) const;
};

template<> struct hash<mpz_t> {
    size_t operator()(const mpz_t x) const;
};

template<> struct hash<mpz_class> {
    size_t operator()(const mpz_class &x) const;
};

}

#endif /* HASH_MPZ_H_ */

File hash_mpz.cpp:
#include "hash_mpz.h"
#include <cstddef>
#include <string_view>

constexpr size_t pi_size_t() {
    if (sizeof(size_t) == 4) {
        return 0xc90fdaa2; // floor(pi/4 * 2^32)
    } else if (sizeof(size_t) == 8) {
        return 0xc90fdaa22168c234; // floor(pi/4 * 2^64)
    } else {
        throw std::logic_error(
                "sizeof(size_t) not supported. only 32 or 64 bits are supported. you can easily add the required code for other sizes.");
    }
}

inline size_t scramble(size_t v) {
    return v ^ (pi_size_t() + (v << 6) + (v >> 2));
}

namespace std {

size_t std::hash<mpz_srcptr>::operator()(const mpz_srcptr x) const {
    string_view view { reinterpret_cast<char*>(x->_mp_d), abs(x->_mp_size)
            * sizeof(mp_limb_t) };
    size_t result = hash<string_view> { }(view);

    // produce different hashes for negative x
    if (x->_mp_size < 0) {
        result = scramble(result);
    }

    return result;
}

size_t hash<mpz_t>::operator()(const mpz_t x) const {
    return hash<mpz_srcptr> { }(static_cast<mpz_srcptr>(x));
}

size_t hash<mpz_class>::operator()(const mpz_class &x) const {
    return hash<mpz_srcptr> { }(x.get_mpz_t());
}

}

File main.cpp:
#include <iostream>
#include <gmpxx.h>
#include <unordered_map>

#include "hash_mpz.h"

using namespace std;

int main() {
    mpz_class a;

    mpz_ui_pow_ui(a.get_mpz_t(), 168, 16);

    cout << "a      : " << a << endl;
    cout << "hash( a): " << (hash<mpz_class> { }(a)) << endl;
    cout << "hash(-a): " << (hash<mpz_class> { }(-a)) << endl;

    unordered_map<mpz_class, int> map;
    map[a] = 2;
    cout << "map[a] : " << map[a] << endl;

    return 0;
}

4. Question
Is there anything which can benefit from further improvement?


texts: Multiplication of any two matrices using lists and for in loop

texts:
I've just started learning Python and after few lessons I grasped the idea of lists and loop and decided to create my first project.

Objective: Calculate multiplication of any two matrices from user's input.

The code is working as intended but as this is my first one, I would be happy for some hints as far what is written well and what is e.g. hard to read by someone, wrongly used method or unnecessary complication.

 I specifically wanted to stay within basic knowledge and not use for example NumPy for learning reason. There will be time for libraries in future.

Thanks all in advance and my code is below:

# This program multiplicates two matrices of any number of rows and columns.
# The matrix elements are filled by User
# The result is calculated and saved as list

print('MATRIX MULTIPLICATION\n')

# Ask user for dimensions of first matrix
r = int(input("Matrix1: Number of rows?: "))
c = int(input("Matrix1: Number of columns?: "))

# Print design of first Matrix for better understanding of elements' naming convention
print('''\nElements of matrix1:''')
element = ''                            # Later will be used to construct each row of the matrix
for vr in range(0, r):                  # vr - variable row
    for vc in range(0, c):              # vc - variable column
        element += 'M' + str(vr + 1) + str(vc + 1) + ' '
    print('|', element, '\b|')
    element = ''

# Create empty Matrix1 and fill it with user input element by element
Matrix1 = [[] for vr in range(0, r)]
for vr in range(0, r):
    Matrix1[vr] = [0 for vc in range(0, c)]

for vr in range(0, r):
    for vc in range(0, c):
        Matrix1[vr][vc] = int(input('M' + str(vr + 1) + str(vc + 1) + ': '))    # + 1 because vr and vc starts at 0 and we want elements be named from 1

# Ask the user for dimension of second matrix
v = int(input("Matrix2: Number of columns?: "))     # Only for columns since M2 rows = M1 columns by definition
print('''\nElements of matrix Matrix2:''')
element = ''
for vr in range(0, c):                  # vr in c because Matrix 2 must have the same number of rows as Matrix1 columns.
    for vc in range(0, v):
        element += 'M' + str(vr + 1) + str(vc + 1) + ' '
    print('|', element, '\b|')
    element = ''

# Create Empty Matrix2 and fill it with user input element by element
Matrix2 = [[] for vr in range(0, c)]
for vr in range(0, c):
    Matrix2[vr] = [0 for vc in range(0, v)]

for vr in range(0, c):
    for vc in range(0, v):
        Matrix2[vr][vc] = int(input('M' + str(vr + 1) + str(vc + 1) + ': '))

# Create empty Product Matrix for Result of multiplication of Matrix1 and Matrix2
Product = [[] for vr in range(0, r)]                # Number of rows defined by number of rows in Matrix1
for vr in range(0, r):
    Product[vr] = [0 for columns in range(v)]       # Number of columns defined by number of columns in Matrix2

# Calculate the Product of two tables
Products = 0            # dummy variable for calculating sum of product of each row and column
for vv in range(0, v):
    for vr in range(0, r):
        for vc in range(0, c):
            Products += Matrix1[vr][vc] * Matrix2[vc][vv]
        Product[vr][vv] = Products
        Products = 0        # clear the variable when looped for whole column of Matrix2

print('Matrix1: ', Matrix1)
print('Matrix2: ', Matrix2)
print('Result of Matrix Multiplication:', Product)

# Footnotes
print('\n\nCreated by: MK')
input('Press "Enter" to Exit')        # Easy way to Exit program If run from script


texts: Converting from `std::array>` to `void*`

texts:
I'm doing some work with Vulkan, in this I need to pass a set of values of various types.
Currently I'm using std::array<std::variant<>> in my interface, but I must pass Vulkan a void*.
To convert to the void* I use this function:
template <uint32_t Size>
void* voidArray(std::array<std::variant<uint32_t,float>,Size>& array, uint32_t size) {
    char* bytes = new char[size];
    uint32_t byteCounter = 0;
    for(uint32_t i=0;i<array.size();++i) {
        if(float* flt = std::get_if<float>(&array[i])) {
            *reinterpret_cast<float*>(bytes+byteCounter) = *flt;
            byteCounter += sizeof(float);
        }
        else if(uint32_t* uin = std::get_if<uint32_t>(&array[i])) {
            *reinterpret_cast<uint32_t*>(bytes+byteCounter) = *uin;
            byteCounter += sizeof(uint32_t);
        }
    }
    void* data = static_cast<void*>(bytes);
    return data;
}

I get the size variable earlier within a larger function (names are a little more context specific):
// std::array<std::variant<uint32_t,float>,NumPushConstants>& pushConstants
std::optional<uint32_t> pushConstantSize = std::nullopt; // later used for `size`
auto size_fn = [](auto variant) -> uint32_t {
    using T = std::decay_t<decltype(variant)>;
    if constexpr (std::is_same_v<uint32_t, T>) { return sizeof(uint32_t); }
    if constexpr (std::is_same_v<float, T>) { return sizeof(float);}
};
pushConstantSize = std::accumulate(pushConstants.begin(),pushConstants.end(),0,
    [size_fn](uint32_t acc, auto variant) { return std::move(acc) + std::visit(size_fn,variant); }
);

Both of these implementations, most prominently the first rouse my suspicion of being bad.
Are they bad? Is there a better way? Am I missing something?


texts: Finding minimum of a function dependent on a constant number

texts:
Question-

My approach

I noticed that the minimum of a row is when t=k-one of the numbers of that row.
Suppose in the above sample case,
t=4 which is 6-2.
Since we have to find the minimum maximum testing all k-no will give the solution.
Any tips to improve this technique as for cases where each number is unique and number of rows is high this will become slow?

plus stores unique k-no
curmax stores the current maximum for the current 't'.
ans is the minimum of all those maximums.

Code

#include<iostream>
#include<set>
using namespace std;
int main()
{
    set<int>plus;
    int n,k;
    cin>>n>>k;
    int a[n],b[n],c[n];
    for(int i=0;i<n;i++)
    {
        cin>>a[i]>>b[i]>>c[i];
        plus.insert(k-a[i]);
        plus.insert(k-b[i]);
        plus.insert(k-c[i]);
    }
    int ans=1000000000,curmax=-1,tempsum;
    for(auto x:plus)
    {
        curmax=-1;
        for(int i=0;i<n;i++)
        {
            tempsum=(a[i]+x)%k+(b[i]+x)%k+(c[i]+x)%k;
            if(tempsum>curmax)
                curmax=tempsum;
        }
        if(curmax<ans)
            ans=curmax;
    }
    cout<<ans;
}


texts: Formatting date difference in human-friendly terms

texts:
I've written a function to take the difference between two dates and display it in a particular format. I've used a lot of if-else statements, which seems a little messy. Is there a way to shorten this up? Would using the ternary operator make sense?

$date1 = '2018-04-30 10:36:29';
$date2 = '2018-04-30 10:35:29';

echo dateDiff($date1, $date2);

function dateDiff($date1, $date2)
{
    $date_1 = new DateTime($date1);
    $date_2 = new DateTime($date2);

    $diff = $date_1->diff($date_2);

    if($diff->days > 365){
      return $date_1->format('Y-m-d');
    }

    elseif($diff->days < 366 AND $diff->days > 7){
      return $date_1->format('M d');
    }

    elseif($diff->days > 2 AND $diff->days < 8){
      return $date_1->format('L - H:i');
    }

    elseif($diff->days == 2) return "Yesterday ".$date_1->format('H:i');

    elseif($diff->days < 2 AND $diff->days > 0 OR $diff->days == 0 AND $diff->h > 1) return $date_1->format('H:i');

    elseif($diff->days == 0 AND $diff->h < 1 AND $diff->i >= 1) return $diff->i." min ago";

    elseif($diff->days == 0 AND $diff->h < 1 AND $diff->i < 1) return "just now";

    else return $error = "Error!";

}


texts: Pythonic way to read csv files from a folder in repository

texts:
Background
In one of our repositories we have a folder called player_test where we store all player_test related .py files. We realized that there are certain static csv files we use to do some processing. So we decided to create a folder called player_test_input inside the player_test folder. The player_test_input should store all the csv files.
CODE
def get_player_call_logic_df() -> pd.DataFrame:
    df = pd.read_csv(
        "../dev/player-assignment/src/player_test/player_test_input/player_call_logic.csv"
    )
    return df

Issue
In the above function get_player_call_logic_df I read the csv using relative path.
However I am not sure if there is a more pythonic way to do this?
We use pathlib quite a bit in our codebase and avoid using relative path but was not sure how that would apply in this case. I am always trying to figure out how i can use the modern python features and best practices more.


texts:
I have the following function count.ones that takes in a data frame data.l in which the observations have been subdivided into bins defined by indices, a vector of consecutive indices x, and the length of the sliding window width over consecutive indices. The goal of this function is to slide over the indices and count the number of observations labeled as ones.

count.ones = function(x,data.l,width){
  labvec = data.l$lab
  indvec = data.l$index
  return(sapply(1:(length(x)-(width-1)),
                       function(j) sum(labvec[indvec%in%x[j:(j+(width-1))]])))
}

My data is as follows:

library(ks)
library(zoo)
library(plyr)
library(BBmisc)
library(ggplot2)
library(rje)

set.seed(1234)
n1 = n2 = 50000
X1 = rnorm.mixt(n=n1,mus=c(0.4,0.8),sigmas=c(0.04,0.04),props=c(0.97,0.03))
X2 = rnorm.mixt(n=n2,mus=c(0.4,0.8),sigmas=c(0.04,0.04),props=c(0.98,0.02))

n1 = length(X1)
n2 = length(X2)

#pooled observations - label X1's as 1 and X2's as 0
dat = data.frame(X=c(X1,X2),lab=c(rep(1,n1),rep(0,n2)))

N = n1+n2

#number in each bin
n = N^(1/3)

dat$quant = with(dat, cut_number(dat$X, n = round(N/n)))

#number of bins
M = length(levels(dat$quant))
dat$index = factor(dat$quant, levels = levels(dat$quant),
                   labels = 1:length(levels(dat$quant)))

Example function call:

indx.contig = seq(M)
count.ones(x=indx.contig,data.l=dat,width=1) #can vary width for any integer >= 1

This function seems to be slower than expected as it's only performing the simple task of counting the number of 1's in each sliding window. This would become problematic as n1 and n2 increase into the millions (which is ultimately what I want to use). Is there a way to speed this up? I initially looked into rollapply in the zoo package, but it is not as flexible as my code.

It is important for me to look at consecutive indices. If, for example, I had:

indx.vec = c(1:10,14:20)

I would first create a list with two elements: one containing 1:10 and the other containing 14:20. I would then run count.ones on each of the elements using sapply.


texts: Encrypter - Double Vigenere Cipher in Python

texts:
I wrote this encrypter based on the idea of a Vigenere cipher, but instead of using only one key, it "makes" another key from the existing key. The length of the second key also depends on the different characters in the first key. And so it uses both keys in the shifting of letters.

def scram(key):
    key2 = []
    #make the length of the second key varying from key to key for harder cracking
    length = (key[0]-32)+(key[int(len(key)/2)]-32)+(key[len(key)-1]-32)
    #make the max length = 256
    length = length % 256
    #if the length is less than 64, multiply by two to make it longer
    while(length < 64):
        length*=2

    #scrambles the letters around
    for x in range(length):
        #basically shifts the key according to the current character,
        #how many times it has looped the key, where it is in the key,
        #and the modulo of x and a few prime numbers to make sure that
        #an overlap/repeat doesn't happen.
        toapp = (x%(len(key)-1)) + (x/(len(key)-1)) + (key[x%(len(key)-1)]) + (x%3) +(x%5)+(x%53)+(x%7)
        toapp = int(toapp % 94)
        key2.append(toapp)

    return key2

def cipher(mes,key,ac):
    #makes the second key
    key2 = scram(key)
    res=[]

    #do proper shifting in the keys
    for x in range(len(mes)):
        temp=mes[x]

        if(action == "2"):
            temp = temp - key[x%(len(key)-1)] - key2[x%(len(key2)-1)]
        else:
            temp = temp + key[x%(len(key)-1)] + key2[x%(len(key2)-1)]

        temp = int(temp % 94)

        res.append(chr(temp+32))

    return res

#encrypt or decrypt
action = input("type 1 to encypt. type 2 to decrypt:")
#input
m= input("Text:")
k= input("key - 4 or more char:")

#changes the letters to ascii value
mes= []
for x in m:
    mes.append(ord(x)-32)

key= []
for x in k:
    key.append(ord(x)-32)

#encrypts it
result = cipher(mes,key,action)

for x in result:
    print(x,end="")

print("")

y = input("Press enter to continue...")

Are there more efficient ways to do it? Is this a safe way to encrypt text? Can you crack the text encrypted with this program?


texts: Calculate the number of days passed from a given year

texts:
I have this code for calculating the number of days passed from a given year:

for (int currentYear = localDate.getYear() - 1; currentYear >= STARTING_YEAR; currentYear--){
            LocalDate date = LocalDate.of(currentYear,5,5); //an arbitrary day of year
            jdn += date.lengthOfYear();
        }
jdn += localDate.getDayOfYear();

This code is working as expected.

I am not comfortable with choosing an arbitrary day to only get the length of the year. Is there any better approach?


texts:
I have the following code which produces successive generations of Conway's Game of Life:

life =: 3 : '+./ (>(($ y) $ 1);y) *. > =&(+/ (>,{ ;~(1 0 _1))|. y) each 3 4'

Usage:

RR =: 5 7 $ 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0

NB. First five gens of RR
life^:(i.5) RR

NB. in ASCII
' *' {~ life^:(i.5) RR

Explanation of code:

>,{ ;~(1 0 _1)

Produces all possible 1 rotations of a matrix y.

|. y

Applies 1 rotations to y

+/

Adds all 1 rotations leading to neighbor-count for each cell

=&

Creates a monadic function which takes a single number and compares it to the neighbor-counts

each 3 4

Applies the function to 3 and 4 to find cells with 3 or 4 surrounding cells including self alive.

>

Unboxes to apply bitwise and

(>(($ y) $ 1);y)

I want all cells that correspond to 3 (($ y) $ 1) and only the cells that are already currently living the correspond to 4 (y).

+./

Or the result together to produce the next generation.

I would like to know if there's a better way to do this and shorten code. A lot of the things I did seem very hacky.