texts: Clang preprocessor concatenates an extra space vs. gcc - standard C99

texts:
I maintain a C library project both on gcc and clang.

I am looking for advice on how to make the following macros more portable, terse, readable or standard abiding.

When I compile

#define STRINGIFY(arg) STRINGIFY_(arg)
#define STRINGIFY_(arg) #arg

#define VERSION 1.01
#define PROJECT myProject
#define SUB_PROJECT mySub
#define DASH -

#include STRINGIFY(PROJECT DASH SUB_PROJECT DASH VERSION.c)

I get

clang 6.0.0 standard C99

myProject - mySub - 1.01.c

gcc 7.4.0 standard C99

myProject-mySub-1.01.c

I came up with the following solution

#define STRINGIFY(arg) STRINGIFY_(arg)
#define STRINGIFY_(arg) #arg
#define ID(arg) arg

#define VERSION 1.01
#define PROJECT myProject
#define LIB myLib
#define DASH -
#define DOTC .c

#define FILEVERSION(a, b, c, d, e) STRINGIFY(ID(a)ID(b)ID(c)ID(d)ID(e)ID(DOTC))

#include FILEVERSION(PROJECT, DASH, LIB, DASH, VERSION)


texts:
How can I optimize this code to have fewer loops and return values for unit testing?

 public class Diamond {

public void DiamondShape(int num) {

   for(int ucount=num;ucount>0;ucount--) {
//Loop to print blank space
    for(int count_sp=1;count_sp<ucount;count_sp++)
        System.out.printf(" ");
//Loop to print *
    for(int count_ast=num;count_ast>=ucount;count_ast--)
        System.out.printf("* ");
    System.out.println();
   }

//Loop for lower half
  for(int lcount=1;lcount<num;lcount++) {
    //Loop to print blank space
    for(int count_sp=0;count_sp<lcount;count_sp++)
            System.out.printf(" ");
    //Loop to print *
        for(int count_ast=num-1;count_ast>=lcount;count_ast--)
            System.out.printf("* ");
    System.out.println();
    }
  }
}

Output when num = 3:

   *
  * *
 * * *
  * *
   *

This is how the output should be. num indicates the star in center line.


texts: Maximum product of a triplet in array in linear time

texts:
Given an array of integers, find the highest product you can get from three of the integers.

  Input:  [1, -4, 3, -6, 7, 0]

  Output: 168

I would love to hear from how this might be refactored/improved.

GitHub

public static int highestProduct(int[] numbers) {
    int largest, secondLargest, thirdLargest;
    int smallest, secondSmallest;

    largest = secondLargest = thirdLargest = Integer.MIN_VALUE;
    smallest = secondSmallest = Integer.MAX_VALUE;

    for (int number : numbers) {

        // logic to find the largest numbers
        if (number > largest) {
            thirdLargest = secondLargest;
            secondLargest = largest;
            largest = number;
        } else if (number > secondLargest) {
            thirdLargest = secondLargest;
            secondLargest = number;
        } else if (number > thirdLargest) {
            thirdLargest = number;
        }

        // logic to find the smallest numbers
        if (number < smallest) {
            secondSmallest = smallest;
            smallest = number;
        } else if (number < secondSmallest) {
            secondSmallest = number;
        }
    }

    return Math.max(largest * secondLargest * thirdLargest,
            largest * smallest * secondSmallest);
}

   @Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void invalidInput() {
    thrown.expect(InvalidArgumentException.class);
    HighestProductOfThree.highestProduct(new int[]{1, 2});
}

@Test
public void allPositiveNumbers() {
    Assert.assertEquals(30000, HighestProductOfThree.highestProduct(new int[]{1, 3, 2, 100, 100}));
    Assert.assertEquals(40, HighestProductOfThree.highestProduct(new int[]{1, 2, 4, 5}));
}

@Test
public void allNegativeNumbers() {
    Assert.assertEquals(-30, HighestProductOfThree.highestProduct(new int[]{-20, -10, -5, -3, -2}));
}

@Test
public void mixedNumbers() {
    Assert.assertEquals(300, HighestProductOfThree.highestProduct(new int[]{-10, -10, 1, 3, 2}));
    Assert.assertEquals(168, HighestProductOfThree.highestProduct(new int[]{1, -4, 3, -6, 7, 0}));
}


texts: Compare an array with a file and form groups from elements of an array

texts:
I have a text file with letters (tab delimited), and a numpy array (obj) with a few letters (single row). The text file has rows with different numbers of columns. Some rows in the text file may have multiple copies of same letters (I will like to consider only a single copy of a letter in each row). Also, each letter of the numpy array obj is present in one or more rows of the text file.

Letters in the same row of the text file are assumed to be similar to each other. Imagine a similarity metric (between two letters) which can take values 1 (related), or 0 (not related). When any pair of letters are in the same row then they are assumed to have similarity metric value = 1. In the example given below, the letters j and n are in the same row (second row). Hence j and n have similarity metric value = 1.

Here is an example of the text file (you can download the file from here):

b   q   a   i   m   l   r
j   n   o   r   o
e   i   k   u   i   s

In the example, the letter o is mentioned two times in the second row, and the letter i is denoted two times in the third row. I will like to consider single copies of letters rows of the text file.

This is an example of obj:

obj = np.asarray(['a', 'e', 'i', 'o', 'u'])

I want to compare obj with rows of the text file and form clusters from elements in obj.

This is how I want to do it. Corresponding to each row of the text file, I want to have a list which denotes a cluster (In the above example we will have three clusters since the text file has three rows). For every given element of obj, I want to find rows of the text file where the element is present. Then, I will like to assign index of that element of obj to the cluster which corresponds to the row with maximum length (the lengths of rows are decided with all rows having single copies of letters).

import pandas as pd
import numpy as np

data = pd.read_csv('file.txt', sep=r'\t+', header=None, engine='python').values[:,:].astype('<U1000')
obj = np.asarray(['a', 'e', 'i', 'o', 'u'])

for i in range(data.shape[0]):
    globals()['data_row' + str(i).zfill(3)] = []
    globals()['clust' + str(i).zfill(3)] = []
    for j in range(len(obj)):
        if obj[j] in set(data[i, :]): globals()['data_row' + str(i).zfill(3)] += [j]

for i in range(len(obj)):
    globals()['obj_lst' + str(i).zfill(3)] = [0]*data.shape[0]

    for j in range(data.shape[0]):
        if i in globals()['data_row' + str(j).zfill(3)]:
            globals()['obj_lst' + str(i).zfill(3)][j] = len(globals()['data_row' + str(j).zfill(3)])

    indx_max = globals()['obj_lst' + str(i).zfill(3)].index( max(globals()['obj_lst' + str(i).zfill(3)]) )
    globals()['clust' + str(indx_max).zfill(3)] += [i]

for i in range(data.shape[0]): print globals()['clust' + str(i).zfill(3)]

>> [0]
>> [3]
>> [1, 2, 4]

The code gives me the right answer. But, in my actual work, the text file has tens of thousands of rows, and the numpy array has hundreds of thousands of elements. And, the above given code is not very fast. So, I want to know if there is a better (faster) way to implement the above functionality and aim (using Python).


texts: MySQL connection using a static connection

texts:
I have been using a static class to connect and retrieve information from a MySQL database and also reading about how static works in php. I'm still not sure if the code is bad or not and why (besides the usual static are dangerous). Also, code improvements suggestions will be appreciated.

class Database {

    const STOREDPROCEDURE = 1;
    const ADHOC = 2;

    private static $instance;

    private static function call() {

        if (!isset(self::$instance)) {
            self::$instance = new MySQLi('localhost', 'root', '', 'alfred');
            if (self::$instance -> connect_error) throw new Exception(self::$instance -> connect_error);
            self::$instance -> set_charset('utf8');
        }

        return self::$instance;

    }

    public static function query() {

        //
        $arguments = func_get_args();
        $count = count($arguments);

        //
        $references = array();
        for ($i = 2; $i <= count($arguments) - 1; $i++) $references[$i] = &$arguments[$i];

        //
        $query = $count === 0 ? '' : str_repeat('?, ', $count - 4) . '?';
        $query = 'CALL' . ' ' . $arguments[1] . '(' . $query . ');';

        //
        $stmt = self::call() -> prepare($query);
        if ($count > 2) call_user_func_array(array($stmt, 'bind_param'), $references);

        //
        $stmt -> execute();
        $stmt -> store_result();

        //
        $result = array();
        while ($metadata = $stmt -> result_metadata()) {

            //
            $fields = array();
            foreach ($metadata -> fetch_fields() as $field) {
                $reference[$field -> name] = '';
                $fields[$field -> name] = &$reference[$field -> name];
            }

            //
            call_user_func_array(array($stmt, 'bind_result'), $fields);

            //
            $rows = array();
            while ($stmt -> fetch()) {
                $row = new stdClass();
                foreach ($fields as $name => $value) $row -> $name = $value;
                array_push($rows, $row);
            }

            //
            array_push($result, empty($rows) ? null : $rows);

            //
            $stmt -> next_result();

        }

        //
        $stmt -> free_result();
        $stmt -> close();

        //
        return $result;

    }

}

You can use the code by doing:

        $response = Database::query(
            Database::STOREDPROCEDURE,
            'UserRead',
            'sss',
            $useremail,
            $userpassword,
            $userhash
        );


texts:
My solution to Leetcode Next Permutation in Python.

  Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

  If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

  The replacement must be in-place and use only constant extra memory.

  Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

  1,2,3 → 1,3,2
  3,2,1 → 1,2,3
  1,1,5 → 1,5,1

Q:if the following code is Big \$O(N)\$.

def nextPermutation(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    def swap(i, j):
        while i < j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
            j -= 1

    n = len(nums)
    index = n - 2
    while index > -1 and nums[index] >= nums[index + 1]:
        index -= 1
    if index == -1:
        swap(0, n - 1)
        return
    i = n - 1
    while i > index and nums[i] <= nums[index]:
        i -= 1
    nums[i], nums[index] = nums[index], nums[i]
    swap(index + 1, n - 1)


texts: Faster/Better Processing for SQL While Loop

texts:
I have a list of about 55k Accounts that I am cleaning up.  95% of them are from US/Canada which is what I'm most concerned with.  I am going through record by record and will perform various checks and fill in or correct City, State, Zip, Country.  I have a table with every City, State, and Zip for US and Canada that I check against.  For this part, maybe 20% will be processed after grabbing the info.

I am doing a kind of proof of concept right now, and it's taking forever.  I just hit the 1hr mark with 24,500 (Less than 7 records/sec)  .  I didn't expect this to take so long.  Next will be running a similar process on the Contacts, and there are over 400k contacts.  I'm afraid how long that will take!!

Is there a better way to do this to decrease the time taken?

Here is the code right now:

-- MS SQL Server 15.0.2070.41
ALTER PROCEDURE [dbo].[SetLocationInfo]
AS
BEGIN

DECLARE
    @maxRecords int = 0,
    @cnt        int = 1,
    @city       varchar(255),
    @state      varchar(255),
    @zip        varchar(255),
    @country    varchar(255)

SELECT TOP(1) @maxRecords = id2 FROM Account ORDER BY Id2 DESC

-- BEGIN LOOP
WHILE @cnt <= @maxRecords
BEGIN
    -- Resets Variables
    SET @city = NULL
    SET @state = NULL
    SET @zip = NULL
    SET @country = NULL

    -- Pulls BILLING Address Info from Record
    SELECT
        @city = [BillingCity],
        @state = [BillingState],
        @zip = [BillingPostalCode],
        @country = [BillingCountry]
      FROM [Account] WHERE Id2 = @cnt

    -- Searches for and Sets BILLING Country
    IF (@country IS NULL) OR ((@country != 'United States') AND (@country != 'Canada'))
    BEGIN
        SELECT TOP(1) @country = Country FROM [CityStateInfo]
          WHERE
          (City = @city AND State_abbr = @state) OR
          (City = @city AND Zip = LEFT(@zip,5)) OR
          (Zip = LEFT(@zip,5))

        IF @country IS NOT NULL
            UPDATE Account SET [BillingCountry] = @country WHERE Id2 = @cnt
    END

    -- Resets Variables
    SET @city = NULL
    SET @state = NULL
    SET @zip = NULL
    SET @country = NULL

    -- Pulls SHIPPING Address Info from Record
    SELECT
        @city = [ShippingCity],
        @state = [ShippingState],
        @zip = [ShippingPostalCode],
        @country = [ShippingCountry]
      FROM [Account] WHERE Id2 = @cnt

    -- Searches for and Sets SHIPPING Country
    IF (@country IS NULL) OR ((@country != 'United States') AND (@country != 'Canada'))
    BEGIN
        SELECT TOP(1) @country = Country FROM [CityStateInfo]
          WHERE
          (City = @city AND State_abbr = @state) OR
          (City = @city AND Zip = LEFT(@zip,5)) OR
          (Zip = LEFT(@zip,5))

        IF @country IS NOT NULL
        BEGIN
            PRINT CAST(@cnt AS varchar(10)) + ': ' + @country
            UPDATE Account SET [ShippingCountry] = @country WHERE Id2 = @cnt
        END
    END

    -- Increments Counter
    SET @cnt = @cnt + 1
END
-- END LOOP

END


texts:
This is a piece of C89 code testing a function titled logging_function(), which takes two arguments and uses them to log a bit of information.

In this case, the first argument to the function is the string to be logged, and the second argument is a string holding a path in a filesystem to a log file. The first string is printed, with a timestamp, to stdout and the log file.

Note: although yes input on the main() function would be wonderful, I'd love it if you gave thoughts on the function logging_function() itself.

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

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

typedef struct tm tm;

int logging_function(char input_string[], char log_file_string[])
{
    /*Initializations.*/
    char output_string[32767];
    FILE* log_file_stream;
    time_t current_time_epoch_format;
    tm* current_time_calandar_format;

    /*Creating timestamp in output string, amending first argument to output string, and logging.*/
    if ((strlen(input_string) + 23) > 32767) return EXIT_FAILURE;
    if ((current_time_epoch_format = time(&current_time_epoch_format)) == -1) return EXIT_FAILURE;
    if ((current_time_calandar_format = localtime(&current_time_epoch_format)) == NULL) return EXIT_FAILURE;
    if (strftime(output_string, 23, "[%d-%m-%Y %H:%M:%S] ", current_time_calandar_format) != 22) return EXIT_FAILURE;
    if ((log_file_stream = fopen(log_file_string, "a")) == NULL) return EXIT_FAILURE;
    if (printf("%s\n", strcat(output_string, input_string)) < 1) return EXIT_FAILURE;
    if (fprintf(log_file_stream, "%s\n", output_string) < 1) return EXIT_FAILURE;
    if (fclose(log_file_stream) == EOF) return EXIT_FAILURE;
    return EXIT_SUCCESS;
}

int main(int argc, char** argv)
{
    /*Initializations.*/
    int EXIT_CODE;

    /*Print the returned integer from logging_function and exit.*/
    printf("%d\n", (EXIT_CODE = logging_function(argv[1], argv[2])));
    exit(EXIT_CODE);
}


texts: Call a method from all GameObjects implementing a specific interface in Unity

texts:
my player has a gun with 3 bullets. If he runs out of ammo the scene should reset itself. I don't want to load the scene again, some components should reset themselves by using an interface.

So my observer class keeps track of the bullets and when there is nothing "active" anymore it should reset the scene.

When a bullet goes inactive it starts calling the observer.

public class Observer : MonoBehaviour
{
    [SerializeField]
    private Projectile[] projectiles; // my 3 bullets

    public void ResetScene()
    {
        for (int i = 0; i < projectiles.Length; i++)
        {
            Projectile currentProjectile = projectiles[i];

            if (currentProjectile.IsActive) // Are any bullets left?
            {
                return; // Leave this method
            }
        }

        MonoBehaviour[] sceneObjects = FindObjectsOfType<MonoBehaviour>(); // find all objects in the scene

        for (int i = 0; i < sceneObjects.Length; i++)
        {
            MonoBehaviour currentObj = sceneObjects[i];
            IRewindable currentComponent = currentObj.GetComponent<IRewindable>(); // try to get the interface component

            if (currentComponent != null) // does the gameobject implement this interface?
            {
                currentComponent.Rewind(); // make it rewind itself
            }
        }
    }
}

I think the code below the first loop might not be the best. Is there a more optimized way of finding all interface components and call their Rewind method?


texts: Command-line implementation of Mastermind

texts:
I just finished this command-line implementation of the Mastermind board game that allows two players to play against each other. I'm fairly new to Ruby, but I think I did a decent job with this. However, I'm sure there are some things I could've done better, so please let me know if there are.

class Codebreaker
  attr_accessor :colors

  def initialize
    @colors = []
  end
end

require 'io/console'

class Codemaker
  attr_accessor :code_colors

  def make_code
    puts "\nCodemaker, select 4 colors! Please enter them separated by spaces, with no commas.  To prevent cheating, your input will be hidden.  Try to not make any typos :)"
    input = STDIN.noecho(&:gets).chomp
    @code_colors = input.split(" ")
    puts "Excellent!"
  end
end

class Game
  require_relative "codebreaker.rb"
  require_relative "codemaker.rb"

  def initialize
    @code_breaker = Codebreaker.new
    @code_maker = Codemaker.new
    @turn = 1
    start_game
  end

  def start_game
    puts "Welcome to Mastermind!
    \nRules:
    \nThe codemaker creates a code consisting of four colors chosen from the provided list.
    It is the goal of the codebreaker to crack the code in 12 turns, entering the same exact colors in the same order.  To attempt to crack the code, simply
    keep guessing.
    \nYou may choose from the following colors: red, blue, green, yellow, orange, purple, white, and black."
    @code_maker.make_code
    turn
  end

  def turn
    while @turn < 12
      code_breaker_input
      compare
      @turn += 1
      if @turn == 12
        puts "Unfortunately, you didn't guess the codemaker's code in the allotted 12 turns.  Better luck next time!"
        exit
      end
    end
  end

  def code_breaker_input
    puts "\nCodebreaker, please make your selection! Enter colors in lowercase, separated by spaces, with no commas."
    @code_breaker.colors = gets.chomp
  end

  def compare
    b_colors = @code_breaker.colors.downcase.split(" ")
    m_colors = @code_maker.code_colors
    correct_indexes = []
    correct_colors = []

    b_colors.zip(m_colors).map { |a, b|
      if a == b
        correct_indexes << "X"
      else correct_indexes << "O"       end
    }

    b_colors.each { |color|
      m_colors.any? { |c_color|
        correct_colors << color if c_color == color
      }
    }

    puts correct_indexes.join(" ")
    puts "Colors guessed correctly: #{correct_colors.join(", ")}"

    #checks win condition
    if correct_indexes.all? { |index| index == "X" }
      puts "The codemaker cracked the code!"
      exit
    end
  end
end

game = Game.new
```


texts: Help me condense a series of lengthy javascript conditional arrays

texts:
I'm not too used to working with arrays in javascript, so was wondering if there is a good way to condense this down.

Any pointers much appreciated!

you can see it in action @ http://www.productionlocations.com/locations

if($('.filters').length) {
    if(url === 'http://www.productionlocations.com/locations' || url === 'http://www.productionlocations.com/locations/') {
        searchval[0] = 'Find a location…';
        searchval[1] = 'Try searching by zip code, like 90012…';
        searchval[2] = 'Know your location ID? Find it like so: #xxxx';
        searchval[3] = 'Search locations by type, like apartment, office, or retail...';
        searchval[4] = 'Search locations by area, like downtown, Pasadena, or Hollywood...';
        searchval[5] = 'Search locations by style, like art deco, tudor, or industrial...';
        searchval[6] = 'Search locations by feature, like fireplace, pond, or tiled floors...';
    } else {
        searchval[0] = 'Modify your search by type, like apartment, office, or retais...';
        searchval[1] = 'Modify your search by area, like downtown, Pasadena, or Hollywood...';
        searchval[2] = 'Modify your search by style, like art deco, tudor, or industrial...';
        searchval[3] = 'Modify your search by feature, like fireplace, pond, or tiled floors...';
        searchval[4] = 'Modify your search…';
        searchval[5] = 'Modify your search by zip code, like 90012…';
    }

    searchkey = Math.floor(Math.random() * searchval.length);
    $('#s').val(searchval[searchkey]);
} else {
    searchval[0] = 'Find a location…';
    $('#s').val(searchval[0]);
    inputReplace();
}


texts:
I have written a function to get the actual page range to display that page range in pagination.

My function is working properly. But I think that I have written bad code. Can someone review my code and give me some feedback to improve my code?

Here is the code:

const pageRange = (() => {
  let startPage = activePage < pageNeighbours + 1 ? 1 : activePage - pageNeighbours;
  const endPage = totalPages < (pageNeighbours * 2) + startPage
    ? totalPages : (pageNeighbours * 2) + startPage;
  const diff = (startPage - endPage) + (pageNeighbours * 2);
  startPage -= (startPage - diff > 0 ? diff : 0);
  let actualPageRange = new Array((endPage - startPage) + 1)
    .fill().map((_, i) => i + startPage);
  if (actualPageRange[0] !== 1) actualPageRange = [1, ...actualPageRange];
  if (actualPageRange[1] !== 2) actualPageRange = [1, '...', ...actualPageRange.slice(1)];
  if (actualPageRange[actualPageRange.length - 1] !== totalPages) {
    actualPageRange = [...actualPageRange, totalPages];
  }
  if (actualPageRange[actualPageRange.length - 2] !== totalPages - 1) {
    actualPageRange = [...actualPageRange.slice(0, actualPageRange.length - 1), '...', totalPages];
  }
  return actualPageRange;
})();

In the above code:

activePage refers to the current page number.

pageNeighbours refers to the number of pages that should be shown besides active page

totalPages is self-explanatory

Update

After this function execution, I will use pageRange to create output like:


texts: OpenCV numpy image tranformation efficiency

texts:
I am doing a few image transformations - resize, offset, and crop. I am doing all these operations separately, but I feel like they can be better combined to get a speed improvement. This is happening hundreds of times in a loop, so I am looking to optimize this code.
Any suggestions would be great - I am somewhat new to numpy.
Here is my code as it is now:

# original image is only loaded into memory once:
self.original_image = cv2.imread(self.file_path, cv2.IMREAD_UNCHANGED)

# image is resized...
image_resize = cv2.resize(self.original_image, (0, 0), fx=zoom, fy=zoom)

# offset image
M = np.float32([[1, 0, x_total], [0, 1, y_total]])
image_offset = cv2.warpAffine(image_resize, M, (self.original_image_width, self.original_image_width))

#image crop
image = image_offset[0:self.output_raster_height, 0:self.output_raster_width].copy()

#numpy to pil and away!
corrected_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
from_pil = PImage.fromarray(corrected_img)
from_pil.save(p.stdin, 'JPEG')

Suggestions would be much appreciated!


texts: How do I make my Rock-Paper-Scissor program more JavaScript-like?

texts:
I have implemented my first program in JavaScript, Rock-Paper-Scissors. I would like JavaScript developers to help me make this program more JavaScript-like by following the idioms of the language. I am also open to any suggestions related to simplification of logic and code readability.

The following is the complete listing of the program:

<html>
<head></head>
<body>
    <script>
        var choiceArray = ["paper", "rock", "scissors"];

        var getUserChoice = function()
        {
            var userChoice = undefined;
            var userChoiceIndex = undefined;

            while (true)
            {
                userChoice = prompt("What do you like - paper, scissor or rock");
                userChoiceIndex = choiceArray.indexOf(userChoice);

                if (userChoiceIndex >= 0 && userChoiceIndex <= 2)
                    return userChoice;

                alert("Invalid Choice!");
            }
        }

        var getComputerChoice = function()
        {
            var computerChoiceIndex = Math.floor(Math.random() * 3);
            return choiceArray[computerChoiceIndex];
        }

        var decideWinner = function(userChoice, computerChoice)
        {
            if (userChoice === computerChoice)
                return "There is a tie!";

            if (userChoice === "paper")
            {
                if (computerChoice === "rock")
                {
                    return "paper wins!";
                }
                else //scissors
                {
                    return "scissors win!";
                }
            }
            if (userChoice === "rock")
            {
                if (computerChoice === "paper")
                {
                    return "paper wins!";
                }
                else //scissors
                {
                    return "rock wins!";
                }
            }
            else //scissors
            {
                if (computerChoice === "paper")
                {
                    return "scissors wins!";
                }
                else //rock
                {
                    return "rock wins!";
                }
            }
        }

        var runGame = function()
        {
            var userChoice = getUserChoice();
            var computerChoice = getComputerChoice();
            var gameResult = decideWinner(userChoice, computerChoice);
            gameResult = "Computer Choice = " + computerChoice + ". " + gameResult;
            alert(gameResult);
        }

        runGame();
    </script>
</body>
</html>


texts: Plotting the Mandelbrot set at different zoom levels

texts:
I'm interested in making an animated movie of a zoom in on a part of the Mandelbrot set.  My code works well for a few zooms, but upon trying to zoom in quite far, I find that the fractal becomes "smoothed out".  Am I missing something that prevents me from seeing the fractal structure at higher zoom levels?  Am I hitting machine precision in the computations?  Here's what I'm talking about:

Zoom level 3:

Zoom level 9:

Zoom level 20:

The first plot looks good, the second is okay, and the third is not fractal at all.

If there are any other deficiencies or improvements I'd be glad to hear about them as well.

Here's my code:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib import animation
import time

# some interesting places in the set
# http://www.nahee.com/Derbyshire/manguide.html

N = 500
nIts = 25
nZooms = 50
x0=0
y0=-1

movie = np.zeros([N,N,nZooms])

x = np.linspace(-2,1,N)
y = np.linspace(-1,1,N)
X,Y = np.meshgrid(x,y)
c = X + 1j*Y
z = 0*c
for i in range(nIts):
    z = z**2 + c

mask = np.abs(z) < 1
z[z>1]=0
z[np.isnan(z)]=0
movie[:,:,0] = mask

# plotting stuff
for j in range(1,nZooms):
    h=1./(2**j)
    print "Plot number ", j
    x = x0+h*np.linspace(-1,1,N)
    y = y0+h*np.linspace(-1,1,N)
    X,Y = np.meshgrid(x,y)
    c = X + 1j*Y
    z = 0*c
    for i in range(nIts):
        z = z**2 + c

    mask = np.abs(z) < 1
    z[z>1]=0
    z[np.isnan(z)]=0
    movie[:,:,j] = mask

fig = plt.figure()

for j in range(nZooms):
    name = "image%d.png" % j
    plt.imshow(movie[:,:,j], cmap = 'RdBu')
    plt.gray()
    plt.axis('equal')
    plt.axis('off')
    # plt.show()
    fig.savefig(name)
    time.sleep(1)


texts: Preventing duplicate key errors in EF-Core InMemory provider through locking

texts:
I have a rest service on Azure AD that calls other rest services. They use AzureAd authentication and AuthContext with a custom TokenCache that stores each users tokens in an InMemory EF Core database. Sometimes I'd get exceptions in AfterAccessNotification when I'd call SaveChanges().

var cache = context.TokenCacheEntries.Find(userObjectId) ?? context.TokenCacheEntries
                                .Add(new TokenCacheEntry { userObjId = userObjectId }).Entity;
                cache.LastWrite = DateTime.Now;
                cache.cacheBits = Serialize();

                // update the DB and the lastwrite
                context.SaveChanges();
                HasStateChanged = false;

A possible cause of this is I have to initialize this context in the Singleton scope because I use it via AuthContext in my JwtBearerEvents.OnTokenValidated method.

I solved the problem with a lock:

    private static object saveLock = new object();

    /// <remarks>
    /// Notification raised after ADAL accessed the cache.
    /// If the HasStateChanged flag is set, ADAL changed the content of the cache
    /// </remarks>>
    private void AfterAccessNotification(TokenCacheNotificationArgs args)
    {

        if (HasStateChanged)
        {
            // SaveChanges() threw an exception that a key already existed once so lets hope this lock fixes that.
            lock (saveLock)
            {
                // retrieve last write from the DB
                var cache = context.TokenCacheEntries.Find(userObjectId) ?? context.TokenCacheEntries
                                .Add(new TokenCacheEntry { userObjId = userObjectId }).Entity;
                cache.LastWrite = DateTime.Now;
                cache.cacheBits = Serialize();

                // update the DB and the lastwrite
                context.SaveChanges();
                HasStateChanged = false;
            }
        }
    }

Is there a better way?


texts: Date and time columns conversion to Time(WithZone)

texts:
I have two columns representing a date and a time.

{dateproc: '2012-03-23', horproc: '2000-01-01 16:15:23 UTC'}

Both are read as a TimeWithZone by Rails. I need to combine them.

This is what I've done. It works, but it doesn't feel elegant, and it just doesn't seem readable.

date_time_combined = dateproc + horproc.seconds_since_midnight.seconds

Any advice on improving it?


texts: VBA script to add formulas to Excel is running slow

texts:
I have written the following VBA script that searches for a text string in column CI and if it finds it the specific text the script adds a formula to a series of cells. The script itself runs correctly but I think it is taking much longer to run than it should. I am assuming there are some form efficient ways to write the code.

I have other scripts in the same Excel workbook that take 30 seconds to run but this script takes almost 7 minutes. It is searching through just over 900 cells in the test case I am using. Which in the grand scheme of thing, that is not really that many cells. How can I make it more efficient?

Private Sub Material_Formulas()

Dim lRow As Integer
Dim tiesMaterial As String
Dim result As String

lRow = Sheets("Material").Range("A2").End(xlDown).Row
lCol = Sheets("Material").Range("A2").End(xlToRight).Column

'Starts the count at column CU
endCount = lCol - 1

    For c = 99 To endCount
        For r = 3 To lRow

        tiesMaterial = Cells(r, 87).Value

        'Looks to see if the cells starting at CU2 contains a number and then iterates through each cell in row 3 to add a formula
        If tiesMaterial = "TIES MATERIAL" Then

            materialID = Sheets("Material").Cells(r, "CQ").Address(False, False)
            materialYear = Sheets("Material").Cells(2, c).Address(False, False)

            'Starting in cell CU3 it adds the formula =INDEX(BOM_Summary_Array,MATCH(CQ3,BOM_Summary_ID,0),MATCH(CU2,BOM_Summary_Head,0))
            Sheets("Material").Cells(r, c).Formula = "=INDEX(BOM_Summary_Array,MATCH(Material!" & materialID & ",BOM_Summary_ID,0),MATCH(Material!" & materialYear & ",BOM_Summary_Head,0))"

        End If

        Next r
    Next c

End Sub


texts: Python program for "0-1 knapsack problem"

texts:
Here is what a knapsack/rucksack problem means (taken from Wikipedia):

  Given a set of items, each with a weight and a value, determine the
  number of each item to include in a collection so that the total
  weight is less than or equal to a given limit and the total value is
  as large as possible. It derives its name from the problem faced by
  someone who is constrained by a fixed-size knapsack and must fill it
  with the most valuable items.

With reference to - https://en.wikipedia.org/wiki/Knapsack_problem - this is the definition of a 0-1 knapsack or a 0-1 rucksack problem:

Here is my version of the "0-1 knapsack problem" in python:

def knapsack(capacity, items, weights, values):

    grid = [[0] * (capacity + 1)]
    for item in range(items):
        grid.append(grid[item].copy())
        for k in range(weights[item], capacity + 1):
            grid[item + 1][k] = max(grid[item][k], grid[item][k -weights[item]] + values[item])

    solution_value = grid[items][capacity]
    solution_weight = 0
    taken = []
    k = capacity
    for item in range(items, 0, -1):
        if grid[item][k] != grid[item - 1][k]:
            taken.append(item - 1)
            k -= weights[item - 1]
            solution_weight += weights[item - 1]

    return solution_value, solution_weight, taken

NOTES - The total weight of the taken items cannot exceed the capacity of the knapsack. The total weight of the items in the knapsack is called “solution weight”, and their total value is the “solution value”.

Here are some example input values,

values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
items = len(values)

print(knapsack(capacity, items, weights, values))
print('knapsack() Time: ' + str(timeit.timeit('knapsack(capacity, items, weights, values)', setup = 'from __main__ import knapsack, capacity, items, weights, values')))

where my budget ($50) is the sack’s capacity, the shares are the items to be packed, the current prices are the weights and the price estimates are the values.

Here is an example output,

(220, 50, [2, 1])
knapsack() Time: 54.669268087000006

NOTE - knapsack() Time is in milliseconds.

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

Any help would be highly appreciated.


texts: Validation/error handling of user input values

texts:
This is a tiny learning program that lead to an interesting question: how can I best/most elegantly handle user entered numbers? This method works, fails cleanly, and reads well. It doesn't apply to types other than build in ones (as far as I know), but for floats and integers it's a nice feature. But it doesn't scale well, and seems cumbersome. Thoughts?

  Read two numbers (a,b) then increment (a) by one if ( a > b ) and (a >
  0)  otherwise decrement (a) by one. Print (a).

  Sample Input:
  27
  36

  Sample Output:
  26

#include <iostream>
#include <stdexcept>

int main() {
    int a, b;

    try {
        std::cin >> a;
        if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n");
        std::cin >> b;
        if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n");

    } catch (const std::runtime_error& e) {
        std::cout << e.what();
        return 1;
    }

    if (a > b && a > 0) {
        ++a;
    } else {
        --a;
    }

    std::cout << a;

    return 0;
}


texts: Section 2: Classes - Design a StackOverflow Post

texts:
Design a class called Post. This class models a StackOverflow post. It should have properties
  for title, description and the date/time it was created. We should be able to up-vote or down-vote
  a post. We should also be able to see the current vote value. In the main method, create a post,
  up-vote and down-vote it a few times and then display the the current vote value.

  In this exercise, you will learn that a StackOverflow post should provide methods for up-voting
  and down-voting. You should not give the ability to set the Vote property from the outside,
  because otherwise, you may accidentally change the votes of a class to 0 or to a random
  number. And this is how we create bugs in our programs. The class should always protect its
  state and hide its implementation detail.

  Educational tip: The aim of this exercise is to help you understand that classes should
  encapsulate data AND behaviour around that data. Many developers (even those with years of
  experience) tend to create classes that are purely data containers, and other classes that are
  purely behaviour (methods) providers. This is not object-oriented programming. This is
  procedural programming. Such programs are very fragile. Making a change breaks many parts
  of the code.

That is the information given to me for this exercise in my C# tutorial.  The following is my working code.  Still trying to grasp Object Oriented Programming.  I believe I did set the properties so that you can get the information but not give the ability to set the Vote property from the outside by setting the property to Private.  I also tried to protect the state of voting so that you could not up-vote or down-vote consecutively, yet allow it to change your vote and show the vote count along with protecting the state of the vote count.

Anyhow if anyone can see how to improve on this, point out a better way, or teach me something new I would greatly appreciate it.

using System;

namespace ExerciseTwo
{
    class Post
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime TimeDateCreated { get; private set; }
        public int VoteCount { get; private set; }
        private bool HasVotedUp;
        private bool HasVotedDown;

        public Post(string title, string description)
        {
            Title = title;
            Description = description;
            TimeDateCreated = DateTime.UtcNow;
            VoteCount = 0;
        }

        public void VoteUp()
        {
            if (HasVotedUp)
            {
                throw new Exception("You have already up-voted.");
            }
            else
            {
                VoteCount++;
                HasVotedUp = true;
                HasVotedDown = false;
            }
        }

        public void VoteDown()
        {
            if (HasVotedDown)
            {
                throw new Exception("You have already down-voted.");
            }
            else
            {
                VoteCount--;
                HasVotedDown = true;
                HasVotedUp = false;
            }
        }
    }
}

Script to demo how it could work.

namespace ExerciseTwo
{
    class Program
    {
        static void Main()
        {
            Post post = new Post("Does my post work?", "Test to see if my post works.");
            System.Console.WriteLine($"Title: {post.Title}");
            System.Console.WriteLine($"Description: {post.Description}");
            System.Console.WriteLine($"Date Created: {post.TimeDateCreated}");
            System.Console.WriteLine($"Post Count: {post.VoteCount}");
            post.VoteDown();
            System.Console.WriteLine($"Post Count: {post.VoteCount}");
            post.VoteUp();
            System.Console.WriteLine($"Post Count: {post.VoteCount}");
        }
    }
}

Thank you for your help!


texts: Reversal of singly linked list in JavaScript

texts:
I have already implemented reversal of link list in javascript. Can somebody tell optimized way of doing it?I want to do it by less code.

Here I am providing the code:

var tempItem;
var finalLastNode;

function reverseLL(ll) {
  var currentObj = ll,
    prevItem, lastItem, currentTempObj;
  currentTempObj = tempItem;
  if (!currentObj) {
    console.log("No change")
  } else {
    while (currentObj.next) {
      prevItem = currentObj;
      currentObj = currentObj.next;
      lastItem = currentObj;
    }
    if (lastItem) {
      if (!tempItem) {
        tempItem = lastItem;
      } else {
        while (currentTempObj.next) {
          currentTempObj = currentTempObj.next;
        }
        if (tempItem && !tempItem.next) {
          tempItem.next = lastItem;
          finalLastNode = ll;
        } else {
          currentTempObj.next = lastItem;
        }
      }
      prevItem && (prevItem.next = null)
      reverseLL(ll);
    } else {
      while (currentTempObj.next) {
        currentTempObj = currentTempObj.next;
      }
      currentTempObj.next = finalLastNode;
    }
  }
  console.log(tempItem);
}
reverseLL(ll1)


texts: JSON file for storing means and standard deviation values per demographic group

texts:
I wrote an ad hoc script in Python 3 that calculates where the patient result reside with a specific demographic group within the Turkish population, but until now I stored the data in the python code itself.

The script grew over time, and it seems like it might be a useful tool for researchers from other countries as well. And since the population data for each country differs, storing the reference data in accessible JSON files will make it possible for others to use.

For this purpose I created this reference data structure, but I'm wondering if it could be better and more compact.

What the program uses this data for

Take the name of the test and the number of it to put it on the display list.
Using the demographic data inputted by the user, find the standard deviation and the means of the tests for that group.
Calculate the Z score. (Since Z score = ((test_result - mean)/standard deviation)
Using the Z score, estimate the percentiles, and print and store the results.

The neuropsychiatric test structure

When evaluating test data, we find where the patient score lies within normal distribution, and whether that percentile is considered healthy, or not.

Different factors may affect this (e.g. age, sex, education, race etc.), but not always. So different neuropsychiatric tests might have a different structure.
As in, one might be affected by age and sex only, but not education. Another one might be affected by sex, but not age. Also, different tests might have different brackets for age and education, this is why I chose to use a low and high value for each group.

Moreover, different tests might have different number of questions, and some might even not have any distribution data. Some have cut-off values, but not distribution data. This can be easily controlled by adding a bool value
(test_has_dist_data = 1/0), and the program will know to use the cutoff value set for the test results, instead of trying to calculate the percentile.

JSON data suggestion

Here's my JSON file condensed (comments are added for code review):

{"test_name" : "mmse", #name of the test to refer in code
 "test_display_name" : "Mini Mental Status Examination" #test name to print
 "test_no" : "1",  #where to put the test in the display list
 "number_of_elements": "3",  #how many questions are in the list
 "element_names": ["question1", "question2", "question3"], #display names of the questions
  "distribution_data": [
  {"gender":"male",
    "age_groups":[
      {"age_low":"0",
       "age_high":"55",
       "edu_groups": [
        {"edu_low":"0",
         "edu_high": "5",
         "norm_exists": "1", #whether data exists or not for this demographic group
         "sd_array":["1", "2", "3"], #array to store the standard deviations
         "mean_array": ["111", "222", "333"] #array to store the means
        },
        {"edu_low":"6",
         "edu_high": "11",
         "norm_exists": "1",
         "sd_array":["1", "2", "3"],
         "mean_array": ["111", "222", "333"]
        },
        {"edu_low":"12",
         "edu_high": "999",
         "norm_exists": "1",
         "sd_array":["1", "2", "3"],
         "mean_array": ["111", "222", "333"]
        }
        ]
      },
      {"age_low":"55",
       "age_high":"69",
       "edu_groups": [
        {"edu_low":"0",
         "edu_high": "5",
         "norm_exists": "1",
         "sd_array":["1", "2", "3"],
         "mean_array": ["111", "222", "333"]
        },
        {"edu_low":"6",
         "edu_high": "11",
         "norm_exists": "1",
         "sd_array":["1", "2", "3"],
         "mean_array": ["111", "222", "333"]
        },
        {"edu_low":"12",
         "edu_high": "999",
         "norm_exists": "1",
         "sd_array":["1", "2", "3"],
         "mean_array": ["111", "222", "333"]
        }
        ]}

      ]
  },

  {"gender":"female"}]

}


texts: Runs a MySQL query, returns Dictionary or false;

texts:
I've been practicing C# and ASP.NET, and have been working on a somewhat larger-scale project than I am currently used to. I am sure there are horrible things wrong with this code that I will find out later, and would rather get some input on it now.

One of the things I'm concerned with is the fact that RunSelectCommand can return false if the database fails to connect, or if the query returns nothing.

Currently, in order to check for that, I do if (!(data is bool)) and if it's not I assume there is data to work with, and I return an error from the web server if not.

If any more information is needed, please let me know! I am very excited for some real peer-reviewed code.

public object RunSelectCommand(MySqlCommand command, List<MySqlParameter> parameterCollection = null)
{
    using (MySqlConnection conn = new MySqlConnection(connectionString))
    using (var cmd = conn.CreateCommand())
    {
        try
        {
            conn.Open();
        }
        catch (MySqlException ex)
        {
            return ex;
        }
        cmd.CommandText = command.CommandText;
        if (parameterCollection != null) // if parameters for query are specified, add them here.
        {
            cmd.Parameters.AddRange(parameterCollection.ToArray());
        }
        using (var reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                Dictionary<string, string> data = new Dictionary<string, string>(); // This is designed for returning only 1 row at a time
                for (int i = 0; i < (reader.FieldCount - 1); i++) // TODO seperate SelectAll command
                {
                    data.Add(reader.GetName(i), reader[i].ToString()); // Iterates through reader and adds data to Dictionary for output to JSON
                }
                conn.Close();
                return data;
            }
            else
            {
                conn.Close();
                return false;
            }
        }
    }
}

Usage example:

[HttpGet("checkapi/{text}")]
    public object CheckApi(string text) // returning object automatically converts to JSon
    {
        MySqlCommand C = new MySqlCommand("SELECT * FROM api WHERE apikey = @apikey");
        List<MySqlParameter> collection = new List<MySqlParameter>()
        {
            new MySqlParameter() { ParameterName = "@apikey", Value = text }
        };
        return mysqlWrapper.RunSelectCommand(C, collection);
    }


texts: Split a long integer into eight 4-bit values

texts:
It's an exercise from a book. There is a given long integer that I should convert into 8 4-bit  values. The exercise is not very clear for me, but I think I understood the task correctly.

I googled how to return with an array in a function. In the splitter function I add the last 4 bits into the values array, then cut the them from the original number.

Is this a good way to do this?

#include <iostream>

int * splitter(long int number)
{
    static int values[8];

    for (int i = 0; i < 8; i++)
    {
        values[i] = (int)(number & 0xF);
        number = (number >> 4);
    }

    return values;
}

int main()
{
    long int number = 432214123;
    int *values;
    values = splitter(number);
    for (int i = 7; i >= 0; i--)
        std::cout << values[i] << " ";
    return 0;
}


texts:
Can this extension method be improved?

    public static string GetAvatar(this System.Security.Principal.IIdentity user)
    {
        var service = SmObjectFactory.Container.GetInstance<IApplicationUserManager>();
        return service.FindByIdAsync(int.Parse(user.GetUserId())).Result.Avatar;
    }

Now in my view I use the extension method this way:

User.Identity.GetAvatar()

But every time the page refreshes, it hits database for getting user's avatar.
I'd like to know this can be improved by caching that or something like that.


texts:
I have an bit array var data = []; ... and I have the following function:

jsPerf

function getBit(n) {
    return (data[~~(n / 32)] >> (n % 32)) & 1;
}

Because this is a bottleneck, I need the fastest cross-browser solution in my code, can anybody help make it any faster?

Also, ~~(n / 32) === Math.floor(n / 32)

It can be algorithm optimization or syntax optimization (such as asm.js) or something else.  Should I change the array type (typedArray or similar)?


texts:
This code is meant to take a rectangular area, and randomly divide it up into smaller rectangles in a binary tree.

I'm somewhat new to Rust.

I'm concerned mostly about the create_subrooms function. I've tried lots of other permutations, but I can't find any more elegant way of writing this, and it still looks pretty ugly in my opinion.

Some specific questions I have:

Would it be poor form to have the function take ownership of root, modify it and return it? This would mean I could create the tree in a single line instead of creating the Room, creating it's children and then explicitly assigning it to the left/right of it's parent
Would I be better off having the function accept four size parameters, instead of creating the root Room beforehand and passing a reference? Or would that be too verbose?

This struct represents a node in the tree:

struct Room {
    x: u32,
    y: u32,
    end_x: u32,
    end_y: u32,
    left: Option<Rc<Room>>>,
    right: Option<Rc<Room>>,
}

And this function takes a previously created root Room, and recursively generates its children:

fn create_subrooms(&mut self, root: &mut Room, depth: u32) {
        if depth < self.max_rec_depth && self.is_valid_size(root) {
            let mut left: Room;
            let mut right: Room;

            // Horizontal and Vertical are the direction along which, the
            // rectangle is split, and the new boundaries are randomly chosen
            // perpendicular to that
            match rand::random::<Direction>() {
                Vertical => {
                    let cut = self.rng.gen_range(root.x, root.end_x);

                    // Not including the 'new' method for brevity,
                    // but it's form is (x, y, end_x, end_y)
                    // children are None by default
                    left = Room::new(root.x, root.y, cut, root.end_y);
                    right = Room::new(cut, root.y, root.end_x, root.end_y);
                }
                Horizontal => {
                    let cut = self.rng.gen_range(root.y, root.end_y);

                    left = Room::new(root.x, root.y, root.end_x, cut);
                    right = Room::new(root.x, cut, root.end_x, root.end_y);
                }
            };

            self.create_subrooms(&mut left, depth + 1);
            root.left = Some(Rc::new(left));

            self.create_subrooms(&mut right, depth + 1);
            root.right = Some(Rc::new(right));
        }
    }

The self parameters are from a Builder struct which is used to customise how the area is divided.

The create_rooms function is initially called like this:

fn divide_room(&mut self) {
    let mut root = SubDungeon::new(0, 0, self.width, self.height);
    self.create_subdungeons(&mut root, 0);
    Rc::new(root)
}


texts:
I have a concept based polymorphism example listed below. I allow the user to provide any type that implements the draw method and then I add it into a vector of unique_ptr to concept base. If I have a pointer or reference I want to be able to deal with that even though the solution has value semantics in mind. I thus created a wrapper type which forwards to the correct implementation. I am hoping to get some feedback on if this is the best way to deal with the issue at hand.

#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>

class drawable_concept{
public:
    drawable_concept() = default;
    virtual ~drawable_concept() = default;
    drawable_concept(drawable_concept const&) = delete;
    drawable_concept& operator = (drawable_concept const& ) = delete;
    virtual void draw() = 0;
};

template<class T>
class drawable_model : public drawable_concept{
public:
    typedef T model_type;
    drawable_model(T const& model) : model_(model){}
    void draw(){
        model_.draw();
    }
    ~drawable_model() = default;
private:
    T model_;
};

template<class T>
class drawable_forwarder{
public:

    drawable_forwarder(T const& item) : item_(item){}

    inline void draw(){
        item_->draw();
    }
private:
    T item_;
};

class graphics_surface{
public:
    void render(){
        std::for_each(std::begin(controls_), std::end(controls_), [] (std::unique_ptr<drawable_concept> const& control){
            control->draw();
        });
    }

    template<class T>
    void push_back(T control){
        auto t = new drawable_model<T>(std::move(control));
        controls_.push_back(std::unique_ptr<drawable_concept>(t));
    }
private:
    std::vector<std::unique_ptr<drawable_concept>> controls_;
};

struct triangle{
    void draw(){
        std::cout << "Triangle" << std::endl;
    }
};

struct square{
    void draw(){
        std::cout << "Square" << std::endl;
    }
};

int main(int argc, const char * argv[])
{

    graphics_surface surface;
    surface.push_back(triangle());
    surface.push_back(square());

    std::shared_ptr<triangle> ptr(new triangle);
    drawable_forwarder<std::shared_ptr<triangle>> fwd(ptr);
    surface.push_back(fwd);

    surface.render();

    return 0;
}


texts: Use of Factory pattern — how to implement it

texts:
I am trying to figure out how Factory pattern works. I implemented it with TypeScript in this github repo: https://github.com/emilecollin/factory_pattern

Basically this is emulating spaceships gaming logic: the program will ask you to input in the terminal one of these options: "alien" or "zombie". With the provided input, the program will select on runtime the proper ship class to instantiate (AlienShip or ZombieShip), and a spaceships fight is mocked. The logic for the decision of which spaceship class to instantiate lives in a «factory method».

The abstract creator:

export abstract class AbstractShipFactory {
  public abstract makeShip(shipType: string): Ship;
}

The concrete creator:

export class EnemyShipFactory extends AbstractShipFactory {
  public makeShip(shipType: string): Ship {
    switch (shipType) {
      case 'alien':
        return new AlienShip();
      case 'zombie':
        return new ZombieShip();
    }
  }
}

The Product interface:

export interface Ship {
  name: string;
  damage: number;
  attack(): string;
}

And the Concrete Product class:

export class AlienShip implements Ship {
  private _name: string = 'alien';
  private _damage: number = 35;

  get name(): string {
    return this._name;
  }

  get damage(): number {
    return this._damage;
  }

  attack(): string {
    return '---->You are being attacked by ' + this.name + ' spaceship and got a damage of ' + this.damage;
  }
}

I'm now sure if I got it right. Still a bit confused about it. Any opinion of this code will be welcome!


texts:
I'm a beginner who wants to learn properly how to write code. The following code takes initial RGB values and gradually changes them (shade by shade) to targeted rgb values, scroll by scroll. The code works, but is there a way to clean this code, and get the same gradual result?

//GRADUALLY CHANGE BACKGROUND COLOR WHILE SCROLLING

//function parameters:
//ElemId: targeted element
//r1,g1,b1: starting color
//r2,g2,b2: finishing color
//scrollFromTop (in px): how much scrollTop until complete color change. can element height value too.

function changeColor(ElemId, r1, g1, b1, r2, g2, b2, scrollFromTop) {
     //get scroll length till complete color change
     //this specifically makes colors change completely when you scroll to the bottom.
     //Instead, you could make scrollFromTop pixel-specific, by deleting this below,
     //and directly adding the wanted argument to the funtion's scrollFromTop parameter.
     var pageHeight = document.getElementById(ElemId).scrollHeight;
     var windowHeight = window.innerHeight;
     var scrollFromTop = pageHeight - windowHeight;

     //get difference between two colors
     function diff(a, b) {
         return Math.abs(a - b);
     }
     var redDiff = diff(r1, r2);
     var greenDiff = diff(g1, g2);
     var blueDiff = diff(b1, b2);

     //get unit (shade) by which the color will change by one scroll
     var redUnit = redDiff / scrollFromTop;
     var greenUnit = greenDiff / scrollFromTop;
     var blueUnit = blueDiff / scrollFromTop;

     $(document).scroll(function () {
         //get value of scrollTop each time you scroll
         var scrollTopVal = $(document).scrollTop();

         //add or subtract r,g,b shades when scrolling. Example:
         //subtract if going from rgb(255,255,255) to rgb(0,0,0)
         //add if going the other way
         function direction(x, y, Unit) {
             if (x < y) {
                 return Math.round(x + (Unit * scrollTopVal));
             } else {
                 return Math.round(x - (Unit * scrollTopVal));
             }
         }

         //IF makes sure new target color stays after certain point
         //ELSE changes color shades step by step using the "direction" function as we scroll
         if (scrollTopVal > scrollFromTop) {
             //rgb string
             var rgb = "rgb(" + r2 + ", " + g2 + ", " + b2 + ")";
             $("#" + ElemId).css("background", rgb);
         } else {
             var newRed = direction(r1, r2, redUnit);
             var newGreen = direction(g1, g2, greenUnit);
             var newBlue = direction(b1, b2, blueUnit);

             var rgb = "rgb(" + newRed + ", " + newGreen + ", " + newBlue + ")";
             $("#" + ElemId).css("background", rgb);
         }
     });
}

$(document).ready(function () {
     changeColor("container", 51, 60, 98, 111, 195, 169);
});

For HTML and CSS, or to see the code in action, go here.


texts: Static utility functions to turn arrays into SQL statements

texts:
I have an object that houses only static functions. The functions are stand alone and are not dependent on the state of the object.

I hear that static functions are a nightmare in terms of testing, an anti-pattern if you will. I get it, the state of the object could be impossible to predict.. But these are stateless.

My question is, Should I place these functions into a class of their own or am I ok by leaving them as static methods?

class Utility {

public static function arrayToInsertStatement($table, array $data) {
    $sql = "INSERT INTO %s (%s) VALUES (:%s)";
    return sprintf($sql, $table, implode(', ', array_keys($data)), implode(', :', array_keys($data)));
}

public static function arrayToSelectStatment($table, array $fields, $whereStatement) {
    $sql = "SELECT %s FROM %s %s";
    if ($whereStatement) {
        $whereStatement = sprintf(" WHERE %s", $whereStatement);
    }
    return sprintf($sql, implode(',', $fields), $table, $whereStatement);
}

public static function arrayToUpdateStatement($table, array $data, $whereStatement = null) {
    $t_sql = "UPDATE %s SET %s%s";
    $sets = self::arrayToKeyedArray($data);
    if ($whereStatement) {
        $whereStatement = sprintf(" WHERE %s", $whereStatement);
    }
    return sprintf($t_sql, $table, implode(',', $sets), $whereStatement);
}

public static function arrayToWhereStatement($data, $joinType = 'AND') {
    $joiner = sprintf(" %s ", $joinType);
    return implode($joiner, self::arrayToKeyedArray($data));
}

public static function arrayToOrderBy(array $data) {
    $o = [];
    foreach ($data as $field => $direction) {
        $directionBool = substr(strtolower($direction), 0, strlen($direction)) === substr('descending', 0, strlen($direction));
        $o[] = sprintf($field . ' %1$s', ($directionBool ? 'DESC' : 'ASC'));
    }
    return implode($o, ',');
}

public static function arrayToKeyedArray($data) {
    return array_map(function($value) {
        return sprintf('%1$s = :%1$s', $value);
    }, array_keys($data));
}


texts:
Previous question:

JavascriptObservable Storage

The idea is to have some storage interface that exists of different buckets - known as Eagles:

Eagle('bucket1');
Eagle('bucket2');

Every Eagle data is stored as Feathers.

var e = Eagle('fooEagle');
e.set('myFeather',{
    'foo' : 'bar';
});

These Feathers can be observed for changes (nothing more at this moment):

var f = e.get('myFeather');
f.on('change',function(f, key) {
    console.log(key+ ' index of the Feather was changed to'+ f.get(key)));
});
f.set('foo','newer foo');

You could also retrieve data in a long chain like this:

Eagle('fooEagle').get('myFeather').get('foo');

Does this seem like a good approach? If so, how would you implement events like 'delete'. And would it be useful to let those events bubble up to the Eagle? If so, how?

window.Eagle = (function(){
    "use strict";

    var _eagleInstances = [],
        _featherInstances = [];

    var Feather = (function() {
        var _data = {},
            _observers = {};

        var F = function(data) {
            this._id = _featherInstances.length;
            _featherInstances[this._id] = this;
            _data[this._id] = data;
        }

        F.prototype.has = function(key) {
            return _data[this._id].hasOwnProperty(key);
        }

        F.prototype.get = function(key) {
            return this.has(key) ? _data[this._id][key] : undefined;
        }

        F.prototype.set = function(key, data) {
            _data[this._id][key] = data;
            this.notify('change', key);
            return this;
        }

        F.prototype.on = function(action, callable) {
            if ( ! _observers.hasOwnProperty(action) ) {
                _observers[action] = [];
            }

            _observers[action].push(callable);
        }

        F.prototype.notify = function(action, info) {
            if ( _observers.hasOwnProperty(action) ) {
                for ( var i = 0; i < _observers[action].length; i++ ) {
                    _observers[action][i](this, info);
                }
            }
        }

        return F;
    })();

    var Eagle = (function(){
        var _feathers = {};

        var E = function() {
            this._id = _eagleInstances.length;
            _feathers[this._id] = {};
            _eagleInstances[this._id] = this;
        }

        E.prototype.has = function(featherIdentifier) {
            return _feathers[this._id].hasOwnProperty(featherIdentifier);
        }

        E.prototype.get = function(featherIdentifier) {
            if ( !this.has(featherIdentifier) ) {
                this.set(featherIdentifier, {});
            }
            return _featherInstances[_feathers[this._id][featherIdentifier]];
        }

        E.prototype.set = function(featherIdentifier, data) {
            var f = new Feather(data);
            _feathers[this._id][featherIdentifier] = f._id;
            return f;
        }

        return E;
    })();

    return function(eagleIdentifier) {
        if ( !_eagleInstances.hasOwnProperty(eagleIdentifier) ) {
            _eagleInstances[eagleIdentifier] = new Eagle();
        }
        return _eagleInstances[eagleIdentifier];
    }

})();


texts:
Task: Print sum of first 1000 primes.

public class PrimeSummation {
    public static void main(String[] args) {
        System.out.println(sumFirstPrimes(1000));
    }
    // Calculates the total of the first n primes
    public static int sumFirstPrimes(int n) {
        /* Since 2 is the only even prime it is pre-included;
        affords convenience of skipping other evens.
        3 is as well to skip an otherwise necessary check in isPrime() */
        int result = 5, count = 2;

        for (int i = 5; count < n; i += 2) {
            if (isPrime(i)) { result += i; count++; }
        }
        return result;
    }
    /* Determines if a number is prime, commented out irrelevant checks
    remove comments for general use */
    private static boolean isPrime(int num) {
        // if (num <= 3) { return num > 1; }
        if (/*(num & 1) == 0 || */ num % 3 == 0) { return false; }

        int limit = (int)Math.sqrt(num);

        for (int i = 5; i <= limit; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) { return false; }
        }
        return true;
    }
}

I'm trying to adjust my programming style to a "people first" paradigm. While any and all feedback is welcome, that is the focus.

Is there any ambiguity? Are the variable and method names adequate? I thought I could be more specific but the names would get significantly longer, is there some standard regarding the length of names?
Are the comments sufficient? I structure a general purpose method, but comment out otherwise redundant checks; rendering its use distinct to the task. Given specificity it was also made private. Is this good practice?
On the execution itself, is it satisfactory or are there some pitfalls I don't account for/optimizations I could make?


texts:
I was trying to solve The Simplest Sum from hackerrank. Could anyone please let me know how I can make this code much effective in terms of time and space complexity?

  You are just learning to code and are finished with loops and
  functions. Now, you are given the following pseudocode:

/*
 * The function has two integer parameters: k and n
 * The function returns the value of sum
 */
function f(k, n) {
    sum = 0;

    for (i = 1; i ≤ n; i += 1) {
        sum += i;
        i *= k;
    }

    return sum;
}

  For three given integers k, a, and b, find the value of S mod (10⁹ + 7), where S is defined as:

  $$S=\sum_{n=a}^b f(k,n)$$

  Input Format

  The first line of the input is an integer Q, the total number of
  queries. Each of the next Q lines contains three space separated
  integers k, a, and b.

Constraints

• 1 ≤ Q ≤ 10⁵
  • 2 ≤ k ≤ 10⁵
  • 1 ≤ a ≤ b ≤ 10^18   Constraints left out from the problem description as quoted in 2018

  Output Format

  For each query, print the value of S mod (10⁹ + 7) on a new line.

  Sample Input

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

  Sample Output

14
13
10
5

  Explanation

  Query 2 1 5

f(2, 1) = 1
f(2, 2) = 1
f(2, 3) = 4
f(2, 4) = 4
f(2, 5) = 4

  So, S = f(2, 1)+f(2, 2)+f(2, 3)+f(2, 4)+f(2, 5) = 14
  Query 3 1 5

f(3,1) = 1
f(3,2) = 1
f(3,3) = 1
f(3,4) = 5
f(3,5) = 5

  So, S = f(3,1)+f(3,2)+f(3,3)+f(3,4)+f(3,5) = 13
  Query 4 1 5

f(4,1) = 1
f(4,2) = 1
f(4,3) = 1
f(4,4) = 1
f(4,5) = 6

  So, S = f(4,1)+f(4,2)+f(4,3)+f(4,4)+f(4,5) = 10
  Query 5 1 5

f(5,1) = 1
f(5,2) = 1
f(5,3) = 1
f(5,4) = 1
f(5,5) = 1

  So, S = f(5,1)+f(5,2)+f(5,3)+f(5,4)+f(5,5) = 5

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class maxSum {

static int simplestSum(int k, int a, int b) {
    int count = 1;
    int totalSum = 0;
    while(count <= b) {
        int z = maxSum(k, a);
        int mul = k*a;
        if(mul < b) {
            totalSum = totalSum + (z*(k*a));
        }else {
            totalSum = totalSum + (z*((b-count)+1));
        }

        count = count + (k*a);
        a = count;
    }
    return totalSum;
}

static int maxSum(int k , int a) {
    int sum = 0;
     for (int i = 1; i <= a; i += 1) {
         sum += i;
         i *= k;
     }
     return sum;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int q = in.nextInt();
    for(int a0 = 0; a0 < q; a0++){
        int k = in.nextInt();
        int a = in.nextInt();
        int b = in.nextInt();
        int result = simplestSum(k, a, b);
        System.out.println(result);
    }
    in.close();
   }
}


texts: Calculating the Nth number in the supertable of two numbers

texts:
Below is the problem:

  Little Timmy is exceptionally good at math tables, so his teacher decided to make things a bit more interesting. His teacher gave him two numbers, A and B, and told him to merge the tables of A and B in order (ascending order), removing the duplicates and thus supertable of A and B, and asks Little Timmy the Nth number.  Given A, B and N, calculate the Nth number in the supertable of A and B.

Input

  First line contains number of test cases T . Each test case contains three integers A, B and N.

Output

  For each test case print the Nth number of the supertable.

Here is my code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    int N = Integer.parseInt(line);

    SortedSet<Integer> sort=new TreeSet<>();
    for (int i = 0; i < N; i++) {
        String[] input=br.readLine().split(" ");
        if(input[0].equals(input[1])){
            System.out.println(Integer.parseInt(input[0])*Integer.parseInt(input[2]));
        }else{
        for(int i1=1;i1<Integer.parseInt(input[2]);i1++){
            sort.add(Integer.parseInt(input[0])*i1);
            if(sort.size()==Integer.parseInt(input[2]))
                break;
            sort.add(Integer.parseInt(input[1])*i1);
            if(sort.size()==Integer.parseInt(input[2]))
                break;
        }
        System.out.println(sort.toArray()[Integer.parseInt(input[2])-1]);
        }
    }

The problem is that my code is taking too long to run and I am not passing my test cases because of time constraints. How can I optimize this code so that it may run fast?


texts: Improving iterative manipulation on XML elements

texts:
In this reply, there's an example of how to remove a node from a XML structure.

XElement doc = XElement.Load("test.xml");
doc.XPathSelectElement("//beep").Remove();

Suppose now that we wish to remove not a single node (specifying it by the string value) but a set of nodes (specifying them by an array of strings).

One way to resolve it is to loop through the array and execute the removal for each string element. However, I'd like to know if someone can suggest a neater approach.

IEnumerable<String> beeps = new[] { "//beep" };
XElement doc = XElement.Load("test.xml");
foreach(String beep in beeps)
  doc.XPathSelectElement(beep).Remove();


texts: Counting multiples of 3 up to a given number

texts:
I'm attempting a practice problem in Codeforces that requires you to find the number of multiples of 3 less than or equal to a given number. I have written the following code but it gives a TLE once the test case reaches the order of 108.

int x = Reader.nextInt();
int count = 0;

for(int i = 3; i<=x; i++){
    if(i%3 == 0){
        count++;
    }
}
System.out.println(count);

Is there any way I can further optimize this code? The test cases max out at 109.


texts:
I have a scenario where I need to save a string as a key and DateTime as value into a hash map. Also, I need to remove strings older than 24 hours.

At the moment the HashMap is implemented as below:

HashMap<String, DateTime> sessions = new HashMap<>();
//Adding to the HashMap
sessions.put(session.toString(), DateTime.now());
//Removing from the HashMap
sessions.forEach((str, time)-> {
    if(time.clicks() < DateTime.now().minus(86400000).clicks())
        sessions.remove(str);
});

Would it be less overhead to save the DateTime clicks as Long datatype rather than saving the whole DateTime object? Like below:

HashMap<String, Long> sessions = new HashMap<>();
//Adding to the HashMap
sessions.put(session.toString(), DateTime.now().clicks);
//Removing from the HashMap
sessions.forEach((str, time)-> {
    if(time < DateTime.now().minus(86400000).clicks())
        sessions.remove(str);
});


texts:
This review is very short and very straight-forward. There are two people in the team and the checked-in code looks as follows.

string parameter = GetUnitType();
string target = "PM4000";
if(parameter.CompareTo(target) == 0)
  CarryOutProcess();

I got stuck here and needed to re-check the usage of CompareTo. I can't for my life understand any advantage of the above in comparison to:

string parameter = GetUnitType();
if(parameter == "PM4000")
  CarryOutProcess();

I'm pretty sure it's just a case of intentional obfuscation or, at the very least, lack of understanding a copied code.

Is the former inferior to the latter in every possible way?

The author of the first claims that since both work, they're comparably good and the difference is just a matter of personal taste.


texts:
I have a simple integer sorting problem at hand and to solve it, I am planning to write a variation of bubble sort. It seems to be working fine but I am not sure about it's complexity in big-O. What it could be ?

public class TempBubbleSort
{

static Integer[] myArray = {10,9,8,7,6,5,4,3,2,1};

static int counter = 0;

public static void main(String[] args)
{
    for(int anchor=0; anchor<myArray.length; anchor++)
    {
        for(int compare=anchor+1; compare<myArray.length; compare++)
        {
            counter++;
            // sort ascending
            if(myArray[anchor] > myArray[compare])
            {
                int tmp = myArray[compare];
                myArray[compare] = myArray[anchor];
                myArray[anchor] = tmp;
            }
        }
    }

    System.out.println("Comparision Count : "+counter);

    for(int i : myArray)
        System.out.println(i);
}

}

Output when you run above is :

Comparision Count : 45
1
2
3
4
5
6
7
8
9
10


texts: Find element yielding the largest value w.r.t. custom function

texts:
I made a function to find the element that yields the largest value when put into a custom functor.

I think this is missing from the STL. I can think of three ways to do this in STL:

Transform the container by the functor. Find the maximum in the transformed version. Take the corresponding element from the original container.
Transform the container to an iterable of std::pairs containing the iterators to the original values and the corresponding functor result value. Write a custom comparison function which compares the .second of the pairs. Find max among the pairs with std::max_element. Take .first of the resulting iterator.
Use a custom comparator functor in std::max_element (return f(lhs) < f(rhs)).

The first two are really cumbersome and the third calls the functor twice as many times as necessary. Hence this:

template<typename Iterable, typename UnaryFun>
auto maxElementBy(Iterable const& iterable, UnaryFun criterion)
    -> decltype(std::begin(iterable))
{
    typedef decltype(criterion(*std::begin(iterable))) CriterionResult;

    auto itCurrent = std::begin(iterable);
    auto itEnd = std::end(iterable);

    if (itCurrent == itEnd)
    {
        return itEnd;
    }

    CriterionResult bestValue = criterion(*itCurrent);
    auto itBest = itCurrent;
    ++itCurrent;

    for (; itCurrent != itEnd; ++itCurrent)
    {
        CriterionResult currentValue = criterion(*itCurrent);
        if (bestValue < currentValue)
        {
            itBest = itCurrent;
            bestValue = std::move(currentValue);
        }
    }
    return itBest;
}

Any suggestions?


texts: Listening for values changed by the memory

texts:
I'm fetching some values from the memory. I would like to create some custom events that I can listen to for each value. Since there are no existing events regarding memory changes, I've decided to go with a polling solution. I'm restarting the timer below manually just to make certain the work is finished.

Would this be an okay solution (considering the circumstances) to my problem? Do you see any issues with creating multiple timers? As far as I know, each instance will run on its own thread.

This was the best I could come up with right off the bat. I would like to hear your input regarding possible improvements:

var vc = new ValueChange(1000, Blah.GetMemoryValue());
vc.PropertyChanged += OnPropertyChanged;

void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    Console.WriteLine("prop change");
}

public class ValueChange : INotifyPropertyChanged
{
    private int _val;
    private readonly System.Timers.Timer _timer;

    private int Value
    {
        set
        {
           _val = value;
            RaisePropertyChanged("Val");
        }
        get
        {
            return _val;
        }
   }

   public ValueChange(double polingInterval, int val)
   {
        _val = val;

       _timer = new System.Timers.Timer { AutoReset = false, Interval = polingInterval };
       _timer.Elapsed += TimerElapsed;
       _timer.Start();
   }

   private void TimerElapsed(object sender, ElapsedEventArgs e)
   {
       var newValue = Blah.GetMemoryValue();

       if (Value != newValue)
       {
           Value = newValue;
       }

        _timer.Start();

   }

   public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string caller)
    {
       if (PropertyChanged != null)
       {
           PropertyChanged(this, new PropertyChangedEventArgs(caller));
       }
    }
}


texts:
I'm trying to reword the code below to avoid using the Select and Selection terms.  I tried to Range("S"...).Copy instead of .Select but that didn't work for some reason.  Does anyone know a way I can reword this to avoid Select and Selection statements and why my change .Select to .Copy wouldn't have worked?

The code below looks in Column A for the identifiers Tango and Alpha.  Then it uses those identifiers to figure out the range between rows to select in Column S and copies and pastes them as values.  I can confirm the code does run as is.

Sub copy_paste()
        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell1 As Range
        Dim FoundCell2 As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

        Const WHAT_TO_FIND1 As String = "Tango"
        Set FoundCell1 = ws.Range("A:A").Find(What:=WHAT_TO_FIND1)

        Const WHAT_TO_FIND2 As String = "Alpha"
        Set FoundCell2 = ws.Range("A:A").Find(What:=WHAT_TO_FIND2)

        Range("S" & FoundCell1.Row + 1 & ":S" & FoundCell2.Row - 1).Select
        Selection.Copy
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
         :=False, Transpose:=False

End sub


texts:
I've implemented the queue data structures using array in java. Anything I need to change in my code?

Queue.java

import java.util.Arrays;

public class Queue<T> {

    private int front;
    private int rear;
    int size;
    T[] queue;

    public Queue(int inSize) {
        size = inSize;
        queue = (T[]) new Object[size];
        front = -1;
        rear = -1;
    }

    public boolean isempty() {
        return (front == -1 && rear == -1);
    }

    public void enQueue(T value) {
        if ((rear+1)%size==front) {
            throw new IllegalStateException("Queue is full");

        } else if (isempty()) {
            front++;
            rear++;
            queue[rear] = value;

        } else {
            rear=(rear+1)%size;
            queue[rear] = value;

        }
    }

    public T deQueue() {
        T value = null;
        if (isempty()) {
            throw new IllegalStateException("Queue is empty, cant dequeue");
        } else if (front == rear) {
            value = queue[front];
            front = -1;
            rear = -1;

        } else {
            value = queue[front];
            front=(front+1)%size;

        }
        return value;

    }

    @Override
    public String toString() {
        return "Queue [front=" + front + ", rear=" + rear + ", size=" + size
                + ", queue=" + Arrays.toString(queue) + "]";
    }

}

QueueImpl.java

public class QueueImpl {

    public static <T> void main(String[] args) {
        Queue newQueue = new Queue(5);
        newQueue.enQueue(10);
        newQueue.enQueue(20);
        newQueue.enQueue(30);
        newQueue.enQueue(40);
        newQueue.enQueue(50);
        System.out.println((T) newQueue.toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.toString());
        newQueue.enQueue(60);
        newQueue.enQueue(70);
        System.out.println((T) newQueue.toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.deQueue().toString());
        System.out.println((T) newQueue.toString());

    }

}


texts:
In helpcovid git commit e27dd3b123c18300665 we have a stupid bug related to Linux GNU glibc argp program argument parsing.

void
hcv_parse_program_arguments(int &argc, char**argv)
{
  struct argp_state argstate;
  memset (&argstate, 0, sizeof(argstate));
  argstate.input = &hcv_progargs;
  hcv_progargs.hcv_progmagic = HCV_PROGARG_MAGIC;
  static struct argp argparser;
  argparser.options = hcv_progoptions;
  argparser.parser = hcv_parse1opt;
  argparser.args_doc = "*no-positional-arguments*";
  argparser.doc = "github.com/bstarynk/helpcovid"
                  " - a GPLv3+ free software to help organizing"
                  " against Covid19 - NO WARRANTY";
  argparser.children = nullptr;
  argparser.help_filter = nullptr;
  argparser.argp_domain = nullptr;
  if (argp_parse(&argparser, argc, argv, 0, nullptr, nullptr))
    HCV_FATALOUT("failed to parse program arguments to " << argv[0]);
#warning TODO: complete hcv_parse_program_arguments
} // end hcv_parse_program_arguments

The bug is obvious, but I cannot find it.

At runtime, with the main  function being:

int
main(int argc, char**argv)
{
  hcv_early_initialize(argv[0]);
  hcv_parse_program_arguments(argc, argv);
  HCV_SYSLOGOUT(LOG_NOTICE, "start of " << argv[0] << std::endl
                <<  " version:" << hcv_versionmsg);
  HCV_SYSLOGOUT(LOG_INFO, "normal end of " << argv[0]);
  return 0;
} // end of main

we observe immediately:

rimski.x86_64 ~/helpcovid 19:12 .0 % ./helpcovid
** HELPCOVID FATAL! hcv_main.cc:84:: corrupted program arguments
**** FATAL ERROR hcv_main.cc:84
./helpcovid[3684197]: FATAL STOP hcv_main.cc:84 (Success)
zsh: abort (core dumped)  ./helpcovid

happening in

// parse a single program option
static error_t
hcv_parse1opt (int key, char *arg, struct argp_state *state)
{
  /* Get the input argument from argp_parse, which we
     know is a pointer to our arguments structure. */
  struct hcv_progarguments *progargs
    = reinterpret_cast<hcv_progarguments *>(state->input);
  if (!progargs || progargs->hcv_progmagic != HCV_PROGARG_MAGIC)
    // this should never happen
    HCV_FATALOUT("corrupted program arguments"); //@@@@@@@@@@@@@@@@@@@
  switch (key)
    {
    default:
      return ARGP_ERR_UNKNOWN;
    }
} // end hcv_parse1opt

The error being at line with //@@@@@@@@@@@@@@@@@@@, file hcv_main.cc line 84. The gdb debugger tells that progargs is a null pointer (and should not be).


texts:
This is a program that I created using Python. Please help me optimize the code.

import time
import sys
import socket
from time import localtime, strftime

# start up system

def start():
    print("Welcome, please choose what to do")
    choice = input('register/login ')
    if choice == 'register':
        register()
    elif choice == 'login':
        username()
    elif choice == 'admin':
        username()
    else:
        problems()

def register():
    registeragain = False
    global user
    global passs
    user = input('Please register your username : ')
    passs = input('Please register your password : ')
    register = input('Do you want to register another account? Y/N : ')
    if register == 'Y':
        registeragain = True
        register()
    elif register == 'N':
        username()
    else:
        print("Error")
        problems()

# login system

def username():
    global admin
    admin = 'Max'
    userinputname = input('Please enter the username : ')
    if userinputname == admin or userinputname == user:
        password()
    elif userinputname != user:
        print('Wrong username, please try again')
        username()
    else:
        problems()

def password():
    x = 1
    global adminpass
    adminpass = 'Luo'
    userinputpass = input('Please enter the password : ')
    if userinputpass == adminpass:
        adminlogin()
    elif userinputpass == passs:
        loading()
    elif userinputpass != passs:
        print('Wrong password, please try again')
        x += 1
        if x > 2:
            exit

    else:
        problems()

# main menu

def loading():
    toolbar_width = 40
    # setup toolbar
    sys.stdout.write("[%s]" % (" " * toolbar_width))
    sys.stdout.flush()
    # return to start of line, after '['
    sys.stdout.write("\b" * (toolbar_width+1))

    for i in range(toolbar_width):
        time.sleep(0.1)  # do real work here
        # update the bar
        sys.stdout.write("-")
        sys.stdout.flush()

    sys.stdout.write("]\n")  # this ends the progress bar
    main()

def main():
    time.sleep(3)
    print("Welcome to the main screen")
    time.sleep(3)
    print("Menu: current time, ipchecker, quit")
    time.sleep(2)
    mainmenu = input('Enter: ')
    if mainmenu == 'current time':
        telldate()
    elif mainmenu == 'ipchecker':
        ipchecker()
    elif mainmenu == 'quit':
        leave()
    elif mainmenu == 'cal':
        cal()
    else:
        problems()

# solutions

def problems():
    print("We are truly sorry that you have experienced a problem, please contact us at 123pythonlogin@gmail.com")
    option = input('Would you like to return to the main menu? Y/N ')
    if option == 'Y':
        main()
    else:
        exit()

# admin
def adminlogin():
    print("Welcome admin")
    mainadmin = input('Enter: ')
    if mainadmin == 'current time':
        telldate()
    elif mainadmin == 'ipchecker':
        ipchecker()
    elif mainadmin == 'quit':
        leave()
    elif mainadmin == 'cal':
        cal()
    else:
        problems()

# functions

def telldate():
    localtime = time.asctime(time.localtime(time.time()))
    print("Local current time :", localtime)
    main()

def ipchecker():
    hostname = socket.gethostname()
    IPAddr = socket.gethostbyname(hostname)
    print("Your Computer Name is:" + hostname)
    print("Your Computer IP Address is: " + IPAddr)
    main()

def cal():
    numx = int(input('Enter the first number: '))
    numy = int(input('Enter the second number: '))
    op = input('Enter the operation(+, -, *, /): ')
    if op == '+':
        sum = numx + numy
        print('Your sum is ' , sum)
        main()
    elif op == '-':
        diff = numx - numy
        print('The difference is ',diff)
        main()
    elif op == '*':
        mult = numx * numy
        print('The multiple is ' ,mult)
        main()
    elif op == '/':
        divd = numx / numy
        print('The result is ' ,divd)
        main()
    else:
        problems()

def leave():
    exit()

start()


texts:
This is my DAO object that takes the Cypher query as a string, and returns a JSON representation of the graph it returns.

Because it's using a Spring JdbcTemplate to access the database, the jdbc query will return any errors wrapped in a DataAccessException.

What I'm wanting to do here, is detect whether the error being thrown is due to an invalid query (in which case I want to return a message to the user saying so), or for now, any other error, in which case I'll file it as 'An unexpected error occurred'.

public String runQuery(String q) throws JsonGenerationException, JsonMappingException, UncategorizedSQLException, DataAccessException
 {
    Graph g = null;
            try {
                g = jdbcTemplate.query(q, new Neo4jGraphResultSetExtractor());
            } catch (DataAccessException e) {

                if (e instanceof UncategorizedSQLException)
                    {
                    //Invalid cypher query
                    throw (UncategorizedSQLException)e;
                    }

                else throw e;
            }

    json = g.toJson(); //throws JsonGenerationException, JsonMappingException
    return json;
}

When I call the DAO from my Business Layer:

public String submitCypherQuery(String query) {

    try {
        return neoConn.runQuery(query);
    } catch (ClassNotFoundException e) {

        return handleUnexpectedError(e);

    } catch (JsonGenerationException e) {
        return handleUnexpectedError(e);
    } catch (JsonMappingException e) {
        return handleUnexpectedError(e);
    } catch (IOException e) {
        return handleUnexpectedError(e);
    }
    catch (UncategorizedSQLException e)
    {
        return new ErrorMessage(errorInvalidQuery).toJson();
    }
    catch (DataAccessException e)
    {
        return handleUnexpectedError(e);
    }

}

Is this an OK way of doing this?

One question I have is that both UncategorizedSQLException, DataAccessException are unchecked exceptions, meaning that even though the DAO has declared them as being thrown - the compiler is fine with calling these methods without being surrounded in a try/catch.

This isn't especially useful - this is the exact case I want to force the developers to handle!


texts: Creating the design matrices for a canonical correlation analysis

texts:
I have this code to generate symmetric matrices for testing how the design of the canonical correlation analysis I am performing works out. This is a extension of this solution

Each row of the matrix represent a dataset (it is symmetric), and if the value is 0 it means no interaction between the datasets, if it is higher that there is an interaction. The end goal of this code is just to make a grid search of the design that explains better the data I have.
However as I need to come up with different designs adding more datasets or less I would like to know how to improve this into a function that would be more general, specially the nested for loops part (If I test it with 5 datasets I add more for loops and then more unlist at the end).

Initial matrix (I usually work with 4 datasets):

C <-  matrix(0,ncol = 4, nrow = 4)

Weights for the interactions of each dataset (4 to avoid to many combinations):

nweight <- 4
weight <- seq(from = 0, to = 1, length.out = nweight)

Initiate the list that will contain the matrices

C_list <- vector("list", nweight)
cweight <- as.character(weight)
names(C_list) <- cweight

Loop for each position I want to change to obtain all the combinations of weights I want to test.

for(i1 in cweight) {
  C_list[[as.character(i1)]] <- vector("list", nweight)
  names(C_list[[(i1)]]) <- cweight
  for (i2 in cweight) {
    C_list[[(i1)]][[(i2)]] <- vector("list", nweight)
    names(C_list[[(i1)]][[(i2)]]) <- cweight
    for (i3 in cweight) {
      C_list[[(i1)]][[(i2)]][[(i3)]] <- vector("list", nweight)
      names(C_list[[(i1)]][[(i2)]][[(i3)]]) <- cweight
      for(i4 in cweight) {
        C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]] <- vector("list", nweight)
        names(C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]]) <- cweight
        for (i5 in cweight) {
          C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]][[(i5)]] <- vector("list", nweight)
          names(C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]][[(i5)]]) <- cweight
          for (i6 in cweight) {
            C[1, 2] <- as.numeric(i1)
            C[2, 1] <- as.numeric(i2)

            C[1, 3] <- as.numeric(i2)
            C[3, 1] <- as.numeric(i2)

            C[1, 4] <- as.numeric(i3)
            C[4, 1] <- as.numeric(i3)

            C[2, 3] <- as.numeric(i4)
            C[3, 2] <- as.numeric(i4)

            C[2, 4] <- as.numeric(i5)
            C[4, 2] <- as.numeric(i5)

            C[4, 3] <- as.numeric(i6)
            C[3, 4] <- as.numeric(i6)
            C_list[[i1]][[i2]][[i3]][[i4]][[i5]][[i6]] <- C
          }
        }
      }
    }
  }
}

Unlist the list of list of list of ... nested matrices to end up with a long list of matrices with the weights for each dataset

C_list2 <- unlist(unlist(unlist(unlist(unlist(C_list, FALSE, FALSE),
                                       FALSE, FALSE), FALSE, FALSE),
                         FALSE, FALSE), FALSE, FALSE)


texts:
I have a small module that gets the lemma of a word and its plural form. It then searches through sentences looking for a sentence that contains both words (singular or plural) in either order. I have it working but I was wondering if there is a more elegant way to build this expression.

Note: Python2

words = ((cell,), (wolf,wolves))
string1 = "(?:"+"|".join(words[0])+")"
string2 = "(?:"+"|".join(words[1])+")"
pat = ".+".join((string1, string2)) +"|"+ ".+".join((string2, string1))
# Pat output: "(?:cell).+(?:wolf|wolves)|(?:wolf|wolves).+(?:cell)"

Then the search:

pat = re.compile(pat)
for sentence in sentences:
    if len(pat.findall(sentence)) != 0:
        print sentence+'\n'

Alternatively, would this be a good solution?

words = ((cell,), (wolf,wolves))
for sentence in sentences:
    sentence = sentence.lower()
    if any(word in sentence for word in words[0]) and any(word in sentence for word in words[1]):
        print sentence


texts: Determining whether a provided credit card number is valid according to Luhn’s algorithm

texts:
I have been working on credit problem for edx CS50 and got it working as intended. an issue I find with it is the way I have to reinitialise the cardNumber variable each time it enters a loop, and there are plenty of loops in my solution. Same goes for my bool value. Is there a better, cleaner way to go around this?

#include <stdio.h>
#include <cs50.h>

// Implement a program that determines whether a provided credit card number
// is valid according to Luhn’s algorithm.

int main(void)
{
    long long userInput;

    // Prompt for user input as long long.
    do
    {
        userInput = get_long_long("Enter credit card number to validate: ");

        // Ensure user inputs integer otherwise prompt "Retry: "
        if (userInput < 0)
        {
            printf("Retry: \n");
        }
    } while (userInput < 0);

    long long cardNumber = userInput;
    int checkSum = 0;
    int secDig, lastDig, multDig;

    // start from second to last digit (cc_number / 10) % 10 and multiply every other digit by 2.
    while (cardNumber > 0)
    {
        // sum digits that weren't multiplied.
        lastDig = (cardNumber % 10);
        // add the sum to the sum of the digits that weren't multipied by 2.
        checkSum += lastDig;

        secDig = (cardNumber / 10) % 10;
        cardNumber /= 100;

        // multiply every other digit
        multDig = secDig * 2;

        // add those products (separate /10, return modulus of 10) digits together.
        if (multDig > 10)
        {
            checkSum += (multDig % 10) + 1;
        }
        else if (multDig == 10)
        {
            checkSum += 1;
        }
        else
        {
            checkSum += multDig;
        }
    }

    // validate checksum
    // if sum of digits ends in 0 ergo % 10 = 0 then number is valid.
    bool valid = false;
    if (checkSum % 10 == 0)
    {
        valid = true;
    }

    int numOfDigits = 0;
    cardNumber = userInput;

    // validate number's length
    // track number's length
    while (cardNumber > 0)
    {
        cardNumber /= 10;
        numOfDigits++;
    }

    cardNumber = userInput;

    // validate company's identifier
    // if 15 digits, starts with 34 or 37 - AMEX

    if (valid == true && numOfDigits > 12)
    {
        if (numOfDigits == 15)
        {
            for (int i = 0; i < numOfDigits - 2; i++)
            {
                cardNumber /= 10;
            }
            if (cardNumber == 34 || cardNumber == 37)
            {
                printf("AMEX\n");
                valid = true;
            }
            else
            {
                valid = false;
            }
        }
        // if 16 digits, starts with 51-55 - MASTERCARD
        cardNumber = userInput;
        if (numOfDigits == 16)
        {
            for (int i = 0; i < numOfDigits - 2; i++)
            {
                cardNumber /= 10;
            }
            if (cardNumber >= 51 && cardNumber <= 55)
            {
                printf("MASTERCARD\n");
                valid = true;
            }
            else
            {
                valid = false;
            }
        }
        // if 13 OR 16 digits, starts with 4 - VISA
        cardNumber = userInput;
        if (numOfDigits == 13 || numOfDigits == 16)
        {
            for (int i = 0; i < numOfDigits - 1; i++)
            {
                cardNumber /= 10;
            }
            if (cardNumber == 4)
            {
                printf("VISA\n");
                valid = true;
            }
            else
            {
                valid = false;
            }
        }
        if (valid == false)
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }
}

All comments are part of pseudocode for this solution. I left them there to satisfy style50. I would appreciate advice so I can write cleaner next time and make it into a habit. I am a beginner starting CS degree next year with only experience with doing C# courses with Mosh Hamedani.