texts: Writing an MVC project for the first time - how close am I?

texts:
I've recently started programming (learning Ruby) and wrote a small game. Now I've started reading about MVC and am trying to refracture my code to follow that architecture. The only classes with big changes so far are the intended controller and view (which is completely temporary.

# This file will handle the Demigod class, which is the player controlled class
#
# =============================================================================

require_relative 'UiHandler'
require_relative 'GameData'
require_relative 'World'

class Demigod
  attr_reader :resources
  @world

  # Starts a new game - each demigod has one world to rule
  # accepts different starting resources as a parameter
  def initialize (world, resources = GameData::STARTING_RESOURCES)
    @world = world
    @resources = resources
  end

  # Handles a turn, main function of the game
  def turn

    # calculates new amount of resources using the production function
    # world.production accepts a resources hash and returns a newly
    # calculated resource hash based on production
    @resources = @world.production(@resources)
    p @resources

    #do_event # ========= TODO ========= #

    # part 2 of every turn
    UiHandler.print_world(@world)
    UiHandler.print_turn_message

    # Asks the user for a tile to do his action on
    decision = UiHandler.get_decision()

    until (@world.valid?(decision) || decision == '')
      UiHandler.print_error(UiHandler::NO_TILE)
      UiHandler.print_turn_message
      decision = UiHandler.get_decision()
    end

    unless decision == ''
      tile = @world.get_tile decision # returns the tile at decision

      # checks for legality of move on tiles using tile.accepts? and tile.check_cost
      until tile.accepts?(decision)
        break if decision == ''
        UiHandler.print_tile_options(tile)
        decision = UiHandler.get_decision()
        if (!tile.accepts?(decision))
          UiHandler.print_error(UiHandler::INVALID)
        elsif (!tile.check_cost(decision, @resources))
          decision = nil
          UiHandler.print_error(UiHandler::RESOURCES)
        end
      end

      if decision != ''
        price = GameData.get_price(decision)
        @resources = reduce(price)
        @world.advance(tile, decision)
      end
    end

    # Clears the screen
    UiHandler.clear_messages()
  end

private

  # calls an new event         # === TODO === #
  def do_event
  end

  # Reduces resources TOBEMOVED to world
  def reduce(amount)
    amount.each do |name, value|
      @resources[name] -= value
    end
    @resources
  end

end

Stuff I realized while writing this question:

resources really shouldn't be here, though I'm not sure if they deserve their own class or should just be in the world (the main model).
I think that the loop dealing with incorrect input should be part of the view, since it interacts directly with the user for input, but I'm not sure how to do it.

I would appreciate a review of how the entire code fits MVC, but I don't expect it.


texts:
I am trying to write my own implementation of indexOf for learning purposes. I have an implementation of as follows. I'm sure a more efficient and shorter implementation exists.

function _indexOf(needle, haystack) {

    var n = needle.split("");
    var h = haystack.split("");

    var n_len = n.length;
    var h_len = h.length;

    for (var i = 0; i < h_len; i++) {

        var j = 0;
        var flag = false;

        while (h[i] == n[j] || flag) {

            if (flag)
                j = 0;

            flag = false;

            i++;
            j++;

            if (h[i] == n[0])
                flag = true;

            if (j >= n_len)
                return i - n_len;

        }

    }

    return -1;

}

Here's a test: assert(_indexOf("ced","ccceccecedeeced")==7) // true


texts: Credit card validation with reversed array

texts:
I want a review of this code.

<?php
  $array = $_POST['array'];  //array holding numbers
  $array = array_reverse($array);          // reversing the array
  echo "
 Credit card Before :- ";
  for($i=0;$i<sizeof($array);$i++)
    echo $array[$i];
  echo "
";
  echo "
 Credit card after applaying mod 10 Algorthim :- ";
  //start converting the number
  for($i=0;$i<sizeof($array);$i++){
    if($i%2==1){
      $array[$i] += $array[$i];
        if($array[$i]> 9 ){

          $array[$i] -= 9;
        }
      }
      //suming all the resulted number
      $total +=$array[$i];
      if($i%2==1)
        echo "".$array[$i]."";
      else
        echo $array[$i];
    }
    echo "
";
      if($total % 10 ==0){
        echo "This creidet card is valid";
      }else{
        echo "This creidet card is not valid";
      }
?>


texts:
I wrote this Caesar cipher and decipher just for the sake of practising OOP (previous answers to my java questions all seem to point to OOPness).

What it is:

  The Caesar cipher is one of the earliest known and simplest ciphers.
  It is a type of substitution cipher in which each letter in the
  plaintext is 'shifted' a certain number of places down the alphabet.

Currently I have a Cipher interface and a CaesarCipher class: I am planning to add a Vigenère Cipher soon.

Code:

Cipher.java

public interface Cipher {

    public String cipher(String text);

    public String decipher(String cipherText);

    public char getCipheredChar(char textChar);

    public char getDecipheredChar(char cipherChar);

}

CaesarCipher.java

public class CaesarCipher implements Cipher {

    private static final int LETTERS = 'Z' - 'A' + 1;

    private int shift;

    public CaesarCipher(int shift) {
        if (shift < -LETTERS || shift > LETTERS) {
            throw new IllegalArgumentException("The value of shift: " + shift
                    + " is invalid.");
        }
        this.shift = shift;
    }

    public int getShift() {
        return shift;
    }

    @Override
    public String cipher(String text) {
        char[] result = text.toCharArray();
        for (int i = 0; i < result.length; i++) {
            result[i] = getCipheredChar(result[i]);
        }
        return new String(result);
    }

    @Override
    public String decipher(String cipherText) {
        this.shift = -shift;
        String result = cipher(cipherText);
        this.shift = -shift;
        return result;
    }

    @Override
    public char getCipheredChar(char textChar) {
        if (textChar > 'A' && textChar < 'z') {
            char result = (char) (textChar + shift);
            char compare = Character.isUpperCase(textChar) ? 'Z' : 'z';
            char lowCompare = Character.isUpperCase(textChar) ? 'A' : 'a';
            return (char) (result > compare ? result - 26
                    : (result < lowCompare ? result + 26 : result));
        }
        return textChar;
    }

    @Override
    public char getDecipheredChar(char cipherChar) {
        this.shift = -shift;
        char result = getCipheredChar(cipherChar);
        this.shift = -shift;
        return result;
    }

}

And tests!

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class TestCipher {

    @Test
    public void testShift1() {
        CaesarCipher cipher = new CaesarCipher(1);
        assertEquals("AaBbCc", cipher.decipher("BbCcDd"));
        assertEquals("Bzdrzq", cipher.decipher("Caesar"));
        assertEquals("Bzdrzq Bhogdq...", cipher.decipher("Caesar Cipher..."));
    }

    @Test
    public void testShift5() {
        CaesarCipher cipher = new CaesarCipher(5);
        assertEquals("AaBbCc", cipher.decipher("FfGgHh"));
        assertEquals("Xvznvm", cipher.decipher("Caesar"));
        assertEquals("Xvznvm Xdkczm...", cipher.decipher("Caesar Cipher..."));
    }

}

Concerns:

Are my tests fine?
Is my OOP structure good?
And as usual, anything else?


texts:
I'm new to bash scripting. I have pieced together a bash script to rsync my website files and databases.

Any guidance on ways I could improve or make my script more secure would be greatly appreciated.

#!/bin/bash

set -e

site_host=(
    "test1@grid.co.uk"
    "test2@grid.co.uk"
)

backup_dest=(
    "/Users/computername/Desktop/rsync/site1.co.uk"
    "/Users/computername/Desktop/rsync/site2.co.uk"
)

now=`date "+%d/%m/%Y %H:%M:%S"`
today=`date +"%d-%m-%Y"`
yesterday=`date -v -1d +"%d-%m-%Y"`
backup_old=`date -v -2d +"%d-%m-%Y"`

log="/Users/computername/Desktop/rsync/rsync.log"

site_count=${#site_host[@]}

db_creds=()
db_creds+=("")
db_creds+=("localhost,user,pass,dbname")

for (( i = 0; i < site_count; i++ )); do

    # Source and destination
    site_source="${site_host[$i]}:~/public_html"
    site_dest="${backup_dest[$i]}/$today/"

    # DB creds
    for val in ${db_creds[$i]}; do
        subset=($(echo $val | tr ',' ' '))
        db_host=${subset[0]}
        db_user=${subset[1]}
        db_pass=${subset[2]}
        db_name=${subset[3]}
    done

    if [ "$db_host" ]; then

        # Set DB seperate directory
        mkdir -p ${backup_dest[$i]}/$today/db

        # Database backup
        ssh -p22 ${site_host[$i]} "mysqldump \
                --host=$db_host \
                --user=$db_user \
                --password=$db_pass \
                --databases $db_name \
                --lock-tables \
                | bzip2" > ${backup_dest[$i]}/$today/db/$today.sql.bz2

        echo "$now - SUCCESS - DB Backup - ${backup_dest[$i]}/$today/db/$today.sql.bz2" >> $log

    fi

    # Remove old backups
    if [ -d "${backup_dest[$i]}/$backup_old" ]; then

        rm -Rf ${backup_dest[$i]}/$backup_old;

        echo "$now - DELETED - Full Backup - ${backup_dest[$i]}/$backup_old" >> $log

    fi

    if  rsync -zavx -e 'ssh -p22' \
            --numeric-ids \
            --delete -r \
            --link-dest=../$yesterday $site_source $site_dest;
    then

        echo "$now - SUCCESS - File Backup - ${backup_dest[$i]}/$today" >> $log

    else

        echo "$now - FAILED - File Backup - ${backup_dest[$i]}/$today" >> $log

    fi

done


texts:
I want to get a recursive list of files in a directory but I want relative paths and not the full paths that Directory.GetDirectories() would return using the AllDirectories search option. This is because I want to move the list of files to another location and perform a custom check on each file. I could try converting each absolute path to a relative path but that's a bit messy, so I decided to create a recursive function that generates relative paths as it goes.

public static string[] GetRelativeFilesRecursive(string path)
{
    IEnumerable<string> GetRelativeFilesRecursive(string basePath, string subFolder)
    {
        IEnumerable<string> getRelativeArray(Func<string, IEnumerable<string>> func)
        {
            return func(Path.Combine(basePath, subFolder)).Select(file => Path.Combine(subFolder, Path.GetFileName(file)));
        }

        IEnumerable<string> files = getRelativeArray(Directory.GetFiles);
        IEnumerable<string> directories = getRelativeArray(Directory.GetDirectories);

        foreach (string directory in directories)
        {
            files = files.Concat(GetRelativeFilesRecursive(basePath, directory));
        }

        return files;
    }

    return GetRelativeFilesRecursive(path, "").ToArray();
}

I'm using nested functions to make it more modular, i.e. I'd rather have one function that I can copy and paste as a whole than have multiple functions that could become separated. I'm using IEnumerable<string> instead of string[] because otherwise I'd have to call ToArray() on every Concat() call and I'm worried that would be bad for performance.

What do you think? Is this a good way to do this?


texts: Form validation evaluation to avoid exploits

texts:
Please advise if the form validation script below is secure enough to avoid most types (all types?) of contact form exploits? I ahve found this script online, added some extra php finctions in hope to make it safer, but not complitely sure if it is good for the purpose.

if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = strip_tags(trim($_POST["message"]));

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        //http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "email_here";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.

    $email_headers = "MIME-Version: 1.0\r\n";
    $email_headers .= "Content-type: text/html; charset=utf-8\r\n";
    $email_headers .= "From: $name <$email>\r\n";
    $email_headers .= "Reply-To: $email\r\n";
    $email_headers .= "Return-Path: $email\r\n";
    $email_headers .= "Organization: Bilingual Counselling\r\n";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        //http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        //http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

}


texts: Better way to deep copy than this? How can I make it generic by `Collection` type?

texts:
Could I make this method for deep copy generic to the Collection type?
That method is so simple and I can't imagine ever needing to change it, so maybe I should just use the "cut / paste" code re-usage design pattern to handle the Collection typing problem?

public class Start {
    public static void main(String[] args) {
        try {
            test();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static<T> List<T> deepCopy(List<T> listOrg) throws Exception {
        List<T> listCopy = new ArrayList<T>();

        for(T item : listOrg) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(item);

            InputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            T itemCopy = (T) ois.readObject();

            listCopy.add(itemCopy);
        }

        return listCopy;
    }

    // --- testing ---
    static void test() throws Exception {
        List<StringBuilder> fooOrg = new ArrayList();
        for(int i = 0; i < 5; i++) {
            fooOrg.add(new StringBuilder("number=" + i));
        }

        List<StringBuilder> fooCopy = deepCopy(fooOrg);
        fooCopy.get(0).append("-->altered?");
        fooCopy.add(new StringBuilder("xtra item"));

        System.out.println("--fooOrg--");
        for(int i = 0; i < fooOrg.size(); i++) {
            System.out.println("#" + i + ":: " + fooOrg.get(i));
        }
        System.out.println();
        System.out.println("---fooCopy---");
        for(int i = 0; i < fooCopy.size(); i++) {
            System.out.println("#" + i + ":: " + fooCopy.get(i));
        }
    }
}


texts:
In light of the recent "SQL frenzy" of sorts in The 2nd Monitor, I decided to take a stab at writing my own SEDE query. Essentially, what it does is find questions that could be answered based on the following parameters.

-- @MinQuestionVotes - The minimum amount of votes on a question.
-- @MaxQuestionAnswers - The maximum amount of answers to a question.
-- @QuestionTags - The tags that should be on the questions.

At the moment, I feel that those parameters are necessary for finding possible questions to answer, but if you feel that one isn't needed, just mention it. Anyways, here's the code, and here's the SEDE query link.

-- User parameters for finding questions. Here is
-- a brief description of what each parameter does.

  -- @MinQuestionVotes - The minimum amount of votes on a question.
  -- @MaxQuestionAnswers - The maximum amount of answers to a question.
  -- @QuestionTags - The tags that should be on the questions.
DECLARE @MinQuestionVotes INT = ##MinQuestionVotes##;
DECLARE @MaxQuestionAnswers INT = ##MaxQuestionAnswers##;
DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTag1##;

-- SELECT the final results. Data is filtered based
-- on the following conditions.

  -- ClosedDate  IS EQUAL TO              null
  -- PostTypeId  IS EQUAL TO              question
  -- Score       GREATER THAN OR EQUAL TO @MinQuestionVotes
  -- AnswerCount LESS THAN OR EQUAL TO    @MaxQuestionAnswers
  -- Tags        CONTAIN                  @QuestionTags
SELECT
    Posts.Id AS [Post Link]
  , OwnerUserId AS [User Link]
  , Posts.Score
  , Posts.Tags
  , Posts.ViewCount
  , Posts.AnswerCount
  FROM Posts
    INNER JOIN PostTags ON Posts.Id = PostTags.PostId
    INNER JOIN Tags ON PostTags.TagId = Tags.Id
  WHERE
    Posts.PostTypeId = 1 AND
    Posts.ClosedDate IS NULL AND
    Posts.Score >= @MinQuestionVotes AND
    Posts.AnswerCount <= @MaxQuestionAnswers AND
    Tags.TagName LIKE CONCAT('%', @QuestionTags, '%');

Finally, here's an example of possible inputs. When entering into the QuestionTags field, you need to surround your tags with single quotes, like this: 'python'.

@MinQuestionVotes:   1
@MaxQuestionAnswers: 0
@QuestionTags:       'python'


texts: Swift - Finding longest binary gap of a given integer

texts:
I recently had the chance to try Codility's algorithm training, and the very first one in the list is finding the longest binary gap of a given integer.
I tried to implement this in Swift, and after finishing it up, I looked at answers all over the internet. My approach is a bit different from what I have seen from others.

What is a Binary Gap?

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

The following is from the console which makes it easy to understand the implementation.
Binary String of "1041" is: "10000010001"
Position of 1's: [0, 6, 10]
The longest binary gap is 5

Basically what I am doing is:

Iterating each binary character, and store the position/index of 1's in an array.
As I am looping through, I find the binary gap between two 1's by subtracting the current index of 1 with previous index of 1, so that it gives me how many 0's are present in between them. I then decrement whatever value I get by 1 ('cause arrays...).
As I am looping through, I keep track of the longest binary gap in a variable.

The complexity is O(n), and I'd like to know if this approach is in any way efficient in terms of memory, or any scope of improvements with this? Thanks for your time.

Code:
public func getLongestBinaryGapFor(_ N : Int) -> Int {

    var arrayOfIndexes:[Int] = []
    let binaryString = String(N, radix:2)

    print("Binary String of \"\(N)\" is: \"\(binaryString)\"")

    var longestBinaryGap:Int = 0
    var index = 0

    for char in binaryString {
        if char == "1" {
            arrayOfIndexes.append(index)
            let currentBinaryGap = getCurrentBinaryGapFor(arrayOfIndexes)
            if arrayOfIndexes.count == 2 {
                longestBinaryGap = currentBinaryGap
            } else if index > 2 {
                if currentBinaryGap > longestBinaryGap {
                    longestBinaryGap = currentBinaryGap
                }
            }
        }
        index += 1
    }

    print("Position of 1's: \(arrayOfIndexes)")
    return longestBinaryGap
}

func getCurrentBinaryGapFor(_ array:[Int]) -> Int {
    var currentBinaryGap = 0
    if array.count >= 2 {
        let currentPosition = array.count - 1
        let previousPosition = currentPosition - 1
        currentBinaryGap = array[currentPosition] - array[previousPosition] - 1
        return currentBinaryGap
    } else {
        return currentBinaryGap
    }
}


texts: Read files from a directory using Promises

texts:
Using javascript functions and the old way of doing things I wrote a piece of code to copy the first file in a directory to a file Test.

console.log("Copy First File");
var fs = require('fs');
fs.readdir(".", function(err, files) {
    if (err) {console.log(err);process.exit(1);}

    fs.exists(files[0], function(exits) {
        fs.readFile(files[0], function(err, data) {
            if (err) {console.log(err);process.exit(1);}

            fs.writeFile('Test', data, function(err) {
                if (err) {console.log(err);process.exit(1);}

                console.log("Data Copied");
            });

        })
    });
});

After reading about Promises (and several failed attempts). I managed to convert the above to use Promise and .then() chaining.

function getAListOfFiles() {
    return new Promise(function(resolve, reject) {
        fs.readdir(".", function(err, files) {
            if (err) {
                reject(err);
            }
            else {
                resolve(files);
            }
        });
    });
}
function checkFirstFileExists(files) {
    return new Promise(function(resolve, reject) {
        fs.exists(files[0], function(exists) {
            if (!exists) {
                reject("No File");
            }
            else {
                resolve(files[0]);
            }
        });
    });
}
function readFileData(file) {
    return new Promise(function(resolve, reject) {
        fs.readFile(file, function(err, data) {
            if (err) {
                reject(err);
            }
            else {
                resolve(data);
            }
        });
    });
}
function writeFileData(data) {
    return new Promise(function(resolve, reject) {
        fs.writeFile('Test', data, function(err) {
            if (err) {
                reject(err);
            }
            else {
                resolve("A-OK");
            }
        });
    });
}

console.log("Copy First File");
var fs = require('fs');

new Promise(function(resolve, reject) {
    resolve(1);
})
.then(getAListOfFiles)
.then(checkFirstFileExists)
.then(readFileData)
.then(writeFileData)
.then(function(comment) {
    console.log("Data Copied " + comment);
})
.catch(function(err) {
    console.log("Error: " + err);
});

I want to know is my use of Promise and chaining idiomatic? What can I do better? It seems much longer than the original and thus slightly harder to read.

Particularly interested if:

new Promise(function(resolve, reject) {
    resolve(1);
})
.then(getAListOfFiles)
.then(...

Is more idiomatic than

getAListOfFiles()
.then(...


texts:
I solved the Nested List Python challenge on HackerRank.com passing all test cases. Although this problem can likely be solved with a short script with clever one-liners, my approach was instead to solve it in a clean, understandable way in functional style.

Here is a summary of the challenge, see link above for full description:

  Print the name(s) of any student(s) having the second lowest grade; if there are multiple students, order their names alphabetically and print each one on a new line.

  The first line contains an integer, \$N\$, the number of students.
  The \$2N\$ subsequent lines describe each student over \$2\$ lines; the first line contains a student's name, and the second line contains their grade.

I haven't used nested lists much until now and I found myself having to search the internet a good bit for parts of the functions (in particular the get_lowest_grade function) and I would like to improve this code as much as possible.

def get_students(num_students: int) -> list:
    """Returns a list of names and grades of N students read from stdin
    where each name and respective grade is separated by a new line."""
    students = []
    for s in range(0, num_students):
        name = input()
        grade = float(input())
        students.append([name, grade])
    return students

def get_lowest_grade(students: list) -> float:
    """Returns the lowest grade from a list of students[name, grade]."""
    lowest_grade_student = min(students, key = lambda x: x[1])
    return lowest_grade_student[1]

def get_lowest_grade_students(students: list) -> list:
    """Returns the students with the lowest grade
    from a list of students[name, grade]."""
    return [s for s in students if s[1] == get_lowest_grade(students)]

def exclude_lowest_grade_students(students: list) -> list:
    """Returns a list of students with the lowest graded students excluded
    from a list of students[name, grade]."""
    return [s for s in students if s[1] != get_lowest_grade(students)]

def get_student_names_sorted_alpha(students: list) -> list:
    """Returns a list of names sorted alphabetically from a list of students[name, grade]"""
    names = [s[0] for s in students]
    return sorted(names)

def main():
    num_students = int(input())
    students = get_students(num_students)
    lowest_excluded = exclude_lowest_grade_students(students)
    second_lowest = get_lowest_grade_students(lowest_excluded)
    for name in get_student_names_sorted_alpha(second_lowest):
        print(name)

if __name__ == '__main__':
    main()


texts: Time complexity of finding a triangle in undirected graph

texts:
Recently I posted the following solution on Stack Overflow and comments made me to rethink about the time complexity of my solution which I am sure is \$O(V+E)\$. Please suggest reasons as to why I am wrong.

import java.util.*;
class Triangle
{
 static ArrayList<LinkedList<Integer>> g;
 static int []visited;
 static int []level;
 static int []parent;
 static Queue<Integer> q=new LinkedList<Integer>();
 public static void create_graph()
 {
     int n,i,k,j;
     Scanner s=new Scanner(System.in);
     System.out.println("enter the value of number of vertices");
     n=s.nextInt();
     visited=new int[n];
     level=new int[n];
     parent=new int[n];
     for(i=0;i<n;++i)
      {visited[i]=0;level[i]=-1;}
     g=new ArrayList<LinkedList<Integer>>();
     for(i=0;i<n;++i)
     {
         g.add(new LinkedList<Integer>());
         System.out.println("enter the number of vertices adjacent to "+ (i)+" and what are they?" );
         k=s.nextInt();
         for(j=1;j<=k;++j)
           g.get(i).add(s.nextInt());
     }
 }
 public static boolean BFS(int so,int l)
 {
        int i;
        visited[so]=1;
        q.add(so);
        level[so]=l;
        while(q.size()!=0)
        {
            i=q.poll();
            for(int e:g.get(i))
             {
                if(visited[e]==0)
                {visited[e]=1;
                 level[e]=level[i]+1;
                 q.add(e);
                 parent[e]=i;
                }
                else if(level[e]==level[i]&&parent[e]==parent[i])
                 return true;
             }
        }
        return false;
 }
 public static void main(String []args)
 {
      int so,i;
      Scanner s=new Scanner(System.in);
      create_graph();
      if(BFS(0,0))
       System.out.println("The graph contains a triangle");
      else  System.out.println("The graph does not contain a triangle");
 }
}


texts:
I want to use the output of the terminal command ldd:

root@kali-vm:~/Desktop# ldd simple
    linux-gate.so.1 =>  (0xb7722000)
    libcurl-gnutls.so.4 => /usr/lib/i386-linux-gnu/libcurl-gnutls.so.4 (0xb769c000)
    libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7539000)
    libidn.so.11 => /usr/lib/i386-linux-gnu/libidn.so.11 (0xb7505000)

And use it to build a dictionary that uses the library name as key and the path to the library as value. I've come up with this little Python snippet:

  # Get List of Librairies in Dictionary
  lddOut = subprocess.check_output(['ldd', fileName])
  libraries = {}
  for line in lddOut.splitlines():
    arr = line.split(" => ")
    library = arr[0].strip('\t')
    try:
      path = arr[1].split(' (0x')[0]
    except:
      pass
    libraries[library] = path

It works fine for my needs but I'm at the point where I don't want my code to just work but want it optimized and well structured/programmed. How can I improve this snippet?

EDIT: Note that I do not want the address (ie 0xbxxxxxx) in my dictionary


texts: Optimization of multiple arrays for filtering

texts:
My app will be running on an iPad with A7. I pass in 3 JSON arrays and right now do some simple filtering, in the future the operation will be much more complicated.  I realize the if statement is slowing down the process, but how can I avoid it?  Is there a way to have this loop on one CPU and run the GUI on the other CPU (assign affinity)?

class func filterPhenotypeByPvalues(
    phenotypeJSON:[String],
    SNPJSON:[String],
    dataJSON:[Float],
    limit:Float) -> ([Float],[String],[String])
  {
    let dbg:Bool = true
    var PvalueFiltered:[Float] = []
    var PhenotypeFiltered:[String] = []
    var SNPFiltered:[String] = []
    //initialize arrays with value
    //[Float](count: data.count, repeatedValue: 0.0)

    var i:Int = 0

    let startTime = CFAbsoluteTimeGetCurrent()

    for (i = 0; i < dataJSON.count; i++) {
      if dataJSON[i] <= limit {
        PvalueFiltered.append(-log10(dataJSON[i]))
        PhenotypeFiltered.append(phenotypeJSON[i])
        SNPFiltered.append(SNPJSON[i])
      }
    }

    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    if(dbg){println("Time elapsed filterPhenotypeByPvalues: \(timeElapsed) s")}

    return (PvalueFiltered,PhenotypeFiltered,SNPFiltered)
  }

A very small sample of the JSON data file:

{
    "data": [
        ["rs6855911","Negative control - flare length",0.0000000002],
        ["rs6855911","BMD of intertrochanter region - gm/cm sq",0.0000000007],
        ["rs1501908","BMD of intertrochanter region - gm/cm sq",0.000000001]
    ]
}

Screenshot of timing profile:


texts:
I'm working on my first real Elixir application, after dabbling for a few years. In my elixir/phoenix application I have to work with data over an external REST API. For my purposes, I can tolerate some staleness in the data so I would like to cache the data from the external system and consult the cache during request handling instead of calling out to their API for every request. So I have this plan to write one module which connects to the API, and then access it through a caching proxy module, which uses Cachex to cache return results for some small amount of time. This is the proxy module:
defmodule MyApp.SlowApiCache do
  alias MyApp.SlowApi
  Code.ensure_compiled(SlowApi)

  for {func, arity} <- SlowApi.__info__(:functions) do
    args = Macro.generate_arguments(arity, __MODULE__)
    def unquote(func)(unquote_splicing(args)) do
      cache_key = {unquote(func), unquote_splicing(args)}
      Cachex.fetch!(:slow_api_cache, cache_key, fn ->
        SlowApi.unquote(func)(unquote_splicing(args))
      end)
    end
  end
end

So it simply generates a matching function for each function in the wrapped module and when the cache misses then it passes it on to the real API module. In my code I write the data pulling functions in the MyApp.SlowApi module but in the rest of the program I access those functions through the MyApp.SlowApiCache functions instead.
Does this make sense or am I shooting myself in the foot somehow? Is this going to have issues in production? Is this kind of thing idiomatic in Elixir?


texts:
Description:

Implement a method to perform basic compression using counts of repeated characters. If the compressed string is not smaller then return the original string.

Code:

class Main {
  public static String compress(String in) {
    if (in == null) {
      throw new IllegalArgumentException("Input string cannot be null");
    }
    if (in.length() <= 1) {
      return in;
    }
    StringBuffer out = new StringBuffer();
    int count = 1;
    for (int i = 1; i < in.length(); i++) {
      char current  = in.charAt(i);
      char previous = in.charAt(i - 1);

      if (current == previous) {
        count++;
      }
      else {
        out.append(previous);
        out.append(count);
        count = 1;
      }
    }
    out.append(in.charAt(in.length() - 1));
    out.append(count);
    return out.toString().length() < in.length() ? out.toString() : in;
  }

  public static void main(String[] args) {
    try {
      System.out.println("Should not happen: " + compress(null));
    } catch (IllegalArgumentException e) {
      System.out.println("Got expected exception for null");
    }
    System.out.println(compress("").equals(""));
    System.out.println(compress("a").equals("a"));
    System.out.println(compress("ab").equals("ab"));
    System.out.println(compress("aa").equals("aa"));
    System.out.println(compress("aabcccccaaa").equals("a2b1c5a3"));
    System.out.println(compress("aabb").equals("aabb"));
  }
}

Question:

The solution was just based on intuition. The last append was by trial and error which I didn't like (I may be more nervous during the real interview). I would like to know if there is any way to avoid such mistakes, possibly using loop invariants?


texts:
Here is a basic itoa function that I've written trying to use recursion:
void itoa(int number, char buffer[])
{
    static int idx=0, size=0;
    if (number == 0) {
        buffer[size] = '\0';
        idx = size = 0; // reset for next call
    }
    else {
        size++, idx++;
        itoa(number/10, buffer);
        buffer[size-idx--] = (number % 10) + '0';
    }
}

How does it look? It is not thread-safe due to the static, but is that an issue for a function such as this? If so, how could I update that? What other ways could I make improvements to it?


texts:
I have a method which compares two lists of strings. If the strings, and only the strings, from listA appear in listB, return true. Else return false.

internal bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds)
    {
        bool result = true;

        if (Ids.Count == XmlIds.Count)
        {
            foreach (var hwId in Ids)
            {
                if(!XmlIds.Contains(hwId))
                {
                    result = false;
                    break;
                }
            }
        }
        else
        {
            result = false;
        }

        return result;
    }

My initial unit test is passing (no edge cases etc. yet), but I was wondering if there is a more compact, but still readable, way to do it.


texts: Dispatch different parameters to different classes with single interface

texts:
I have a set of classes that have similar funcionality but very different interfaces. I created two interface classes with polymorphic methods so I can operate over then. When creating calling the methods, I have to pass a set of parameters, in this case a JSON file, that is also different for each class. Is there a way to create a generic interface without having to do ifs to select which parameter to pass to each class?

import library_A
import library_B
import json

class ApproachA():

    def __init__(self, params):
        self.params = params
        self.entity = library_A.Model(self.params)

    def run(self, data):
        return self.entity(data)

class ApproachB():

    def __init__(self, params):
        self.params = parse_params(params)
        self.entity = library_B.Model(self.params)

    def run(self, data):
        real_data = do_something(data)
        return self.entity(data)

if __name__ == "__main__":
    with open('params.json') as f:
        params = json.loads(f)

    entity_list = []
    # here lies the problem
    for key, param in params.items():
        if key == "model_a":
            entity_list.append(Approach_A(param))
        elif key == "model_b":
            entity_list.append(Approach_B(param))

while the JSON parameter file is as follows:

{
    "model_a": {"param_1":10, "param_2":22},
    "model_b": {"thing":"strudel", "param_cc": 102, "talk":False}
}

I definitely want to avoid these ifs sequences and couplings, as things similar to these tests have to be done in several places in the code. I also would like to avoid an abstract base class. I´m trying to keep things as functional as possible, without heavy OO concepts.


texts:
Any improvements?

import datetime
import json

class CustomEncoder(json.JSONEncoder):

    def default(self, obj):
        """
        This method will only be called if an object is passed to the parent JSON encoder in the case
        it doesn't know how to deal with.
        In case the object passed to the encode method of JSON that is by default json serializable [eg.: list]
         this method will not be called
        """
        if isinstance(obj, datetime.datetime):
            # Return a JSON object where each parameter of the datetime object is a key in a dictionary.
            return {
                '_type': 'datetime',
                'year': obj.year,
                'month': obj.month,
                'day': obj.day,
                'hour': obj.hour,
                'minute': obj.minute,
                'second': obj.second
            }
        elif isinstance(obj, datetime.timedelta):
            return {
                '_type': 'timedelta',
                'days': obj.days,
                'seconds': obj.seconds,
                'microseconds': obj.microseconds
            }

        # In case the object passed is not serializable by default and,
        # is not implemented above; the default method will fall through here. In which case:

        # Pass the object back to the default JSON handler and:
        return super().default(obj)  # Let the default JSON handler output the error: not serializable.

class CustomDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    @staticmethod
    def object_hook(obj):
        decodes = {'datetime': datetime.datetime, 'timedelta': datetime.timedelta}

        if '_type' in obj:

            data_type = obj.pop('_type')

        # This line will return either:
        # a decoded object of a type specified in the "decodes" dictionary
        # or obj without any modification to it's type in case the type is not implemented yet.

        return decodes.get(data_type, lambda **kwargs: kwargs)(**obj)

# Testing:

now = datetime.datetime.now()

encoded_datetime_data = json.dumps(now, cls=CustomEncoder, indent=2)
decoded_datetime_data = json.loads(encoded_datetime_data, cls=CustomDecoder)

encoded_timedelta_data = json.dumps(datetime.timedelta(0), cls=CustomEncoder, indent=2)
decoded_timedelta_data = json.loads(encoded_timedelta_data, cls=CustomDecoder)

encoded_array = json.dumps([1, 2, 3, 4], cls=CustomEncoder, indent=2)
decoded_array = json.loads(encoded_array, cls=CustomDecoder)

print(encoded_datetime_data)
print(decoded_datetime_data)
print(type(decoded_datetime_data))

print(encoded_timedelta_data)
print(decoded_timedelta_data)
print(type(decoded_timedelta_data))

print(encoded_array)
print(decoded_array)
print(type(decoded_array))

class Nothing:
    pass

# This will fail: (TypeError: Object of type Nothing is not JSON serializable)
encoded_nothing_data = json.dumps(Nothing(), cls=CustomEncoder)
decoded_nothing_data = json.loads(encoded_nothing_data, cls=CustomDecoder)
```


texts: Finding the length of the number of paths in a matrix

texts:
I found this problem from leetcode.com. We are asked to find the longest increasing path in a matrix. I finally came up with a recursion to achieve this but I found that when I increase the rows and columns to a large size then my program takes a long time to run.

I am wondering if there is any way I can optimize my code for speed, or perhaps if there is a better approach I can consider. I know that some have used dynamic programming and depth first search to achieve good speeds but to be honest I haven't really gotten there yet in my programming level.

#include <algorithm>
#include <cmath>
#include <vector>
#include <iostream>
#include <random>

using namespace std;

#define MATRIX_SIZE 1000

void printPath() {

}

int check(int i, int j, vector<vector<int> > matrix, vector<vector<int> > length) {
    if (length[i][j] == -1) {
        int currentValue = matrix[i][j];

        int len = 0;
        if ((i > 0) && (matrix[i-1][j] > currentValue)) { // check up
            len = max(len, check(i-1, j, matrix, length));
        }
        if ((i + 1 < matrix.size()) && (matrix[i+1][j] > currentValue)) { // check left
            len = max(len, check(i+1, j, matrix, length));
        }
        if ((j > 0) && (matrix[i][j-1] > currentValue)) { // check down
            len = max(len, check(i, j-1, matrix, length));
        }
        if ((j+1 < matrix[i].size()) && (matrix[i][j+1] > currentValue)) { // check right
            len = max(len, check(i, j+1, matrix, length));
        }
        length[i][j] = len + 1; // Include current cell
    }
    return length[i][j];
}

int longestPath(vector<vector<int> > matrix) {
    int n = matrix[0].size();
    int m = matrix.size();
    vector<vector<int> > length(m, vector<int>(n,-1));

    int len = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            len = max(len, check(i, j, matrix, length));
        }
    }
    return len;
}

int main() {
    // Specify the number of rows and columns of the matrix
    int n = MATRIX_SIZE;
    int m = MATRIX_SIZE;

    // Declare random number generator
    mt19937 gen(10);
    uniform_int_distribution<> dis(1, 1000000);

    // Fill matrix
    vector<vector<int> > matrix;
    for(int i = 0; i < m; i++) {
            vector<int> row;
        for(int j = 0; j < n; j++) {
            row.push_back(0);
        }
        matrix.push_back(row);
    }

    // Apply random number generator to create matrix
    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            matrix[i][j] = dis(gen);
        }
    }

    // Print matrix to see contents
//  for(int i = 0; i < m; i++) {
//      for(int j = 0; j < n; j++) {
//          cout << matrix[i][j] << " ";
//      }
//      cout << endl;
//  }
//  cout << endl;

    int result = longestPath(matrix);
    cout << result << endl;

}


texts: Intersection of Two Arrays - Space Time And Complexity

texts:
The problem is as follows: Given two arrays, write a function to compute their intersection.

The below code is my solution.I'm just curious as to what the space time and complexity of below algorithm would be.

var intersection = function(nums1, nums2) {
    const intersectionArr =  nums1.filter((value)=> nums2.includes(value));
    return [...new Set(intersectionArr)];
};


texts:
Validate IP Address
I got this problem during an interview. And would like to get some code review. I also wrote several tests with the expected output, and they all passed as expected.

Validate an IP address (IPv4). An address is valid if and only if it
is in the form "X.X.X.X", where each X is a number from 0 to 255.
For example, "12.34.5.6", "0.23.25.0", and "255.255.255.255" are valid
IP addresses, while "12.34.56.oops", "1.2.3.4.5", and
"123.235.153.425" are invalid IP addresses.

Examples:

"""

ip = '192.168.0.1'
output: true

ip = '0.0.0.0'
output: true

ip = '123.24.59.99'
output: true

ip = '192.168.123.456'
output: false
"""

def validateIP(ip):
  #split them by '.' , and store them in an array
  #check the array if the length is 4 length
  arr = ip.split('.')
  if len(arr) != 4:
    return False
  #0 check for special edge cases when non-digit
  #1. check if they are digit,
  #2. check if check the integer is between 0 and 255

  for part in arr:
    if len(part) > 1:
      if part[0] == '0':
        return False
    if not part.isdigit():
      return False
    digit = int(part)
    if digit < 0 or digit > 255:
      return False
  return True

#case#0

ip0="08.0.0.0" # False
test0= validateIP(ip0)
print(test0)

#case#1
ip1 = "192.168.0.1"
test1 = validateIP(ip1)
print(test1)

#case#2
ip2 = '0.0.0.0'
test2 = validateIP(ip2)
print(test2)

#case#3
ip3 = '123.24.59.99'
test3 = validateIP(ip3)
print(test3)

#case#4
ip4 = '192.168.123.456'
test4 = validateIP(ip4)
print(test4)

#case5
ip5 = "255.255.255.255"
test5 = validateIP(ip5)
print(test5)


texts: AudioMetaTagger: recursively read files and gather metadata

texts:
So the idea is to read metadata recursively in a chosen directory, load their metadata and display it into a table.

Here is the simplified example of what I am doing.

public class AudioMetadataExtractorTest {

    public static void main(String[] args) {
       String audioFiles = "C:\\Music";

       File dir = new File(audioFiles);
       Collection col = checkData(dir);

       for(Object object : col){
        File fil = (File) object;
        System.out.println(fil.getAbsolutePath());
        try {
            printMetaData(fil);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
       System.out.println(col.size());
   }

In this case I am using the apachi.commons library to gather all files.

    public static Collection checkData(File dir){
    Collection files = FileUtils.listFiles(
              dir,
              new RegexFileFilter("^(.*mp3)"),
              DirectoryFileFilter.DIRECTORY
            );
    return files;
}

And with jaudiotagger read and print the metadata.

    public static void printMetaData(File file) throws Exception {
    AudioFile audioFile = null;
    audioFile = AudioFileIO.read(file);
    Tag tag = audioFile.getTag();
    for (FieldKey key : FieldKey.values()) {
        if(key==FieldKey.ALBUM){
        System.out.println(key + " " + tag.getFirst(key));
        }
    }
}

While this code works, it is extremely slow. I am confident there is a more efficient way of doing this.

Is it bad practice to loop over objects and cast them within the loop?
Is the jaudiotagger library an intrinsically slow library?


texts: Take an Integer and print it in a Different Base Recursively (c++)

texts:
This was for a school project in my Data Structures class (I am still a very very young programmer). The purpose was to pass an interger and a base into a function and print out the result of changing that integer into that base. The project guidelines state that we can only pass an integer that is >= 0 and <= 1000000000.
The Main Function uses ifstream to stream a text document with the input into the main function.
I would like to know if there is anyway I can improve upon the BaseConverter function or anything else in the program before I submit it for grading.
I will put the full program below:
#include <iostream>
#include <fstream>
using namespace std;

/****************************************************************************************************
Function Name: BaseConverter
Description: The purpose of this function is to take the user decimal number and base that are passed
             to it and use them to recursively convert the decimal number into the base. The function
             prints the correct result to the problem onto the screen and returns void.
*****************************************************************************************************/

void BaseConverter(int num, int base)
{
    if (num == 0)
    {
        cout << "";
    }

    if (num >= base)
    {
        BaseConverter(num / base, base);

        if (num % base > 9)
        {
            cout << char(num % base + 55);
        }
        else
        {
            cout << num % base;
        }
    }

    else
    {
        cout << num % base;
    }
}

/*****************************************************************************************************
MAIN PROGRAM
******************************************************************************************************/

int main()
{
    ifstream fin("numbers.txt");

    int userNum, base;

    //sentinel control loop
    fin >> userNum >> base;
    while (userNum >= 0)
    {
        //display for input to ensure that correct input is being passed
        cout << userNum << " " << base << endl;

        if (userNum > 1000000000)
        {
            cout << "Decimal number too large for this program" << endl;
            cout << endl;
        }
        else
        {
            // call for function and output display
            cout << userNum << " in base " << base << " is ";
            BaseConverter(userNum, base);
            cout << endl;
            cout << endl;
        }

        fin >> userNum >> base;
    }

    fin.close();
    return 0;
}


texts:
I have inherited some legacy code that I'm now trying to clean up.

I feel like the 2nd null check is redundant, see comments:

private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof ArrayOfColumn)) return false; // Here is first check if the obj is not null, if there is instaceof ArrayOfColumn then it's not null
        ArrayOfColumn other = (ArrayOfColumn) obj;
        if (obj == null) return false; // Therefore this check is redundant and "return false" will never execute, so it's dead code
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.column==null && other.getColumn()==null) ||
             (this.column!=null &&
              java.util.Arrays.equals(this.column, other.getColumn())));
        __equalsCalc = null;
        return _equals;
    }

Anything else?


texts: Printing a table of letter frequencies using Python

texts:
What is the recommended (standard, cleaner, more elegant, etc.) method in Python to get a string with all the alphabet letters?

Here's three versions of code to generate a dictionary with keys as letters and 0 as all values. The aim is to parse a text and count how often a letter appears.

from string import ascii_lowercase
frequency = {letter: 0 for letter in ascii_lowercase}

A downside of this method is that the constant shows up in the pydoc output for the module in which it is imported.

frequency = {chr(letter): 0 for letter in range(ord('a'), ord('z')+1)}

frequency = {letter: 0 for letter in 'abcdefghijklmnopqrstuvwxyz'}

This is the snippet of code where it is used:

frequency = {chr(letter): 0 for letter in range(ord('a'), ord('z')+1)}

# The 'text' variable is taken from somewhere else, we define it here for example's sake
text = 'StackExchange Code Review'
for c in text.lower():
    if c in frequency.keys():
        frequency[c] += 1
        total += 1

output = OrderedDict(sorted(frequency.items(), key = lambda x: x[0]))
for l in output.keys():
    print(l + ':' + '{:>8}'.format(output[l]) + '{:9.2f}'.format(100 * output[l] / (total if total > 0 else 1)) + ' %')


texts: Draggable toolbar header class, inheriting from a draggable parent class

texts:
I have written a draggable parent class using a module pattern:

var draggable = {};
(function(){
var initialMouseX = undefined;
var initialMouseY = undefined;
var startX = undefined;
var startY = undefined;
var draggedObject = undefined;
var startDragX = undefined;
var startDragY = undefined;
var eventHandler = undefined;
var canvas = undefined;
var that = this;

this.setCanvasObject = function(cnv){
 canvas = cnv;
};

this.setEventHandler = function(eH){
eventHandler = eH;
};
this.setClickable = function(element){ ... };

this.setDraggable = function(element){ ... };

this.startDragMode = function(ev){ ... };

this.dragMouse = function(ev){ .... };

this.setPosition = function(dX, dY){ ... };

this.releaseElement = function() {
...
};

}).apply(draggable);

Here is my child class, using the same module pattern:

var toolbarHeader = {};

(function(){

this.__proto__ = draggable;

var that = this;

this.__proto__.startDragMode = function(ev){

var evt = ev || window.event;
var target = evt.target || evt.srcElement;
target = target.parentNode;

...

}).apply(toolbarHeader);

I want my toolbarHeader's startDragMode method to override the parent method, and inherit the rest of the parent's methods.

Is this how I should be using inheritance? Is this a good design? Please keep in mind that the module design pattern was chosen for extensibility and to avoid the hassle of namespacing and instantiation.


texts:
This is the "Longest Valid Parentheses" problem from leetcode.com:

  Given a string containing just the characters "(" and ")",
  find the length of the longest valid (well-formed) parentheses substring.
  For "(()", the longest valid parentheses substring is "()", which has length 2. Another example is ")()())", where the longest valid parentheses substring is "()()", which has length 4.

I was studied this interview question during mock-interview. And I was able to test it against the test cases.

Start from the longest length, and use a stack to identify if it is valid. If not, length - 1.

Put the elements index in the string into a stack, if "(" then add to the stack. If ")" if stack not empty, if s[stack.top()] == "(", stack.pop(), else stack.push(i). If stack is empty, stack.push(i).

The most important idea is that the substring between the adjacent indices in stack is valid.The most important aspect with dynamic programming is what the subscript j represent. Let longest be the array for dp. longest[i] is the longest substring end with i.

def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype:
        """
        if len(s) <= 1: return 0
        longest = [0] * len(s)
        max_len = 0
        for i in range(1, len(s)):
            if s[i] == ")":
                if s[i-1] == "(":
                    longest[i] = 2 + (longest[i-2] if i - 2>= 0 else 0)
                    print "hrere"
                    print longest[i]
                    if longest[i] > max_len: max_len = longest[i]
                else:
                    if i - longest[i-1] - 1 >= 0 and s[i-longest[i-1]-1] == "(":
                        longest[i] = 2 + longest[i-1] + (longest[i-longest[i-1]-2] if i-longest[i-1]-2 >= 0 else 0)
                        if longest[i] > max_len: max_len = longest[i]
        return max_len


texts:
After wrestling with CMake I now have a fully working solution.
It works, however, I completely massacred the CMake File:
This is my main cmake file:
cmake_minimum_required(VERSION 3.17)
project(Odin)

include(ProcessorCount)
ProcessorCount(N)
if(NOT N EQUAL 0)
    set(CMAKE_BUILD_PARALLEL_LEVEL ${N})
endif()

message("Parallelizing with ${N} Cores")

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
set(CMAKE_CXX_EXTENSIONS NO)

include_directories(Odin/engine)
include_directories(Odin/uci)
include_directories(Odin/util)
include_directories(Odin/util/iters)

# add our cmake modules under cmake/
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")

# Include CPM dependency manager
include(CPM)

if(WIN64)
SET(BOOST_ROOT "C:/Program Files (x86)/boost/boost_1_74_0")
include_directories(${BOOST_ROOT})
include_directories(${BOOST_ROOT}/stage/lib)
endif()

find_package(Boost 1.74.0 REQUIRED serialization)

message(STATUS "---------------------")
message(STATUS "Boost_FOUND: ${Boost_FOUND}")
message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
message(STATUS "Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}")
message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
message(STATUS "---------------------")

#EndBoost

add_executable(Odin
        Odin/engine/Odin.cc
        Odin/main.cc
        Odin/engine/Board.cc
        Odin/util/Utility.cc
        Odin/util/iters/BoardIterator.cc
        Odin/engine/Node.cc
        Odin/engine/Link.cc
        Odin/engine/Odin.h
        Odin/engine/Board.h
        Odin/engine/Figure.h
        Odin/util/Utility.h
        Odin/engine/Node.h
        Odin/engine/Link.h
        Odin/util/iters/BoardIterator.h)

add_library(Engine
        Odin/engine/Odin.cc
        Odin/main.cc
        Odin/engine/Board.cc
        Odin/util/Utility.cc
        Odin/util/iters/BoardIterator.cc
        Odin/engine/Node.cc
        Odin/engine/Link.cc
        Odin/engine/Odin.h
        Odin/engine/Board.h
        Odin/engine/Figure.h
        Odin/util/Utility.h
        Odin/engine/Node.h
        Odin/engine/Link.h
        Odin/util/iters/BoardIterator.h)

target_link_libraries(Engine PRIVATE Boost::serialization)
target_link_libraries(Odin PRIVATE Boost::serialization)

if(UNIX)
set(CMAKE_CXX_FLAGS "-O3 -march=native")
endif(UNIX)

#Make Tests
#enable testing
enable_testing()

# Pull doctest using CPM
cpmaddpackage("gh:onqtam/doctest#2.4.5")

# add the CMake modules for automatic test discovery so we can use
# doctest_discover_tests() CMake
set(CMAKE_MODULE_PATH "${doctest_SOURCE_DIR}/scripts/cmake"
        ${CMAKE_MODULE_PATH})

add_subdirectory(Testing)

To be honest, sometimes I had no idea what I was doing.
You see that I have to add every file into library and into the executable Odin.
This is not that smart.
I actually want my idea to still be able to add a .cpp file to the Odin - executable.
However my test must still run, and they require me to add all the files twice.
You can find my tests (cmake) here:
https://github.com/SuchtyTV/Odin/tree/master/Testing
Here are some questions:

How do I walk around this library/executable non-sense?
How do I ensure the Release build will be well optimized?
Can I download Boost with CPM, if so, how would I do that and how would that look in the cmake file?
Any other advices?


texts: Try-catch flow to handle two failing services

texts:
We need to create a car with apiCar and log in two places CosmosDB and the logger, whether there is an error or not. Except if the error happens in Cosmos, in that case we only log in the logger. Finally, if there is an exception, any exception, we need rethrow it so the "MyFunction" caller can handle it.
This is my best shot that works but I don't like it. Is there any way to improve it?
public async Task MyFunction(Car car)
{
    try
    {
        var apiCar = await _APIService.CreateAsync(car);
        car.Status = CarStatus.Created;

        _logger.LogInformation("Created apiCar for car: {carId}", car.Id);
    }
    catch (ApiErrorException exception)
    {
        _logger.LogError(exception, "API exception for car: {carId}", car.Id);
        car.Status = CarStatus.Error;
        car.ErrorMessage = exception.Body.Error.Message;
    }
    catch (Exception exception)
    {
        _logger.LogError(exception, "Exception for car: {carId}", car.Id);
        car.Status = CarStatus.Error;
        car.ErrorMessage = exception.Message;
    }

    try
    {
        await _cosmosService.UpdateItemAsync(car);
    }
    catch (CosmosException exception)
    {
        _logger.LogError(exception, "Cosmos exception for car: {carId}", car.Id);

        throw;
    }

    if (car.Status == CarStatus.Error)
    {
        throw new Exception();
    }
}


texts:
This is a follow on to a previous question:
Part 3: User Scripts
All the code I am submitting here is available in github

The reason to write these tools is so I can prototype and quickly verify that I am doing things correctly before implementing them in C++. This is mainly necessary because the documentation these scripts are based on are relatively bad and confusing.

The scripts used by users:
s3cp
#!/usr/bin/env bash

badflag=0
declare -a ARGS

function usage {
    echo "Usage:"
    echo "s3cp  <file> <s3-url> [--key=<key>] [--secret=<secret>] [--verbose] [--dryrun]"
    echo "s3cp  <s3-url> <file> [--key=<key>] [--secret=<secret>] [--verbose] [--dryrun]"
    echo
    echo "s3-url:  s3://<bucket>/<Object-Path>"
    exit 1
}

verbose=''
dryrun=0
access=${AMZ_ACCESS_KEY}
secret=${AMZ_SECRET_KEY}
for var in "$@"; do
    if [[ "${var}" == '--verbose' ]]; then
        verbose='/dev/stdout'
        continue
    fi
    if [[ "${var}" == '--dryrun' ]]; then
        dryrun=1
        continue;
    fi
    if [[ "${var%=*}" == "--key" ]]; then
        access=${var#*=}
        continue;
    fi
    if [[ "${var%=*}" == "--secret" ]]; then
        secret=${var#*=}
        continue;
    fi
    flag=${var#-}
    if [[ "${flag}" != ${var} ]]; then
        badflag=1
        echo "Bad flag: ${var}"
        continue
    fi
    ARGS+=("$var")
done

if [[ "${access}" == "" || "${secret}" == "" ]]; then
    echo "Error: No Access or Secret provided."
    echo "These can be set in the environment variables AMZ_ACCESS_KEY/AMZ_SECRET_KEY or passed with flags"
    usage
fi

if [[ ${#ARGS[@]} != 2 || ${badflag} != 0 ]]; then
    usage
fi

src=${ARGS[0]}
dst=${ARGS[1]}

doUpload=0
doDownload=0
srcS3=${src#s3://}
if [[ "${src}" == "${srcS3}" ]]; then
    doUpload=1
fi
dstS3=${dst#s3://}
if [[ "${dst}" == "${dstS3}" ]]; then
    doDownload=1
fi

if [[ ${doUpload} == 0 && ${doDownload} == 0 ]]; then
    echo "Neither source or destination is on S3. Just use normal cp"
    usage
fi
if [[ ${doUpload} == 1 && ${doDownload} == 1 ]]; then
    echo "Both source or destination is on S3. Don't support move yet."
    usage
fi

dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source ${dir}/s3/signature

if [[ ${doUpload} == 1 ]]; then
    source ${dir}/s3/upload
    upload "${src}" "${dst}" "${access}" "${secret}" '' "${verbose}" "${dryrun}"
else
    source ${dir}/s3/download
    download "${src}" "${dst}" "${access}" "${secret}" '' "${verbose}" "${dryrun}"
fi


texts:
Below are two functions that work no problem in my current script. They are written to be ran in Python 2.7.x

def tor_browser_initialise():
        """ This function checks whether the Tor Browser is running. If it isn't,
        it will open the Tor Browser.
        """
        processlist = []
        for p in psutil.process_iter():
            try:
                process = psutil.Process(p.pid)
                pname = process.name()
                processlist.append(pname)
            except:
                continue
        if "tor.exe" not in processlist:
            process = subprocess.Popen(r"C:\Program Files (x86)\Tor Browser\Browser\firefox.exe", stdout=subprocess.PIPE)
            time.sleep(30)

def connect_tor(url):
    """ This function accepts a URl as an argument. It accesses the URL via TOR before
    returning the HTML source code to the function that called it. This function also
    uses random browser information.
    """
    LOCALHOST = "127.0.0.1"
    PORT = 9150
    useragent_list = ['Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0',
                   'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/29.0',
                   'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36',
                   'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36',
                   'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0',
                   'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
                   'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',
                   'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30']
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, LOCALHOST, PORT)
    socket.socket = socks.socksocket
    request = urllib2.Request(url)
    request.add_header('User-Agent', random.choice(useragent_list))
    response = urllib2.urlopen(request)
    return response

I'd like to know if there is a more concise and Pythonic way of writing the two functions. I haven't listed the dependant libraries / modules at the beginning of the code, but it does work correctly.


texts: First BDD/RSpec tests, would like some review regarding idioms, conventions and style

texts:
This is my first attempt at BDD and RSpec. I'm more of a C# xUnit kind of guy.

I wrote this class while developing a 2D random tile map generator (just for fun). The project is still ongoing.

I would particularly like some review on:

Test granularity/scope in relation to BDD
Use of RSpec
Are these too much like unit tests?
Adherence to Ruby and RSpec idioms, conventions, coding style

I am also open to any other kind of comments and review.

require './map_factory'

describe MapFactory, "map creation" do
    before(:each) do
        @map_factory = MapFactory.new
    end

  it "should return a new Map instance" do
    map = @map_factory.make(20, 20)
    map.should be_an_instance_of(Map)
  end

  it "should be a map of the specified size" do
    map = @map_factory.make(20, 20)
    map.width.should equal(20)
    map.height.should equal(20)
    map.tiles.length.should equal(400)
  end

  it "should be an island" do
    map = @map_factory.make(20, 20)

    # an island should have water all around it
    for x in 0...map.width
        map.tile_at(x, 0).type.should eq(:water)
        map.tile_at(x, 19).type.should eq(:water)
    end

    for y in 0...map.height
        map.tile_at(0, y).type.should eq(:water)
        map.tile_at(19, y).type.should eq(:water)
    end
  end

  it "should have more than half the tiles be landmass" do
    map = @map_factory.make(40, 40)

    number_of_water_tiles = 0
    number_of_land_tiles = 0

    map.tiles.each do |tile|
        if tile.type == :water then
            number_of_water_tiles += 1
        else
            number_of_land_tiles += 1
        end
    end

    number_of_land_tiles.should be > number_of_water_tiles
  end
end


texts: Calculate Mersenne prime numbers in MATLAB

texts:
A Mersenne prime is equal to (2^n - 1), where n is an integer.
31 is a Mersenne prime since 31 = 2^5 -1. I need to write a code that calculates Mersenne primes between 1 and 10,000. Lastly I'm not allowed to use the build in function isprime.

I have used the formula to calculate till an arbitrary n then used a for loop to verify if the numbers I got are prime numbers.

Running the script I get  3, 7, 31, 127, 8191.

How could I make the code look cleaner?
Do you think my code is giving me the right answer?

    for k = 1:50000 %calculates mersenne primes using mersenne formula

        p(k) = 2^k -1;

    end
    p = p(p<10000 & p>1);
    psize =size(p);
    x = psize(2);
 mersenneprime = 0; k = 2; f = 0;

for m = 1:x %verifies if mersenne are prime numbers
    k = k +1;
a = p(m);
b = p(m)-1;
    if all((rem(a,2:b)) ~= 0)
          flag = 1;
      else
          flag = 0;
    end
      if flag == 1
          f = f+1;
          mersenneprime(f) = p(m);
      end
end %it eliminates 7 numbers from original array
mersenneprime


texts: Adding extension methods to IServiceCollection in ASP.NET Core

texts:
I have the following extension method to add themes support to my application:

public static void AddThemes(this IServiceCollection services, Action<ThemesOptions> setup) {
    services.Configure(setup);
}

Where ThemesOptions is defined as:

public class ThemesOptions {
    public IEnumerable<string> Themes { get; set; }
}

Now in my application's startup ConfigureServices method I can say:

services.AddThemes(options => {
    options.Themes = Configuration.GetSection("Themes").Get<ThemesOptions>().Themes;
});

I'm not sure that I like that I have to set every property for the options. Alternatively I tried:

services.AddThemes(options => {
    options = Configuration.GetSection("Themes").Get<ThemesOptions>();
});

And:

services.AddThemes(options => Configuration.GetSection("Themes"));

However when I inject IOptions<ThemesOptions> the Themes property is null.

An alternative to I changed my extension method to:

public static void AddThemes(this IServiceCollection services, IConfiguration configuration) {
    services.Configure<ThemesOptions>(configuration.GetSection("Themes"));
}

Now I can say the following within my application's Startup ConfigureServices method:

services.AddThemes(Configuration);

This worked fine, however, I feel the problem with this approach is that the extension method only allows the options to be set from the configuration.

I'd appreciate it if someone could confirm whether my first solution is correct and if it can be improved upon.


texts: Displaying current date and time using JavaScript and HTML time tag

texts:
I am creating  a simple support ticket system. I thought It would be a nice little feature to show the current date and time. Since I want to show the current time I thought JavaScript would be best versus using PHP. I have looked at different questions posted by other user about the topic and created the following snippet. My question is if this is a efficient way to get and display the date and time using JavaScript date object. I also thought is would be appropriate to use the <time> tag. I also ask if I have used it in the correct form.

JavaScript and HTML

var monthName = new Array('January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var hourap = new Array(12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
function showTime(){
    var dateObj = new Date();
    var day = dateObj.getDate(), month = dateObj.getMonth(), year = dateObj.getFullYear(), hour = dateObj.getHours(), minutes = (dateObj.getMinutes()<=9?'0'+dateObj.getMinutes():dateObj.getMinutes());
    var string  = monthName[month]+
    ' '+day+
    ', '+year+
    '
'+hourap[hour]+
    ':'+minutes+
    ' '+(hour<=11?'am':'pm');
    var timeDiv = document.getElementById('time');
    if(timeDiv !== null) {
        timeDiv.innerHTML = string;
        timeDiv.setAttribute('datetime',year+'-'+(month+1<=9?'0'+(month+1):month+1)+'-'+day+' '+hour+':'+minutes);

    };
};
setInterval(showTime,1000);
<time id="time"></time>

HTML output

<time id="time" datetime="2015-01-30 22:00">January 30, 2015
10:00 pm</time>

Any suggestions or comments would be appreciated. Please note that I wish to script it using pure JavaScript and not jQuery.


texts: Complex data structure organization in javascript?

texts:
Upon suggestion in the original question within Stack Overflow, I'm bringing this question here.

Question Explained:

In a website that I built, I used complex multidimensional arrays to organize a multitude of information tables linked to events. I want to know if what I did was a viable efficient solution for the specific situation, or if something else would have made more sense, like using database tables or take an object oriented approach.

This is what I did:

I built a set of dropdown menus with javascript, The first list (category) determined what items where shown on the second list (service). If the user hovered over a category, the correlating services were displayed on the second list. If the user selected a service, a list of items in that service where shown in another part of the page(itemlist). Each item on the itemlist had unique values, prices, and 2 possible types, either check boxes or numerical entries.

Hopefully that will make the following array examples make sense. All you need to know further about these arrays is that they correlate to achieve the above result.

the below array is in image form for your convenience. Stack Overflow refused to keep my formatting, making it unreadable.

There are over 20 copies of this (above) array item with different services.

  ServiceArray[0][0]:
  [0]is the id to be assigned to the element.
  ['1]is text name to be outputted.
  ['2]is a variable name to be assigned.
  ['3]is a key value to be appended to each item so I can call on a correlating value in the first array set.
  ['4]is an example to be listed

the downsides to this approach are obvious. The complex array structures become difficult to manage. When working with the variables, I had to continuously recount each variable to find the array keys. In the end though, i was able to use this approach very dynamically for the drop-downs and service lists. Here are a few examples of the code used to dynamically generate the content with these arrays.

$(".dropdown-service > p").click(function () {
    var thisKey = $(this).data("key");
    $("#ServiceOutput").text($(this).text());
    $(".layer4").append('
');
    for (var i = 0; i < ServiceArray[Category][thisKey][4][1][5].length; i++) {

        var listId = ServiceArray[Category][thisKey][6][1][i][7];
        var listTitle = ServiceArray[Category][thisKey][8][1][i][0];
        var List = "";

        for (var x = 0; x < ServiceArray[Category][thisKey][9][1][i][10].length; x++) {
            var Time = ServiceArray[Category][thisKey][11][1][i][12][x][13];
            var Content = ServiceArray[Category][thisKey][14][1][i][15][x][0];
            var Hours = ServiceArray[Category][thisKey][16][1][i][17][x][18];
            List += '

' + Content + ' ('+ Hours +'Hrs)

';
        }

        $(".layer4").append('

' + listTitle + '

' + List + '

');
    }
    $(".layer4").append('
');
});

So the ultimate question:

Is this method the best for the specific situation, or could I have done something more efficient to save time an effort while achieving the same result?


texts: Model class representing a financial calculator

texts:
Here is my Model class's new header file:

@interface MMCalculator : NSObject

@property (readonly) CGFloat calculatedPay;
@property (readonly) CGFloat calculatedSavingsForStuff;
@property (readonly) CGFloat calculatedSavingsForProfitFormula;
@property (readonly) CGFloat calculatedSavingsForTaxes;

- (void)calculateValuesWithMonthlyRevenue:(CGFloat)monthlyRevenue;

@end

Here is my Model class's new implementation file:

#import "MMCalculator.h"

#pragma mark - Const Variables
static CGFloat const kPercentageToPayYourself = 0.50;
static CGFloat const kPercentageToSaveForStuff = 0.20;
static CGFloat const kPercentageToSaveForProfitFormula = 0.20;
static CGFloat const kPercentageToSaveForTaxes = 0.10;

@interface MMCalculator ()

@property (readwrite) CGFloat calculatedPay;
@property (readwrite) CGFloat calculatedSavingsForStuff;
@property (readwrite) CGFloat calculatedSavingsForProfitFormula;
@property (readwrite) CGFloat calculatedSavingsForTaxes;

@end

@implementation MMCalculator

#pragma mark - Calculator Methods
- (void)calculateValuesWithMonthlyRevenue:(float)monthlyRevenue
{
    //Call all 4 calculation methods and set calculated properties
    self.calculatedPay = [MMCalculator calculateYourPay:monthlyRevenue];
    self.calculatedSavingsForStuff = [MMCalculator calculateSavingsForStuff:monthlyRevenue];
    self.calculatedSavingsForProfitFormula = [MMCalculator calculateSavingsForProfitFormula:monthlyRevenue];
    self.calculatedSavingsForTaxes = [MMCalculator calculateSavingsForTaxes:monthlyRevenue];

}

+ (CGFloat)calculateYourPay:(CGFloat)monthlyRevenue
{
    return kPercentageToPayYourself * monthlyRevenue;
}

+ (CGFloat)calculateSavingsForStuff:(CGFloat)monthlyRevenue
{
    return kPercentageToSaveForStuff * monthlyRevenue;;
}

+ (CGFloat)calculateSavingsForProfitFormula:(CGFloat)monthlyRevenue
{
    return kPercentageToSaveForProfitFormula * monthlyRevenue;
}

+ (CGFloat)calculateSavingsForTaxes:(CGFloat)monthlyRevenue
{
    return kPercentageToSaveForTaxes * monthlyRevenue;
}

@end

Key things I am looking for advice on:

Are my constants defined in the correct location in my Model class's implementation file?
Even though the compiler does not force me to, would it be better to declare my private methods in the class extension? I want to make sure I'm following best practices.
Now that the Model's instance methods have been changed to class methods, should I change the public calculateValuesWithMonthlyRevenue: method to a class method as well?
Any other general comments are welcome.


texts: User registration and authentication using hashed passwords

texts:
I'm working on a game project (with Unity) that shall handle user credentials and other data. The game connects send requests to a php script and this script send requests to the database. After spending some days learning about sql injections and password handling, I came up with this approach. I am obviously still very naive with all this, but I would like to know if it is good or not. The first one is the script for creating a new user, and the second one is for login.

<?php

$servername = "localhost";
$username = "whatever";
$password = "whatever";
$dbname = "whatever";

try {

    $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $salt = bin2hex(random_bytes(strlen($_POST["providedpass"])));
    $hashpsw = hash('sha256', $_POST["providedpass"].$salt);

    $name = $_POST["usrnm"];

    $stmt = $db->prepare("INSERT INTO users (username, password, salt, level) VALUES (?,?,?,?)");

    if ($stmt->execute(array($name,$hashpsw, $salt, 1))) {

        echo "USER CREATED";
    }

    $db = null;

} catch (PDOException $e){

    echo "Error: " . $e->getMessage();
}

?>

-

<?php

$servername = "localhost";
$username = "whatever";
$password = "whatever";
$dbname = "whatever";

try {

    $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");

    $providedname= $_POST["usrnm"];

    $stmt->execute(array($providedname));

    while($row = $stmt->fetch(PDO::FETCH_OBJ)){

            echo "FOUND USER";

            $hashpsw = hash('sha256', $_POST["providedpass"].$row->salt);

            if($hashpsw == $row->password) {

                        echo "CORRECT CREDENTIALS";

            }

    }

    $db = null;

} catch (PDOException $e){

    echo "Error: " . $e->getMessage();

}
?>


texts:
I feel like I don't understand how polymorphism works in Python. Here is something I put together.

class _Tag(object):
    def __init__(self):
        #DisjointedTag and JoinedTag will bypass __init__.
        #Also, self will not be defined within this class.
        #Bottom line, this class is just for inheritance.
        raise NotImplementedError;

    def join_attributes(self):
        self.joined_pieces=''.join(self.funct_pieces);
        self.__class__=JoinedTag;

    def to_disjointed(self):
        self.__class__=DisjointedTag;

    def add_attribute(self, attribute, value):
        self.funct_pieces.insert(
            -1, ' {}="{}"'.format(attribute, value)
        );
        self.to_disjointed();

class Tag(_Tag):
    def __init__(self, name):
        self.funct_pieces=[
            i.format(name) for i in ['<{0}', '>{{}}</{0}>']
        ];
        self.joined_pieces='';

    def __call__(self, contents):
        self.join_attributes();
        return self(contents);

class JoinedTag(_Tag):
    def __call__(self, contents):
        return self.joined_pieces.format(contents);

class DisjointedTag(_Tag):
    #JoinedTag.__call__ has 1 mandatory parameter so this also needs one.
    def __call__(self, place_holder):
        raise TypeError(
            '{} is disjointed because attributes were added to it.'.\
            format(self)
        );

Here is an example:

>>> p=Tag('p')
>>> p('hi')
'
hi
'
>>> p.add_attributes('align', 'left')
>>> p.join_attributes();
>>> p('hi')
'
hi
'

I could have joined the attributes on every call but that would waste time. The code I made has no if statements, so it should be more readable according to the philosophy of polymorphism. However, it is very hard to read. I figure I've done something wrong or I'm not used to reading polymorphic code.


texts:
I'm working on Tic Tac Toe and I want do it for any ROW x COL board with any WIN_SIZE (e.g. 4x4 board requires 3 to win). I've done the hasWon method already but I'm not sure is it done right. Can you check what can I do better here?

public boolean hasWon(Seed theSeed) {
    int count = 0;

    for (int col = 0; col < COLS; ++col) {               //check columns
        if (cells[currentRow][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
    }
    count = 0;

    for (int row = 0; row < ROWS; ++row) {              //check rows
        if (cells[row][currentCol].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
    }
    count = 0;

    int row = currentRow;

    for (int col = currentCol; col >= 0; --col) {      //check forward diagonal
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
        row--;
        if (row < 0)
            break;
    }
    row = currentRow;
    count--;
    for (int col = currentCol; col < COLS; ++col) {
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
        row++;
        if (row == ROWS)
            break;
    }

    count = 0;
    row = currentRow;

    for (int col = currentCol; col >= 0; --col) {  //check backward diagonal
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
        row++;
        if (row == ROWS)
            break;
    }

    row = currentRow;
    count--;
    for (int col = currentCol; col < COLS; ++col) {
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
        row--;
        if (row < 0)
            break;
    }
    return false;
}


texts:
I have a simple script that will take a list of hosts and ping each host (there's about 200) a single time before moving on. This is not the most effecient method I am sure, as it is very linear. And it takes a few minutes to complete. I would ideally like to run this script every minute (so each IP address is checked every minute (the actual running of the script is controlled externally).

I was looking for some pointers on potentially making the script more effecient/dynamic.

import sys
import os
import platform
import subprocess

plat = platform.system()
scriptDir = sys.path[0]
hosts = os.path.join(scriptDir, 'hosts.txt')
hostsFile = open(hosts, "r")
lines = hostsFile.readlines()
if plat == "Windows":
    for line in lines:
        line = line.strip( )
        ping = subprocess.Popen(
            ["ping", "-n", "1", "-l", "1", "-w", "100", line],
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE
        )
        out, error = ping.communicate()
        print out
        print error

if plat == "Linux":
    for line in lines:
        line = line.strip( )
        ping = subprocess.Popen(
            ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1", line],
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE
        )
        out, error = ping.communicate()
        print out
        print error

hostsFile.close()


texts: Assembly Language (AVR) Button Scanning/Debouncing Routine

texts:
So, I'm very new to assembly language programming for microcontrollers.

I'm using an AVR XMega A3BU X-plained board, and I've got a program where I need to interface with 7 buttons. 3 of them are on the board, and 4 are connected to a cheap 4 button membrane keypad.

I need to debounce the switches (hardware solutions are not an option), and I've constructed the following routine to do it; I feel like it's horribly inefficient and has several design flaws, but I can't tell.

(The CPU clock is running at 32 MHz and the timer interrupt occurs every 100ms.)

C programming is not an option, I must use assembly.

Is there a better way to do this?

;------------------------------------------------------------------------------
; Timer interrupt service routine - tcf0_isr
;------------------------------------------------------------------------------
; TODO - document this routine
;------------------------------------------------------------------------------
.equ        DEBOUNCE_VALUE   =0xFF                   ;

tcf0_isr:                                       ;
            push        r16                     ;
check_ib1:                                      ;
            lds         r16,PORTE_IN            ;
            sbrs        r16,5                   ; if(ib1 is down)
            rjmp        ib1_is_down             ;   debounce ib1
            clr         r16                     ; else reset debounce counter
            sts         ib1downcnt,r16          ;       *
            jmp         check_ib2               ;       *
ib1_is_down:                                    ;
            lds         r16,ib1downcnt          ; Debounce ib1
            inc         r16                     ;       *
            sts         ib1downcnt,r16          ;       *
            cpi         r16,DEBOUNCE_VALUE      ;       *
            breq        ib1_debounced           ;       *
ib1_debounced:                                  ;       *
            call        sel_wng_pressed         ; Call ib1 handling routine
check_ib2:                                      ; Check 2nd button on board
            ; todo
check_ib3:                                      ; Check 3rd button on board
            ; and so on
check_eb1:                                      ; Check 1st external button
            ; and so on
check_eb2:                                      ; Check 2nd external button

check_eb3:                                      ; Check 3rd external button

check_eb4:                                      ; Check 4th external button
            pop         r16                     ;
            reti                                ;
;------------------------------------------------------------------------------


texts:
I've got a quite simple WPF application, trying to implement a correct MVVM pattern.

The application in itself is simple: one listItem and one textbox + button for searching. On init, the entire content of a "large" (~50k to ~1million lines) file is loaded into the listItem. When the users enters text in textbox and clicks on the button, I go through the entire file and get the corresponding elements and refresh the listItem.

Right now, everything is fairly dirty, as you can see in the code below. I'm wondering how I can deal with this file. Should I keep everything in memory like I'm doing right now? Or should I reparse the file every time I need to? And how would all of this fit in MVVM pattern? I was thinking of a "Messages" class as a Model.

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.LoadConversation();
    }

    private MessagesProcessor _messageProcessor = new MessagesProcessor("c.txt");

    private void LoadConversation()
    {
        foreach (var msg in _messageProcessor.Messages)
        {
            ListBoxConversation.Items.Add(msg.ToString());
        }
    }

    private void onSearchBtnClick(object sender, RoutedEventArgs e)
    {
         var results = new List<Message>();
         results.AddRange(this._messageProcessor.GetSearchResults(word));
         foreach (var result in results.OrderBy(p => p.Date))
         {
                ListBoxConversation.Items.Add(result.ToString());
         }
    }
}

MessageProcessor.cs

 public class MessagesProcessor
 {
    private List<Message> _messages;

    public List<Message> Messages
    {
        get
        {
            return _messages;
        }
    }

    public MessagesProcessor(string pathOfBaseFile)
    {
        this._messages = ParseBaseMessageFile(pathOfBaseFile);
    }

    public IEnumerable<Message> GetSearchResults(string word)
    {
        return this._messages.Where(msg => msg.Content.Contains(word, StringComparison.OrdinalIgnoreCase));
    }
 }

Message.cs

public class Message
{
    public DateTime Date { get; set; }
    public string Content { get; set; }
    public string Author { get; set; }

    public override string ToString()
    {
        return "[" + this.Date.ToString("d") + " " + this.Date.ToString("t") + "]" + this.Author + " : " + this.Content;
    }
}


texts: Trying for an efficient and readable merge-sort implementation

texts:
My first implementation of merge sort in C++.
I'm looking for any sort of optimization and/or conventional practice tips, such as using the appropriate data types and naming my variables appropriately.
#include <iostream>

void print_array(int[], size_t);

void merge_sort(int[], size_t, size_t);

int main() {
    size_t size;

    std::cout << "Enter the size of the container: ";
    std::cin >> size;

    int arr[size];
    for (size_t i = 0; i < size; ++i) {
        std::cout << "[" << i+1 << "] Enter the next integer element: ";
        std::cin >> arr[i];
    }

    std::cout << std::endl << "Unsorted array: ";
    print_array(arr, size);
    std::cout << std::endl << std::endl;

    merge_sort(arr, 0, size-1);

    std::cout << "Sorted array: ";
    print_array(arr, size);
}

void print_array(int arr[], size_t size) {
    for (size_t i = 0; i < size; ++i) {
        std::cout << arr[i] << ' ';
    }
}

void merge_sort(int arr[], size_t start, size_t end) {
    if (end > start) {
        size_t middle = (start+end)/2;

        merge_sort(arr, start, middle);
        merge_sort(arr, middle+1, end);

        int l[middle-start+1];
        int r[end-middle];

        for (size_t i = start; i <= middle; ++i) {
            l[i-start] = arr[i];
        }

        for (size_t i = middle+1; i <= end; ++i) {
            r[i-(middle+1)] = arr[i];
        }

        size_t i = 0, j = 0, k = start;
        while (i < middle-start+1 && j < end-middle) {
            if (l[i] < r[j]) {
                arr[k] = l[i++];
            } else {
                arr[k] = r[j++];
            }
            ++k;
        }

        for (size_t z = i; z < middle-start+1; ++z) {
            arr[k] = l[z];
            ++k;
        }

        for (size_t z = j; z < end-middle; ++z) {
            arr[k] = r[z];
            ++k;
        }
    }
}


texts:
After doing some research on google i didn't find any good info on how to implement timeout with fetch (looks like there are multiple proposals but that's about it so nothing has implemented it). For what i'm doing i absolutely need i though. So i came up with simple solution that i would like a code review on.

        var responseReturned = false;
        var timedOut = false;

        fetch(url,
                    {
                        method: "post",
                        credentials: "same-origin"
                })
                .then((res) => {
                    responseReturned = true;
                    checkResponseStatus(res);
                })
        .then(function () {
            if (!timedOut) {
            //some screen logic
            }
         })
         .catch(function (ex) {
            if (!timedOut) {
             //handle errors
            }
         });

   setTimeout(() => {
     if (!responseReturned) {
        timedOut = true;
        spanSubmitErr.style.display = "inline";
     }
   }, 8000);

The issue we are having is with clients is the JavaScript is doing a HTTP Post to our servers. We have had some clients that their ISP was having connection issues so their networking equipment was dropping packets. We have had others that they lost connection so javascript never got a response from our servers. So what i'm trying to do is to say if the javascript doesn't receive a response back within 8 seconds that the page is going to assume something went wrong.


texts: Duplicating Rails model for a form with meta-programming

texts:
Can someone please review my code:

# dup/ish -> //github.com/rails/rails/issues/5449

class Form
  include Mongoid::Document

  attr_accessor :source

  def self.ish(prefix, suffix, &block)
    klass_name = prefix.classify + suffix

    dup.tap do |klass|
      klass.class_eval do
        define_singleton_method(:name) do
          prefix.classify
        end
      end

      klass.class_eval(&block)

      Object.const_set(klass_name, klass)
    end
  end

  def self.compose(klass_name, id, source)

    mongoid_translate = {:models => {}, :attributes => {}}

    form = ish(klass_name, id) do

      translate = {}

      source.flatten.each do |widget|
        if widget.include?('validate')
          validates *widget.values_at('name', 'validate')
          translate.store *widget.values_at('name', 'translate')
        end

        if widget.include?('name')
          if 'upload' == widget['type']
            has_many(:attachments)
            accepts_nested_attributes_for(:attachments)
          elsif 'repeat' == widget['type']
            part_klass = Form.compose(widget['name'], id, widget['parts'])
            embeds_many(widget['name'].pluralize, :class_name => part_klass.class.to_s)
            accepts_nested_attributes_for(widget['name'].pluralize)
          end
        end
      end

      mongoid_translate[:attributes][self.name.downcase.to_sym] = translate
    end

    I18n.backend.store_translations(:pt_BR, {:mongoid => mongoid_translate})

    form.new.tap do |form|
      form.source = source
    end
  end

  def prepare
    self.source.flatten.each do |widget|
      if widget.include?('name')
        if 'repeat' == widget['type']
          parts = send("#{widget['name'].pluralize}")

          if parts.empty?
            parts.build

            widget['parts'].each do |part|
              parts[0].write_attribute(part['name'], nil)
            end
          end
        elsif 'upload' == widget['type']
          attachments.build if attachments.empty?
        else
          begin
            send(widget['name'].to_sym)
          rescue NoMethodError
            write_attribute(widget['name'], nil)
          end
        end
      end
    end
  end
end


texts: Generate alternate saturday dates list within range in R

texts:
library(tidyr)
d = seq(as.Date("2018-01-01"),Sys.Date()+365,by='day')
saturdayList = d[weekdays(d)=='Saturday']

altSaturdayList = data.frame(lapply(split(saturdayList, format(saturdayList, "%Y-%m")), function(x)
  na.omit(x[c(2,4)])))

altSaturdayList = subset(gather(altSaturdayList),select = c(value))
HolidayList = rbind(HolidayList, setNames(altSaturdayList, "Holidays"))
HolidayList = rbind(HolidayList, setNames(as.data.frame(as.Date("2018-11-06")), "Holidays"))
HolidayList = arrange(unique(HolidayList),Holidays)

rm(d)
rm(saturdayList)
rm(altSaturdayList)

The above code generates a list of dates which contain 2nd and 4th saturday of every month within that date range.

As you can tell I have generated and deleted intermediate variables like d, saturdayList and altSaturdayList. I was wondering how I can make this code better and efficient?

I learned about %>% operator but I don't know how I can do it with no input.

Any tips to improve the code is welcomed. Thanks


texts: Running DNS lookup over million IP addresses

texts:
I need to run over all the IP addresses on the CIDR 10.96.0.0/12 network.
There are 1,048,574 IP addresses.
I created a multi threaded program in Go to do it, but even when I use 100 threads it takes lots of time (didn't check exactly but it is more than 10 minutes).
Is there are way I can do it more efficient?
By the way, on Windows it takes couple of minutes but I did also test on container in Linux and it took 40 seconds to scan 500K IP addresses. But let me know if you have faster way to check it.
My program:
package main

import (
    "fmt"
    "log"
    "net"
)

func getIPAddresses(cidr string) ([]string, error) {
    ip, ipnet, err := net.ParseCIDR(cidr)
    if err != nil {
        return nil, err
    }

    var ips []string
    for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
        ips = append(ips, ip.String())
    }
    // remove network address and broadcast address
    lenIPs := len(ips)
    var ipAddresses []string

    switch {
    case lenIPs < 2:
        ipAddresses = ips

    default:
        // Shouldn't be panic here because we are checking the lenIPs before
        ipAddresses = ips[1 : len(ips)-1]
    }

    return ipAddresses, nil
}

//  http://play.golang.org/p/m8TNTtygK0
func inc(ip net.IP) {
    for j := len(ip) - 1; j >= 0; j-- {
        ip[j]++
        if ip[j] > 0 {
            break
        }
    }
}

func main() {
    ipAddresses, err := getIPAddresses("10.96.0.0/12")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("[*] Scanning %d IP addresses\n", len(ipAddresses))

    //var hostsMap map[string][]string
    //l := sync.Mutex{}
    threads := 100
    sem := make(chan bool, threads)

    count := 0
    for _, ip := range(ipAddresses) {

        sem <- true

        go func(ip string) {
            count += 1
            if count % 1000 == 0 {
                fmt.Printf("Scan: %d addresses\n", count)
            }
            _, err := net.LookupAddr(ip)
            if err != nil {
                //log.Fatal(err)
                //fmt.Println("Error")
            }

            <- sem
        }(ip)
    }

    for i := 0; i < cap(sem); i++ {
        sem <- true
    }

    fmt.Println("DONE")
}