texts: Response to an answer: Solution to maxMirror problem

texts:
Garrett Openshaw had an okay answer to Codingbat maxMirror challenge

But there were a couple of issues with the code he gave, so I decided to review it and make it a little bit better.

I don't have access to Java here at work so I instead changed the code in C# which wasn't too much trouble.

I added a List<int[]> to keep track of all the test cases and added an extra loop to the outside of the the rest of the code.

I moved some variables as I mentioned in my comment to Garret's answer, and also moved some variables to the correct scope.  It seems like there should be more I can do to simplify this answer.

There was indentation and bracketing issues that made it difficult to read that I also changed.

List<int[]> sequences = new List<int[]> {
     new int[] {1, 2, 1, 2, 1},
     new int[] {1, 2, 3, 8, 9, 3, 2, 1},
     new int[] {1, 2, 1, 4},
     new int[] {7, 1, 2, 9, 7, 2, 1}
 };

foreach (var sequence in sequences)
{
    int maxLength = 1;
    int endIndex = sequence.Length - 1;
    for (int frontIndex = 0; frontIndex < endIndex; frontIndex++)
    {
        for (int i = endIndex; i > frontIndex; i--)
        {
           if (sequence[frontIndex] == sequence[i])
            {
                var currentLength = 0;
                while (frontIndex + currentLength < sequence.Length && i - currentLength >= 0)
                {
                    if (sequence[frontIndex + currentLength] == sequence[i - currentLength])
                    {
                        currentLength++;
                    }
                    else break;
                }
                if (currentLength > maxLength)
                {
                    maxLength = currentLength;
                }
            }
        }
    }
    Console.WriteLine("Max length is " + maxLength);
    Console.ReadLine();
}


texts:
I am practicing my coding on leetcode, and my submission, although correct for small cases, is timing out for large ones. Could you please let me know how to improve my code?

The question is as follows (https://leetcode.com/problems/longest-increasing-path-in-a-matrix/):

Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Here is my solution. I tried to use memoization, but it's just not fast enough: I think I'm missing something fundamental -- I do not have a CS background.

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix)
    {
        //base case
        if (matrix.size() == 0 || matrix[0].size() == 0)
        return 0;

        //create hash matrix populated with -1
        int height = matrix.size();
        int length = matrix[0].size();
        vector<int> temp(length,-1);
        vector<vector<int>> hash(height,temp);

        int maximum;
        //run longestpathfrom on all node
        for(int i=0; i<height; i++)
        {
            for(int j = 0; j<length; j++)
            {
                longestpathfrom(matrix,i,j,hash,maximum);
            }
        }
        return maximum;
    }

    int longestpathfrom(vector<vector<int>> matrix, int i, int j, vector<vector<int>>& hash, int& maximum)
    {
        //Returns the longest path from your current position
        //Also uses memoization via hash.
        //also keeps track of the max...

        //If you already calculated this value, just return it.
        if (hash[i][j]!=-1)
        return hash[i][j];

        //directions
        vector<vector<int>> dirs {{-1,0},{1,0},{0,-1},{0,1}};

        //pathlength:
        int pathlen = 0;

        //Take the max of longestpathfrom over all valid neighbours:
        for (int I=0; I<4; I++)
        {
            //Generate indices of where you are checking path length from
            int x = i+dirs[I][0];
            int y = j+dirs[I][1];

            //Check index validity:
            if (x<0 || y<0 || x>matrix.size()-1 || y>matrix[0].size()-1)
            continue;

            if (matrix[i][j]<matrix[x][y])
            pathlen = max(pathlen, longestpathfrom(matrix, x, y, hash, maximum));
        }

        //add 1 for the square you're already on
        pathlen++;

        //update hash
        hash[i][j]=pathlen;

        //update max
        maximum = max(maximum,pathlen);

        return pathlen;
    }
};


texts: Function that calls the database connection and query

texts:
I made a function that contains the database connection and query. Now I'm always calling this function every time I need to query a database. Is it good or is there another way better?

Database connection:

    /* Database Configuration */
DEFINE( "DATABASE_HOST", "" );
DEFINE( "DATABASE_USERNAME", "" );
DEFINE( "DATABASE_PASSWORD", "" );
DEFINE( "DATABASE_ESSENTIALS", "" );

        /* Database Connection & Data Manipulation */
    function connect_database( $database_id ) {
        try {
            $databases = array( "essentials"  => DATABASE_ESSENTIALS );

            $connection = new PDO( "mysql:host=" . DATABASE_HOST . ";dbname=" . $databases[ $database_id ], DATABASE_USERNAME, DATABASE_PASSWORD );
            $connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        } catch ( PDOException $exception ) {
            trigger_error( $exception->getMessage() );
        }

        return $connection;
    }

    function prepare_and_execute_query( $database_id, $query, $statement_id, $values ) {
        $statement = $this->connect_database( $database_id )->prepare( $query );

        if ( $statement_id == "get_system_configuration" ) {
            $statement->bindParam( ":system_configuration_id", $values[ 0 ] );
        }

        $statement->execute();

        return $statement;
    }

    function get_system_configuration( $system_configuration_id ) {
        return ( ( $system_configuration_row = $this->prepare_and_execute_query( "essentials", "SELECT value FROM `[main]system_configurations` WHERE system_configuration_id = :system_configuration_id", "get_system_configuration", array( $system_configuration_id ) )->fetch() ) ? ( ( !( empty( $system_configuration_row[ "value" ] ) ) ) ? ( $system_configuration_row[ "value" ] ) : ( $system_configuration_row[ "default_value" ] ) ) : ( trigger_error( "Undefined system configuration id" , E_USER_ERROR ) ) );
    }

Sample usage of system configuration function:

<!DOCTYPE html>
<html lang="<?php echo $essentials_global->get_system_configuration( "html_lang" ); ?>">


texts:
I have implemented an iterative in-place quicksort algorithm in Python, which by default selects the pivot as the last element:

def quicksort(array):
    """
    Sorts an array of integers using the quick-sort algorithm.

    :param array: the array to be sorted
    :type array: list<int>
    :return: the sorted array
    :rtype: list<int>
    """
    indexes_stack = list()
    idx = (0, len(array) - 1)
    indexes_stack.append(idx)
    for idx in indexes_stack:
        elem_idx = idx[0]
        pivot_idx = idx[1]
        while pivot_idx > elem_idx:
            pivot = array[pivot_idx]
            elem = array[elem_idx]
            if elem > pivot:
                array[pivot_idx] = elem
                array[elem_idx] = array[pivot_idx - 1]
                array[pivot_idx - 1] = pivot
                pivot_idx -= 1
            else:
                elem_idx += 1

        boundar_low = idx[0]
        boundar_high = idx[1]
        if pivot_idx > 1 and boundar_low < pivot_idx - 1:
            indexes_stack.append((boundar_low, pivot_idx - 1))
        if pivot_idx < len(array) -1 and pivot_idx + 1 < boundar_high:
            indexes_stack.append((pivot_idx + 1, boundar_high))

    return array

# Test the sorting function
counter = 0
while counter < 1000:
    test = [int(100 * random.random()) for i in xrange(15)]
    assert (quicksort(list(test)) == sorted(test)), test
    counter += 1

I've tested it with various inputs and it seems to be correct, but I wonder if it can become more efficient or clean.


texts: Python array literal syntax sugar similar to Perl and Ruby

texts:
Background

Python (version 2.7.2)

Problem

You want to specify an array in your code.
You want to use the 'syntax sugar' available in Ruby and Perl.
You are a fanatic about readable code but also saving keystrokes.

Solution

Python Triple-quoted string
Python splitlines
Python list comprehension

Pitfalls

The solution may look ugly or un-Python-ish

Question

Are there any refactorings, suggestions or comments on this approach?

### ********************
## setup an array using append
ary_names = []
ary_names.append('alpha')
ary_names.append('bravo')
ary_names.append('charlie')
ary_names.append('delta')
ary_names.append('echo')

### ********************
## setup an array using triple-quoted string
ary_names = [
  item.strip() for item in
  """

  alpha
  bravo
  charlie
  delta
  echo

  """
  .splitlines()
  if(not item.strip()=='')
]

"""
Here is a ruby example for comparison

ary_names = %w[
  alpha
  bravo
  charlie
  delta
  echo
]
"""


texts:
Here is a simple Phase Locked Loop, which is a circuit used in radio communications for synchronisation between transmitter and receiver.

The loop works by calculating the (phase) difference between the input signal, and a reference oscillator, and then adjusting the reference until the phase difference is zero. In this code, the adjustment is made by approximating a digital biquad filter's output - simply by multiplying by the Q factor of the filter.

My main concern with this code, is that it would require some re-writing if I wanted to extend it.

import numpy as np
import pdb

class SimPLL(object):
    def __init__(self, lf_bandwidth):
        self.phase_out = 0.0
        self.freq_out = 0.0
        self.vco = np.exp(1j*self.phase_out)
        self.phase_difference = 0.0
        self.bw = lf_bandwidth
        self.beta = np.sqrt(lf_bandwidth)

    def update_phase_estimate(self):
        self.vco = np.exp(1j*self.phase_out)

    def update_phase_difference(self, in_sig):
        self.phase_difference = np.angle(in_sig*np.conj(self.vco))

    def step(self, in_sig):
        # Takes an instantaneous sample of a signal and updates the PLL's inner state
        self.update_phase_difference(in_sig)
        self.freq_out += self.bw * self.phase_difference
        self.phase_out += self.beta * self.phase_difference + self.freq_out
        self.update_phase_estimate()

def main():
    import matplotlib.pyplot as plt
    pll = SimPLL(0.002)
    num_samples = 500
    phi = 3.0
    frequency_offset = -0.2
    ref = []
    out = []
    diff = []
    for i in range(0, num_samples - 1):
        in_sig = np.exp(1j*phi)
        phi += frequency_offset
        pll.step(in_sig)
        ref.append(in_sig)
        out.append(pll.vco)
        diff.append(pll.phase_difference)
    #plt.plot(ref)
    plt.plot(ref)
    plt.plot(out)
    plt.plot(diff)
    plt.show()

Here is the output.


texts: Average readouts from multiple IR sensors with Arduino

texts:
I've written an Arduino sketch to continuously read values from multiple analog IR distance sensors, average the last 7 values and output in millimeters. Being pretty new to both Arduino and embedded programming, I'm sure there's a lot of room for improvement. Any critique would be highly appreciated, including idioms and built-in functions I could have used.

My plan is to extend this program to run LED strips based on the sensor values.

#define LOOP_PERIOD_MS 10 // run loop every 10 ms
#define IR_WIN_LENGTH 7 // IR sensor moving-average window
#define IR_NUM_SENSORS 4 // Number of IR sensors, must be 1-6 and connected to the first analog pins

// Declare IR sensor functions
void ir_read_new_vals();
uint16_t ir_get_cur_mm( uint8_t sensor_i );
uint16_t ir_get_avg_mm( uint8_t sensor_i );

// Variables
unsigned long loop_start_ms = 0; // When the last loop iteration started

// Setup
void setup() {
  // Initialize serial communication
  Serial.begin(115200);
}

// Main loop: Read and print IR sensor data continuously
void loop() {
  // Limit loop frequency
  while ( millis() - loop_start_ms < LOOP_PERIOD_MS )
    delayMicroseconds(10);
  loop_start_ms = millis();
  // Print timestamp
  Serial.print( loop_start_ms );
  // Read and print IR sensor values
  ir_read_new_vals();
  for ( uint8_t sensor_i = 0; sensor_i < IR_NUM_SENSORS; sensor_i++ ) {
    Serial.print(",");
    Serial.print(ir_get_avg_mm(sensor_i));
  }
  // print new line
  Serial.println("");
}

// IR sensor functions

uint8_t ir_i = IR_WIN_LENGTH; // array index for the last read value
uint16_t ir_vals_mm[IR_NUM_SENSORS][IR_WIN_LENGTH]; // "rolling" stored values for sensors
bool ir_avg_is_valid = false; // whether moving-average window is filled

// Read, scale and store values from analog sensors
// The four sensors are connected to analog pins 0, 1, 2, 3
void ir_read_new_vals() {

  // Increment "rolling array" index
  ir_i = ( ir_i + 1 ) % IR_WIN_LENGTH;

  // Read each sensor
  for ( uint8_t sensor_i = 0; sensor_i < IR_NUM_SENSORS; sensor_i++ ) {
    // Dummy sensor read (suggested when switching ADC pin)
    analogRead(sensor_i);
    // Read sensor value (values 0..1023 corresponds to 0..5V)
    uint32_t raw = analogRead(sensor_i);
    // Clamp values to 5-80cm
    if ( raw > 600 )
      raw = 600;
    if ( raw < 80 )
      raw = 80;
    // Rescale value to mm according to datasheet curve and store
    ir_vals_mm[sensor_i][ir_i] = (uint16_t)( 67870 / ( raw - 3 ) - 40 );
  }

  // Check if the moving-average window was filled
  if ( ! ir_avg_is_valid && ir_i == IR_WIN_LENGTH - 1 )
    ir_avg_is_valid = true;
}

// Return last read sensor value in mm
uint16_t ir_get_cur_mm( uint8_t sensor_i ) {
  return ir_vals_mm[sensor_i][ir_i];
}

// Return moving average of sensor values
uint16_t ir_get_avg_mm( uint8_t sensor_i ) {
  // Return 0 if not enough values
  if ( ! ir_avg_is_valid )
    return 0;
  // Sum sensor values
  uint32_t accum_mm = 0;
  for ( uint8_t i = 0; i < IR_WIN_LENGTH; i++ )
    accum_mm += ir_vals_mm[sensor_i][i];
  // Divide and return
  return accum_mm / IR_WIN_LENGTH;
}


texts:
This currently does what I intend:

import Control.Arrow (Kleisli, runKleisli)
import Control.Applicative (WrappedArrow(WrapArrow))
import Control.Lens.Traversal (preview)

nested :: Request -> Maybe Response
nested = runKleisli . unwrapArrow
       $ WrapArrow (Kleisli (preview (prefixed "/name") >=> app1))
     <|> WrapArrow (Kleisli (preview (prefixed "/surname") >=> app2))

  where
    prefixed :: Text -> Prism' Request Request
    prefixed = _

    app1,app2 :: Request -> Maybe Response
    app1 = _
    app2 = _

The idea here is to implement a kind of nested HTTP routing. Given the already existing applications app1 and app2, I want to reroute the incoming Request to either of those applications based on whether the path of the Request is prefixed with "/name" or "/surname". The prefixed Prism' strips such prefix from the Request path if present, otherwise it fails.

However I'd like to get rid, somehow, of WrapArrow, Kleisli and preview, and possibly, runKleisli . unwrapArrow. I suspect that this can be done with Control.Lens.Wrapped or Data.Profuntor but I still can't see exactly how.

I wouldn't like to a add an extra dependency for this case but I'm currently using lens in my project, so anything from lens or its dependencies is welcome.


texts: Simplifying member functions in Blackjack game

texts:
For my display functions in my Blackjack game, I want to control each player's stats output based on whether a turn is in progress or has ended.  Normally, you could only see one card that your opponent(s) hold, while the rest are only revealed at the end of each turn.  My code does that well, but I'm having trouble making it more concise.
The display function in Game is called to display each player's stats (name, chips, and hand).  It takes a Boolean argument to determine if it should display each CPU's partial stats (during each turn) or full stats (after each turn).  At the function call in Game, the bool argument is passed to the respective display function in Player, where the human player and CPU player have individual display procedures.  The display functions in Player primarily display the chip amounts and card rank totals.  They also call respective Hand display functions which, again, solely depend on the Boolean argument for displaying the CPUs' stats.
How could I simplify this code to achieve the same output (shown below the code)?
Game.cpp
displayStats(false); // function call elsewhere in Game

void Game::displayStats(bool showCPUResults) const
{
    players[0].displayPlayerStats(); // displays player stats

    for (int i = 1; i < numPlrs; i++)
        players[i].displayCPUStats(showCPUResults); // displays CPU stats
}

Player.cpp
void Player::displayPlayerStats() const
{
    // always shown
    std::stringstream ss;
    std::cout << "\n* " << name << ": ";
    std::cout << "($" << chips << ") ";

    // displays two-digit card rank total (always shown)
    if (totalCardsValue <= 9)
        ss << "(0" << totalCardsValue << ")  ";
    else
        ss << "(" << totalCardsValue << ")  ";

    std::cout << ss.str();

    // displays human player's hand
    playerHand[0].displayPlayerHand();
}

void Player::displayCPUStats(bool showResults) const
{
    // always shown
    std::stringstream ss;
    std::cout << "\n* " << name << ": ";
    std::cout << "($" << chips << ") ";

    if (!showResults)
    {
        std::cout << "      ";
        playerHand[0].displayCPUHand(showResults);
    }
    else
    {
            // only shown after each turn
        if (totalCardsValue <= 9)
            ss << "(0" << totalCardsValue << ")  ";
        else
            ss << "(" << totalCardsValue << ")  ";

        std::cout << ss.str();

            // displays CPU's hand
        playerHand[0].displayCPUHand(showResults);
    }
}

Hand.cpp
void Hand::displayPlayerHand() const
{
    // displays player's full hand (always)
    for (unsigned i = 0; i < cards.size(); i++)
        std::cout << cards[i] << " ";
}

void Hand::displayCPUHand(bool showCPUHand) const
{
    // displays CPU's first card (always)
    std::cout << cards[0] << " ";

    // displays the rest of the CPU's cards (only after each turn)
    if (showCPUHand)
    {
        for (unsigned i = 1; i < cards.size(); i++)
            std::cout << cards[i] << " ";
    }
}

Output during a turn...

Jamal: ($1000) (23)  [8C] [6H] [9C]
CPU1: ($1000) [AD]

...and after a turn...

Jamal: ($1000) (23)  [8C] [6H] [9C]
CPU1: ($1000) (21)  [AD] [KH]


texts:
I had to jump through some hoops to get a localized enum working. I went through dozens of SO articles that never actually answered the relevant conundrum with a working solution. So I made my own:

I have two resource files: LocalizedStrings.resx and LocalizedStrings.es-MX.resx
With two corresponding lines:

GENDER_FEMALE   Female

GENDER_MALE     Male

... and ...

GENDER_FEMALE   Mujer

GENDER_MALE     Hombre

… respectively.

I have an Enum Extension:

public static class EnumExtensionMethods
{
    public static string GetDisplay(this Enum enumValue)
    {
        object[] attr = enumValue.GetType().GetField(enumValue.ToString())
            .GetCustomAttributes(typeof(DisplayAttribute), false);

        return attr.Length > 0
           ? ((DisplayAttribute)attr[0]).GetName()
           : enumValue.ToString();
    }
}

My actual Enum:

public enum Gender
{
    [Display(ResourceType = typeof(LocalizedStrings), Name = "GENDER_MALE")]
    Male = 1,
    [Display(ResourceType = typeof(LocalizedStrings), Name = "GENDER_FEMALE")]
    Female = 0
}

I load the values into a Winforms ComboBox’s items, (I could not get binding it to an entity to work) with the OnLoad event:

foreach (Gender value in Enum.GetValues(typeof(Gender)))
{
    GenderComboBox.Items.Add(new KeyValuePair<string, Gender>(value.GetDisplay(), value));
}

GenderComboBox.DisplayMember = "Key";
GenderComboBox.ValueMember = "Value";
GenderComboBox.SelectedIndex = 1;

Finally, I have to set the entity value with this event:

private void GenderComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!GenderComboBox.Focused)
        return;

    if (GenderComboBox.SelectedIndex == -1)
        return;

    KeyValuePair<string, Gender> gender = (KeyValuePair<string, Gender>) GenderComboBox.SelectedItem;

    Person person = (Person)PersonBindingSource.Current;

    person.Gender = gender.Value;
}

All of the previous code just to get a Localized Enum. Is there not a better way?


texts:
Some numbers have funny properties. For example:

$$\eqalign{89 &→ 8^1 + 9^2 &= 89 &= 89 × 1 \\ 695 &→ 6^2 + 9^3 + 5^4 &= 1390 &= 695 × 2 \\ 46288 &→ 4^3 + 6^4 + 2^5 + 8^6 + 8^7 &= 2360688 &= 46288 × 51}$$

Given a positive integer \$n\$ written in decimal as \$abcd\dotso\$, and a positive integer \$p\$, we want to find a positive integer \$k\$, if it exists, such that the sum of the digits of \$n\$ taken to the successive powers \$p\$, \$p+1\$, \$p+2\$, …, is equal to \$nk\$. In other words:

  Is there an integer \$k\$ such that \$ a^p + b^{p+1} + c^{p+2} + d^{p+3} + \dotsb = nk\$?

If it is the case we will return \$k\$, if not return \$-1\$.

Note: \$n\$, \$p\$ will always be given as strictly positive integers.

dig_pow(89, 1) should return \$1\$ since \$8^1 + 9^2 = 89 = 89 × 1\$.
dig_pow(92, 1) should return \$-1\$ since there is no \$k\$ such that \$9^1 + 2^2\$ equals \$92k\$
dig_pow(695, 2) should return \$2\$ since \$6^2 + 9^3 + 5^4 = 1390 = 695 × 2\$
dig_pow(46288, 3) should return \$51\$ since \$4^3 + 6^4 + 2^5 + 8^7 + 8^6 = 2360688 = 46288 × 51\$

import math

def dig_pow(n,p):

    '''
    Formula :

    (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

    '''

    ''' calculate LHS '''
    digits, temp = [], n
    for i in range(len(str(n))):
        digits.append(temp%10)
        temp = temp / 10

    Tsum = 0
    for i in reversed(digits):
        Tsum = Tsum + math.pow(i,p)
        p = p + 1

    ''' Calculate RHS '''
    if Tsum % n == 0:
        return Tsum / n
    else:
        return -1

print dig_pow(46288, 3)
print dig_pow(89, 1)
print dig_pow(695, 2)
print dig_pow(92, 1)

Please feel free to suggest better/faster approaches.


texts:
As many people will undoubtedly recognise, this is a question in a well known series of problems that I won't name ;)

It's been a long time since I've written any F# and I'm not sure I've ever come across any canonical style guidelines so I'd like feedback on all aspects of the code.

let largestPrimeFactor (number:int64) =
    let rec inner n current =
        if (n * n) > current then
            current
        else if current % n <> 0L then
            let nextCandidate = if n = 2L then 3L else n + 2L
            inner nextCandidate current
        else
            inner n (current / n)
    inner 2L number

Usage is simply:

let largestFactor = largestPrimeFactor 999999866000004473L

// 999999937

I'm not really concerned with performance... I know about the various sieve options (Eratosthenes, Atkins) and decided that trial division for a single prime was adequate.


texts:
I have a bash script I'm trying to distribute to people in my class. The script requires some dependencies to operate, namely wkhtmltopdf and pdfkit. I can install those dependencies with homebrew, but I can't assume users have that. I've written an install/uninstall script for Mac, and my partner made one for Linux, but both of them seem so hacky to me.

I would like a more robust approach for distributing my bash script with its dependencies.

Here is the Mac OS install/uninstall script:

#!/usr/bin/env bash

arg=$1
uninstall="-u"

if [[ ${arg} == *"$uninstall"* ]];
then
    echo "Uninstalling eesubmit..."

    echo "Removing the shortcut..."
    sudo rm /usr/bin/eesubmit
    echo "The eesubmit shortcut has been removed"

    echo "Removing the source code and username file for eesubmit..."
    rm -rf ~/.eesubmit/
    echo "The source code and username file for eesubmit has been removed"

    echo "eesubmit requires other dependencies that may have been installed when eesubmit was installed"
    echo "Some of these dependencies may have already been installed"
    echo "Please review these dependencies and tell us if you want to remove them"

    echo "Do you want to uninstall pdfkit (a Python package that runs on top of wkhtmltopdf)? (y/n)"
    read uninstallPdfkit
    if [ ${uninstallPdfkit} = "y" ];
    then
        pip uninstall pdfkit
    fi

    echo "Do you want to uninstall wkhtmltopdf (a library for converting HTML to PDFs)? (y/n)"
    read uninstallWkhtmltopdf
    if [ ${uninstallWkhtmltopdf} = "y" ];
    then
        brew uninstall pdfkit --force
    fi

    echo "Do you want to uninstall homebrew (a package manager for Mac OS)? (y/n)"
    read uninstallHomebrew
    if [ ${uninstallHomebrew} = "y" ];
    then
        ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
    fi

    echo "Uninstallation complete!"
else
    echo "Installing homebrew (a package manager for Mac OS)..."
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    echo "Homebrew installation complete"

    echo "Installing wkhtmltopdf (a library for converting HTML to PDFs)..."
    brew install wkhtmltopdf
    echo "wkhtmltopdf installation complete"

    echo "Installing pdfkit (a Python package that runs on top of wkhtmltopdf)..."
    pip install pdfkit
    echo "pdfkit installation complete"

    echo "Adding a shortcut for eesubmit (this may require your password)..."
    if [ -f ~/.eesubmit/eesubmit/main/submitting.bash ];
    then
        sudo cp ~/.eesubmit/eesubmit/main/submitting.bash /usr/bin/eesubmit
        echo "The shortcut has been created"
        echo "Installation complete!"
    else
        echo "Error: The main eesubmit script is not installed" 1>&2
        echo "Are you sure you cloned the repository correctly?"
        echo "Try running these commands"
        echo "    mkdir -p ~/.eesubmit"
        echo "    cd ~/.eesubmit"
        echo "    git clone https://github.com/DakotaAndMichael/eesubmit.git"
        echo "Then, run this script again"
    fi
fi


texts: Using multiple popup windows with bPopup

texts: I'm using a lightweight jQuery popup plugin called 'bPopup'. I'm using it on my website at the moment to load multiple popup windows when clicked. I was recently told that my code was inefficient as I was loading multiple popups with multiple JavaScript 'listeners':


texts: How can I optimize my Von Neumann neighborhood algorithm?

texts:
I am working on a small project that requires finding Von Neumann neighborhoods in a matrix. Basically, whenever there is a positive value in the array, I want to get the neighborhood for that value. I used an iterative approach because I don't think there's a way to do this in less than O(n) time as you have to check every single index to make sure all of the positive values are found. My solution is this:
is_counted = {}
recursions = []

def populate_dict(grid, n):
    rows = len(grid)
    cols = len(grid[0])
    for i in range(rows):
        for j in range(cols):
            if grid[i][j] > 0:
                find_von_neumann(grid, i, j, n, rows, cols)

    return len(is_counted.keys())

def find_von_neumann(grid, curr_i, curr_j, n, rows, cols):
    #print(curr_i, curr_j)
    recursions.append(1)
    if n == 0:

        cell = grid[curr_i][curr_j]

        if cell > 0:
            key = str(curr_i) + str(curr_j)
            if key not in is_counted:
                is_counted[key] = 1

    if n >= 1:

        coord_list = []
        # Use Min so that if N > col/row, those values outside of the grid will not be computed.
        for i in range(curr_i + min((-n), rows), curr_i + min((n + 1), rows)):
            for j in range(curr_j + min((-n), cols), min(curr_j + (n + 1), cols)):
                dist = abs((curr_i - i)) + abs((curr_j - j))

                if n >= dist >= -n and i >= 0 and j >= 0 and i < rows and j < cols:

                    coord_list.append([i, j])

        for coord in coord_list:
            key = str(coord[0]) + str(coord[1])
            if key not in is_counted:
                is_counted[key] = 1

neighbors = populate_dict([

    [-1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1],
    [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1],
    [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1],
    [-1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [-1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    ],
    2)

print(neighbors)

I went with a hash table as my data structure but I believe that currently the worst case runtime would look very similar to O(n^2). For example if N (the distance factor) is equal to the amount of rows or columns AND every single value is positive, its going to be inefficient. Am I missing something with my solution, for example could using dynamic programming possibly help cut down on the runtime or is this already a good solution?
I'm fairly new to algorithms and runtime analysis so please correct me if I messed up on anything in my own analysis of this , thanks!


texts:
A Wilson prime is a prime number p such that p² divides (p−1)!+1. The first three Wilson Primes are 5, 13 and 563 and the fourth is larger than \$2×10^{13}\$. I was curious as to how much memory/processing power it would take to calculate the Wilson Primes using a brute force type method.

When I was coding this I kept efficiency in mind, and for this reason I used Stacks rather than Vectors.

#include <iostream>
#include <stack>

using namespace std;

stack<int> findPrimesUnder(int limit){ //stack is used for O(k) complexity where k is constant
    stack<int> primes;

    for(int i = 2; i <= limit; i++){
        int numFactors = 0;
        for(int j = i-1; j > 1; j--){//anything divided by itself is 1 so can be excluded for efficiency by subtracting 1 from i
                                     //also, anything divided by 1 is itself so is excluded for efficiency;
            if (float(i)/j == i/j){
                numFactors++;
            }
        }
        if(numFactors == 0)
            primes.push(i);

    }

    return primes;
}

int factorial(int n){
    if(n == 1){
        return 1;
    }
    else{
        return n*factorial(n-1);
    }
}

int main(){
    int limit;
    cout << "Enter limit: "; cin >> limit;

    stack<int> primes = findPrimesUnder(limit);
    stack<int> wilsonPrimes;

    bool descriptive = false;

    while(!primes.empty()){
        unsigned long long int firstWilsonCheck = (factorial(primes.top()-1)+1)/primes.top();//((p-1)! + 1)/p is always an int where p is prime
        double secondWilsonCheck = double(firstWilsonCheck)/primes.top();

        if(secondWilsonCheck == int(secondWilsonCheck))
            wilsonPrimes.push(primes.top());

        if(descriptive){
            cout << "Prime: " << primes.top() << endl;
            cout << "First Check: " << firstWilsonCheck << endl;
            cout << "Second Check: " << secondWilsonCheck << endl;

            cout << "------------------------" << endl;
        }

        primes.pop();
    }

    cout << "These are the Wilson Primes under " << limit << ":" << endl;
    while(!wilsonPrimes.empty()){
        cout << wilsonPrimes.top() << endl;
        wilsonPrimes.pop();

    }

    return 0;
}

Output:

Enter limit: 100
These are the Wilson Primes under 100:
5
13
37
41
43
47
53
59
61
67
71
73
79
83
89
97

This code calculates the first two Wilson Primes fine (5 and 13), however it cannot calculate any after 13 because the numbers just get too big, I assume.

My questions are:

How could this code be made to be more efficient?
How can I increase precision on larger numbers?


texts: Selecting kids for a Christmas play with similar heights

texts:
I am doing this problem on SPOJ:

  My kid's kindergarten class is putting up a Christmas play.  (I hope he gets the lead role.)  The kids are all excited, but the teacher has a lot of work.  She has to produce costumes for a scene with \$K\$ soldiers.  She wants to buy all the costumes in the same size, allowing for some small amount of length alteration to be done by the kids' parents later.  So she has taken all the kids' height measurements.  Can you help her select \$K\$ kids from her class of \$N\$ to play the soldier role, such that the height difference between the tallest and shortest in the group is minimized, and alternations will be easiest?  Tell her what this minimum difference is.

  INPUT

  The first line contains the number of test cases \$T\$. \$T\$ test cases follow each containing 2 lines.

  The first line of each test case contains 2 integers \$N\$ and \$K\$.
  The second line contains \$N\$ integers denoting the height of the \$N\$ kids.

  OUTPUT

  Output \$T\$ lines, each line containing the required answer for the corresponding test case.

  CONSTRAINTS

  \$T \le 30\$
  \$1 \le K \le N \le 20000\$
  \$1 \le \text{height} \le 1000000000\$

My approach

I am first storing all the heights in the array and then sorting the array using quicksort (I also tried std::sort), and after that finding the minimum difference using sliding window (I do not exactly know the name of algorithm, I heard it is known as sliding window).

After optimizing my code to the best that I can, my code takes 0.05s to execute all test cases, but when I see the best result, it is 0.00s or 0.02s, so less than 0.05s.

By the way, I had also tested with std::sort but it was only marginally faster (0.05 s instead of 0.06 s). How can I optimize it more?

#include <cstdio>
#include <algorithm>
#include<iostream>
int partition(int *arr, const int left, const int right) {
const int mid = left + (right - left) / 2;
const int pivot = arr[mid];
// move the mid point value to the front.
std::swap(arr[mid],arr[left]);
int i = left + 1;
int j = right;
while (i <= j) {
    while(i <= j && arr[i] <= pivot) {
        i++;
    }

    while(i <= j && arr[j] > pivot) {
        j--;
    }

    if (i < j) {
        std::swap(arr[i], arr[j]);
    }
}
std::swap(arr[i - 1],arr[left]);
return i - 1;
}

void quicksort(int *arr, const int left, const int right, const int sz)
{

if (left >= right) {
    return;
}

int part = partition(arr, left, right);

quicksort(arr, left, part - 1, sz);
quicksort(arr, part + 1, right, sz);
}

using namespace std;

int main(){
int T,N,K,h[20000];

scanf("%d",&T);

while(T--){
    scanf("%d %d",&N,&K);

    for(int i = 0;i < N;++i) scanf("%d",&h[i]);
    quicksort(h,0,N-1,N);

    int ans = h[K - 1] - h[0];

    for(int i = 1;i + K - 1 < N;++i)
        ans = min(ans,h[i + K - 1] - h[i]);

    printf("%d\n",ans);
}

return 0;
}


texts:
I decided to polish my skills a little bit after learning about one dimensional arrays, and built my own mini project - hangman game.
I'd like to have some criticism, I know it's not perfect and far from it, but please be aware, it's my FIRST EVER real project with more than 20 + lines of code.

import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;

public class Main {
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {

        String[] words = {"java", "hello"};
        int random = (int)(0 + Math.random() * words.length);
        String wordToGuess = words[random];
        boolean isGuessed = false;
        int counter=0;
        int maxGuess = 7;
        char[] chars = new char[wordToGuess.length()];
        for (int i =0; i<chars.length; i++)
            chars[i] = '-';
        while (!isGuessed && counter <7) {

            System.out.println("Enter your guess: ");
            char guess = input.next().charAt(0);
            counter++;
            maxGuess--;
            for (int i = 0; i < wordToGuess.length(); i++) {
                if (wordToGuess.charAt(i) == guess)
                    chars[i] = guess;
            }
            if (doesContain(chars)) {
                for (int j = 0; j < wordToGuess.length(); j++) {
                    System.out.print(chars[j] + " ");

                }
                System.out.println("Guess left: " + maxGuess);

            } else {
                System.out.println("Good job! The word is: ");
                for (int j = 0; j < wordToGuess.length(); j++) {
                    System.out.print(chars[j] + " ");
                }
                System.out.print("Number of tries: ");
                System.out.print(counter);
                isGuessed = true;

            }
        }

    }

    public static boolean doesContain(char[] chars) {
        for (int i =0; i<chars.length; i++) {
            if (chars[i] == '-')
                return true;
        }
        return false;
     }

 }


texts:
After learning about linked list implementations of a queue I was asked to try a resizing array implementation. I'm looking for constructive criticism.

import java.util.NoSuchElementException;

/**
 * ResizingQueue - Resizing Array Implementation.
 *
 * @author Rocky
 * @version 2016-05-31
 */
public class ResizingQueue<Item> {

    private Item[] queue;
    private int size;
    private int index;

    public ResizingQueue() {
        queue = (Item[]) new Object[1];
        size = 0;
        index = 0;
    }

    /**
     * Returns the size of the queue
     *
     * @return Integer representing the number of items in the queue
     */
    public int size() {
        return this.size;
    }

    /**
     * Returns whether or not the queue is empty
     *
     * @return True if the queue is empty
     */
    public boolean isEmpty(){
        return size == 0;
    }

    /**
     * Adds an item onto the end of the queue. If the size of the queue reaches
     * the length of the array, the length of the array is doubled.
     *
     * @param item Item to be added. Must not be null
     * @throws NullPointerException if the parameter item is null
     */
    public void enqueue(Item item) {
        if (item == null) {
            throw new NullPointerException("Item must not be null");
        }
        if (size == queue.length) {
            resize(2 * queue.length);
        }
        queue[size + index] = item;
        size++;
    }

    /**
     * Removes and returns the item at the front of the queue. If the size of
     * the queue reaches 25% of the length of the array, the length of the array
     * is halved.
     *
     * @return Item at the front of the queue
     * @throws NoSuchElementException if dequeue() is called while the queue is
     * empty
     */
     public Item dequeue() {
        if (isEmpty()) {
            throw new NoSuchElementException("There is nothing in the queue");
        }
        if (size < queue.length / 4) {
            resize(queue.length / 2);
            index = 0;
        }
        Item item = queue[index];
        queue[index++] = null;
        size--;
        return item;
    }

    /**
     * Resizes the array when capacity reaches 100% or 25%
     *
     * @param capacity New capacity for the array
     */
    private void resize(int capacity) {
        Item[] copy = (Item[]) new Object[capacity];
        for (int i = 0; i < size; i++) {
            copy[i] = queue[i + index];
        }
        queue = copy;
    }

}


texts: Scrape data from website into dataframe(s) using Split function

texts:
Outline:

This code uses the Split function to extract specific information from the following website: https://www.webscraper.io/test-sites/tables.

The required information are the four tables visible on the page with headers "#", "First Name","Last Name","Username".  I am extracting the information within these into 4 dataframes.

Example table:

Description:

I use the requests library to make the GET request, and split the response text on "table table-bordered" to generate my individual table chunks.

There is a fair amount of annoying fiddly indexing to get just the info I want, but the tutorial I am following requires the use of the Split function, and not something far more logical, to my mind, like Beautiful Soup, where I could just apply CSS selectors, for example, and grab what I want. The latter method would be less fragile as well.

I have written a function, GetTable, to parse the required information from each chunk and return a dataframe. There is a difference between the Split delimiter for table 1 versus 2-4.

There isn't an awful lot of code but I would appreciate any pointers on improving the code I have written.

I am running this from Spyder 3.2.8 with Python 3.6.

Code:

def GetTable(tableChunk):
    split1 = tableChunk.split('tbody')[1]
    split2 = split1.split('<table')[0]
    values = []

    aList = split2.split('>\n\t\t\t\t<')
    if len(aList) !=1:
        for item in aList[1:]:
                values.append(item.split('</')[0].split('d>'[1])[1])
    else:
        aList = split2.split('</td')
        for item in aList[:-1]:
           values.append(item.split('td>')[1])

    headers =  ["#", "First Name", "Last Name", "User Name"]
    numberOfColumns = len(headers)
    numberOfRows = int((len(values) / numberOfColumns))

    df = pd.DataFrame(np.array(values).reshape( numberOfRows, numberOfColumns ) , columns = headers)
    return df

import requests as req
import pandas as pd
import numpy as np

url = "http://webscraper.io/test-sites/tables"
response = req.get(url)
htmlText = response.text
tableChunks = htmlText.split('table table-bordered')

for tableChunk in tableChunks[1:]:
   print(GetTable(tableChunk))
   print('\n')


texts:
This is my first attempt at a hash map and I feel it is a great start. Although it does have a certain naive feel that I'm having trouble with.

public class HashMap<TKey, TValue>
{
    const int BlockSize = 100000;
    const int NumberOfBlocks = 42950;

    readonly Entry[][] _blocks = new Entry[NumberOfBlocks][];
    readonly IEqualityComparer<TKey> _comparer = EqualityComparer<TKey>.Default;

    public void Add(TKey key, TValue value)
    {
        uint hashCode = (uint)_comparer.GetHashCode(key);
        int blockIndex = (int)(hashCode / BlockSize);
        int slotIndex = (int)(hashCode - blockIndex * BlockSize);

        var block = _blocks[blockIndex];
        if (block == null)
        {
            block = _blocks[blockIndex] = new Entry[BlockSize];
        }

        var entry =  block[slotIndex];
        if (entry == null)
        {
            entry = block[slotIndex] = new Entry(key, value);
        }
        else
        {
            while (entry != null && entry.Next != null)
            {
                if (_comparer.Equals(key, entry.Key))
                {
                    throw new Exception();
                }
                entry = entry.Next;
            }
            entry = entry.Next = new Entry(key, value);
        }
    }

    public bool ContainsKey(TKey key)
    {
        uint hashCode = (uint)_comparer.GetHashCode(key);
        int blockIndex = (int)(hashCode / BlockSize);
        int slotIndex = (int)(hashCode - blockIndex * BlockSize);

        var block = _blocks[blockIndex];
        if (block == null)
            return false;

        var entry = block[slotIndex];
        while (entry != null)
        {
            if (_comparer.Equals(key, entry.Key))
                return true;
            entry = entry.Next;
        }
        return false;
    }

    class Entry
    {
        public readonly TKey Key;
        public readonly TValue Value;
        public Entry Next;

        public Entry(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }
    }
}


texts:
I use this Matlab code:

load ~/emailAnalysis/results.txt
results=results(size(results,1)-400:size(results,1),:)
temp = results(:,3)-1238370000;
h=plot(temp,smooth(results(:,1)),':b')
set(h,'LineWidth',1)
ylim([0 80])
xlim([max(temp)-(86400*7),max(temp)-1])
set(gca,'XGrid','on')
ylabel('Emails')
hold on
i=plot(temp,smooth(results(:,4)),'r')
j=plot(temp,smooth(results(:,5)),'-g')
k=plot(temp,smooth(results(:,6)),'m')
xlim([max(temp)-(86400*7),max(temp)-1])
set(gca,'XTick',[1:86400:(86400*max(temp))+1])
set(gca,'XTickLabel',['Mon';'Tue';'Wed';'Thu';'Fri';'Sat';'Sun'])
set(j,'LineWidth',2)
set(h,'LineWidth',1)
set(i,'LineWidth',2)
set(k,'LineWidth',2)
xlabel('Time')
title('Size of inbox over time (seven days)')
print -r3000 -djpeg /XXXX/inbox7day.jpeg
hold off

to generate this graph:

from data like:

34 2012-01-21 1327152611 5 16 10
32 2012-01-21 1327154411 5 14 9
32 2012-01-21 1327156209 5 14 9
34 2012-01-21 1327158012 5 14 9
34 2012-01-21 1327159808 5 15 9
34 2012-01-21 1327161611 5 15 9
34 2012-01-21 1327163406 5 15 9
33 2012-01-21 1327165211 5 13 9
34 2012-01-21 1327167011 5 13 9
31 2012-01-21 1327168810 4 12 8

but it's a little slow, and also probably not very elegant (it's my first use of Matlab) I'm interested in any tips for best practice, tips for speeding it up, or examples of how I might do the same things in R...


texts: Using XSLT to turn content of WYSIWYG stored in XML into HTML

texts:
The CMS I use uses the Xalan XSLT processor which is a XSLT version 1.0 processor. Editors who use WYSIWYG fields within the CMS can save content that will look like either:

<story>

Story Text which may have formatting.

</story>

or:

<story>Story Text which may have formatting.</story>

or even:

<story>

Story Text which may
 have formatting.

</story>

In order to handle those varying cases I've been using:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/system-index-block">
    <xsl:for-each select="story">
        <xsl:choose>

            <xsl:when test="./p|./div">

                <xsl:copy-of select="./text()|./*"/>
            </xsl:when>

            <xsl:otherwise>

                    <xsl:copy-of select="./text()|./*"/>

            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Is there a better way of producing well formed HTML from this data? Is there a way to simply this?


texts: Check if path exists directed graph, without using collection

texts:
I have written code to find whether the path exists between source and destination in a directed graph. I have used BFS and instead of ArrayList or queue. I have written my own helper class.

Please let me know how the code can be improved.

public class Graph {

    private int numVertex;
    // Helper class, which can act like Adjacency List or Queue for BFS search.
    private HelperClass[] adjList;

    public Graph(int n) {
        numVertex = n;
        adjList = new HelperClass[n];
        for (int i = 0; i < n; i++) {
            adjList[i] = new HelperClass();
        }
    }

    public void setAdjacencyList(HelperClass[] adjList) {
        this.adjList = adjList;

    }

    // Assuming that source and destination will be in the range of vertices.
    public boolean isPathExists(int source, int destination) {
        if (source == destination)
            return true;
        // else do BFS until the destination is found or all the nodes are
        // visited.
        HelperClass hc = new HelperClass();
        boolean[] isVisited = new boolean[numVertex];
        hc.add(source);
        isVisited[source] = true;
        while (!hc.isEmpty()) {
            int current = hc.poll();
            if (current == destination) {
                return true;
            }
            int leftIndex = adjList[current].first;
            int rightIndex = adjList[current].last;
            while (leftIndex < rightIndex) {
                int temp = adjList[current].array[leftIndex++];
                if (!isVisited[temp]) {
                    hc.add(temp);
                }

            }
        }
        return false;
    }

    public static class HelperClass {
        // assuming the maximum array size will not be more than 10000.
        int[] array = new int[10000];
        int first = 0;
        int last = 0;

        public void add(int x) {
            array[last++] = x;
        }

        public int poll() {
            if (!isEmpty()) {
                return array[first++];
            } else {
                return -1;
            }
        }

        public boolean isEmpty() {
            return first == last ? true : false;
        }

    }

}


texts:
I want to create a photo rating function. If I click thumbs up then votes increase, and if I click thumbs down then votes decrease.

function pictures(state = [], action) {
        switch(action.type) {
            case ADD_PICTURE:
                return [{
                    id: action.id,
                    picture: action.picture,
                    votes: 0
                    }
            , ...state];
            case LIKE_UP_PICTURE:
                return state.map(picture => {
                    if(picture.id === action.id) {
                    return {...picture, votes: picture.votes + 1}
                    }
                return picture;
                });
            case LIKE_DOWN_PICTURE:
                return state.map(picture => {
                    if(picture.id === action.id) {
                    return {...picture, votes: picture.votes - 1}
                    }
                return picture;
                });
            default:
                return state;
        }
    }


texts:
My code is working now. As you can see in the list.h some type definitions are too long and hard to read. Is there a way to do some short ones? And what happens if the code throws an exception? (I know I will have leaking memory parts) What can I do to collect garbage? And what other functions might be added to code to enhance it?

list.h

#ifndef LIST_H_
#define LIST_H_

#include <iostream>

template <typename T>
class list{
public:
    list();
    ~list();
    class node;
    typedef T           value_type;
    typedef T&          reference;
    typedef node        node_type;
    typedef node_type*  node_pointer;

    list&           push_back(value_type);
    value_type      pop_front();
    node_pointer    begin() const;
private:
    node_pointer    head, tail;
};

template <typename T>
class list<T>::node{
public:
    node(value_type value = 0);
    ~node();
    void            setData(value_type);
    value_type      getData() const;
    void            setNext(node_pointer);
    node_pointer    getNext() const;

private:
    value_type      data;
    node_pointer    ptr_next;
};

template <typename T>
inline list<T>::node::node(value_type value) : data(value), ptr_next(nullptr){
    //std::cout << "*" << value << "\t";
}

template <typename T>
inline list<T>::node::~node(){
    //std::cout << "node dtor" << std::endl;
}

template <typename T>
void list<T>::node::setData(value_type value){
    this->data = value;
}

template <typename T>
typename list<T>::value_type        list<T>::node::getData() const{
    return this->data;
}

template <typename T>
void list<T>::node::setNext(node_pointer ptr){
    this->ptr_next = ptr;
}

template <typename T>
typename list<T>::node_pointer  list<T>::node::getNext() const{
    return this->ptr_next;
}

template <typename T>
list<T>::list() : head(nullptr), tail(nullptr){
    //std::cout << "list ctor" << std::endl;
}

template <typename T>
list<T>::~list(){
    list<T>::node_pointer ptr = this->head, next_ptr;
    while(ptr != nullptr){
        //std::cout << "@" << ptr->getData() << "\t";
        next_ptr = ptr->getNext();
        delete ptr;
        ptr = next_ptr;
    }
}

template <typename T>
list<T>&    list<T>::push_back(value_type value){
    node_pointer item = new node_type(value);
    if(this->tail) this->tail->setNext(item);
    this->tail = item;
    if(!this->head) this->head = this->tail;

    return *this;
}

template <typename T>
typename list<T>::value_type    list<T>::pop_front(){
    if(this->head){
        node_pointer    item = this->head;
        value_type      value = this->head->getData();

        this->head = this->head->getNext();
        delete item;

        return value;
    }

return 0;
}

template <typename T>
typename list<T>::node_pointer list<T>::begin() const{
    return this->head;
}

template <typename T>
std::ostream & operator<<(std::ostream &stream, list<T> &obj){
    typename list<T>::node_pointer ptr = obj.begin();
    while(ptr != nullptr){
        stream << ptr->getData() << ' ';
        ptr = ptr->getNext();
    }
    return  stream;
}

#endif /* LIST_H_ */

main.cpp

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

    list<int> numbers;
    numbers.push_back(3).push_back(5).push_back(11);
    cout << numbers;

    return 0;
}


texts:
I posted the first part of this game earlier, and now I finished the second part.

From the first part we just had to have a random value to get the cards, and the bet always stayed at $25. For the second part the user could choose their bet, enter 0 to quit the game completely, and just hit enter to default to 25 on their first round, or can stay with their bet from the previous round.

My code is super messy and very long. I know it can be cleared up and made much shorter as I've seen people with around 70 lines of code.

import random

def main():
  restart = True

  bank_balance = 1000
  player_name = input("Please enter your name: ")
  #Default bet
  user_bet=25
  while restart:

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")

    bet = input_bet(user_bet, bank_balance)

    #Returned value from input_bet to stop the program
    if (bet == -10):
      break

    win_lose = play_hand(player_name, bet)
    bank_balance+=win_lose

    print(f'Your bank balance: ${bank_balance}')

def input_bet(bet, money):
  correct = False
  while not correct:
    if (money <=0):
      print('You ran out of money')
      return -10

    str_bet=input("Bet? (0 to quit, press 'Enter' to stay at $25) ")

    if (str_bet == ''):
      print(f'Staying at ${bet}')
      return bet

    try:
      enough_money = False
      while not enough_money:
        bet=int(str_bet)
        if (bet > money):
          print('not enough money')
          str_bet=input("Bet? (0 to quit, press 'Enter' to stay at $25) ")
          bet=int(str_bet)
        if (bet < 0):
          print('Enter a number greater than 0')
          str_bet=input("Bet? (0 to quit, press 'Enter' to stay at $25) ")
          bet=int(str_bet)
        elif (bet == 0):
          return 0
        elif (bet <= money):
          print(f'Betting ${bet}')
          enough_money=True
          return bet

      correct = True

    except ValueError:
      print('Please enter a whole number')

def play_hand(name, bet):
  player= []
  dealer= []

  play_again = True

  dealer.append(random.randint(1, 11))

  player.extend([random.randint(1, 11), random.randint(1, 11)])

  print ('The dealer received card of value', *dealer)
  print(name, 'received cards of value', player[0], 'and', player[-1])
  print(f'Dealer total is {sum(dealer)}')
  print(f"{name}'s total is {sum(player)}", '\n')

  stay = False
  bust = False

  while (sum(player) <= 21 and stay == False and play_again == True):
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')

      print(f'Dealer total is {sum(dealer)}')
      print(f"{name}'s cards are", *player)
      print(f"{name}'s total is {sum(player)}", '\n')

    elif (hors == 's'):
      stay=True
      print('stay')

  if (sum(player) > 21 ):
    bust = True
    print('You busted!')
    return -bet

  while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
    dealer.append(random.randint(1, 11))
    print('The dealers cards are', *dealer)
    print('The dealers total is', sum(dealer), '\n')

  if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
    print("The dealer wins!")
    return -bet

  elif (sum(player) <= 21 and sum(player) > sum(dealer)):
    print("You win!")
    return bet

  if (sum(dealer) > 21):
    print ('You win! The dealer busted!')
    return bet

  if (sum(dealer) == sum(player)):
    print('Its a Tie! ')
    return 0

main()


texts: Code Reiview for an PHP PDO Queries? is there a better way to do it?

texts:
so this is my code for a equipping an item in my game dev't:

try {
        $db = getConnection();

        $db->beginTransaction();

        $sql_chara_gold = $db->query("SELECT chara_gold FROM chara WHERE chara_id = $shop->chara_id");
        $get_chara_gold = $sql_chara_gold->fetchColumn();

        $sql_shop_price = $db->query("SELECT item_price FROM shop WHERE item_id = $shop->item_id");
        $get_shop_price = $sql_shop_price->fetchColumn();

        if($get_chara_gold >= $get_shop_price){
            $sql_put_item = "INSERT INTO bag(chara_id, item_id, item_qty)
            VALUES(:id,:item_id,1)
            ON DUPLICATE KEY
            UPDATE item_qty = item_qty +1";

            $sql_set_gold = "UPDATE chara ch
            INNER JOIN item it
            ON it.item_id = :item_id
            SET ch.chara_gold = ch.chara_gold - it.item_price
            WHERE chara_id = :id";

            $sql_set_qty =  "UPDATE shop
            SET item_qty = item_qty - 1
            WHERE item_id = :item_id";

            $stmt = $db->prepare($sql_put_item);
            $stmt->bindParam("id", $shop->chara_id);
            $stmt->bindParam("item_id", $shop->item_id);
            $stmt->execute();

            $stmt = $db->prepare($sql_set_gold);
            $stmt->bindParam("id", $shop->chara_id);
            $stmt->bindParam("item_id", $shop->item_id);
            $stmt->execute();

            $stmt = $db->prepare($sql_set_qty);
            $stmt->bindParam("item_id", $shop->item_id);
            $stmt->execute();

            $db->commit();

            $db = null;

            echo json_encode($shop);
        }else{
            echo '{"error":{"text":'.json_encode($get_shop_price).'}}';
        }


texts: A Better Understanding of LC-3 - Branch Loop to Stop When Encountering a Negative

texts:
Im going to start with that im trying to do.
Change this program to loop until it encounters a sentinel value, which is a negative number. The data begins at x3100. Use only one branch command. There will always be at least one positive integer in the list. No count controlled loop.
When the program ends, R2 must contain the number of values summed and R3 must contain the sum of those values.
.ORIG x3000

AND R3, R3, #0

AND R2, R2, #0

ADD R2, R2, #12

BRz #5

LDR R4, R1, #0

ADD  R3, R3, R4

ADD R1, R1, #1

ADD R2, R2, #-1

BRnzp #-6

.END

My textbook along with the professor are not being of much help so i came here to try a get a better understanding.
I know I can remove/get rid of the other two Branch Loop commands as I need only one, but I do not know how to structure that loop and getting R2 and R3 to work, it just seems they want to stay at 0.
EDIT: That was because i did not run it, i only opened it in the simulator.
I'm also not sure how i can just skip from x3000 to x3100 to fill data being provided from this loop.


texts: Resolving promises on resolver using ui-router

texts:
We're rewriting some parts of our application. We're trying to avoid the promise anti-pattern and do things properly, but I'm not certain that we did so.

More precisely, we are rewriting the resolver of a state using ui-router.

.state( 'catalogue', {
  // skipped on purpose not relevant content
  resolve :
    boxCreateData : function( $stateParams, $q, Basket, Customer ) {

      var defer = $q.defer(),
          basket = null,
          customer = null;

      Basket.fromApi( $stateParams.id )
        .then( function( basket ) {
          Customer.fromApi( basket.getCustomer() )
            .then( function( customer ) {
              defer.resolve( { basket : basket, customer : customer } );
            });
        });

      return defer.promise;

    }
});

Basket.fromApi and Customer.fromApi are static methods of their corresponding "class"es, Basket and Customer. Both implementations are like this (more or less; it's not the whole code, but it shows the concept. Customer.fromApi is the same):

Basket.fromApi = function( id ) {
  var defer = $q.defer();
  boxesResource.get( { id : id }, function( response ) {
    // various manipulation here with the response...
   defer.resolve( new Basket( ... ) );
  });
  return defer.promise;
};

Note we are using the get method of $resource.

The major issue here is that until we have the basket, we can't query the customer (because customer ID comes in the basket object).

We are querying first the basket with the basket ID. Once we have it, we can get the customer ID from the basket object and then, retrieve the customer object.

I just don't like the then pyramid. I'm not sure if we are missing something or in this case, there is no other way to do it.

Is there a cleaner way to accomplish the same thing?


texts:
I am currently completing "The Odin Project" and one of the first projects was to create a google homepage. I was wondering if some people could tell me all the long winded and unnecessary code I added and also tell me how I can better go about sticking the footer to the bottom of the page.

https://github.com/LHUF/google-homepage

HTML:

    <!DOCTYPE html>

        <title>Google</title>
        <link rel="stylesheet" href="style.css">

About Store

Gmail Images

        <form method="GET">
            <input type="text" id="searchbar"></input>

            <input type="submit" value="Google Search" class="searchbuttons"></input>
            <input type="submit" value="I'm Feeling Lucky" class="searchbuttons" id="imfeelinglucky"></input>
        </form>

United Kingdom

Advertising Business How Search Works

Privacy Terms Settings

CSS:

#imfeelinglucky {
    margin-left: 10px;
}

.searchbuttons {
    margin-top: 20px;
    text-align: center;
    height: 30px;
}

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

#searchbar {
    width: 400px;
    height: 25px;
    margin-top: -30px;
}

#searcharea {
    text-align: center;
    padding-top: 200px;

}

#unitedkingdom {
    position: relative;
    bottom: 5%;
    border-top-style: solid;
    border-bottom-style: solid;
    border-top: 1px;
    border-bottom: 1px;
    padding-top: 5px;
    padding-bottom: 5px;
    margin-top: 505px;
    color: rgba(0,0,0,.54);
    background: #f2f2f2;
    padding-left: 25px;
    font-size: 15px;
}

.gmailimages {
    position: absolute;
    top: 1%;
    right: 1%;
}

.aboutstore {
    position: absolute;
    top: 1%;
    left: 1%;
}

#bottomrightoptions {
    padding-right: 25px;
    font-size: 13px;
    padding-top: 15px;
    color: rgba(0,0,0,.54);
    background: #f2f2f2;
    position: absolute;
    float: right;
    padding-left: 800px;
    bottom: 0.5%;
    right: 0%;

}

#bottomleftoptions {
    padding-left: 25px;
    font-size: 13px;
    padding-top: 15px;
    color: rgba(0,0,0,.54);
    background: #f2f2f2;
    position: absolute;
    float: left;
    padding-right: 800px;
    bottom: 0.5%;
    left: 0%;
}

#about {
    margin-right: 5px;
}

#gmail {
    margin-right: 5px;
}

.links {
    color: #000;
    text-decoration: none;
    font-size: 13px;
}

body {
    font-family: Arial, sans-serif;
    margin:0;
    padding:0;
}


texts: Fantasy game inventory — Ch. 5 Automate the Boring Stuff

texts:
Here is a practice exercise — Fantasy Game Inventory \$-\$

  You are creating a fantasy video game. The data structure to model the
  player’s inventory will be a dictionary where the keys are string
  values describing the item in the inventory and the value is an
  integer value detailing how many of that item the player has. For
  example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches,
  42 gold coins, and so on.

  Write a function named display_inventory() that would take any
  possible “inventory” and display it like the following -

  Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62

  Hint - You can use a for loop to loop through all the keys in a
  dictionary.

I have written the following code. Any feedback is highly appreciated.

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def display_inventory(inventory):
    total_items = 0
    print ("Inventory:")
    for item in inventory:
        print(str(inventory[item]) + ' ' + item)
        total_items += inventory[item]
    print("Total number of items: " + str(total_items))

if __name__ == '__main__':
    display_inventory(stuff)


texts: Query optimization PHP for string concatination

texts:
I have an entity RegistrationForm which has a OneToMany-relationship with  SurveyAnswer.

An answer can either have a collection of FormOptions (when the answer is of type MULTIPLE_CHOICE) or a content represented by a string (type TEXT-FIELD, TEXTAREA etc.).

Below is a function inside the RegistrationForm-entity that tries to obtain a string-based representation of the answer's content.

public function getAnswerByColumnId($columnId) {
    foreach ($this->surveyAnswers as $answer) {
        if ($answer->getFormQuestion()->getId() == $columnId) {
            $formOptions = $answer->getFormOptions();
            if (count($formOptions) > 0) {
                $content = '';
                foreach ($formOptions as $key => $option) {
                    if ($key == 0) {
                        $content .= $option->getName();
                    } else {
                        $content .= ' , ' . $option->getName();
                    }
                }
                return $content;
            } else {
                return $answer->getContent();
            }
        }
    }
    return 'No column match, contact admin';
}

I am creating a table out of the registration forms. Each registration form has a few answers that are of a multiple-choice type.

The result is that the foreach ($formOptions as $key => $option) {...-section is pumping the amount of queries up from 200 to 2500.  How can I improve this?


texts: Iterative depth first search using adjacency matrix

texts:
I have written code for graph traversal using adjacency matrices in an iterative approach. The code should print the graph in a DFS way.

#include <iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    int c[n][n];
    int i,j;
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            cin>>c[i][j];
        }
    }
    int dfs[n];
    for(i=0;i<n;i++){
        dfs[i]=-1;
    }
    dfs[0]=1;
    j=1;
    for(i=0;i<n;i++){
        if(dfs[i]==1&&i>j)
        cout<<i;
        dfs[i]=1;
        while(c[i][j]!=0&&j<n&&i<n){
            if(dfs[j]==-1)
            {
                dfs[j]=1;
            }
            if(dfs[j]==1){
                cout<<j;
                j++;
            }
        }
    }
}

Is my code correct? If not, correct me. Can we decrease time complexity?


texts: More elegant way to round decimals in Python?

texts:
I am working with currencies, and so have been using the decimal module to rule out any floating point weirdness in the following maths.

I have to add together a number of decimal amounts, find an average of them, add ten percent, and then round it to the nearest round £. I then need to do more decimal maths with the output, so it'll need to be a decimal (or an integer) so I can play with it.  Adding the decimals has been fairly straightforward,  but doing the rest of the maths has left me with this line:

result = decimal.Decimal(round((sum_of_items / count_of_items) * decimal.Decimal(1.1), 0))

It strikes me that this isn't particularly elegant, as I'm converting the decimal average+10% to a float just to round it off, and then turning the result back into a decimal.

Am I risking any floating point weirdness with that brief conversion back to floating point? And is there any way to achieve the same effect as round using the decimal module so I don't have to go decimal->float->decimal?


texts: An Angular service to provide window and document objects

texts:
In some components and services I need the window and document. So I created a small service, that provides these two objects.

windowAndDocument.service.ts:

import { Inject, Injectable } from '@angular/core';

import { DOCUMENT } from '@angular/common';

function getWindow (): any {
  return window;
}

@Injectable({
  providedIn: 'root',
})

export class WindowAndDocumentService {
  public window = null;

  constructor(@Inject( DOCUMENT ) public document :HTMLDocument) {
    this.window = getWindow();
  }
}

This works fine and can be imported into other services.

some.service.ts:

import { Injectable } from '@angular/core';

import { WindowAndDocumentService } from './windowAndDocument.service';

@Injectable({
  providedIn: 'root',
})

export class SomeService {
  constructor(private wads: WindowAndDocumentService) {}

  soSomething() {
    console.log(this.wads.window);
    console.log(this.wads.document.doctype);
  }
}

My questions are:

Is this the optimal way to provide window and  document?
Can this be written more concisely? I find it kind of odd, that one variable is injected and the other is pulled from a function call.

It's a given that the app runs in the browser.


texts:
This program is yet to become user-friendly and is still in development, but I wanted to improve the current code.

from random import choice
from os import system

clear = lambda: system('cls') # FOR WINDOWS ONLY

words = [i.strip() for i in open('words.txt').readlines()]

# Possible stages
STAGES = [
"""

    -------
""",

"""
    _______
    |   |
    |
    |
    |
    |
    -------
""",

"""
    _______
    |   |
    |   O
    |
    |
    |
    -------
""",

"""
    _______
    |   |
    |   O
    |   |
    |
    |
    -------
""",

"""
    _______
    |   |
    |   O
    |  /|
    |
    |
    -------
""",

"""
    _______
    |   |
    |   O
    |  /|\\
    |
    |
    -------
""",

"""
    _______
    |   |
    |   O
    |  /|\\
    |  /
    |
    -------
""",

"""
    _______
    |   |
    |   O
    |  /|\\
    |  / \\
    |
    -------
"""]

class HangMan:
    def __init__(self):
        self.current_stage = 0                              # The stage in which the hangman is
        self.letters = [chr(i) for i in range(97, 97 + 26)] # Possible characters
        self.word = choice(words)                           # Random word
        self.current_word = ['_'] * len(self.word)          # The letters which the player has unlocked till now

    def get_input(self) -> int:
        """ Takes the player's input and processes it """

        print(*self.letters)
        print()

        char = input('Please enter a letter from the above set: ')

        while char.lower() not in self.letters:
            print(f'Invalid letter: {char}\n')
            char = input('Please enter another letter: ')

        print()
        return self.process_char(char)

    def process_char(self, given_char: str) -> int:
        """

        Processes the input and returns 0, 1, or 2

        0 -> Win
        1 -> Neither a win nor a loss
        2 -> Lose

        """

        self.letters.remove(given_char.lower())
        unlocked = 0

        for index, char in enumerate(self.word):
            if char.lower() == given_char.lower():
                self.current_word[index] = char
                unlocked += 1

        if '_' not in self.current_word:
            print('You\'ve won!')
            return 0

        if not unlocked:
            print('Whoops! Wrong letter!')

            if not self.next_stage():
                clear()
                print(STAGES[self.current_stage])
                print('You\'ve lost!')
                return 2
        else:
            print(f'Yay! You\'ve unlocked {unlocked} letter{"" if unlocked == 1 else "s"}!')

        return 1

    def next_stage(self) -> bool:
        """ Returns if this stage is the last """

        self.current_stage += 1

        if self.current_stage < len(STAGES) - 1:
            return True

        return False

    def game(self) -> None:
        """ Starts the game """

        while True:
            clear() # Comment if you are not using a command console

            print('Currently unlocked letters:', ''.join(self.current_word))
            print()
            print(STAGES[self.current_stage])

            x = self.get_input()

            if x == 0 or x == 2:
                print(f'The word was {self.word}!')

            print()
            input('Press enter to continue...')

            if x == 0 or x == 2:
                return

man = HangMan()

man.game()

How do I improve this? (Make this look better, make it faster, etc.)


texts:
Can this time converter be written more efficiently? I'm new to Java, and I would like to know.

main

import javax.swing.JFrame;

public class main {
        public static void main(String[] args) {
    window wn = new window();
        wn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        wn.setSize(275, 170);
        wn.setVisible(true);
    }
}

time

public class time {
    private int hour;
    private int minute;
    private String ampm;

    public void setTime(int h, int m, String t) {
        hour = ((h>=0 && h<=24) ? h : 0);
        minute = ((m>=0 && m<=60) ? m : 0);
        ampm = t;
    }

    public String to24h() {
        if (ampm == "PM") {
            hour += 12;
        }
        return String.format("%02d:%02d", hour, minute);
    }
}

window

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;

@SuppressWarnings("serial")
public class window extends JFrame {

    private JLabel label;
    private JTextField hours;
    private JTextField minutes;
    private JTextField output;
    private JButton twelve_button;
    public time timeConvert = new time();
    int tHours;
    int tMinutes;
    private String[] times = {"AM", "PM"};
    private JComboBox combo;
    String tAMPM;

    public window() {
        super("Time Converter");
        setLayout(new FlowLayout());

        label = new JLabel("Time");
        add(label);

        hours = new JTextField(2);
        add(hours);

        label = new JLabel(":");
        add(label);

        minutes = new JTextField(2);
        add(minutes);

        combo = new JComboBox(times);
        add(combo);

        twelve_button = new JButton("Convert to 24 hours");
        add(twelve_button);

        output = new JTextField(10);
        output.setEditable(false);
        add(output);

        label = new JLabel("It's my 'hello world' of java development!");
        add(label);

        label = new JLabel("by jackwilsdon");
        add(label);

        theHandler handler = new theHandler();

        hours.addActionListener(handler);
        minutes.addActionListener(handler);
        twelve_button.addActionListener(handler);
    }

    private class theHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (event.getSource() == twelve_button) {
                if (hours.getText() != null && minutes.getText() != null) {
                    try {
                        tHours = Integer.parseInt(hours.getText());
                        tMinutes = Integer.parseInt(minutes.getText());
                        tAMPM = (String)combo.getSelectedItem();
                        timeConvert.setTime(tHours, tMinutes, tAMPM);
                        if (tHours > 12) {
                            output.setText("Please enter a 12 hour number!");
                        } else if (tMinutes > 60) {
                            output.setText("Please enter a 12 hour number!");
                        } else {
                            output.setText(timeConvert.to24h());
                        }
                    }
                    catch(NumberFormatException nFE) {
                        output.setText("Please enter a number!");
                    }
                }
            }
        }
    }
}


texts:
I want to make a vertical cycle slideshow. This works perfectly for me but I'm just wondering if it's possible to achieve the same functioning with a better code. I don't know if my code would provoke a problem in some situations or not.

jsFiddle

var pare = $('#slider'); // selecting the holder element;
var ob = $('#slider > li'); // selecting items to handle;
var elm_show = 3; //  number of imgs to show at once;
var spd = 1000; // spd of scrolling;

var nex = ob.eq(0).height();
var leng = ob.length;
var jleng = leng-1;

ob.eq(jleng).css('top',-1*(leng*nex));// returning the last item to the first case;
pare.height(nex*elm_show); // define the holder length to display the desired number of item to be shown;

function anime(){
ob.each(function(i,item){$(item).animate({"top":"+="+nex+"px"},spd,

    "linear",function(){if ($(item).position().top == jleng*nex)
   {$(item).css('top',-1*nex*(i+1))}});})
 setTimeout(anime, 0);
 }

 anime();


texts:
I have a simple function that takes an Integer n and return a string representing the array from 1..n.

nthLine :: Integer -> String
nthLine n = intercalate " " $ map show [1..n]

The main function takes input n from the user and prints the nthLine out to screen:

getInteger :: String -> Integer      # This seems redundant
getInteger xs = (read xs)::Integer

nthLineStr :: String  -> String      # And so does this function
nthLineStr xs = nthLine (getInteger xs )

main = do line <- fmap nthLineStr getLine
          putStrLn line

Any tips on how this may be simplified/made better?


texts:
Can someone please review this code for me? I have not implemented all the methods for simplicity.

/**
 * Implements a blocking bounded queue from a given non-blocking unbounded queue implementation
 */
abstract class DerivedQueue<E> implements Queue<E>
{
    DerivedQueue(Queue<E> queue, int size)
    {
        if(queue==null | size <0)
        {
            throw new RuntimeException("Bad Input");
        }
        fQueue = queue;
        fSize = size;
    }

    Queue<E> fQueue;
    int fSize;
    int fCnt;

    @Override
    public boolean addAll(Collection<? extends E> arg0)
    {
        return false;
    }

    @Override
    public boolean isEmpty()
    {
        return (fCnt==0);
    }

    public E remove()
    {
        if(fCnt==0)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e);
            }
        }

        E elem =  fQueue.remove();
        fCnt--;
        notifyAll();
        return elem;
    }

    @Override
    public boolean add(E elem)
    {
        if(fCnt == fSize)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e);
            }
        }

        return fQueue.add(elem);
    }

}

Open questions:

Would calling notifyAll() lead to multiple waiting threads checking the while() condition at the same time, and hence there is a possibility that before the while gets satisfied, 2 threads are already out of it causing an outOfBound exception? Or does the methods need to be marked synchronized at all, and instead I can use a synchronized block for reading or writing part of the array while the checking of constrained and waiting can remain unsynchronized?
Is there a way to notify precisely only the consumer threads (waiting in take) or only the producer (waiting input) threads in this example? notifyAll notifies all of them.


texts: Reducing a 2D array to its longest unique series that aren't contained within any other

texts:
I have an array whose members are arrays containing strings. Each array has 5 elements, some of which may be empty but always at the end of the array. The order of the strings matters because their hierarchical labels—call them catLists. I need all the longest unique lists, ie. some of the shorter catLists are contained within longer ones, and for my purposes the shorter ones are redundant.

Here's a sample of the data:

// in fact my $catLists array is hundreds of elements long and changing weekly
$catLists = array(
                    0 => array('500ml', '750ml', '', '', '')
                    1 => array('sml', 'med', 'lrg', 'xlg', 'xxl'),
                    2 => array('big', 'bigger', 'biggest', '', ''),
                    3 => array('sml', 'med', 'lrg', '', ''),
                    4 => array('big', '', '', '', ''),
                    5 => array('300ml', '500ml', '750ml', '1L', '')
                    6 => array('1L', '750ml', '', '', ''));

// but if this were the list, then my desired output would be
$reducedCatLists = array(
                      0 => array('sml', 'med', 'lrg', 'xlg', 'xxl'),
                      1 => array('big', 'bigger', 'biggest'),
                      2 => array('300ml', '500ml', '750ml', '1L'),
                      3 => array('1L', '750ml'));

Although sequence matters, position doesn't, which is why, for my purposes, $catLists[0] would be considered contained within $catLists[5] but $catLists[6] wouldn't.

I've no idea how to do this efficiently; right now I'm reducing every array to a string and then comparing substrings, but it's not clear to me that this is a good way to do this (self-taught programmer who leans toward design rather than math—no CS here at all).

$catList_strings = array();
        $reduced_catLists = array();
        foreach ($catLists as $i => $catList) {
            $stringified = implode("",$catList);
            $contained = false;
            foreach ($catList_strings as $cl_str) {
                if ( strpos($stringified, $cl_str) ) $contained = true;
            }
            if (!$contained) {
                $catList_strings[] = $stringified;
                $reduced_catLists[] = array_filter($catList);
            }
        }

When this goes live I'd really like it not to be a burden to the server.


texts:
This is my OnAppearingAsync method where I as a page load in Xamarin I filter data, group it together, set data based on it, order the groups e.t.c. However the code is rather long and looks a bit messy, I've tried to refactor it myself but I always get stuck on where I'm supposed to start.

How can I improve this? Everything works beautifully and efficiently as far I know, I just believe it would never pass any code review in current status (We don't have code review though)

public async Task OnAppearingAsync(string houseCode)
        {
            HouseCode = houseCode;

            var client = AppClientHelper.Get();

            var groupHolders = new ObservableCollection<SubBrandGroup>();

            // Get The Groups
            List<SubBrandViewModel> subBrandViewModels = client.GetSubBrandViewModels(HouseCode);

            // Filter the subBrands
            var filteredSubBrands = subBrandViewModels.Where(item => CurrentCustomerCardViewModel.AllowedCategories.AllowedSubBrands.Contains(item.Code)).ToList();

            foreach (var subBrandViewModel in filteredSubBrands)
            {
                var basicItems = client.GetBaiscItemViewModelsBySubGroup(subBrandViewModel.HouseCode, subBrandViewModel.Code);

                // Apply the proper price, unique customer values e.t.c
                foreach (var basicItem in basicItems)
                {
                    basicItem.PropertyChanged += OnOrderCountUpdate;
                    await SetUniqueBrandStatusBrandStatus(basicItem);
                }

                // Order Item in SubGroup by alphabetical order
                var sortedItems = basicItems.OrderBy(item => item.Description).ToList();

                SubBrandGroup subBrand = new SubBrandGroup(subBrandViewModel.Name, true, subBrandViewModel.AdditionalCollateralItem, sortedItems);

                // Add group if not empty
                if (subBrand.Count != 0)
                {
                    groupHolders.Add(subBrand);
                }

                Currency = basicItems.FirstOrDefault()?.Currency;
            }

            if (groupHolders.Count == 0) return;

            // Order the groups
            int[] map = { 0, 2, 5, 3, 1, 4 };

            // Sort the group
            var sortedGroups = groupHolders.OrderBy(x => map[(int)x.AdditionalCollateralItem]).ToList();

            // Assign the new sorted items to the list
            ProductList = new ObservableCollection<SubBrandGroup>(sortedGroups);
        }


texts:
I wrote a Python script for implementing an A* algorithm. Map, Start and Goal are given.

The code works well as far as I tested it but I want to get feedback from the best out there too. So I am sharing the code here. Map is given to you as pickle file.

In the code M is:

class Map:
    def __init__(self, G):
        self._graph = G
        self.intersections = networkx.get_node_attributes(G, "pos")
        self.roads = [list(G[node]) for node in G.nodes()]

Graph = pickle.load(pickleFile)
M = Map(Graph)

Start/Goal are two integers representing nodes.

def shortest_path(M, start, goal):
    explored = set([start])
    frontier = dict([(i,[start]) for i in M.roads[start]]) if start!=goal else {start:[]}
    while frontier:
        explore = g_h(frontier,goal,M)
        for i in [i for i in M.roads[explore] if i not in frontier.keys()|explored]:
            frontier[i]=frontier[explore]+[explore]
        frontier = cleanse_frontier(frontier,M)
        if explore==goal:return frontier[explore]+[explore]#break when goal is explored.
        explored.add(explore)
        del frontier[explore]#once explored remove it from frontier.

def g_h(frontier,goal,M):
    g_h = dict([(path_cost(frontier[node]+[node],M)+heuristic(node,goal,M),node) for node in frontier])
    return g_h[min(g_h)]

def heuristic(p1,p2,M):#Euclidean Heuristic from the node to the goal node
    M=M.intersections
    return ((M[p1][0]-M[p2][0])**2+(M[p1][1]-M[p2][1])**2)**0.5

def path_cost(path,M,cost=0):#Euclidean distance for the path
    M=M.intersections
    for i in range(len(path)-1):
        cost += ((M[path[i]][0]-M[path[i+1]][0])**2+(M[path[i]][1]-M[path[i+1]][1])**2)**0.5
    return cost

def cleanse_frontier(frontier,M):
    """If any node can be removed from the frontier if that can be reached
    through a shorter path from another node of the frontier, remove it
    from frontier"""
    for node in list(frontier):
        for i in [i for i in frontier if i!=node]:
            if node not in frontier:continue
            if frontier[i]==frontier[node]:continue
            if i not in M.roads[node]:continue
            if path_cost(frontier[node]+[node]+[i],M)<path_cost(frontier[i]+[i],M):
                del frontier[i]
    return frontier


texts: Testing whether an abstract object is an instance of one of the several concrete classes

texts:
I have an abstract object and I need to test whether it is an instance of one of the several concrete classes. Every concrete class has a Value property that is not inherited.

The following points need to be true:

Single cast per class
Short circuit when one test is successful
No unnecessary casts

This is the solution I came up with:

public string Value { get; set; }

code in the setter of ObserverDto:

_observerDto = value; // underlying field
var oldValue = Value;

// single cast before test, goto to emulate if - else if
var booleanObserverDto = ObserverDto as BooleanObserverDto;
if (booleanObserverDto != null)
{
    Value = booleanObserverDto.CurrentValue == true ? booleanObserverDto.TrueText :
            booleanObserverDto.CurrentValue == false ? booleanObserverDto.FalseText : booleanObserverDto.CurrentValue.ToString();
    goto castDone;
}

var intObserverDto = ObserverDto as IntObserverDto;
if (intObserverDto != null)
{
    Value = intObserverDto.CurrentValue.ToString();
    goto castDone;
}

var decimalObserverDto = ObserverDto as DecimalObserverDto;
if (decimalObserverDto != null)
{
    Value = Convert.ToSingle(decimalObserverDto.CurrentValue).ToString(CultureInfo.CurrentCulture);
    goto castDone;
}

var stringObserverDto = ObserverDto as StringObserverDto;
if (stringObserverDto != null)
    Value = stringObserverDto.CurrentValue;

castDone:;

if(string.IsNullOrEmpty(Value))
    Value = "NULL";

if(!Value.Equals(oldValue))
    UpdateObserver(Name, Value);

I don't know of any possibility to have a statement between if and else if, but it might be better than using goto. Is there any way I could do a cast before an else if?

I can't change anything about the class structure or make it more generic because these classes are from a library I need to use.


texts: Use of pointers with file-reading program

texts:
I'm working on a school assignment, and it's working fine, but I have a feeling I'm over-using pointers, and I just can't think of a way to not pass a triple pointer to the function readFile.

I'd be more than grateful for your suggestions, and if you have any other suggestions on how to improve my code I'd be glad to hear those too!

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>

#define handle_error(message) \
    do { perror(message); exit(EXIT_FAILURE); } while(0)
int readFile(char ***names, FILE *file, int *size);
void *_realloc(void *ptr, size_t size);

int main(void) {
    char **names;
    int names_size;
    FILE *file;
    int chars_read;
    int i;

    names = NULL;
    file = NULL;
    names_size = 0;
    chars_read = 0;

    file = fopen("names", "r");
    readFile(&names, file, &names_size);
    printf("%s\n", names[0]);
    fclose(file);
    return EXIT_SUCCESS;
}

int readFile(char ***names_p, FILE *file, int *size) {
    int chars_read;
    int line;
    int chunk_size;
    int name_size;
    int name_length;
    char cur_char;
    char **names;
    char *name;

    name = NULL;
    names = NULL;
    line = 0;
    name_length = 0;
    name_size = 0;
    chunk_size = 2;
    chars_read = 0;
    while((cur_char = fgetc(file)) != EOF && cur_char != '\r'){
        if(cur_char == '\n') {
            if(name_size > 0) {
                names = _realloc(names, sizeof(char*) * (line+1));
                names[line] = _realloc(name, name_length + 1);
                names[line][name_length] = '\0';
                name_size = 0;
                name_length = 0;
                name = NULL;
                line++;
        }
    } else {
            if(name_size < name_length + 1) {
                name = _realloc(name,
                    sizeof(char) * (name_size =
                    (name_size + 1) * chunk_size));
            }
            name[name_length] = cur_char;
            name_length++;
        }
        chars_read++;
    }
    *names_p = names;
    *size = line;
    return chars_read;
}

void *_realloc(void *ptr, size_t size) {
    void *temp = realloc(ptr, size);
    if(temp == NULL) {
        int error = errno;
        if(error == ENOMEM) printf("size: %d\n", error);
        handle_error("realloc");
    }
    return temp;
}


texts:
I'm using ArrayList<Nodes> to store adjacent nodes, and ArrayList<Integer> to store the corresponding weights of the vertices. Is this efficient if I only use it for small inputs? Is it efficient for large inputs as well?

class Node {
    public ArrayList<Node> adjacent = new ArrayList<Node>();
    public ArrayList<Integer> weights = new ArrayList<Integer>();
    boolean visited;
}


texts: Scraping and analyzing recent articles on bitcoin

texts:
This script scrapes recent articles on bitcoin, does sentiment analysis, and does some mock trading based on the sentiment of the articles.  I'm looking for advice on code style, and I would love to learn how to write beautiful Ruby.

require 'coinbase'
require 'sanitize'
require 'cgi'
require 'htmlentities'
require 'sentimental'
require 'simple-rss'
require 'open-uri'
require 'sqlite3'
require 'date'

@db = SQLite3::Database.open('instructions.db')
@db.execute("CREATE TABLE IF NOT EXISTS instructions2(Id INTEGER PRIMARY KEY AUTOINCREMENT, Date TEXT, Do_now TEXT, Do_later TEXT, Buy_price TEXT, Sell_price TEXT)")
@rss = SimpleRSS.parse(open('http://fulltextrssfeed.com/news.google.com/news?pz=1&cf=all&ned=us&hl=en&q=Bitcoin&output=rss'))
@coinbase = Coinbase::Client.new(ENV['COINBASEKEY'])
@coder = HTMLEntities.new
Sentimental.load_defaults
@analyzer = Sentimental.new
@ran_today = false
@scores_today = []
@log = File.open('log.txt', 'w')

def write_log(me)
  @log << DateTime.now.to_s + " : " + me.to_s
end

def check_sentiment
  @ran_today = true
  @rss.items.each do |item|
    @scores_today.push(@analyzer.get_score(clean(item.description)))
  end
  react_sentiment
end

def react_sentiment
  avg = @scores_today.reduce(:+).to_f / @scores_today.size
  do_now = :nothing
  do_later = :nothing
  #if negative, sell now, buy when low
  if avg > 3.0
    do_now = :buy
    do_later = :sell
  elsif avg < -2.0
    do_now = :sell
    do_later = :buy
  end
  write_log("day's sentiment score : " + avg.to_s)
  method(do_now).call
  write_log(@db.execute("INSERT INTO instructions2(Date, Do_now, Do_later, Buy_price, Sell_price) VALUES (?, ?, ?, ?, ?)", (Date.today+2).to_s, do_now.to_s, do_later.to_s, check_buy.to_s, check_sell.to_s))
end

def read_instructions
  @db.execute("SELECT Id, Date, Do_now, Do_later, Buy_price, Sell_price FROM instructions2;").each do |id, date, do_now, do_later, buy_price, sell_price|
    if Date.today.to_s == date
      if do_now == "buy"
        if check_buy < sell_price.to_f
          buy
        else
          puts "want to buy, buy " + buy_price + "  > sell " + sell_price
        end
      elsif do_now == "sell"
        if check_sell > buy_price.to_f
          sell
        else
         puts "want to sell, sell " + sell_price + " > buy " + buy_price
        end
      end
      @db.execute("DELETE * FROM instructions2 WHERE Date=?", Date.today.to_s)
    end
  end
end

def buy
  write_log("would buy at " + check_buy.to_s + " at " + Date.today.to_s)
end

def sell
  write_log("would sell at " + check_sell.to_s + " at " + Date.today.to_s)
end

def nothing
  write_log("would do nothing at " + Date.today.to_s)
end

def check_sell
  @coinbase.sell_price(1)
end

def check_buy
  @coinbase.buy_price(1)
end

def clean(stuff)
  Sanitize.clean(CGI.unescapeHTML(stuff).to_s.force_encoding('UTF-8'))
end

check_sentiment
read_instructions
@ran_today = true
while true
  if Time.now.hour == 23 and not @ran_today
    check_sentiment
  elsif Time.now.hour == 1
    read_instructions
  elsif Time.now.hour == 24
    @ran_today = false
    @scores_today = []
  end
  sleep(60000)
end


texts:
I'm implementing an interface to the Force.com REST API, with very specific ideas about which parts of the API I need. My problem is with testability of consumers of this API abstraction.

The first thing I came up with was a Gateway, one method per action:

interface SalesforceApiGateway {
    fun getLastUpdated(type: ObjectType, backTill: Duration = Duration.ofDays(1)): LastUpdated
    fun getDetails(type: ObjectType, uuid: String, fields: List<String> = emptyList()): Details

    data class LastUpdated(val error: Throwable? = null, val response: LastUpdatedResponse? = null)
    data class Details(val error: Throwable? = null, val response: DetailsResponse? = null)
}

Consumers would get an instance of this interface @Injected, so tests could easily implement the interface and pass that to the unit under test.

But adding more object types and keeping responses meaningful and statically typed became increasingly difficult. Which is why I switched to the following:

interface SalesforceApiClient: HttpClient, BackendAuthenticator<SalesforceCredentials> {}

sealed class SalesforceRequest<T>(val apiClient: SalesforceApiClient) {
    fun getLastUpdated(backTill: Duration = Duration.ofDays(1)): List<String> {
        val req: HttpGet = buildHttpRequest()
        val resp = apiClient.execute(req)
        return ObjectMapper().readValue(resp.entity.content,
            object: TypeReference<List<String>>() {})
    }

    fun getDetails(uuid: String): T {
        val req: HttpGet = buildDetailRequest(uuid)
        val resp = apiClient.execute(req)
        return ObjectMapper().readValue(resp.entity.content, getValueClass())
    }

    abstract fun getObjectType(): String
    abstract fun getFields(): List<String>
    abstract fun getValueClass(): Class<T>

    class UserRequest(api: SalesforceApiClient): SalesforceRequest<User>(api) {
        override fun getObjectType() = "USER"
        override fun getFields() = User::class.members.map { it.name }
        override fun getValueClass(): Class<User> = User::class.java
    }
}

Voila, typed responses and a set of requests you can reason about at compile time. API consumers are happy now.

But how do I test around this beast? Of course, I can mock SalesforceApiClient, which is just the sum of HttpClient and BackendAuthenticator. But I feel dirty leaking knowledge about the structure of Force.com REST responses into unit tests for users of UserRequest. This kind of feeling tells me there's something wrong my class design. How can I do better?