texts: Simple data-fetching and conversion into JSON using two different patterns

texts:
I'm trying to fetch and convert data into JSON format. Some days ago I was using MySQLi but someone told me this is susceptible to SQL injections when I asked a question for code review. Now I'm trying to use PDO.

PHP MySQLi (OOP-based)

$CompanyRes = array();
$Company = "select * from `ws_company` where `cm_status` = 1";
$CompanyQuery = mysqli_query($this->connection,$Company);
while($rowCom = mysqli_fetch_assoc($CompanyQuery)){
    $CompanyRes[] = $rowCom;
}

PDO-based

$CompanySts=$this->pdoConnection->prepare("select * from `ws_company` where `cm_status` = 1");
$CompanySts->execute();
header("Content-type: application/json; charset=utf-8");
$CompanyRes = array();
while ($row = $CompanySts->fetch(PDO::FETCH_ASSOC)) {
    $CompanyRes[] = array_map('utf8_encode', $row);
}

Both are same work for me, but I wanted to know if the second one is correct or not, and if I'm missing something.


texts: Method for Access to a Resource with 'Retry' Logic

texts:
I am trying to implement so me 'retry' logic in a Data Access layer where the DB occassionaly times out (and the method is called several thousand times a day). This is the best I can come up with, but I don't like throwing the exception if the code falls out of my while loop; it doesn't feel like a succinct solution. Can it be improved?

NB: No need for multi-threaded access.

private static currentDbAttempt

private static Int32? GetDbValue()
        {
            currentDbAttempt = 1;
            while(currentDbAttempt <= MAX_DB_ATTEMPTS)
            {
                try
                {
                    Int32? nextId = [some DB work]
                    return nextId.Value;
                }
                catch (Exception ex)
                {
                    if (currentDbAttempt == MAX_DB_ATTEMPTS)
                        throw new Exception(string.Format("Error in [method name]. Tried {0} times",
                            MAX_DB_ATTEMPTS), ex);

                    _log.WarnFormat("Error in [method name]: {0}. Try count {1}",
                        ex.Message, currentDbAttempt++);
                }
            }

            // Code smell...
            throw new Exception("[method name] - shouldn't reach here.");

        }


texts: Recursive BFS solution for tree traversal

texts:
I'm somewhat new to the wonderful world of Python, outside of simple codecademy-like challenges online.

This function was part of a project for school. It's tested and works, but I'm looking for some feedback. Did I over-think it? I don't think recursion was necessary, but I was in that mindset from the previous portion of the assignment which was a similar function for DFS.

Below is my code, the input format (a dictionary) and a visual representation of the tree that I used to test it:

def BFS(tree,level=["A"]):
  bfs_list = []
  if len(level) > 0:
    bfs_list += level
    sub_level = []
    for vertex in level:
      sub_level += tree[vertex]
    bfs_list += BFS(tree,sub_level)
  return bfs_list

#            ___A___
#           /       \
#          C         D
#        / | \     / | \
#       P  R  L   F  Q  S
#         / \       / \
#        O   E     G   H
#                 / \
#                N   M
#
tree = {"A" : ["C", "D"],
        "C" : ["P","R","L"],
        "R" : ["O","E"],
        "G" : ["N", "M"],
        "Q" : ["G", "H"],
        "D" : ["F", "Q", "S"],
        "P" : [],
        "L" : [],
        "N" : [],
        "M" : [],
        "H" : [],
        "S" : [],
        "F" : [],
        "O" : [],
        "E" : []}
print(BFS(tree))


texts: Calculating percentages in arbitrary number of columns

texts:
Given this sample input:

ID     Sample1     Sample2      Sample3
One      10          0            5
Two      3           6            8
Three    3           4            7

I needed to produce this output using GNU AWK (awk in Linux, gawk in BSD):

ID    Sample1 Sample2 Sample3
One   62.50   0.00    25.00
Two   18.75   60.00   40.00
Three 18.75   40.00   35.00

This is how I solved it:

function percent(value, total) {
    return sprintf("%.2f", 100 * value / total)
}
{
    label[NR] = $1
    for (i = 2; i <= NF; ++i) {
        sum[i] += col[i][NR] = $i
    }
}
END {
    title = label[1]
    for (i = 2; i <= length(col) + 1; ++i) {
        title = title "\t" col[i][1]
    }
    print title
    for (j = 2; j <= NR; ++j) {
        line = label[j]
        for (i = 2; i <= length(col) + 1; ++i) {
            line = line "\t" percent(col[i][j], sum[i])
        }
        print line
    }
}

What do you think about this implementation? How would you improve it?


texts: Unbounded knapsack solution with items of equal value

texts:
My solution correctly solves the problem, but I would like to optimize its performance. For a capacity of 7 and bars = [ 4, 1, 1, 2, 1], the output is 7.

def knapsack(capacity, bars)
    if capacity == 0 || bars.nil? || bars[0].nil?
        return 0
    end

    solutions = []
    sum = 0
    (1..capacity).each do |i|
        break if sum > capacity
        bars.combination(i).lazy.each do |comb|
            sum = comb.reduce(&:+)
            solutions << sum
        end
    end

    solutions.select{|i| i <= capacity}.max
end


texts: Index of letter removed to make string palindrome

texts:
This code finds the index in the string and removes the one which will make the string a palindrome. If the string is already a palindrome, it should return -1.

This code works correct, but I am looking for a better implementation of it. Here is the problem description.

def palindrome(string):
    return string == string[::-1]

def palindrome_index(string, start, end):
    while start < end:
        if string[start] == string[end]:
            start, end = start+1, end-1
            continue
        if palindrome(string[start:end]): return end
        return start
    return -1
N = input()
strings = [str(raw_input()) for _ in range(N)]
for string in strings:
    print palindrome_index(string, 0, len(string)-1)

Can this be written shorter?  The size of input strings can be as large as 105, hence a recursive approach won't work.


texts:
I attempted to recreate the Polybius square, also called the Polybius checkerboard, which was used in Ancient Greece for cryptography. Since it is an uncommon cipher, it is nowhere on Code Review.

Although the program technically works, it ended up very messy.

#include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
#include <unordered_map>

std::string getChoice();
std::vector<std::string> getCoords();

int main(){
    std::string choice = getChoice();

    if(choice == "e"){
        std::cout << "Input string: ";
        std::string input;
        std::getline(std::cin, input);
        input.erase(remove_if(input.begin(), input.end(), isspace), input.end());

        std::unordered_map<char, unsigned int> alphaToInt = {
            {'A', 11},
            {'B', 12},
            {'C', 13},
            {'D', 14},
            {'E', 15},
            {'F', 21},
            {'G', 22},
            {'H', 23},
            {'I', 24},
            {'J', 24}, // same as I
            {'K', 25},
            {'L', 31},
            {'M', 32},
            {'N', 33},
            {'O', 34},
            {'P', 35},
            {'Q', 41},
            {'R', 42},
            {'S', 43},
            {'T', 44},
            {'U', 45},
            {'V', 51},
            {'W', 52},
            {'X', 53},
            {'Y', 54},
            {'Z', 55},
        };

        for(int i = 0; i < input.length(); ++i){
            std::cout << alphaToInt[input[i]] << ' ';
        }
    } else{
        std::vector<std::string> coords = getCoords();
        std::string output;

        const std::string squareIJ[5][5] = {
            {"A", "B", "C", "D", "E"},
            {"F", "G", "H", "I", "K"},
            {"L", "M", "N", "O", "P"},
            {"Q", "R", "S", "T", "U"},
            {"V", "W", "X", "Y", "Z"},
        };

        for(int i = 0; i < coords.size(); ++i){
            std::string coord = coords[i];
            output.append(squareIJ[coord[0] - '1'][coord[1] - '1']);
        }

        std::cout << output;

    }

    std::cout << '\n';
    return 0;
}

std::string getChoice(){
    std::string choice;
    do{
        std::cout << "Encrypt or decrypt [e/d] = ";
        std::getline(std::cin, choice);
        if(choice == "E") choice = "e";
        std::transform(choice.begin(), choice.end(), choice.begin(), ::tolower);
    } while(choice != "e" && choice != "d");

    return choice;
}

std::vector<std::string> getCoords(){
    std::cout << "Coordinates (separate with spaces): ";
    std::string strCoords;
    std::getline(std::cin, strCoords);
    std::stringstream streamCoords(strCoords);
    std::istream_iterator<std::string> begin(streamCoords);
    std::istream_iterator<std::string> end;
    std::vector<std::string> coords(begin, end);
    return coords;
}

The Polybius square is a simple way to assign characters numbers, and then "encrypt" and "decrypt" based off of those numbers. As shown in the unordered map and char array, the numbers correspond to the row and column on a 5x5 square:

The getChoice() function simply gets the e or d character to choose encryption or decryption.

The getCoords() function gets a string, and then tokenizes the string into a vector of strings, each corresponding to the coordinates of a character.

Example of "encryption":

Encrypt or decrypt [e/d] = e
Input string: BAT
12 11 44

Example of "decryption":

Encrypt or decrypt [e/d] = d
Coordinates (separate with spaces): 12 11 44
BAT

This code, in my opinion, is quite messy. How can I improve it?


texts: find_index for first occurrence of pattern in text

texts:
This is an implementation of find_index for a pattern in text. I got asked this coding question in a coding interview.

This Python function returns the starting index of the first occurrence of pattern in text and returns None if no index is found. For example, find_index('ababc', 'abc') returns 2 and find_index('abc', 'z') returns None.

I have the following implementation that handles most of the cases and I think the worst case running time is \$O(m*n)\$.

def find_index(text, pattern):
    assert isinstance(text, str), 'text is not a string: {}'.format(text)
    assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
    #if it's empty string, return 0
    if pattern == '':
        return 0
    text_index = 0
    while text_index != len(text):
        for i in range(len(pattern)):
            if text_index + i < len(text):
                if text[text_index + i] != pattern[i]:
                    break
                if i == len(pattern) - 1:
                    return text_index
        text_index += 1

I am not sure if I exhausted all of the edge cases, but I ran the following unit test, and it passed all tests.

import unittest

class StringsTest(unittest.TestCase):
   def test_find_index_with_matching_patterns(self):
        assert find_index('abc', '') == 0  # all strings contain empty string
        assert find_index('abc', 'a') == 0  # single letters are easy
        assert find_index('abc', 'b') == 1
        assert find_index('abc', 'c') == 2
        assert find_index('abc', 'ab') == 0  # multiple letters are harder
        assert find_index('abc', 'bc') == 1
        assert find_index('abc', 'abc') == 0  # all strings contain themselves
        assert find_index('aaa', 'a') == 0  # multiple occurrences
        assert find_index('aaa', 'aa') == 0  # overlapping pattern
        assert find_index('thisisabsolutelycrazy', 't') == 0

    def test_find_index_with_non_matching_patterns(self):
        # Negative test cases (counterexamples) with non-matching patterns
        assert find_index('abc', 'z') is None  # remember to test other letters
        assert find_index('abc', 'ac') is None  # important to test close cases
        assert find_index('abc', 'az') is None  # first letter, but not last
        assert find_index('abc', 'abz') is None  # first 2 letters, but not last

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


texts: getDayOfTheWeek function, without using built-in date libraries

texts:
I have an assignment to create a method to retrieve the proper day of the week for any given date, without using the Java calendar.  After countless hours of trying to implement the algorithm in the outline, I've finally finished it and it appears to work! I feel like it's really sloppy. Any tips on how to clean it up or remove any dead code you see?

Here's the algorithm I had to implement:

Only look at the last two digits of the year and determine how many 12s fit in it
Look at the remainder of this division
How many 4s fit into that remainder
Add the day of the month
Add the month code:

Jan = 1
Feb = 4
Mar = 4
Apr = 0
May = 2
Jun = 5
Jul = 0
Aug = 3
Sep = 6
Oct = 1
Nov = 4
Dec = 6
Add your numbers, then mod by 7

Some dates require special offsets:

January and February dates in leap years: subtract 1 from step 5
Dates in the 1600s: add 6 to step 5
Dates in the 1700s: add 4 to step 5
Dates in the 1800s: add 2 to step 5
Dates in the 2000s: add 6 to step 5
Dates in the 2100s: add 4 to step 5

public String getDayOfTheWeek()
{
    int shortYear = yearNumber %  ONE_HUND_MOD;
     /* gives the last two digits of the four digit year */
    int anotherShortYear = yearNumber % ONE_HUND_MOD;
     /* gives the last two digits of the four digit year to another variable */
    int twelvesFirstStep = (shortYear / TWELVE_DIVIDE);
     /* gives the number of 12s that fit in the last two digits of the year(step1) */
    int secondStepRemainder = anotherShortYear % TWELVE;
    /* gives the remainder of whats left from dividing the last
       two digits of year by 12(step 2) */
    int thirdStepRemainder = secondStepRemainder / FOUR;
    /* gives the division by 4 of the remainder of the previous step (step 3) */
    int numericalDay = 0;
    int temp = twelvesFirstStep + secondStepRemainder +
        thirdStepRemainder + dayNumber +getMonthCode(); // all variables combined
    if (monthNumber ==JANUARY ||
          monthNumber == FEBRUARY && isLeapYear() == true)
    {
        temp--;
    }
    else
    {
        temp = temp;
    }

    if (yearNumber >= CENTURY_SIXTEEN && yearNumber < CENTURY_SEVENTEEN
                 || yearNumber >= CENTURY_TWENTY && yearNumber < CENTURY_TWENTY_ONE)
    {
        numericalDay = (SIX+temp) % MOD_BY_SEVEN;
    }
    else if(yearNumber >=CENTURY_SEVENTEEN && yearNumber < CENTURY_EIGHTEEN
                 || yearNumber >= CENTURY_TWENTY_ONE && yearNumber <CENTURY_TWENTY_TWO)
    {
        numericalDay = (FOUR+temp) % MOD_BY_SEVEN;
    }
    else if(yearNumber >=CENTURY_EIGHTEEN && yearNumber < CENTURY_NINETEEN)
    {
        numericalDay =(TWO+temp) % MOD_BY_SEVEN;
    }

    else
    {
        numericalDay = temp % MOD_BY_SEVEN;
    }

    if(numericalDay == TRANSLATED_DAY_SAT)
    {
        return SATURDAY_STRING;
    }
    else if(numericalDay == TRANSLATED_DAY_SUN)
    {
        return SUNDAY_STRING;
    }
    else if(numericalDay ==TRANSLATED_DAY_MON)
    {
        return MONDAY_STRING;
    }
    else if(numericalDay == TRANSLATED_DAY_TUES)
    {
        return TUESDAY_STRING;
    }
    else if(numericalDay == TRANSLATED_DAY_WED)
    {
        return WEDNSEDAY_STRING;
    }
    else if(numericalDay ==TRANSLATED_DAY_THU)
    {
        return THURSDAY_STRING;
    }
    else
    {
        return FRIDAY_STRING;
    }

}


texts:
I was doing a basic problem on coding a factorial \$n!\$:

function factorialize(num) {
  if (num < 0) {
 return undefined;
  } else if (num === 0) {
    return 1;
  }
  else {
    return num * factorialize(num - 1);
  }
}

The site I'm learning from accepted this solution, but they're only testing for nonnegative integers, i.e for \$n \ge 0\$, not negative integers.

So I got curious on how to compute a negative factorial \$(-n)!\$. Many pages say it's undefined, but I found two saying it could be defined.

Link 1
Link 2

The gist I got is that:

\$|n!| = |(-n)!|\$

Their absolute values are the same but the negative factorials change signs.

Examples:

\$4! = (-4)! = 24\$

\$5! = 120\$ but \$(-5)! = -120\$

The formula that I gathered from the two linked pages is:

\$(-n)! =  |n|! * (-1)^n\$

And this reflects my code. From test cases, I think I've nailed it. I just want to ask if there's a better way of coding it. Someone from here
remarked that using recursion is memory-inefficient.

function factorialize(num) {
 if (num === 0) {
   return 1;
  } else if (num > 0) {
     return num * factorialize(num - 1);
  } else {
     return Math.pow(-1, num) * Math.abs(num) * factorialize(Math.abs(num) - 1);
    }
  }

// test cases below
    console.log(factorialize(-1)); // -1
    console.log(factorialize(1)); // 1
    console.log(factorialize(0)); // 1
    console.log(factorialize(-2)); // 2
    console.log(factorialize(2)); // 2
    console.log(factorialize(-3)); // -6
    console.log(factorialize(3)); // 6
    console.log(factorialize(-4)); // 24
    console.log(factorialize(4)); // 24
    console.log(factorialize(-5)); // -120
    console.log(factorialize(5)); // 120


texts:
If it is possible, could someone please revise my code to see if any improvements can be made?

  <title>Roamfree - Official Website</title>
  <link rel="stylesheet" href="index.css">

Welcome to the Roamfree Homepage!

About Roamfree

    Roamfree is a small company that wants to be recognised by the internet and we
    decided to make a website to hold ALL our future products, apps and games!
      This is a Prototype website (not even alpha) so I need support from
      the online community so my coding skills will progress further and this company
      will (eventually) grow!

Relyr

Well Relyr is the measuring app that I am currently developing
  and it is optimised for iOS 8 and is targeted at the Iphone 5s (sorry Ipad users)
  and you press Start then you walk with your Iphone with you and afterwards you press
  Stop then using GPS it approximately calculates how far you walked, this is mainly for
  architects and builders but perfectionists can also use it as well :)

Updates

So, my first update for this newly founded company as I am VERY happy to have
 a opportunity to get some of the profits and of course the fans and supporters as well
 and here's to a (hopefully) HUGE future for this company because of the support
 and help from you guys.

Navigation

Where do you want to go?

Home

Shop

News

About

Contact Us


texts: Compressing a 'char' array using bit packing

texts:
I have a large array (around 1 MB) of type unsigned char (i.e. uint8_t). I know that the bytes in it can have only one of 5 values (i.e. 0, 1, 2, 3, 4). Moreover, we do not need to preserve '3's from the input, they can be safely lost when we encode/decode.

So I guessed bit packing would be the simplest way to compress it, so every byte can be converted to 2 bits (00, 01..., 11).

As mentioned, all elements of value 3 can be removed (i.e. saved as 0), which gives me option to save '4' as '3'. While reconstructing (decompressing) I restore 3's to 4's.

I wrote a small function for the compression but I feel this has too many operations and is just not efficient enough. Any suggestions or hints on how to handle the operations more efficiently but maintaining the readability will be of much help.

/// Compress by packing ...
void compressByPacking (uint8_t* out, uint8_t* in, uint32_t length)
{
  for (int loop = 0; loop < length/4; loop ++, in += 4, out++)
  {
    uint8_t temp[4];

    for (int small_loop = 0; small_loop < 4; small_loop++)
    {
      temp[small_loop] = *in;           // Load into local variable

      if (temp[small_loop] == 3)        // 3's are discarded
        temp[small_loop] = 0;
      else if (temp[small_loop] == 4)   // and 4's are converted to 3
        temp[small_loop] = 3;

    } // end small loop

    // Pack the bits into write pointer
    *out = (uint8_t)((temp[0] & 0x03) << 6) |
                    ((temp[1] & 0x03) << 4) |
                    ((temp[2] & 0x03) << 2) |
                    ((temp[3] & 0x03));

  } // end loop
}

Cross-posted from SO


texts:
I have an iOS Swift app with 8 buttons that call the same segue, but this is very repetitive. How can I refactor so it uses the same function prepare?

@IBAction func backButtonPressed(_ sender: Any) {
    self.vcWithType = VCtype.back.rawValue
    self.postion = "back"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func mountButtonPressed(_ sender: Any) {
    self.vcWithType = VCtype.mount.rawValue
    self.postion = "mount"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func kneeRideButtonPressed(_ sender: Any) {
    self.vcWithType = VCtype.knee.rawValue
    self.postion = "knee"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func sideKbuttonPressed(_ sender: Any) {
    self.vcWithType = VCtype.sideK.rawValue
    self.postion = "side"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func northSouthBpressed(_ sender: Any) {
    self.vcWithType = VCtype.northSouth.rawValue
    self.postion = "north"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func guardBpressed(_ sender: Any) {
    self.vcWithType = VCtype.guarda.rawValue
    self.postion = "guard"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func halfGuardBpressed(_ sender: Any) {
    self.vcWithType = VCtype.halfGuard.rawValue
    self.postion = "half"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

@IBAction func turtleBpressed(_ sender: Any) {
    self.vcWithType = VCtype.turtle.rawValue
    self.postion = "turtle"
    self.performSegue(withIdentifier: "showCategory", sender: sender)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if (segue.identifier == "showCategory") {

        if let vc: CategoryViewController = segue.destination as? CategoryViewController {
            vc.vcWithType = self.vcWithType
            vc.chaza = self.postion

        }

    }

}


texts:
This script to locate torrent files in a given directory, and if they have been seeding for 2 weeks, delete the files.

I realize the comments are overboard. The reason for that is it's being shared with people who don't program.

What should I have done differently?

import os  # for listdir(), path(), remove(), and getctime()
from time import time, ctime, sleep
import datetime as dt  # datetime to compare dates

# Path to torrents
torrents_folder = r'C:\users\user\torrents\folder'
# Torrent files as a list
torrents = os.listdir(torrents_folder)
# Months will be used to swap month prefix and corresponding month number
months = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08",
          "Sep": "09", "October": "10", "Nov": "11", "Dec": "12", }
# Set the number of days to elapse from creation date before file is deleted
days_to_wait = dt.timedelta(days=14)

# function to remove torrent
def torrent_remover(month):
        # Format the date, casting month to string
        start_date = dt.datetime.strptime(str(month), "%m %d %Y")
        # Elapsed Time. See line 12
        end_date = start_date + days_to_wait
        # Today's date for comparison
        today = dt.datetime.today()

        if end_date <= today:
            print("Removing: ", torrent, "\tTorrent expired on", end_date)
            # Create full path from the torrent folder and torrent file
            torrent_files = os.path.join(torrents_folder, torrent)
            # Delete the torrents
            os.remove(torrent_files)
        else:
            print("Nothing to remove")
            exit()

# Start the loop
for torrent in torrents:
    if torrent.endswith(".torrent"):
        # Get date time from each file then join file and folder to create full path
        date = ctime(os.path.getctime(os.path.join(torrents_folder, torrent)))
        # Remove the timestamp
        remove_timestamp = date.replace(date[11:19], "")
        # Remove the day
        new_date = remove_timestamp.replace(remove_timestamp[0:4], "")
        # Return single value in list
        month = [month for month in months if month in new_date][0]
        if month in new_date:
            # Returns the month number when passed month key
            month_number = months[month]
            # Replace the month prefix with the corresponding number
            reformatted_date = new_date.replace(month, month_number)
            # Send to delete function to be deleted.
            torrent_remover(reformatted_date)


texts: Make a popup window that will stay open for 3 seconds

texts:
I am doing an assignment and I have a task where I need to make a simulation where under certain conditions it opens a popup window and then closes it after 3 seconds. This is how I did it:

if(condition) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        Platform.runLater( () -> {
            try {
                Monument atr = ((Monument)matrica[red][kolona]);
                FXMLLoader loader = new FXMLLoader(getClass().getResource("PopUp.fxml"));
                Scene scene = new Scene(loader.load());
                loader.<PopUpController>getController().setImage(atr.getImage());
                Stage stage = new Stage();
                stage.setScene(scene);
                stage.sizeToScene();
                stage.setResizable(false);
                stage.setTitle("Image");
                stage.show();
                sleep(3000);
                ((Stage)(stage.getScene().getWindow())).close();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
    });
    executor.shutdown();
}

I use Platform.runLater because I am accessing the UI from a different thread. My question is, is there any better way of doing this?


texts: CareerCup (Bloomberg): Check if string is valid based on brackets

texts:
The goal of this problem is to determine if a string with brackets is valid. Below is a summary of the question from careercup.

Check if string s is valid based on brackets

"(({{}}))" is a valid s
"{[]}" is a valid s
"[{[}]]" is not valid

I know this is a rather basic exercise. I am looking for feedback on whether my solution is sound and efficient. I would also like to know if my code is clean. Also is there too much for a 45 minute interview? The solution is shown below.

public class Question_ValidStringWithBrackets
{
    public bool IsValidBracketString(String s, BracketValidator validator = null)
    {
        if (s == null)
            throw new ArgumentNullException("A string is required");

        if (validator == null)
            validator = BracketValidator.CreateDefaultValidator();

        Stack<char> openStack = new Stack<char>();

        foreach (var curBracket in s)
        {
            if (validator.IsOpen(curBracket))
            {
                openStack.Push(curBracket);
            }
            else if (openStack.Count == 0 || validator.IsMatchingPair(openStack.Pop(), curBracket))
            {
                return false;
            }
        }
        return openStack.Count == 0;
    }

    public class BracketValidator
    {
        private HashSet<char> openBrackets = new HashSet<char>();
        private Dictionary<char, char> closedOpenedPair = new Dictionary<char, char>();

        public void AddPair(char open, char close)
        {
            if (char.IsWhiteSpace(open) || char.IsWhiteSpace(close))
                throw new ArgumentException("A bracket must be specified. An empty character is not allowed.");

            if (openBrackets.Contains(open) || openBrackets.Contains(close))
                throw new ArgumentException("Brackets exist already.");

            if (closedOpenedPair.ContainsKey(open) || closedOpenedPair.ContainsKey(close))
                throw new ArgumentException("Brackets exist already.");

            openBrackets.Add(open);
            closedOpenedPair.Add(close, open);
        }

        public Boolean IsOpen(char open)
        {
            return openBrackets.Contains(open);
        }

        public bool IsMatchingPair(char open, char close)
        {
            return closedOpenedPair.TryGetValue(open, out char actualClose) && actualClose == close;
        }

        public static BracketValidator CreateDefaultValidator()
        {
            var validator = new BracketValidator();
            validator.AddPair('{', '}');
            validator.AddPair('[', ']');
            validator.AddPair('(', ')');

            return validator;
        }
    }
}


texts:
A BST has two nodes swapped. Figure out which two nodes.
Looking for code-review, optimizations and best practices.

public class SwappedNodes {

    private TreeNode root;

    SwappedNodes(List<Integer> items) {
        create(items);
    }

    private void create (List<Integer> items) {
        if (items.isEmpty()) {
            throw new IllegalArgumentException("The item is empty");
        }
        root = new TreeNode(items.get(0));

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode current = queue.poll();
                int left = 2 * i + 1;
                int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode {
        private TreeNode left;
        private int item;
        private TreeNode right;

        TreeNode (int item) {
            this.item = item;
        }
    }

    private static class PrevNode {
        private TreeNode prevNode;
        PrevNode (TreeNode prevNode) {
            this.prevNode = prevNode;
        }
    }

    /**
     * Returns the 2 nodes which if swapped results in binary search tree.
     */
    public int[] getSwappedNode( ) {
        final List<TreeNode> list = new ArrayList<>();
        computeSwappedNodes (root, new PrevNode(null), list);

        int[] result = {list.get(0).item, list.get(list.size() - 1).item};
        return result;
    }

    private void computeSwappedNodes (TreeNode node, PrevNode prevNode, List<TreeNode> list) {
        if (node == null) return;

        computeSwappedNodes (node.left, prevNode, list);
        if (prevNode.prevNode != null) {
            if (prevNode.prevNode.item > node.item) {
                list.add(prevNode.prevNode);
                list.add(node);
            }
        }

        prevNode.prevNode = node;

        computeSwappedNodes (node.right, prevNode, list);
    };
}

public class SwappedNodesTest {

    // both values in different branches
    @Test
    public void testDifferentBranches() {
        SwappedNodes sn1 = new SwappedNodes(Arrays.asList(10, 4, 25, 2, 20, 8, null));
        int[] a1 = {20, 8};
        assertArrayEquals(a1, sn1.getSwappedNode());
    }

    // parent child relationship
    @Test
    public void testParentChild() {
        SwappedNodes sn3 = new SwappedNodes(Arrays.asList(10, 2, 20, 5, 8, 15, 29));
        int[] a3 = {5, 2};
        assertArrayEquals(a3, sn3.getSwappedNode());
    }

    @Test
    public void testAncestor() {
        SwappedNodes sn4 = new SwappedNodes(Arrays.asList(8, 5, 20, 2, 10, 15, 29));
        int[] a4 = {10, 8};
        assertArrayEquals(a4, sn4.getSwappedNode());
    }

}


texts:
I am in the process of learning Java and going through the Euler problems. For Problem 4 I decided to also implement a TDD approach with JUnit.

My questions are:

Is there a better TDD approach to this problem?

I wrote out all these test cases initially. Some obviously pass and some fail initially because I'm checking a boolean. This makes it impossible to write a failing test in this fashion, should I have written only a failing scenario (say test100), then added in more as my method worked?

Being new to Java, are there obvious code organization things I am missing?
Any naming tips would be appreciated as well as I am terrible at this generally!

I have three source files:

main.java

public class main {

    public static void main(String[] args) {

        PalindromeChecker p = new PalindromeChecker();
        int largest=0;
        int product;

        for (int i = 999; i>100; i--){

            for (int j = 999; j>100; j--){
                product = i*j;
                if (p.isPalindrome(product) && product > largest) {
                    largest = product;
                }
            }
        }
        System.out.println(largest);
    }
}

PalindromeChecker.java

public class PalindromeChecker {

    public boolean isPalindrome(int input){

        String str = new Integer(input).toString();
        int len = str.length();

        for(int i = 0; i < Math.ceil(len/2.0); i++){

            if (str.charAt(i) != str.charAt(len-i-1)) {
                return false;
            }
        }

        return true;

    }
}

PalindromeCheckerTest.java

import static org.junit.Assert.*;
import org.junit.Test;

public class PalindromeCheckerTest {

    @Test
    public void test10() {
        PalindromeChecker checker = new PalindromeChecker();
        assertFalse("10 failed",checker.isPalindrome(10));
    }
    @Test
    public void test112() {
        PalindromeChecker checker = new PalindromeChecker();
        assertFalse("112 failed",checker.isPalindrome(112));
    }
    @Test
    public void test900() {
        PalindromeChecker checker = new PalindromeChecker();
        assertFalse("900 failed",checker.isPalindrome(900));
    }

    @Test
    public void test1000() {
        PalindromeChecker checker = new PalindromeChecker();
        assertFalse("1000 failed",checker.isPalindrome(1000));
    }

    @Test
    public void test909() {
        PalindromeChecker checker = new PalindromeChecker();
        assertTrue(checker.isPalindrome(909));
    }

    @Test
    public void test1001() {
        PalindromeChecker checker = new PalindromeChecker();
        assertTrue(checker.isPalindrome(1001));
    }

    @Test
    public void test11() {
        PalindromeChecker checker = new PalindromeChecker();
        assertTrue(checker.isPalindrome(11));
    }

    @Test
    public void test111() {
        PalindromeChecker checker = new PalindromeChecker();
        assertTrue(checker.isPalindrome(111));
    }

}


texts: First text game with Python - Higher or Lower

texts:
Recently I have been learning Python programming, for about a week. I have covered all basic stuff - loops, strings, input masks - and have challenged myself by making a little game. It isn't much, that I know, but I was just wandering whether or not I have done everything correctly.

Any feedback regarding functions and methods used would be greatly appreciated.

import random
cards = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
suits = ["Spades","Hearts","Clubs","Diamonds"]
x = 1
while x < 20:
    for i in range(1,9):
        cardVal = cards[random.randint(0,12)]
        cardNum = cards.index(cardVal)
        suitVal = suits[random.randint(0,3)]
        if i == 1:
            print("Your starting card is the",cardVal,"of",suitVal)
        HoL = str(input("Higher (H), Lower (L) or Same (S): "))
        if HoL == "H":
            newCval = cards[random.randint(0,12)]
            newCnum = cards.index(newCval)
            if newCnum < cardNum + 1:
                print("Sorry, you fail. Card is",newCval,"of",suitVal)
                break
            elif newCnum > cardNum:
                print("Good job! Card is",newCval,"of",suitVal)
            else:
                print("Sorry, you fail. Card is",newCval,"of",suitVal)
                break
        if HoL == "L":
            newCval = cards[random.randint(0,12)]
            newCnum = cards.index(newCval)
            if newCnum > cardNum - 1:
                print("Sorry, you fail. Card is",newCval,"of",suitVal)
                break
            elif newCnum < cardNum:
                print("Good job! Card is",newCval,"of",suitVal)
            else:
                print("Sorry, you fail. Card is",newCval,"of",suitVal)
                break
        if HoL == "S":
            newCval = cards[random.randint(0,12)]
            newCnum = cards.index(newCval)
            if newCnum != cardNum:
                print("Sorry, you fail. Card is",newCval,"of",suitVal)
                break
            else:
                print("Good job! Card is",newCval,"of",suitVal)
    print("Congratulations!")
    repeat = str(input("Enter 'Yes' to run again: "))
    if repeat != "Yes":
        break


texts:
This is a follow up to this question. I'm only interested to see if this is implemented correctly for move-only types.

#include <vector>
#include <iterator>
#include <algorithm>
#include <utility>

namespace sorting {
  namespace detail {
    template<typename RandomIt>
    RandomIt middle_iterator(RandomIt begin, RandomIt end) {
      return std::next(begin, (end - begin) / 2);
    }

    template<typename RandomIt1, typename RandomIt2, typename OutIt>
    OutIt merge(RandomIt1 left, RandomIt1 left_end, RandomIt2 right, RandomIt2 right_end, OutIt out) {
      while(left < left_end && right < right_end) {
        if (*left < *right) {
          *out++ = std::move(*left++);
        } else {
          *out++ = std::move(*right++);
        }
      }

      std::move(left, left_end, out);
      std::move(right, right_end, out);
      return out;
    }
  }

  template<typename RandomIt1, typename RandomIt2>
  void merge_sort(RandomIt1 begin, RandomIt2 end, RandomIt2 scratch_begin, RandomIt2 scratch_end) {
    if (end - begin > 1) {
      const auto mid = detail::middle_iterator(begin, end);
      const auto scratch_mid = detail::middle_iterator(scratch_begin, scratch_end);
      merge_sort(scratch_begin, scratch_mid, begin, mid);
      merge_sort(scratch_mid, scratch_end, mid, end);
      detail::merge(scratch_begin, scratch_mid, scratch_mid, scratch_end, begin);
    }
  }

  template<typename RandomIt>
  void merge_sort(RandomIt begin, RandomIt end) {
    using value_type = typename std::iterator_traits<RandomIt>::value_type;
    auto scratch_buffer = std::vector<value_type>(std::make_move_iterator(begin), std::make_move_iterator(end));
    merge_sort(begin, end, scratch_buffer.begin(), scratch_buffer.end());
  }
}


texts: AppVersion Struct & VersionParse Exception

texts:
I am working on an app that will interact with assembly (app) versions. I created a struct for that, along with an exception for parsing error.

Here's the code:

    [Serializable]
    public class VersionParseException : Exception
    {
        public VersionParseException()
        { }

        public VersionParseException(string message)
            : base(message)
        { }

        public VersionParseException(string message, Exception innerException)
            : base(message, innerException)
        { }

        protected VersionParseException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        { }

    }

    public struct AppVersion
    {
        int _majorVersion;
        public int MajorVersion
        {
            get { return _majorVersion; }
            set
            {
                _majorVersion = value;
            }
        }

        int _minorVersion;
        public int MinorVersion
        {
            get { return _minorVersion; }
            set
            {
                _minorVersion = value;
            }
        }

        int _buildNumber;
        public int BuildNumber
        {
            get { return _buildNumber; }
            set
            {
                _buildNumber = value;
            }
        }

        int _revision;
        public int Revision
        {
            get { return _revision; }
            set
            {
                _revision = value;
            }
        }

        public string Version
        {
            get { return MajorVersion.ToString() + "." + MinorVersion.ToString() + "." + BuildNumber.ToString() + "." + Revision.ToString(); }
            set
            {
                try
                {
                    MajorVersion = int.Parse(value.Split('.')[0]);
                    MinorVersion = int.Parse(value.Split('.')[1]);
                    BuildNumber = int.Parse(value.Split('.')[2]);
                    Revision = int.Parse(value.Split('.')[3]);
                }
                catch (Exception exception)
                {
                    throw new VersionParseException("Invalid App Version", exception);
                }
            }
        }
    }

Is there any better way to handle AppVersions and exceptions occurring in the process of using it?

And here's an example of using the struct:

AppVersion version1;
version1.Version = "0.500.965.201";
Console.WriteLine(version1.MinorVersion); // outputs "500"
version1.BuildNumber = 753;
Console.WriteLine(version1.Version);      // outputs "0.500.753.201"

Another example on throwing the exception:

AppVersion version2;
version2.Version = "0.blabla.987.test"; //Throws VersionParseException


texts:
Below is my solution to Climbing the Leaderboard on HackerRank:

  Alice is playing an arcade game and wants to climb to the top of the
  leaderboard. Can you help her track her ranking as she beats each
  level? The game uses Dense Ranking, so its leaderboard works like
  this:

  The player with the highest score is ranked number 1 on the
  leaderboard.
  Players who have equal scores receive the same ranking
  number, and the next player(s) receive the immediately following
  ranking number.

  For example, four players have the scores 100, 90, 90, and 80.
  Those players will have ranks 1, 2, 2, and 3, respectively.

  When Alice starts playing, there are already \$n\$ people on the
  leaderboard. The score of each player \$i\$ is denoted by \$s_i\$. Alice plays for \$m\$
  levels, and we denote her total score after passing each level \$j\$ as \$alice_j\$.
  After completing each level, Alice wants to know her current rank.

  You are given an array, \$scores\$, of monotonically decreasing leaderboard
  scores, and another array, \$alice\$, of Alice's cumulative scores for each
  level of the game. You must print \$m\$ integers. The \$j^{th}\$ integer should
  indicate the current rank of alice after passing the \$j^{th}\$ level.

For example, when \$scores\$ is:

100 100 50 40 40 20 10

And \$alice\$ is:

5 25 50 120

The rankings for each score of Alice are 6, 4, 2, 1.

My code below works for most test cases,
except the last few where it times out.

function dedupe(arr, n) {
  const result = [];

  for(let i = 0; i < n; i++) {
    if(!result.includes(arr[i])) {
      result.push(arr[i]);
    }
  }

  return result;
}

const cache = {};

function binarySearchRankings(input, keySearch, min, max) {
  if(keySearch > input[0]) {
    return 1;
  }

  if(cache[keySearch]) {
    return cache[keySearch];
  }

  let mid = 0;

  while(min <= max) {

    mid = Math.ceil((min + max) / 2);

    if(keySearch === input[mid]) {
      const result = ++mid;
      cache[keySearch] = result;
      return result;
    } else if(keySearch >= input[mid]) {
      max = mid - 1;
    } else {
      min = mid + 1;
    }
  }

  if(keySearch <= input[mid]) {
    cache[keySearch] = mid + 2;
    return mid + 2;
  }

  if(keySearch > input[mid]) {
    cache[keySearch] = mid + 1;
    return mid + 1;
  }

  return mid;
}

const deduped = dedupe(scores, n);

for(var i = 0; i < m; i++) {
  const a = binarySearchRankings(deduped, alice[i], 0, deduped.length -1);

  console.log(a);
}


texts:
I am currently using the following glsl code to retrieve separate textures from a tile atlas:

#version 330 core
in vec2 TexCoord;
out vec4 color;

uniform sampler2D image;

void main()
{
    //width and height in tiles of atlas
    int width = 8;
    int height = 8;
    //x and y position of a tile in the atlas
    int x = 1;
    int y = 4;

    float scalarX = 1.0 / width;
    float scalarY = 1.0 / height;

    color = vec4(1.0) * texture(image, vec2((TexCoord.x + x) * scalarX,  (TexCoord.y * scalarY) + y * scalarY));
}

The tile atlas is made up of: 8*8 sprites each with dimensions of: 16*16 pixels

Is this the best method to use when carrying out this task and could my code be improved / made more efficient?


texts:
I tried to implement a queue which stores it's elements in a resizing array. Seems to work fine. Can you tell me if i did something wrong?

public class Queue<T>
{
    private T[] array;

    public Queue()
    {
        array = new T[16];
    }

    private void Enqueue(T item)
    {
        if(Count == array.Length/2)
            Grow();

        array[Count++] = item;
    }

    public void Grow()
    {
        var temp = array;
        array = new T[array.Length * 2];
        Array.Copy(temp,startingPos,array,0,Count);
        startingPos = 0;
    }

    public void Shrink()
    {
        var temp = array;
        array = new T[array.Length / 2];
        Array.Copy(temp,startingPos,array,0,Count);
        startingPos = 0;
    }

    public T Dequeue()
    {
        if(Count == array.Length/4)
            Shrink();

        var item = array[startingPos];
        array[startingPos++] = default(T);
        Count--;
        return item;
    }

    int startingPos = 0;

    public int Count {get;set;}
}


texts: The fastest way to find one unique value when all other values are the same

texts:
I have completed this question and I am wondering what is the fastest way to solve it.
The question is "There is an array with some numbers. All numbers are equal except for one. Try to find it!"
Example:
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55

I came up with the solution:
from collections import Counter

def find_uniq(arr):
    nums = list(Counter(arr).items())
    data = [i for i in nums if i[1] == 1]
    return data[0][0]

I decided on using Counter because I felt comfortable using it but when looking at others answers some use sets and others use counter as well.
I am wondering is my code sufficient and which method to solving this question would lead to the fastest time complexity?


texts: Recursive merge-sort inversion count algorithm very slow

texts:
I am trying to implement a recursive count of inversions in a list of integers by using merge sort and counting the number of split inversions on each recursion. My code works but runs painfully slowly above a list of about 100 integers, and I need to count for ~3 orders of magnitude greater. Can anyone see what I'm doing wrong that makes it so slow?

inversions = np.loadtxt("inversion_text.txt", int).tolist()

def sort_count_inversions(X):
    n = len(X)

    # For subproblems of size 1 there are no inversions and no sorting required
    if n == 1:
        return 0, X
    a = X[:n//2]
    b = X[n//2:]

    # Count the inversions in subproblems
    # Get back the count of inversions and the sorted subproblems
    count_a, sorted_a = sort_count_inversions(a)
    count_b, sorted_b = sort_count_inversions(b)

    # Count the split inversions between sorted sub problems
    # Get back the count of split inversions and the the merge-sorted subproblems (sorted X)
    split_count, a_b = merge_count_split_inversions(sorted_a,sorted_b)

    # return the count of inversions in X and merge-sorted X
    count = split_count + count_a + count_b
    return count, a_b

def merge_count_split_inversions(X, Y):
    n = len(X) + len(Y)
    j = 0
    k = 0
    X_Y = []
    count_split = 0

    # Iterate through X and Y comparing value by value
    for i in range(n):
        # If we have reached the end of X or Y, there are no more inversions so append the remaining values to X_Y
        if j == len(X):
            X_Y.extend(Y[k:])
        elif k == len(Y):
            X_Y.extend(X[j:])
        # Add the smaller of the two compared elements to X_Y
        # If adding from Y, increment count of split inversions by the number of remaining elements in X
        elif X[j] < Y[k]:
            X_Y.append(X[j])
            j += 1
        else:
            X_Y.append(Y[k])
            k += 1
            count_split += len(X) - j

    # Return the total count of split inversions and the result of merge_sorting X and Y (X_Y)
    return count_split, X_Y

sort_count_inversions(inversions)


texts:
I am just now learning Scala a bit on my own time.  I wrote some code that works, but was wondering if you could eyeball it to see if its structure can be improved.  It is a partial octree implementation.

class octree(min_x:Double,
            min_y:Double,
            min_z:Double,
            max_x:Double,
            max_y:Double,
            max_z:Double
       ){
            var children:Array[octree] = new Array[octree](8)
            val min = (min_x,min_y,min_z)
            val max = (max_x,max_y,max_z)

            def side(x:Double,y:Double):Int={
                if(x<y) 1
               else 0
           }
           def index(x:Double,y:Double,z:Double):Int={
                 val center=(0.5*(max._1+min._1),0.5*(max._2+min._2),
                    0.5*(max._3+min._3))
                (side(center._1,x))|(side(center._2,y)<<1)|     (side(center._3,z)<<2)
          }
          def add(x:Double,y:Double,z:Double):octree={
                var i=index(x,y,z)
                print(" "+i)
                if(children(i)==null){
                    var min2_x=min._1
                    var min2_y=min._2
                    var min2_z=min._3
                    var max2_x=max._1
                    var max2_y=max._2
                    var max2_z=max._3

                    val center=(0.5*(max._1+min._1),0.5*(max._2+min._2),
                    0.5*(max._3+min._3))

                    if((i&1)==0) max2_x=center._1
                    else min2_x=center._1
                    if((i&2)==0) max2_y=center._2
                    else min2_y=center._2
                    if((i&4)==0) max2_z=center._3
                    else min2_z=center._3

                    children(i) = new        octree(min2_x,min2_y,min2_z,max2_x,max2_y,max2_z)
                    children(i)
            }
            else children(i).add(x,y,z)
    }
    def find(x:Double,y:Double,z:Double):octree={
             var i=index(x,y,z)
            print(" "+i)
             if(children(i)==null){
                    this
             }
            else children(i).find(x,y,z)
    }
 }


texts:
I wrote a linked list class and don't know how to optimize it, please suggest some ideas for optimizing and fixing possible memory leaks.
#define indexTooLarge -1
template <typename T>
class LincedList
{
public:
    LincedList(){}
    template<typename... Types>
    LincedList(T value,Types... values) :  LincedList(values...)
    {
        push_front(value);
    }
    LincedList(T value)
    {
        push_front(value);
    }
    ~LincedList()
    {
        clear();
    }
    void push_back(T value_a)
    {
        if(tail == nullptr)
        {
            tail = new Node(nullptr,value_a);
            head = tail;
            m_size++;
            return;
        }
        tail->next = new Node(nullptr,value_a);
        tail = tail->next;
        m_size++;
    }
    void push_front(T value_a)
    {
        if(head == nullptr)
        {
            head = new Node(nullptr,value_a);
            tail = head;
            m_size++;
            return;
        }
        head = new Node(head,value_a);
        m_size++;
    }
    void clear()
    {
        Node *buffer;
        for(int i = 0;i<m_size;i++)
        {
            buffer = head;
            head = head->next;
            delete buffer;
        }
        m_size = 0;
    }
    void remove(unsigned int index)
    {
        if(index >= m_size)
            throw indexTooLarge;
        Node *currectNode = head;
        for(int i = 0; i < index-1;i++)
            currectNode = currectNode->next;
        Node* buffer = currectNode->next;
        currectNode->next = currectNode->next->next;
        delete buffer;
        m_size--;
    }
    void remove(unsigned int index,unsigned int lenght)
    {
        if(index+lenght >= m_size)
            throw indexTooLarge;
        Node *currectNode = head;
        for(int i = 0; i < index-1; i++)
            currectNode = currectNode->next;
        Node* buffer = currectNode;
        currectNode = currectNode->next;
        for(int i = 0; i < lenght; i++ )
        {
            Node* buffer2 = currectNode;
            currectNode = currectNode->next;
            delete buffer2;
        }
        buffer->next = currectNode;
        m_size -= lenght;
    }
    T& operator[](unsigned const int &index)
    {
        if(index >= m_size)
            throw indexTooLarge;
        if(index == m_size-1)
            return tail->value;
        Node *currectNode = head;
        for(unsigned int i = 0; i < index;i++)
            currectNode = currectNode->next;
        return currectNode->value;
    }
    void operator=(const LincedList &C1)
    {
        head->value = C1.head->value;
        Node *currectNode = new Node(nullptr,C1[1]);
        Node *C1CurrectNode = C1[1];
        head->next = currectNode;
        for(int i = 2; i < m_size; i++)
        {
            C1CurrectNode = C1CurrectNode->next;
            currectNode->next = new Node(nullptr,C1CurrectNode->value);
            currectNode = currectNode->next;
        }
        tail->value = C1.tail->value;
    }
    unsigned int size()
    {
        return m_size;
    }
private:
    struct Node
    {
         Node* next;
         T value;
         Node(Node* next_a, T value_a) : next(next_a) , value(value_a)
         {}
    };
    unsigned int m_size = 0;
    Node* head = nullptr;
    Node* tail = nullptr;
};

#include <iostream>
int main()
{
    LincedList<int> ll(0,1,2,3);
    std::cout << ll[1] << std::endl; //writes to console 1
    ll.remove(1); //removes the element at index 1
    std::cout << ll[1] << std::endl; //writes to console 2
    ll.push_back(4);//adds to the end 4
    ll.push_front(5);//adds 5 to the beginning
    std::cout << ll.size() << std::endl; //writes to console 5
    ll.remove(1,2); //remove all 2 to 3 elements
    std::cout << ll[1] << std::endl ; //writes to console 3
    return  0;
}


texts: Efficient Implementation of functional and Lazy evaluation in C++

texts:
I am creating a c++ library implementing Java Functional Programming alike interface. In short, the code will look like this:

vector<string> buffer = ... ; // A buffer contains some strings
new IntStream(0, 100).map([](int a){
    return (a * 0x2344DDEF) & 0xF;
}).map([=](int a) {
    return buffer[a];
}).foreach([](string a) {
    cout << a << '\n';
});

Now I want to support parallel evaluation. For the example above, I want to get 100 execution tasks and send them to a thread pool. To do this, I have created EvalOp classes. The stream returns a list of EvalOp objects. They will only perform the actual computation when you invoke EvalOp::eval

template <typename T>
class EvalOp {
public:
    virtual T eval() = 0;
};

template <typename FROM, typename TO>
class TransformOp : public EvalOp<TO> {
public:
    TO eval() override {
        return mapper_(previous_->eval());
    }
protected:
    unique_ptr<EvalOp<FROM>> previous_;
    function<TO(FROM&)> mapper_;
};

template <typename T>
class Stream {
public:
    virtual bool isEmpty() = 0;
    virtual EvalOp<T> next() = 0;
    Stream<N> map(function<N(T)> mapper) {
        return new MapStream<N,T>(this, mapper);
    }
}

template <typename FROM, typename TO>
class MapStream : public Stream<TO> {
protected:
    Stream<FROM>* previous_;
    function<TO(FROM)> mapper_;
public:
    EvalOp<TO> next() override {
        return new TransformOp<FROM, TO>(previous_->next(), mapper_);
    }
}

My stream will now return a bunch of EvalOp objects, which you can throw in a thread pool.

This code gets me the correct result. But as it creates many wrapper classes (the EvalOps), the execution is slower. I did a benchmark of the following two tasks:

uint32_t __attribute__ ((noinline)) hash1(uint32_t input) {
    return input * 0x12345768;
}

uint32_t __attribute__ ((noinline)) hash2(uint32_t input) {
    return ((input * 0x2FDF1234) << 12) * 0x23429459;
}

uint32_t sum = 0;

void summer(uint32_t input) {
    sum += input;
}

BENCHMARK(StreamBenchmark, Serial)(State& state) {
    for(auto _:state) {
        for(int i = 0 ; i < 10000; ++i)
            sum += hash2(hash1(i));
        }
    }
}

BENCHMARK(StreamBenchmark, Wrapper)(State& state) {
    for(auto _:state) {
        IntStream stream(0, 10000);
        stream.map(hash1).map(hash2).foreach(summer);
    }
}

From the benchmark result, I see for each element, only 1ns is spent on actual computation and 40ns overhead is spent on the Stream and EvalOp. I am looking for some suggestions to make a more efficient design. Thank you very much!


texts: Replacing specific words in text with words from another list python

texts:
I've written a short script to use Reddit's PRAW API to search a subreddit for articles and if certain word/words are in the article title, replace those words with a random word taken from a list of other words.  I'm putting it in a dictionary because I'm going to write the url & article title to a database before tweeting it out so I don't send out duplicates.  I'm mostly curious if there's a better way to write the replacer() function.

For example: "World leaders brace for Trump's speech" --> "World leaders brace for spongebob's speech"

nicknames in matches() is a list of nicknames from another file.

def replacer(title, words, randoms):
    '''title is string you want to split.
       words is a list of words you are looking to match.
       randoms is a list of random words to replace with words.'''

    new_title = []
    for word in title.split(' '):
        if word in words:
            word = random.choice(randoms)
        new_title.append(word)

    return ' '.join(new_title)

def matches(login, subreddit):

    page = login.subreddit(subreddit)

    # used for the any statement
    combined_names = ["Name's", "Mister Name's", "Firstname Lastname", "Firstname", "Lastname", "Mister Firstname", "Mister Lastname"]

    # target words to replace
    names_apost = ["Name's", "Mister Name's"]
    names_no_apost = ["Firstname Lastname", "Firstname", "Lastname", "Mister Firstname", "Mister Lastname"]

    # for appropriate conjugation
    nicknames_apostrophe = [i + "'s" for i in nicknames]

    post_dict = {}
    top_posts = page.hot(limit=100)
    for post in top_posts:
        title = post.title
    if any(word in title for word in combined_names):
        first_iter = replacer(post.title, names_apost, nicknames_apostrophe)
        second_iter = replacer(first_iter, names_no_apost, nicknames)
        if post.ups > 1000:
            value = post.ups, post.url
            post_dict[second_iter] = value
    return post_dict


texts:
Please review and let me know which version is better. I'm just trying to find any caveats or better ways to accomplish the a version comparison independent from Android and iOS.

Formats accepted: '1.0.0' or '1' formats and an operator, e.g: compareVersion('1', '1.2.0', '>')

export function compareVersion(version1, version2, operator) {
        const formattedV1 = version1.split(".");
        const formattedV2 = version2.split(".");

        let diff = 0;

        if (formattedV1.length !== formattedV2.length) {
            const lengthDiff = formattedV1.length - formattedV2.length;
            for (let index = 0; index < Math.abs(lengthDiff); index += 1) {
                if (lengthDiff > 0) {
                    formattedV2.push("0");
                } else {
                    formattedV1.push("0");
                }
            }
        }

        for (let index = 0; index < formattedV1.length; index += 1) {
            if (diff === 0) {
                const v1 = parseInt(formattedV1[index]);
                const v2 = parseInt(formattedV2[index]);
                if (isNaN(v1) || isNaN(v2)) {
                    throw new Error("Problem comparing versions: not a valid number");
                }
                if (v1 < v2) {
                    diff = -1;
                }
                if (v1 > v2) {
                    diff = 1;
                }
            }
        }

        switch (operator) {
        case "=":
        case "==":
            return diff === 0;
        case ">=":
            return diff >= 0;
        case "<=":
            return diff <= 0;
        case ">":
            return diff > 0;
        case "<":
            return diff < 0;

        default:
            throw new Error("Problem comparing versions");
        }
    }

OR

export function compareVersions(a, b, operator) {
  const aParts = a.split('.');
  const bParts = b.split('.');

  const pairs = [];

  for (let index = 0; index < Math.max(aParts.length, bParts.length); index += 1) {
    pairs.push({
      a: parseInt(aParts[index]),
      b: parseInt(bParts[index]),
    });
  }

  let diff = 0;

  pairs.forEach((pair) => {
    if (diff === 0) {
      if (pair.a > pair.b) {
        diff = 1;
      }
      if (pair.b > pair.a) {
        diff = -1;
      }
      if (!isNaN(pair.a) && isNaN(pair.b)) {
        diff = 1;
      }
      if (isNaN(pair.a) && !isNaN(pair.b)) {
        diff = -1;
      }
    }
  });

  switch (operator) {
    case '=':
    case '==':
      return diff === 0;
    case '>=':
      return diff >= 0;
    case '<=':
      return diff <= 0;
    case '>':
      return diff > 0;
    case '<':
      return diff < 0;

    default:
      throw new Error('Problem comparing versions');
  }
}


texts:
Can someone improve upon this function of mine?  EnumToSTLContainer is supposed to make a copy of any STL container whose elements are from a specified enum list.

#include <iostream>
#include <vector>
#include <set>

enum MyEnum {A, B, C, D, E, FirstMyEnum = A, LastMyEnum = E};

template <typename CONTAINER>
CONTAINER EnumToSTLContainer (typename CONTAINER::value_type first, typename CONTAINER::value_type last) {
    CONTAINER v;
    for (int N = first;  N <= last;  N++)
        v.push_back(static_cast<typename CONTAINER::value_type>(N));  // But only works for STL containers with push_back defined.
    return v;
}

int main() {
    const std::vector<MyEnum> enumVector = EnumToSTLContainer<std::vector<MyEnum>> (FirstMyEnum, LastMyEnum);
    for (MyEnum x : enumVector)
        std::cout << x << ' ';  // 0 1 2 3 4
//  const std::set<MyEnum> enumSet = EnumToSTLContainer<std::set<MyEnum>> (FirstMyEnum, LastMyEnum);  // won't compile
}

This only works for STL containers with push_back() defined, and need to specify first and last element of the enum list. It does not work if enum values are not consecutive.

Perhaps obtaining an initializer_list using variadic templates would work, which can then return the desired STL container?


texts: Measuring the clock rate of an Intel CPU in C++

texts:
I created a short program to directly measure the clock rate of an Intel CPU. It runs, sleeps for a duration specified by the user, and then measures the number of clock cycles and the amount of time that elapsed while it was asleep, then divides the elapsed clock cycles by the elapsed time to get the frequency of the CPU.

Is the below code up to stuff in terms of style and readability?
Is there any reason the strategy used and described below won't produce accurate results?

Any feedback is appreciated! If you wish to test out the code, you can download it with git clone https://github.com/firetotherain/CPUHertz.git

#include <thread>
#include <chrono>
#include <cstdio>

//Uses assembly command to get the current value of the cycle "counter"
uint64_t get_cycles()
{
    unsigned int lo,hi;
    __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
    return ((uint64_t)hi << 32) | lo;
}

//Defines unit of time to measure seconds
typedef std::chrono::duration<double, std::ratio<1,1>> seconds_t;

//In main(int argc, char** argv) this global variable is initialized to argv[0]
const char* program_name;

//Initialized at the start of the program; gets the current time
auto start_time = std::chrono::high_resolution_clock::now();

//Returns the time since the start of the program, measured in seconds
//Has accuracy identical to that of std::chrono::high_resolution_clock
double age()
{
    return seconds_t(std::chrono::high_resolution_clock::now() - start_time).count();
}

//Prints the program usage
void PrintUsage()
{
    printf("Usage:\n");
    printf("%s [measurment duration]\n", program_name);
}
int main(int argc, char** argv)
{
    using namespace std::chrono_literals;
    program_name = argv[0];
    int sleeptime = 100;
    switch(argc) {
    case 1:
        sleeptime = 100;
        break;
    case 2:
        try
        {
            sleeptime = std::stoi(argv[1]);
        }
        catch(...)
        {
            printf("Error: argument was not an integer.");
            PrintUsage();
            return 1;
        }
        break;
    default:
        printf("Error: too many arguments.");
        PrintUsage();
        return 1;
        break;
    }
    uint64_t cycles_start = get_cycles();
    double time_start = age();
    std::this_thread::sleep_for(sleeptime * 1ms);
    uint64_t elapsed_cycles = get_cycles() - cycles_start;
    double elapsed_time = age() - time_start;
    printf("CPU MHz: %.3f\n", elapsed_cycles / elapsed_time / 1000000.0);
}


texts: Best way to get the best performance of a large CSV upload in PHP

texts:
I am trying to upload a CSV file to a database which has around 800,000 rows. I am able to do this on my server with the following specs:

RAM: 4GB
Rows: 800,000
Time taken: 305 seconds
Usage: 15% RAM
Database: Postgres (Amazon RDS)

My upload code looks like this:

   public function handle()
   {
      set_time_limit (0);
      // try {

            $time_start = microtime(true);
            $counter=0;
            $data = array();
            $file = flag_tables::where('imported','=','0')
                     ->orderBy('created_at', 'DESC')
                     ->first();
              $file_path = Config::get('filesystems.disks.local.root') . '/exceluploads/' .$file->file_name;

              $header = null;
              $totalRows=0;
              $in = fopen($file_path,"r");
              if($in){
                  while(!feof($in)){
                        $content = fgets($in);
                    if($content)    $totalRows++;
                  }
              }

              $totalRows = --$totalRows;
              $file->total_rows = $totalRows;
              $file->save();
              fclose($in);
              $in = fopen($file_path,"r");
              $c=0;

              while ($row = fgetcsv($in)){
                  if ($header === null) { $header = $row;continue;}
                  $data[] = array('data'=> json_encode(array_combine($header, $row)),'created_at'=>date('Y-m-d H:i:s'),'updated_at'=> date('Y-m-d H:i:s'));
                  $counter++;

                   if(count($data) == 1400)
                   {
                      DB::table('price_results')->insert($data);
                      $file = $file->fresh(); //reload from the database
                      $file->rows_imported = (int) $file->rows_imported + $counter;
                      $counter= 0;
                      $file->save();
                      $data = array();
                    }
                  }

              $time_end = microtime(true);
              $time = $time_end - $time_start;
              DB::table('price_results')->insert($data);
              $file = $file->fresh(); //reload from the database
              $file->rows_imported = (int) $file->rows_imported + $counter;
              $file->imported =1;
              $file->total_execution_time=$time;
              $file->save();
              fclose($in);
      // }
      //   catch(\Exception $e)
      //   {
      //     dd($e->getMessage());
      //   }
   }

I would like to make this upload time better, if possible.


texts: CSS3 Flexbox: Creating my own "framework"

texts:
Currently I have an application that is relying on Bootstrap's Grid layout.  I originally chose it because it was easy to learn and looked good.  However, it didn't handle nesting as well as I thought it would.  After investigating and finding out that it used float for all the grid classes, I don't like it as much.

I wanted to replace it, but didn't want to add another CSS framework to my web application (I still think that Bootstrap is great for other things, and wanted to keep the framework).  So, I decided to write my own mini-framework using CSS3's flexbox properties.  I know there is at least one existing framework called Flexboxgrid, but I don't want to bloat my application.  It's also nice and a lot more satisfying to learn and write a set of classes yourself, as long as it doesn't take too much time.  I've read some helpful flexbox articles from Team Treehouse and Chris Wright's blog.

Then, I wanted to apply my knowledge to get a basic understanding of how flexbox works.  This turned out to be more difficult than I imagined... although I achieved a somewhat desirable layout.  The CSS feels "hacky" to me, especially how I set the border and margin on each .flex-row.  This jsfiddle is nowhere near a complete version, but rather the first stepping stone.  Before I go any further, I want to get some feedback on what I can improve.  Here's an example of some of the code:

.flex-row ugliness

.flex-row {
    display: flex;
    display: -webkit-flex;
    flex-wrap: wrap;
    border: 1px solid gray;
    margin: -1px;
}

.flex-row is intended to replace Bootstrap's .row.

EDIT: I should also note that I am using AngularJS, and almost all of the information to be displayed will be generated with ng-repeat.


texts: Header and navbar animations on a website

texts:
I was wondering if there was a way to rewrite this to be a bit more clean. It seems a bit odd to have a mouseenter and a mouseleave for this. Surely there's a toggle of some kind?

$(document).ready(function() {

// Post header animation
$('h1.post').mouseenter(function() {
    $(this).animate({ paddingLeft: 10 }, 300);
});
$('h1.post').mouseleave(function() {
    $(this).animate({ paddingLeft: 0 }, 300);
});

// Navbar hover animation
$("h1#button").mouseenter(function() {
    $(this).animate({opacity: 0.60}, 100);
});
$("h1#button").mouseleave(function() {
    $(this).animate({opacity: 1}, 100);
});

// Contact div toggle
$("h1.icons").click(function() {
    $(".icon-wrapper").slideToggle("slow");
});
});

My website is http://gamer-simms.herokuapp.com if you want to look.


texts:
I want to order columns of a dataframe using a substring of the column name only. Suppose my columns are named

df <- data.frame("x_b"=5,
                 "y_b"=2,
                 "x_a"=6,
                 "y_a"=3,
                 "y_c"=1,
                 "x_c"=4)

and I want to order them using a first-order and a second-order key. The first-order key would be first_order <- c("y", "x") and the second-order key be like second_order <- c("c", "b", "a").

I try kind of ugly code where I build my desired order in a loop:

order <- list()
for (first_key in first_order){
  for (second_key in second_order){
    order <- cbind(order, paste(first_key, second_key, sep="_"))
  }
}

The result is as I want:

> df[as.character(order)]
  y_c y_b y_a x_c x_b x_a
1   1   2   3   4   5   6

But I wouldn't say that my code is very easy, nor quick. Do you have a better suggestion?


texts: Pick out excel cells from a long horizontal list based on an adjacent numerical value

texts:
I've already written this macro that does exactly what I want it to do. However, it's quite large, and I may wish to expand on it in future. Basically, the purpose is to copy and paste items from a horizontal list (where RNG is equal to the number of items there), and take one cell from each. Any suggestions in cutting this down? It feels as if there should be a way, since so little changes from line to line.

Sub Test()

Dim Rng As Range
Dim i As Long
i = 3
While i <= 300
    Set Rng = Range("J" & i)
    If Rng = 0 Then
        i = i + 1
    ElseIf Rng = "" Then
        i = i + 1
    ElseIf Rng = 1 Then
        i = i + 1
    ElseIf Rng = 2 Then
        Rng.Offset(, -9).Resize(, 125).Copy
        Rng.Offset(, -9).Insert Shift:=xlDown
        i = i + 2
    ElseIf Rng = 3 Then
        Rng.Offset(, -9).Resize(, 125).Copy
        Rng.Offset(, -9).Insert Shift:=xlDown
        Rng.Offset(, -9).Resize(, 125).Copy
        Rng.Offset(, -9).Insert Shift:=xlDown
        i = i + 3
    ElseIf Rng = 4 Then
        Rng.Offset(, -9).Resize(, 125).Copy
        Rng.Offset(, -9).Insert Shift:=xlDown
        Rng.Offset(, -9).Resize(, 125).Copy
        Rng.Offset(, -9).Insert Shift:=xlDown
        Rng.Offset(, -9).Resize(, 125).Copy
        Rng.Offset(, -9).Insert Shift:=xlDown
        i = i + 4
    Else
        Stop
    End If
Wend


texts: Analyse an Nginx access log with awk and produce a report

texts:
I'm looking for your opinions on anything that I am doing wrong in the application below, such as best practices, glaringly horrible errors or even just your own personal opinion.

Task: Grab an Nginx access log, ask it some questions and dump responses out to a templated report.

I have removed all comments from this post to keep the reading to a minimum.  You can see the full version at GitHub.

#!/usr/bin/python
import datetime
from os import remove
from subprocess import Popen
from subprocess import PIPE
from subprocess import check_output
from string import Template

class NginxReporter():

    location = None
    template = 'templates/default.html'
    html = None

    def __init__(self, location=None, template=None, execute=False):
        self.location = location

        if template:
            self.template = template

        if execute:
            self.parse()
            self.output()
            self.delete()

    def scpdownload(self, remotelocation=None):
        if remotelocation:
            check_output(['scp', remotelocation, self.location])

    def delete(self):
        remove(self.location)

    def parse(self):
        html = {}

        codes = Popen("awk '{print $9}' " + self.location +
                       " | sort | uniq -c | sort -r", shell=True, stdout=PIPE)

        html['codes'] = self.build(codes)

        statuses = [206, 301, 302, 400, 404, 408, 499, 500]

        for status in statuses:
            statuslist = Popen("awk '($9 ~ /" + str(status) + "/)' "
                               + self.location + " | awk '{print $7}' " +
                               " | sort | uniq -c | sort -r",
                               shell=True, stdout=PIPE)

            html["http_"+str(status)+"_code"] = self.build(statuslist)

        html['generated'] = datetime.datetime.today().strftime('%Y-%m-%d %H:%M')

        self.html = html

    def build(self, output):
        block = ""

        while True:
            out = output.stdout.read()

            if out == '' and output.poll() != None:
                break
            if out != '':
                block = out

        return block

    def output(self):
        file = open(self.template)
        block = Template(file.read())
        print block.substitute(self.html)

Usage

report = NginxReporter('access.log')
""" report.scpdownload("sshuser@server.com:/path/to/nginx/access.log") """
report.parse()
report.output()


texts: Simulate the "cd" command of a file system

texts:
Write a function that provides change directory (cd) function for an
  abstract file system.

  Notes:

  Root path is '/'.
  Path separator is '/'.
  Parent directory is addressable as "..".
  Directory names consist only of English alphabet letters (A-Z and a-z).

  For example, new Path("/a/b/c/d").cd("../x").getPath() should return
  /a/b/c/x.

  Note: The evaluation environment uses '\' as the path separator.

It works, but is there a better way to do this?

public class Path {
    private String path;

    public Path(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    public Path cd(String newPath) {

        //1step consume newPath
        //newPath to list
        //take 1 char, head pull
        //locate it with this.path,
        //          case / ../ ./
        //          this.path end poll
        //return changed path and newPath

        //recursive cd again

        if( "".equals(this.path)||"".equals(newPath)||!this.path.startsWith("/"))
            return this;
        else if(newPath.startsWith("/")) {
            this.path = "/";
            return this.cd(newPath.length()>1?newPath.substring(1):"");

        }
        else{
            if(newPath.startsWith("..."))
                return this;
            else if(newPath.startsWith("../")) {
                this.cdup1();
                return this.cd(newPath.length()>3?newPath.substring(3):"");
            }else if(newPath.startsWith("./")) {
                return this.cd(newPath.length()>2?newPath.substring(2):"");
            }
            else if(newPath.startsWith("..")) {
                this.cdup1();
                return this.cd(newPath.length()>2?newPath.substring(2):"");
            }else if(newPath.startsWith(".")) {
                return this.cd(newPath.length()>1?newPath.substring(1):"");
            }
            else {

                String [] strarr = newPath.split("/");
                if(this.path.endsWith("/"))
                    this.path = this.path+strarr[0];
                else
                    this.path = this.path+"/"+strarr[0];

                String newPath2 ="";
                for (int i = 1; i < strarr.length; i++) {
                    String s = strarr[i];
                    newPath2=newPath2+s+"/";
                }
                return this.cd(newPath2);

            }

        }

    }

    private void cdup1(){
        if("/".equals(this.path)) return ;

        String [] patharr=this.path.split("/");
        System.out.println(patharr.length);
        StringBuffer s = new StringBuffer("/");

        for (int i = 0; i < patharr.length-1; i++) {
            if(!"".equals(patharr[i]))
                s.append( patharr[i]).append("/");
        }

        String endpath = s.toString();

        if(!"/".endsWith(endpath)&&endpath.endsWith("/")) endpath=endpath.substring(0,endpath.length()-1);

        this.path = endpath;
        System.out.println(this.path);

        return;
    }

    public static void main(String[] args) {
        Path path = new Path("/a/b/c/d");
        System.out.println(path.cd("../../../x").getPath());
    }
}


texts:
Project Euler Problem 2 asks for the sum of all even Fibonacci numbers below 4 million.

My first attempt at this problem using functional programming with F#. I would've liked to use some kind of take-while function to keep generating Fibonacci numbers until they fulfilled certain conditions, but alas I could not find such a thing in F#.

open System

let rec fib n = match n with
                | 0 | 1 | 2 -> n
                | _ -> fib (n - 1) + fib (n - 2)

let rec nOfFibTermsUpUntil x y = if fib (y + 1) < x then nOfFibTermsUpUntil x (y + 1) else y

[for n in 0..nOfFibTermsUpUntil 4000000 0 -> fib n]
|> List.filter (fun x -> x % 2 = 0)
|> List.sum
|> printf "The sum of Fibonacci terms up until 4,000,000 is: %d"
Console.ReadKey () |> ignore


texts: Efficient implemetation of AlertDialog callback in Android

texts:
One day I realised that my Android project utilizes AlertDialogs here and there in very ineffective way. The heavily duplicated portion of code looked like this (actually, copied and pasted from some documentation):

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to close application?")
  .setPositiveButton("Yes", new DialogInterface.OnClickListener()
  {
    public void onClick(DialogInterface dialog, int id)
    {
      dialog.dismiss();
      System.runFinalizersOnExit(true);
      System.exit(0);
    }
  })
  .setNegativeButton("No", new DialogInterface.OnClickListener()
  {
    public void onClick(DialogInterface dialog, int id)
    {
      dialog.dismiss();
    }
  });
builder.create().show();

Apparently, this code fragment should be transformed into a function accepting 2 parameters: a question to ask, and an action to perform.

After several iterations of code optimizations (each one of which seemed as the last and most minimal one), I came to the following class:

public abstract class DialogCallback implements DialogInterface.OnClickListener,Runnable
{
  DialogCallback(Context c, String q)
  {
    AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setMessage(q)
      .setPositiveButton("Yes", this)
      .setNegativeButton("No", this);
    builder.create().show();
  }

  public void onClick(DialogInterface dialog, int which)
  {
    dialog.dismiss();
    if(which == DialogInterface.BUTTON_POSITIVE) run();
  }
}

with the following usage:

new DialogCallback(context, "are you sure?")
{
  public void run()
  {
    // some action
  }
};

Is there a way of further optimization? What other methods for effective dialog callbacks can be used?


texts: Inserting a record into a MySQL table using PDO

texts:
Already many days I'm documenting about the SQL Injection. I was wondering if the code I wrote is vulnerable in some of its parts.

<?php
if($_POST['nameone'] AND $_POST['nametwo'])
{
   $conn = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8", 'dbuser', 'dbpass');
   mysql_query('SET NAMES utf8');
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
   $stmt = $conn->prepare("INSERT INTO `test_PDO`(`nameone`, `nametwo`) VALUES (:nomeone,:nometwo)");
   $nameone = $_POST['nameone'];
   $nametwo = $_POST['nametwo'];
   $stmt->bindParam(':nomeone', $nameone);
   $stmt->bindParam(':nometwo', $nametwo);
   $stmt->execute();
   echo "New records created successfully $nameone -- $nametwo";
   $conn = null;
}
?>

<form method="POST">
  Name one: <input type="text" name="nameone">

  Name two: <input type="text" name="nametwo">

  <input type="submit">
</form>

It would be great if somebody could review and confirm that this code is indeed not vulnerable to SQL injection. Or if it is vulnerable, kindly point out where, and how to make it better.


texts: Compressing string in Scala, how to do this immutably?

texts:
I have a string "abbbbccdddd" and the function should return "a1b4c2d4".

This is what I have written in Scala.

Iterative-version

def compress(str: String) = {
  val chars = List(str).flatten.map(_.toString) ++ List(null)
  var result: String = ""

  var lookBack: String = chars.head
  var occurance: Int = 0

  chars.foreach { c =>
    if (c != lookBack) {
      result = result + lookBack.toString + occurance
      occurance = 0
    }

    occurance = occurance + 1
    lookBack = c
  }

  result
}

Recursive-version

def compress(str: String): String = {
  def compressHandler(str: String, lookBack: String, occurance: Int, result: String): String = {
    if(str.isEmpty) {
      result
    } else if(str.head.toString == lookBack) {
      compressHandler(str.drop(1), str.head.toString, occurance + 1, result)
    } else {
      compressHandler(str, str.head.toString, 0, result + lookBack + occurance)
    }
  }

  compressHandler(str + "0", str.head.toString, 0, "")
}

Scala — being a functional language should have much better solutions!

How to improve second (by somehow using map/reduce/fold) and how to do the first following concept of immutability (purely functional)?


texts: Matching any certain selection of inputs

texts:
I have the following RegEx which matches any of a selection of inputs (see the list below).

While it works fine, I'm wondering if there is a better way of writing it, as it looks a little dirty.  I've been using various RegEx builders but couldn't come up with a shorter version, so any tips would be appreciated.

-[0-9]+px$|^[0-9]+px$|^[0-9]+em$|^-[0-9]+em$|^[0-9]+\%$|^auto$|^0$

Here is the list of valid entries (where 10 can be any integer):

10px
-10px
10em
-10em
10%
auto
0


texts: Reading and Converting XML File to Array

texts:
I'm using WordPress ( PHP Based Platform ) and I'm trying to read an external XML File, convert it into a usable array, then compare two arrays - one from the xml file and another from an options database. I've coded it so that it does work but it just looks messy. I'm not sure if it's my naming conventions or how I'm formatting it but to me it looks lengthy and messy. I'm open to any / all suggestions on how to clean this up or make this function better.

The following function checks an XML file of private plugins then cross references it with the list of active plugins to make sure it's there.

/**
 * Get a list of Private Plugins from XML File
 * @return bool|array $plugins( 'name', 'version', 'path', 'slug', 'updated' )
 */
function getPrivate_plugins() {
    $plugins             = false;
    $active_plugins      = get_option( 'active_plugins' );
    $private_remote_path = 'http://domain.com/plugins.xml';
    $ci                  = curl_init( $private_remote_path );
    curl_setopt( $ci, CURLOPT_RETURNTRANSFER, 1 );
    $plugin_list         = curl_exec( $ci );
    curl_close( $ci );

    if( ! empty( $plugin_list ) ) {
        $plugin_obj   = simplexml_load_string( $plugin_list );
        $plugin_json  = json_encode( $plugin_obj );
        $plugin_array = json_decode( $plugin_json, TRUE );
        $plugin_array = ( ! empty( $plugin_array ) && isset( $plugin_array['plugin'] ) ) ? $plugin_array['plugin'] : '';

        if( ! empty( $plugin_array) ) {
            $plugin_array = array_map(
                function( $arr ) {
                    return ( isset( $arr['path'] ) ) ? $arr['path'] : '';
                },
                $plugin_array
            );
            $plugins = array_intersect( array_filter( $plugin_array ), $active_plugins );
            $plugins = ( ! empty( $plugins ) ) ? $plugins : false;
        }
    }

    return $plugins;
}

The only WordPress based function is get_option() which return to $active_plugins an array of paths [0] => 'plugin-directory/plugin-file.php'

The XML File it's reading is simple:

<?xml version="1.0" encoding="UTF-8"?>
<plugins>
    <plugin>
        <name>Private Plugin A</name>
        <slug>private-plugin-a</slug>
        <path>private-plugin-a/private-plugin-a.php</path>
        <version>1.1</version>
        <updated>Feb 23, 2015 03:26pm</updated>
    </plugin>
    <plugin>
        <name>Private Plugin B</name>
        <slug>private-plugin-b</slug>
        <path>private-plugin-b/private-plugin-b.php</path>
        <version>1.2</version>
        <updated>Feb 24, 2015 12:26pm</updated>
    </plugin>
</plugins>


texts:
I have an mail object that returns its headers as an Enumerator of Header objects, which have two methods, getName and getValue. I need to convert that to a nice Clojure map so I wrote this short function:

(defn extract-headers [message]
  (reduce (fn [hs h] (conj hs {(.getName h) (.getValue h)}))
          {}
          (enumeration-seq (.getAllHeaders message))))

Anything to change or improve here?


texts: Anti XSS code encapsulated inside model class, does it belong there?

texts:
I had some XSS protection code I wanted to add into my Web API/MVC application, the model that was used to bind was EditLocationViewModel as below.
My initial plan was to add safeName = AntiXssEncoder.HtmlEncode(locationName, false) into the controller but that would leave the controller littered with AntiXssEncoder code. I figured it could be encapsulated better within the model class, see UpdateLocationViewModel.

I have a small voice saying to me that the XSS code is more than just validation so perhaps should not be on the model class but in fact back in the controller.

Which would be the better approach?
Any other changes that would be recommended?

Before changes...

using System.ComponentModel.DataAnnotations;
namespace SomeNameSpace
{
    public class EditLocationViewModel
    {
        public int LocationId { get; set; }
        [Required(ErrorMessage = "Please enter a Location name.")]
        [MaxLength(50, ErrorMessage = "Location name has exceeded the maximum length of 50 characters.")]
        public string NewLocationName { get; set; }
        public string NewAddress { get; set; }
        public string NewPhoneNumber { get; set; }
        public string NewFaxNumber { get; set; }
    }
}

After changes...

using System.ComponentModel.DataAnnotations;
using System.Web.Security.AntiXss;

namespace SomeNameSpace
{
    public class UpdateLocationViewModel
    {
        private string locationName;
        private string address;
        private string phoneNumber;
        private string fax;

        public int LocationId { get; set; }
        [Required(ErrorMessage = "Please enter a Location name.")]
        [MaxLength(50, ErrorMessage = "Location name has exceeded the maximum length of 50 characters.")]
        public string LocationName
        {
            get { return AntiXssEncoder.HtmlEncode(locationName, false); }
            set { locationName = value.Trim(); }
        }

        public string Address
        {
            get { return AntiXssEncoder.HtmlEncode(address, false); }
            set { address = value?.Trim(); }
        }
        public string PhoneNumber
        {
            get { return AntiXssEncoder.HtmlEncode(phoneNumber, false); }
            set { phoneNumber = value?.Trim(); }
        }
        public string FaxNumber
        {
            get { return AntiXssEncoder.HtmlEncode(fax, false); }
            set { fax = value?.Trim(); }
        }
    }
}


texts:
This is my React component for looping a component i.e. I don't want to use MAP or FOREACH in React Component's HTML.

import React from 'react';

/**
 * @param {items} from props
 * @description -> Works with array of items and render only one children object inside it, ith data object will be available in children component props.
 */

const RFor = (props) => {
    const { items } = props || [];
    return items.map((data, index) =>
{React.cloneElement(props.children, data)}
)
}

export default RFor;

And this is how I use to iterate my component.

<RFor items={TEMP_DATA_ARRAY}>
              <Item />
            </RFor>

What this will do is generate <Item /> till TEMP_DATA_ARRAY and each object is going to be available with data property inside <Item />.
I want to optimize it and this is the best approach I can come up with.


texts: Indeterminate progress bar with Raspberry Pi

texts:
I am writing program for Raspberry Pi that will show indeterminate progress while user waiting. The program will start automatically and will be killed by another shell script.

Here is what I have at the moment. It works, but I feel that it is not perfect. I will be changing this code frequently after users will give their feedback.

#include <wiringPi.h>
#include <stdio.h>

#define PINS_NUMBER 8

void switchPin(int pin, int status, int timeout) {
  digitalWrite(pin, status);
  delay(timeout);
}

void switchLine(int pins[], int status) {
  int i;
  for (i = 0; i < PINS_NUMBER; i++) {
    switchPin(pins[i], status, 200);
  }
}

int main(void){
  wiringPiSetup();

  int leds[PINS_NUMBER] = {0,1,2,3,4,5,6,7};

  int i;
  for (i = 0; i < PINS_NUMBER; i++) {
    pinMode(leds[i], OUTPUT);
  }

  while(1) {
    switchLine(leds, LOW);
    switchLine(leds, HIGH);
  }
  return 0;
}


texts: Deitel Java exercise 6.30: Number-guessing game

texts:
I missed points for putting implementation in the driver class, rather than having the driver class only make call methods in other classes. I'm not sure how to move the implementation outside of the main class. Suggestions are welcome!

/*
*Deitel Chapter 6 Exercise 6.30
*/
package guess;

import java.util.Scanner;

/**
*Driver class for number guessing game
*/
public class GuessDriver {

/**
 *
 * @param args
 */
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    /*
     *instantiate guess class
     */
    Guess Guess = new Guess();

    /*
    *loops program until user guesses correct number
    */
    while (Guess.getGuess() != Guess.secretNumber){
    /*
    *takes input from user
    n*/
    System.out.println("Enter a number from 1 to 1000: ");
    int setGuess = input.nextInt();
    Guess.setGuess(setGuess);

   /*
    *nested if-else statements compares guess against secret number
    */
    if(Guess.secretNumber < Guess.guess){
        System.out.println("too high");
    } else if (Guess.secretNumber > Guess.guess){
        System.out.println("too low");
     } else {
        System.out.println("Congratulations, you win!");
     }
    }
}
}

/*
*Deitel Chapter 6 Exercise 6.30
*/
package guess;
import java.util.Random;

/**
* Takes in and stores an integer, sets value for random number
*/
public class Guess {

/**
 *instance variable
 */
public int guess;

/**
 *instance variable
 */
public int secretNumber = (int) (Math.random() * 999 + 1);

/**
 *return secret number
 * @return
 */
public int getSecretNumber() {
    return secretNumber;
}

/**
 *return guess
 * @return
 */
public int getGuess() {
    return guess;
}

/**
 *set guess
 * @param guess
 */
public void setGuess(int guess) {
    this.guess = guess;
}

}


texts: Replacing an application service class with multiple command handlers

texts:
I have a Controller which uses an application service to accomplish its tasks. The service class is starting to grow big and developing multiple dependencies. So I am thinking of replacing the single big service class with multiple command handlers, each handling a single responsibility. This is how the old and the new code will look like (simplified):

Old Code

@Component
@Path("/app/jobs")
public class JobController {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<JobDto> getJobs() throws JobException {
         return jobService.getJobs();
    }

    @PUT
    @Path("{job_id}/assigned_to/{user_id}")
    public Response assignTo(
            @PathParam("job_id") @NotNull String jobId,
            @PathParam("user_id") @NotNull String userId
            ) throws JobException {

        jobService.assignJobTo(jobId, userId);
        return Response.status(Response.Status.CREATED).build();
    }
    ...
}

New Code

@Path("/app/jobs")
public class JobController {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<JobDto> getJobs() throws JobException {
         return new GetJobListCommandHandler(
                new GetJobListCommand()
        ).handle();
    }

    @PUT
    @Path("{job_id}/assigned_to/{user_id}")
    public Response assignTo(
            @PathParam("job_id") @NotNull String jobId,
            @PathParam("user_id") @NotNull String userId
            ) throws JobException {

        new AssignJobCommandHandler(
                new AssignJobCommand(jobId, userId)
        ).handle();
        return Response.status(Response.Status.CREATED).build();
    }
    ...
}

I am basically following this tutorial in using command handlers. This patterns isolates each responsibility into one class which is great. But now, since my controller methods create the command handler objects, the handlers have become difficult to mock in unit tests. How do I write unit tests for the controller? Earlier the controller class had just a mocked version of the service object. One option could be to break the controller to service one uri (GetJobsController, AssignJobController, etc). But I don't want to do that. I like seeing the hierarchy of resources together and the path annotations work well like this. Is this the right way of going about this? What are the best practices or this approach and how do I write my unit test?

My application is a Spring+Jersey application.


texts: Project Euler #4 (largest palindrome product) in Swift

texts:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit numbers.

What I've so far learned about Swift is that while the Playground is very cool for tinkering around, it definitely does not like big loops.  So this time, I coded parts in the playground, but moved it over to an actual executable project to run the final code.

I'm interested in knowing any Swift tricks I missed.  I did implement a new trick I learned in this solution, the stride feature.

import Foundation

func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed for \(title): \(timeElapsed) s")
}

extension Int {
    func isPalindrome() -> Bool {
        return self == self.reversed()
    }

    func reversed() -> Int {
        var original: Int = self
        var reversed: Int = 0

        while original > 0 {
            reversed *= 10
            reversed += original % 10
            original /= 10
        }

        return reversed
    }
}

func largestPalindrome() {
    var left: Int = 999
    var right: Int = 999

    var largestPalindrome: Int = 0

    for left in stride(from: 999, through: 100, by: -1) {
        for right in stride(from: left, through: 100, by: -1) {
            let product: Int = left * right
            if product > largestPalindrome && product.isPalindrome() {
                largestPalindrome = product
            }
        }
    }

    println(String(largestPalindrome))
}

printTimeElapsedWhenRunningCode("Largest Palindrome", largestPalindrome)

The printTimeElapsedWhenRunningCode function is borrowed from Brad Larson's answer here, and on my computer, it says the code is running in about 0.27 to 0.28 seconds.