texts: Conditionally set attributes in MongoDB based on form fields

texts:
I have code which gets data from a POST request (request.form dict), compares with corresponding attribute in object accident and does some action. The code looks needlessly verbose.  How can I optimize it?

if accident.status == 1:
    if request.form.get('reason') \
        and request.form['reason'] != accident.reason:
        accident.set_reason(request.form['reason'], current_user)
    if request.form.get('note') \
        and request.form['note'] != accident.note:
        accident.note = request.form['note']
else:
    if request.form.get('priority') \
        and int(request.form['priority']) != accident.priority:
        accident.set_priority(current_user, int(request.form['priority']))
    if request.form.get('status') \
        and int(request.form['status']) != accident.status:
        accident.set_status(current_user, int(request.form['status']))
    if request.form.get('duration') \
        and int(request.form['duration']) != accident.duration:
        accident.duration = int(request.form['duration'])
    if request.form.get('service_status') \
        and int(request.form['service_status']) != accident.service_status:
        accident.set_service_status(int(request.form['service_status']))

Below is a stripped down version of Accident class, which is inconsistent because there are many fields, and sometimes setting a field requires many additional actions like logging or checking for user rights. The class derives from MongoEngine schema class.

class Accident(Document):
    priority = IntField(choices=PRIORITIES)
    status = IntField(choices=STATUSES, default=0)
    duration = IntField()
    region = StringField()
    service_status = IntField(choices=(0, 1, 2))
    reason = StringField(default=u"")
    note = StringField(default=u"")

    def set_priority(self, user=None, priority=None):
        self.priority = priority
        # Functions starting with `set_` do some activity that has
        # nothing to do with setting and validating a value. That's
        # why i don't use @property decorator. `to_history(user)` is
        # just an example.
        to_history(user)

    def set_status(self, user, status):
        self.status = status
        to_history(user)

    def set_reason(self, reason, user):
        self.reason = reason
        to_history(user)

    def set_service_status(self, ss):
        self.service_status = ss
        to_history(user)

If this is necessary, how can i improve class structure? It seems like I can't use @property decorator for setters, because my setters accept additional parameters. However I don't like the idea of writing a setter for all possible attributes. I use request.form.get(foo) instead of foo in request.form, because the dictionary may contain foo: None pair, and I don't want to accidentally set an attribute to None.


texts: List all possible numbers from a given array that sums up to a given number

texts:
I have to solve the following problem: Given an array of integers and given an integer value, list all possible numbers frm the array that sums up to the given value.

Example:

Input: array = {1, 2, 2, 3, 4, 5}, int N = 5
Output: {1, 2, 2}, {1, 4}, {5} {2, 3}.

This is my solution:

import java.util.ArrayList;
public class SubSum {
    static ArrayList<ArrayList<Integer>> res;
    public static void main(String[] args) {
        int arr[] = {1, 2, 2, 3, 4, 5};
        int N = 5;
        solve(arr, N);
        for (int i = 0; i < res.size(); i++) {
            for (int j = 0; j < res.get(i).size(); j++) {
                System.out.print(res.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }

    private static void solve(int[] arr, int n) {
        ArrayList<Integer> curr = new ArrayList<Integer>();
        int tmp = 0;
        int currPostion;
        helper(arr, n, tmp, curr, 0);
    }

    private static void helper(int[] arr, int n,
            int tmp, ArrayList<Integer> curr, int currPosition) {
        while(currPosition < arr.length){
            if(tmp == n){
                res.add(curr);
                int lastIndex = curr.size()-1;
                int lastEl = curr.remove(lastIndex);
                helper(arr, n, tmp-lastEl, curr, currPosition+1);

            }
            else{
                if((arr[currPosition] <= n) && (arr[currPosition] + tmp <= n)){
                    curr.add(arr[currPosition]);
                    helper(arr, n, tmp+arr[currPosition], curr, currPosition+1);
                }
                if((arr[currPosition] <= n) && (arr[currPosition] + tmp > n)){
                    helper(arr, n, tmp, curr, currPosition+1);
                    if(curr.size() >= 1){
                        int lastIndex = curr.size()-1;
                        int lastEl = curr.remove(lastIndex);
                        helper(arr, n, tmp-lastEl, curr, currPosition+1);
                    }
                }
            }
        }
    }
}

I couldn't come up with something faster than exhaustive search. Is this the best possible approach? Also any comments about the code are welcome. I don't like it much, since it looks more like functional programming than object oriented, but I don't know how to improve in this direction.


texts: Weekly job to create or update the lessons in all locations

texts:
I'm working in a project with the following structure.

A location can have many timetables with many lessons.

I need to perform a job in all locations every sunday to create or update the lessons.

def perform(*args)
    locations = Location.all
    locations.each do |location|
      timetables = LocationLessonService.fetch(location.id)["timetables"]
      timetables.each do |timetable|
        lessons = timetable["lessons"]
        lessons.each do |lesson|
          Lesson.find_or_initialize_by(external_id: lesson['external_id'])
            .update_attributes(period.merge(location_id: location.id))
        end
      end
    end
  end

Is it possible to remove this nested iteration?Is it possible to optimize this function using the gem virtus or something else?


texts:
I developed a Chinese Poker game for better understanding classes in Python. It is not finished yet, but the main part is.

The game mechanics:

There is 1 board for each player. Each board have 3 rows.
The first row can receive up to 3 cards, and the other 2, 5 cards each. A total of 13 cards in each board
First, each player receive 5 cards and then place then within the boards. Player1 place all his cards, and then Player2 place all his cards.
After that, each player receive 3 cards per turn. Place 2 cards in the boards, and discard the last one. Cards are dealed until the board is full.

My code executes them and the score system is the next step. I'd like you to evaluate my code and point suggestions to improve it.

from random import shuffle

def turn_str(n):
    return '%d' % n

deck =  (map(turn_str, range(2,11)) + ['J', 'Q', 'K', 'A']) * 4
deck.sort()

naipes = ['c', 'h', 's', 'd'] * 13

def add_suits(x, y):
    return x + y

full_deck = map(add_suits, deck, naipes)
shuffle(full_deck)

class User(object):
    def __init__ (self, name):
        self.name = name
        self.board = [[],[],[]]
        self.hand = []

    def receive_cards(self, number_of_cards):
        self.hand = full_deck[0:number_of_cards]
        del full_deck[0:number_of_cards]

    def board_limit(self, board_number):
        if board_number == 1:
            if len(self.board[board_number - 1]) < 3:
                return True
            else:
                return False
        if board_number == 2 or board_number == 3:
            if len(self.board[board_number - 1]) < 5:
                return True
            else:
                return False

    def place_first_cards(self):
        print "Your time to play %s. Here is your hand. Pick a card and choose a row to place it" % self.name
        while len(self.hand) != 0:
            print '-'.join(self.hand)
            for i in self.board:
                print i
            card_placed = int(raw_input("Choose a card (1 - %d): " % len(self.hand)))
            chosen_board = int(raw_input("Choose a board (1-3): "))
            if self.board_limit(chosen_board):
                self.board[chosen_board - 1].append(self.hand[card_placed - 1])
                self.hand.pop(card_placed - 1)
            else:
                print "The board is full. Choose another one."

    def place_cards(self):
        print "Your time to play %s. Here is your hand. Pick a card and choose a row to place it" % self.name
        while len(self.hand) != 1:
            print '-'.join(self.hand)
            for i in self.board:
                print i
            card_placed = int(raw_input("Choose a card (1 - %d): " % len(self.hand)))
            chosen_board = int(raw_input("Choose a board (1-3): "))
            if self.board_limit(chosen_board):
                self.board[chosen_board - 1].append(self.hand[card_placed - 1])
                self.hand.pop(card_placed - 1)
            else:
                print "The board is full. Choose another one."
        self.hand.pop(0)

player1 = raw_input("Player 1, type your nickname: ")
player2 = raw_input("Player 2, type your nickname: ")

user1 = User(player1)
user2 = User(player2)

print "Welcome. %s you will play against %s. Good luck for both of you." % (user1.name, user2.name)

user1.receive_cards(5)
user2.receive_cards(5)

user1.place_first_cards()
user2.place_first_cards()

user1.receive_cards(3)
user2.receive_cards(3)

user1.place_cards()
user2.place_cards()

user1.receive_cards(3)
user2.receive_cards(3)

user1.place_cards()
user2.place_cards()

user1.receive_cards(3)
user2.receive_cards(3)

user1.place_cards()
user2.place_cards()

user1.receive_cards(3)
user2.receive_cards(3)

print user1.board
print user2.board


texts:
I'm just getting started with F# and was writing some unit tests for some functionality I had written. In the interest of brevity, I decided to create some lists of the different test cases and just run through them all in one test instead of creating separate test methods for each one (I'm not focusing on that design decision here, just pointing it out as otherwise my question won't make much sense).

So here's my code:

// simple helper to cut down on repeated code
let testRunner cases func =
    cases |> List.map func

// isNumeric is the function under test, its functionality should be obvious
[<Test>]
let ``IsNumericTest``() =
    let testCases = ["123"; "Foo"; "123Foo123"]
    let expectedResults = [true; false; false]
    let results = testRunner testCases isNumeric
    results |> should equal expectedResults

I started thinking about creating a simple type to encapsulate the test case input and the expected result, something like this:

type TestCase = { Input : string; ExpectedResult : bool}

type TestCases = TestCase list

let testCases = [{Input="123"; ExpectedResult=true};{Input="Foo"; ExpectedResult=false}; {Input="123Foo123"; ExpectedResult=false}]

Then I struggled to think of how to split each of those down to use in my testRunner method until I came up with this:

let results = testRunner (testCases |> List.map (fun (T) -> T.Input)) isNumeric
results |> should equal (testCases |> List.map (fun (T) -> T.ExpectedResult))

But that just looks ugly. Is there a better way to split out the Input value for my testRunner method? I am fine with changing it, but figured that while my question is specific to a unit testing scenario, the lessons I should learn would be widely applicable.


texts:
I'm posting a solution for LeetCode's "Encode and Decode TinyURL". If you'd like to review, please do. Thank you!
Problem
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Code

// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <utility>
#include <random>

static const struct Solution {
    public:
        const std::string encode(
            const std::string long_url
        ) {
            std::string tiny_encoded;

            if (!encoded_url.count(long_url)) {
                for (auto index = 0; index < kTinySize; ++index) {
                    tiny_encoded.push_back(char_pool[rand_generator() % std::size(char_pool)]);
                }

                encoded_url.insert(std::pair<std::string, std::string>(long_url, tiny_encoded));
                decoded_url.insert(std::pair<std::string, std::string>(tiny_encoded, long_url));

            } else {
                tiny_encoded = encoded_url[long_url];
            }

            return kDomain + tiny_encoded;
        }

        const std::string decode(
            const std::string short_url
        ) {

            return std::size(short_url) != kDomainTinySize ||
                   !decoded_url.count(short_url.substr(kDomainSize, kTinySize)) ? "" :
                   decoded_url[short_url.substr(kDomainSize, kTinySize)];
        }

    private:
        static constexpr char kDomain[] = "http://tinyurl.com/";
        static constexpr unsigned int kTinySize = 6;
        static constexpr unsigned int kDomainSize = std::size(kDomain) - 1;
        static constexpr auto kDomainTinySize = kDomainSize + kTinySize;
        static constexpr char char_pool[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        std::unordered_map<std::string, std::string> encoded_url;
        std::unordered_map<std::string, std::string> decoded_url;
        std::random_device rand_generator;
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));


texts: Extracting performance statistics from FTP session transcript

texts:
I've borrowed and written the following code to output the disconnect time. All works well but I'm curious as to how I could tighten/ shorten the code. If anyone feels like having some fun then I'd love to see what can be done. Be a learning lesson for me.

Excerpt of input:

ftp> !:--- FTP commands below here ---
ftp> lcd C:\Utilities\Performance_Testing\
\Utilities\Performance_Testing\: File not found
Verbose mode On .
ftp> verbose
binary
200 Switching to Binary mode.
ftp> put "test_file_5M.bin"
200 PORT command successful.
150 Ok to send data.
226 File receive OK.
ftp: 5242880 bytes sent in Seconds Kbytes/sec.
ftp> 44.81117.00disconnect
221 Goodbye.
ftp> bye

Code:

#Obtain UT external put value.
ut1intput=$(awk '
  NR==70 {
    for(i=1;i<=NF;i++) {
      if($i=="ftp>") {
        sub(/disconnect/, "", $(i+1));
        print $(i+1)
      }
    }
  }' filename.txt)

utintputvalue=`echo $ut1intput | awk -F. '{print $2"."$3}'| sed  's/^..//'`

Output:

utintputvalue is 117.00


texts: Stack implementation in C++ including min(), max() functions in O(1)

texts:
This implementation seems to work. I would love to get any suggestions / comments on how this code could be improved. Are there any potential memory management issues? Any additional methods that would be useful (also, from educational point of view) to implement? Thank you!

Stack.hpp

#ifndef STACK_H
#define STACK_H

#include <iostream>
#include <memory>
#include <vector>
#include <stdexcept>

class Stack {

private:
    struct Node {
        int val;
        // To get min and max value of stack in O(1):
        int maxVal = std::numeric_limits<int>::min();
        int minVal = std::numeric_limits<int>::max();
    };

    std::vector<Node> currStack;

public:

    int size() const { return currStack.size(); }
    bool empty() const { return currStack.empty(); }
    void pop() { currStack.pop_back(); }

    void push(int val);
    int top() const; // O(1)
    int min() const; // O(1)
    int max() const; // O(1)

};

#endif /* STACK_H */

Stack.cpp

#include "Stack.hpp"

void Stack::push(int val) {

    Node tempNode;
    tempNode.val = val;
    if (this->empty()) {
        tempNode.minVal = val;
        tempNode.maxVal = val;
    } else {
        tempNode.minVal = std::min(currStack.back().minVal, val);
        tempNode.maxVal = std::max(currStack.back().maxVal, val);
    }

    currStack.push_back(tempNode);
}

int Stack::top() const {
    if (currStack.empty()) {
        throw std::out_of_range ("Stack is empty");
    }
    return currStack.back().val;
}

int Stack::min() const {
    if (currStack.empty()) {
        throw std::out_of_range ("Stack is empty");
    }
    return currStack.back().minVal;
}

int Stack::max() const {
    if (currStack.empty()) {
        throw std::out_of_range ("Stack is empty");
    }
    return currStack.back().maxVal;
}

main.cpp

#include "Stack.hpp"

int main() {

    // Stack init
    Stack myStack;

    std::cout << "Empty? " << myStack.empty() << "\n";
    std::cout << "Size: " << myStack.size() << "\n";

    try {
        std::cout << "Top: " << myStack.top() << "\n";
        std::cout << "Min: " << myStack.min() << "\n";
        std::cout << "Max: " << myStack.max() << "\n";
    }
    catch (const std::out_of_range& e) {
        std::cout << "Out of range error. " << e.what() << "\n";
    }

    std::cout << "Push some integers: \n";
    myStack.push(5);
    myStack.push(3);
    myStack.push(7);

    std::cout << "Empty? " << myStack.empty() << "\n";
    std::cout << "Size: " << myStack.size() << "\n";

    try {
        std::cout << "Top: " << myStack.top() << "\n";
        std::cout << "Min: " << myStack.min() << "\n";
        std::cout << "Max: " << myStack.max() << "\n";
    }
    catch (const std::out_of_range& e) {
        std::cout << "Out of range error. " << e.what() << "\n";
    }

    std::cout << "Pop some integers: \n";
    myStack.pop();

    std::cout << "Empty? " << myStack.empty() << "\n";
    std::cout << "Size: " << myStack.size() << "\n";

    try {
        std::cout << "Top: " << myStack.top() << "\n";
        std::cout << "Min: " << myStack.min() << "\n";
        std::cout << "Max: " << myStack.max() << "\n";
    }
    catch (const std::out_of_range& e) {
        std::cout << "Out of range error. " << e.what() << "\n";
    }
}


texts:
I have three tables for a blog system.

The blog

CREATE TABLE IF NOT EXISTS lm_blog(
        blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        title VARCHAR(80) NOT NULL UNIQUE,
        action VARCHAR(80) NOT NULL UNIQUE INDEX,
        url VARCHAR(80) NOT NULL UNIQUE,
        summary VARCHAR (255) NOT NULL,
        article TEXT NOT NULL,
        created DATE NOT NULL,
        updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        publish TINYINT UNSIGNED DEFAULT 0,
        PRIMARY KEY(blog_id));

The tags

CREATE TABLE IF NOT EXISTS lm_blog_tags(
        tag_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        tag VARCHAR(32) NOT NULL UNIQUE INDEX,
        description TEXT,
        PRIMARY KEY(tag_id)
    );

And the relationships

CREATE TABLE IF NOT EXISTS lm_blog_tag_relationships(
        blog_id INT UNSIGNED NOT NULL,
        tag_id INT UNSIGNED NOT NULL,
        PRIMARY KEY(blog_id, tag_id),
        FOREIGN KEY (blog_id) REFERENCES lm_blog(blog_id),
        FOREIGN KEY (tag_id) REFERENCES lm_blog_tags(tag_id)
    );

I want to search for blogs by a tag name and have all the tags for that blog. I am currently using GROUP_CONCAT to group the tags and filter it with a HAVING LIKE clause.

I.E to search for aticles with a PHP tag

SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T3.tag SEPARATOR ':') AS tags
FROM  lm_blog_tag_relationships AS T1
INNER JOIN lm_blog AS T2 ON T1.blog_id = T2.blog_id
INNER JOIN lm_blog_tags AS T3 ON T1.tag_id = T3.tag_id
GROUP BY T2.blog_id
HAVING tags   LIKE '%:PHP:%' OR tags LIKE '%:PHP' OR tags LIKE 'PHP:%'
ORDER BY T2.blog_id DESC

I'm assuming there is a better way to get the same results.


texts: Tracking the number of string elements using std::unordered_map

texts:
I'm looking for the most simple and efficient way to track the number of string elements in a container.

Previously, I used std::vector but I tried changing the container to std::unordered_map since I hear that it can be easier and more performant for my use.

My Code :

#include <iostream>
#include <string>
#include <unordered_map>

class Table
{
public:
    void insert(const std::string &name)
    {
        auto it = data.find(name);
        if (it == data.end())
        {
            data[name] = 1;
            return;
        }
        data[name]++;
    }
    void remove(const std::string &name)
    {
        auto it = data.find(name);
        if (it == data.end())
            return;
        if (--data[name] == 0)
            data.erase(it);
    }
    /* get the number of occurrences */
    int count(const std::string &name)
    {
        auto it = data.find(name);
        if (it == data.end())
            return 0;
        return data[name];
    }
private:
    std::unordered_map<std::string, int> data;
};

int main()
{
    Table table;
    table.insert("Apple");
    table.insert("Apple");
    table.insert("Orange");
    table.insert("Orange");
    table.remove("Orange");
    std::cout << "Number of Apples : " << table.count("Apple") << std::endl;
    std::cout << "Number of Oranges : " << table.count("Orange") << std::endl;
    std::cout << "Number of Lemons : " << table.count("Lemon") << std::endl;
}

The Result :

Number of Apples : 2
Number of Oranges : 1
Number of Lemons : 0
Program ended with exit code: 0

Is there a way to improve the class Table so my program can be more efficient than now?

The program seems to work but I used std::unordered_map for the first time so I'm not really sure if my implementation is correctly done.


texts:
Below is a piece of code that is responsible for serializing files.
ZL_LIST and PERS_LIST are XML file structs, I have not shown them here to save space.

Please check my code.

package parser

import (
    "encoding/xml"
    "fmt"
    "golang.org/x/text/encoding/charmap"
    "io"
    "io/ioutil"
    "os"
    "path/filepath"
    "sync"
)

type Files struct {
   Name          string
   PathZipFile   string
   PathUnzipFile string
}

type nameMap map[string]bool

func (ZL_LIST) Parse(FilesName []*Files) {
    unzipPath, err := filepath.Abs("tmp")

    files, err := ioutil.ReadDir(unzipPath)
    f := make([]*Files, 0)
    for _, file := range files {
        fileZip := new(Files)
        if !file.IsDir() && file.Name()[:1] != "." {
            fileZip.Name = file.Name()
            fileZip.PathUnzipFile = filepath.Join(unzipPath, file.Name())
            f = append(f, fileZip)
        }
    }

    if err != nil {
        fmt.Printf("[ERROR] Error retrieving files %v", err)
    }

    names := make(nameMap, 1)
    var wg sync.WaitGroup
    var countHmLmFiles int = -1
    var countHmFiles int = 0
    var countLmFiles int = 0
    var file *Files
    for countHmLmFiles, file = range f {
        wg.Add(1)
        go func(filename *Files) {
            parseHmLm(filename, &countHmFiles, &countLmFiles, &names)
            wg.Done()
        }(file)
    }
    wg.Wait()

    fmt.Printf("[INFO] Read %d files from them  HM files %d and LM files %d ", countHmLmFiles+1, countHmFiles, countLmFiles)
}

func parseHmLm(filename *Files, countHmFiles *int, countLmFiles *int, names *nameMap) {
    fmt.Println("[INFO] считывается файл ", filename.Name, " с заголовком ", filename.Name[:2])
    xmlFile, err := os.Open(filepath.Join(filename.PathUnzipFile))
    if err != nil {
        fmt.Printf("[ERROR] Cannot open file %e \n", err)
    }

    defer xmlFile.Close()

    switch filename.Name[:2] {
    case "HM":
        (*names)[filename.Name] = true
        (*countHmFiles) += 1
        var hFile ZL_LIST
        decoder := xml.NewDecoder(xmlFile)
        decoder.CharsetReader =  charset
        err := decoder.Decode(&hFile)
        if err != nil {
            fmt.Errorf("[ERROR] Cannot decode file %e", err)
        }
    case "LM":
        (*countLmFiles) += 1
        var lFile PERS_LIST
        decoder := xml.NewDecoder(xmlFile)
        decoder.CharsetReader = charset
        err := decoder.Decode(&lFile)
        if err != nil {
            fmt.Errorf("[ERROR] Cannot decode file %e", err)
        }
    }

}

func charset(charset string, input io.Reader) (io.Reader, error) {
    switch charset {
    case "windows-1251":
        return charmap.Windows1251.NewDecoder().Reader(input), nil
    default:
        return nil, fmt.Errorf("unknown charset: %s", charset)
    }
}

Calling function

package api
    import (
    "net/http"
    "github.com/go-chi/render"
    "../../store/parser"
    "fmt"
    "path/filepath"
)
    func (s *Rest) parse(w http.ResponseWriter, r *http.Request) {
        uploadPath, err := filepath.Abs("./upload/")
        if err != nil {
            fmt.Printf("[ERROR] can not find the specified path %e", err)
        }
        unzipPath, err := filepath.Abs("./tmp")
        if err != nil {
            fmt.Printf("[ERROR] can not find the specified path %e", err)
        }
        p := parser.Files{}
        filesName := p.GetFileName(uploadPath, unzipPath)
            p.UnzipFiles(filesName, unzipPath)
        ...
        ...


texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

  A simple rule to estimate your ideal body weight is to allow 110 pounds for the first 5 feet of height and 5 pounds for each additional inch. Write a program with a variable for the height of a person in feet and another variable for the additional inches. Assume the person is at least 5 feet tall. For example, a person that is 6 feet and 3 inches tall would be represented with a variable that stores the number 6 and another variable that stores the number 3. Based on these values, calculate and output the ideal body weight.

This is the code that I have written:

 public class Question9 {

    private static final int INCH_PER_FEET = 12;
    private static final int POUND_PER_INCH = 5;
    private static final int MIN_HEIGHT_FEET = 5;
    private static final int MIN_WEIGHT_POUND = 110;

    public static void main(String[] args) {

        int feet = 6;
        int inches = 3;

        System.out.println(idealBodyWeight(feet, inches) + " pounds");
    }

    private static int idealBodyWeight(int feet, int inches) {
        int pounds = MIN_WEIGHT_POUND;

        if ((feet > MIN_HEIGHT_FEET)) {

            inches += (feet - MIN_HEIGHT_FEET) * INCH_PER_FEET;
        }

        pounds += inches * POUND_PER_INCH;

        return pounds;
    }
}


texts:
My code does a DFS on the given graph and prints all possible paths for a given start and end node. My question is how can this be improved?

Can some form of memoization be used here? There are cases where a path from a certain source - destination is already found and will be an intermediate path for a different source - destination but it is still computed again.
As it is a generator will that make memoization different?
Is there an already existing text book algorithm that I am missing? Does not have to be specifically DFS.
Pythonic / Idiomatic code suggestions are also welcome.

This is my code
from itertools import product

def find_path(g, src, dst):
    """Prints all possible path for a graph `g` for all pairs in `src` and `dst`

    Args:
        g (list): 2d list, graph
        src (list): list of nodes that will be the source
        dst (list): list of nodes that will be the destination
    """

    graph = {}

    # constructing a graph
    for from_, to_ in g:
        graph.setdefault(from_, set()).add(to_)
        graph.setdefault(to_, set()).add(from_) # undirected

    def dfs(src, dst, path, seen):
        """Recursive generator that yields all paths from `src` to `dst`

        Args:
            src (int): source node
            dst (int): destination node
            path (list): path so far
            seen (set): set of visited nodes

        Yields:
            list: all paths from `src` to `dst`
        """
        if src in seen:
            return

        if src == dst:
            yield path + [src]
            return

        seen.add(src)

        for i in graph.get(src, []):
            yield from dfs(i, dst, path + [src], seen)
        seen.remove(src)

    # start finding path for all `src` `dst` pairs
    for source, destination in product(src, dst):
        print(source, destination, list(dfs(source, destination, [], set())))

g = list(product(range(1, 5), repeat=2)) # a graph for testing purpose
src = dst = range(1, 5) # source and destination, in actual code this will be a list
find_path(g, src, dst)


texts:
I am building an application that opens Wireshark services (Wireshark has several services) in order to to different things on Wireshark files like edit, change format, statistics, etc. Each option usually uses a different service, so I want to build my classes with inheritance.

I was wondering if what I want to do is appropriate.

Main class WiresharkServices with the following members and methods:

public class WiresharkProcesses
{
    protected string _filePath; //the file path who send to Wiresahrk process
    protected string _capinfos;
    protected string _dumpcap;
    protected string _editcap;
    protected string _mergecap;
    protected string _rawshark;
    protected string _text2pcap;
    protected string _tshark;
    protected string _wireshark;

    public void initializeServices()
    {
        if (Directory.Exists(@"C:\Program Files (x86)\Wireshark"))
        {
            _capinfos = @"C:\Program Files (x86)\Wireshark\_capinfos.exe";
            _dumpcap = @"C:\Program Files (x86)\Wireshark\_dumpcap.exe";
            _editcap = @"C:\Program Files (x86)\Wireshark\editcap.exe";
            _mergecap = @"C:\Program Files (x86)\Wireshark\_mergecap.exe";
            _rawshark = @"C:\Program Files (x86)\Wireshark\_rawshark.exe";
            _text2pcap = @"C:\Program Files (x86)\Wireshark\_text2pcap.exe";
            _tshark = @"C:\Program Files (x86)\Wireshark\_tshark.exe";
            _wireshark = @"C:\Program Files (x86)\Wireshark\_wireshark.exe";
        }
        else if (Directory.Exists(@"C:\Program Files\Wireshark"))
        {
            _capinfos = @"C:\Program File)\Wireshark\_capinfos.exe";
            _dumpcap = @"C:\Program Files\Wireshark\_dumpcap.exe";
            _editcap = @"C:\Program Files\Wireshark\editcap.exe";
            _mergecap = @"C:\Program Files\Wireshark\_mergecap.exe";
            _rawshark = @"C:\Program Files\Wireshark\_rawshark.exe";
            _text2pcap = @"C:\Program Files\Wireshark\_text2pcap.exe";
            _tshark = @"C:\Program Files\Wireshark\_tshark.exe";
            _wireshark = @"C:\Program Files\Wireshark\_wireshark.exe";
        }
    }
}

When the application is running, I am of course checking if Wireshark is installed on the machine. If not, I throw an exception:

WiresharkServices wservices = new WiresharkServices();
wservices .initializeServices();

and in each class its own methods.

Child class example which receives a file path to convert it to another Wireshark format:

public class Editcap : WiresharkProcesses
{
    private string _newFileName;

    public void startProcess(string filePath)
    {
        FileInfo file = new FileInfo(filePath);
        _newFileName = file.FullName.Replace(file.Extension, "_new") + ".pcap";
        ProcessStartInfo editcapProcess = new ProcessStartInfo(string.Format("\"{0}\"", _editcap))
        {
            Arguments = string.Format("{2}{0}{2} -F libpcap {2}{1}{2}", file.FullName, _newFileName, "\""),
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
            UseShellExecute = false,
            ErrorDialog = false
        };

        using (Process editcap = Process.Start(editcapProcess))
        {
            editcap.WaitForExit();
        }
    }

    public string getNewFileName()
    {
        return _newFileName;
    }
}


texts:
I have an assignment as follows:

  Write a program which reads from the keyboard two integers n and m,
  and a character c from the keyboard. This program should deﬁne and
  call a function:
  print rectangle(n, m, c) which prints a rectangle of
  size n x m consisting of the character c

My solution is:

n=int(input("Enter the lenght of the rectangle: "))
m=int(input("Enter the width: "))
c="c"
def print_rect(n, m, c):
    for a in range(m):
        print (n*c)
print_rect(n, m, c)
input("Press enter to close")

I am sure there are alternative ways to do this assignment. How would you code this assignment? Do you think my solution is OK?


texts: Representation graph as Adjacency List in JavaScript

texts:
I feel quite slow in the understanding of graph representations. So, please, I'd like you to verify that I did understand, at least, the Adjacency List correctly.

So here I'm trying to implement unweighted graph, that supports parallel edges. Whether graph is directed or not, I don't understand how that might affect an implementation, as I will still add edges by pair (start, end) in any case.

-- Update:

To be more specific, I'd like to get a review, of possible problems that my implementation might have, eg:

1) extra operations

2) extra memory

3) incorrect data structure

... and so on, thank you.

--

Here is my code in JavaScript:

1) data format. Below, in the implementation, you'll see a util formatDataToAdjacencyList. Just assume that it returns such shape of the data (from tests):

const result = formatDataToAdjacencyList(data)

            expect(result).toEqual({
                edges: [
                    ['0', '4'],
                    ['1', '2'],
                    ['1', '3'],
                    ['1', '4'],
                    ['2', '3'],
                    ['3', '4'],
                    ['3', '3'],
                    ['0', '1'],
                    ['1', '2'],
                    ['2', '0'],
                ],
                vertices: [
                    '0',
                    '4',
                    '1',
                    '2',
                    '3',
                ]
            })

2) implementation

function GraphAdjacencyList(data) {
    if (data) {
        const formattedData = formatDataToAdjacencyList(data)
        this.adjacencyList = formattedData.edges
        this.vertices = formattedData.vertices
    } else {
        this.adjacencyList = []
        this.vertices = []
    }
}

GraphAdjacencyList.prototype.addVertex = function(nodeLabel) {
    if (this.vertices.indexOf(nodeLabel) !== -1) {
        throw new Error('vertex already exist')
    }

    this.vertices.push(nodeLabel)
}

GraphAdjacencyList.prototype.removeVertex = function(nodeLabel) {
    const index = this.vertices.indexOf(nodeLabel);

    if (index === -1) {
        throw new Error('vertex not found')
    }

    this.vertices.splice(index, 1)
}

GraphAdjacencyList.prototype.addEdge = function(startLabel, endLabel) {
    this.adjacencyList.push([startLabel, endLabel])
}

GraphAdjacencyList.prototype.removeEdge = function(inputStartLabel, inputEndLabel) {
    const index = this.adjacencyList.findIndex(([startLabel, endLabel]) => {
        return startLabel === inputStartLabel || endLabel === inputEndLabel
    })

    if (index === -1) {
        throw new Error('edge doesn\'t exist')
    }

    this.adjacencyList.splice(index, 1)
}
```


texts: Print the lexicographically smallest permutation that satisfies the given formation

texts:
Problem Statement:

  A DOTA game has N heroes, each with a distinct rank from [1..N]. In
  DOTA every formation is characterized as a permutation [1...N] of
  ranks of players.  A formation is Imba when the sum of ranks of every
  two consecutive players is less than or equal to (N+1). Given N, you
  are to print the lexicographically smallest permutation of ranks
  [1...N] that makes the formation Imba.

  Input Format

  The first line will contain an integer T, i.e. the number of the test
  cases followed by T lines, each containing the value of N.

  Constraints

  \$1 \le T \le 5\$
  \$2 \le N \le 105\$

  Output Format

  \$T\$ lines each containing the permutation; the numbers in each line
  should be seperated by a single space.

  Sample Input

2
2
3

  Sample Output

1 2
2 1 3

  Explanation

  In the first case there are two possible permutations [1,2] and [2,1].
  Both of the given permutations satisfy the given constraints and [1,2]
  is lexicographically smaller than [2,1].  In the second case, the two
  possible permutations are [2,1,3] and [3,1,2], of which the former is
  lexicographically smaller.

Is there a more efficient way to go about doing this?

from itertools import permutations
def check_condition(perm,checksum):
    for i in range(len(perm)-1):
        if perm[i] + perm[i+1] <= checksum:
            continue
        else:
            return False
    return True
testcases = int(raw_input())
current = 1
while current <= testcases:
    max_ = int(raw_input())
    checksum = max_ + 1
    list_ = range(1,max_+1)
    for perm in permutations(list_):
        #print(perm)
        if check_condition(perm,checksum):
            print(" ".join(map(str,perm)))
            break
    current += 1


texts:
I wrote a basic menu application for my intro to python. I'm fairly new, and python does look promising.

the_burger = 16.99;
french_fries = 5.99;
currie_sauce = 19.99;
napkins_with_chocolates = 10.50;
juice_box = 89.01;
takeout = 18.99;
total = 0.0;
DONE = False
print("""
+-------------------------------------------+
| The Restaurant at the End of the Universe |
+---------------------------------+---------+
| A\tThe "Big Boy" Burger      | $""" + str(the_burger) + """  |
+---------------------------------+---------+
| B\tFrench Fries              | $""" + str(french_fries) + """   |
+---------------------------------+---------+
| C\tCurrie sauce              | $""" + str(currie_sauce) + """  |
+---------------------------------+---------+
| D\tNapkins with Chocolates   | $""" + str(napkins_with_chocolates) + str(0) + """  |
+---------------------------------+---------+
| E\tJuice Box                 | $""" + str(juice_box) + """  |
+---------------------------------+---------+
| F\tTakeout                   | $""" + str(takeout) + """  |
+---------------------------------+---------+
""");
while(not DONE):
  print("Total:", total);
  Item = input("Select a letter or 'done': ");
  if Item is "A":
    total += the_burger;
  elif Item is "B":
    total += french_fries;
  elif Item is "C":
    total += currie_sauce;
  elif Item is "D":
    total += napkins_with_chocolates;
  elif Item is "E":
    total += juice_box;
  elif Item is "F":
    total += takeout;
  elif Item is "done":
    print("Final total:", total);
    DONE = True


texts:
This code is written in a SSIS Script Component that basically accomplishes what I previously had as a T-SQL script, that was reviewed here.

I need to split a 80 character string that contains 20 buckets of 4 characters each, without any delimiter, and generate a new row for each bucket. I'm using a script component to achieve this in SSIS - here's the code:

using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;

[SSISScriptComponentEntryPoint]
public class ScriptMain : UserComponent
{
    /// <summary>
    /// This code splits a row's [Sizes] column into buckets of 4 characters,
    /// and adds a new row to the output buffer for each non-empty bucket found.
    /// </summary>
    /// <param name="Row">The row that is currently passing through the component</param>
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        var buckets = Regex.Match(Row.Sizes, "^(?<bucket>.{4})+$")
                           .Groups["bucket"].Captures
                           .Cast<Capture>()
                           .Select(capture => capture.Value)
                           .ToArray();
        try
        {
            for (int index = 0; index < buckets.Length; index++)
            {
                var bucket = buckets[index].Trim();
                if (bucket.Contains(' '))
                {
                    // size codes don't contain whitespaces; something went really wrong if that's the case:
                    throw new FormatException("Size code '" + bucket +"' contains a whitespace. This is interpreted as a parse error.");
                }

                if (string.IsNullOrEmpty(bucket))
                {
                    // don't output a row for empty buckets
                    continue;
                }

                OutputSizesBuffer.AddRow();
                OutputSizesBuffer.ETLStart = Row.ETLStart;
                OutputSizesBuffer.SourceId = Row.SourceId;
                OutputSizesBuffer.SourceTable = Row.SourceTable;
                OutputSizesBuffer.SizeRangeId = Row.SizeRangeId;
                OutputSizesBuffer.SizeRangeIndex = index + 1; // make it 1-based.
                OutputSizesBuffer.Code = bucket;
            }
        }
        catch (Exception exception)
        {
            var cancel = false;
            ComponentMetaData.FireError(0, "Script Component", exception.ToString(), string.Empty, 0, out cancel);
        }
    }

}

I would like this code to be reviewed from a performance perspective, because I will be needing very similar script components soon, to process hundreds of thousands of rows; this specific instance works well, but only processes the "master data", which is only a dozen rows or so: if there's a performance issue with this code, it's only later that I'm going to find out - I'd rather get it peer reviewed now and make adjustments before I use similar code to process many, many rows.

Is the error/exception handling overkill? Is the regex pattern self-documenting? (wait, is that even possible?)


texts: Calculating the speed of a bicycle given the gear size and cadence

texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

Bicyclists can calculate their speed if the gear size and cadence is known.  Gear size refers to the effective diameter of the wheel. Gear size multiplied by pi (3.14) gives the distance traveled with one turn of the pedals. Cadence  refers to the number of pedal revolutions per minute (rpm).
The speed in miles per hour is calculated by the following:
Speed(mph)=  Gear Size (inches) * pi * 1(ft)/12 (inches) * 1(mile)/5280 (ft) * Cadence (rpm) * 60 (minutes)/(hour)

This is a program that calculates the speed for a gear size of 100 inches and a  cadence of 90 rpm. This would be considered a high cadence and a maximum gear size for a typical bicycle. In writing your program, don’t forget that the expression 1/12 will result in 0, because both 1 and 12 are integers, and when the integer division is performed, the fractional part is discarded.

This is the code that I have written:
    public class Question6 {

    private static final double PI = 3.14;
    private static final double gearSize = 100;
    private static final double cadence = 90;

    public static void main(String[] args) {
        System.out.println(getSpeed() + " mph");
    }

    private static double distancePerRevolution() {
        return gearSize * PI;
    }

    private static double feetPerInches() {
        return 1.0 / 12;
    }

    private static double milesPerFeet() {
        return 1.0 / 5280;
    }

    private static double minutesPerHour() {
        return 60;
    }

    private static double getSpeed() {
        return distancePerRevolution() * feetPerInches() * milesPerFeet()
                * cadence * minutesPerHour();
    }
}


texts: In need to speed up this code that filters the data of XML using XMLReader

texts:
I am using XMLReader and avoided SimpleXML because I must handle a huge file and for memory issues, SimpleXML is not the ideal solution. However, even I coded the below script in SimpleXML, it gives me the result really much faster.

Because speed and memory is a must for this project, is there any way to speed up this code? What it does, it filters the books and show those that contains the word jQuery.

error_reporting(~0);

$xml = <<<EOD
<?xml version="1.0" encoding="ISO-8859-1"?>
<library>
    <book isbn="781">
        <name>SCJP 1.5</name>
        <info>Sun Certified Java Programmer book</info>
    </book>
    <book isbn="194">
        <name>jQuery is Awesome!</name>
        <info>jQuery Reference Book</info>
    </book>
    <book isbn="199">
        <name>jQuery 101</name>
        <info>All you need to know about jQuery</info>
    </book>
</library>
EOD;

$file = 'data://text/plain;base64,'.base64_encode($xml);

class XMLBookIterator implements iterator
{
    private $file;
    private $reader;
    private $state;
    private $key = 0;
    private $book;
    private $valid;
    public function __construct($file)
    {
        $this->file = $file;
    }
    public function current()
    {
        return $this->book;
    }
    public function key()
    {
        return $this->key;
    }
    public function next()
    {
        $reader = $this->reader;
        while ($next = $reader->read())
        {
            switch ($reader->nodeType)
            {
                case (XMLREADER::ELEMENT):
                    $case = $reader->localName.'|'.$this->state;
                    switch($case)
                    {
                        case 'library|0':
                            break;
                        case 'book|1':
                            $this->book = new stdClass;
                            $this->book->isbn = $reader->getAttribute('isbn');
                            break;
                        case 'name|2':
                            $this->book->name = $reader->readInnerXML();
                            break;
                        case 'info|3':
                            $this->book->info = $reader->readInnerXML();
                            $this->state=0;
                            break;
                        default:
                            throw new Exception(sprintf('Invalid State: %s.', $case));
                    }
                    $this->state++;
                    if ($this->state === 1) break 2;
            }
        }
        $this->valid = $next;
        $this->key++;
    }
    public function rewind()
    {
        if ($this->reader) $this->reader->close();
        $this->reader = new XMLReader();
        $this->reader->open($this->file);
        $this->state = 0;
        $this->next(); // move to first element or invalidate
        if ($this->valid) $this->next(); // get first book
        $this->key = 0;
    }
    public function valid()
    {
        return $this->valid;
    }
}

class BookFilterIterator extends FilterIterator
{
    private $term;
    public function __construct($iterator, $term)
    {
        parent::__construct($iterator);
        $this->term = $term;
    }
    public function accept() {
        $book = parent::current();
        $name = $book->name;
        return false !== stripos($name, $this->term);
    }
}

// filtered books:

$books = new XMLBookIterator($file);

$filtered = new BookFilterIterator($books, 'jQuery');

foreach($filtered as $key => $book)
{
    echo 'book (', $key, '):', "\n";
    print_r($book);
}


texts: Implementation of the Householder Transformation

texts:
I implemented the Householder transformation in Python, so that I can later use it in a QR decomposition. Unfortunately I haven't found a good concise source for reading up on the algorithm.

I am not really satisfied with my code - I mostly dislike its readability due to the number of various computations. I also find my usage of the identity matrices \$I\$ and \$J\$ inefficient. So I would be happy about any suggestions on improving this implementation.

def houseHolder2(m):
    l = len(m)
    for i in range(0, l - 1):
        I = np.eye(l - i)
        ai = m[:, i]
        abs = np.linalg.norm(ai[i:l])
        sign = np.sign(m[i, i])
        vi = np.array([ai[i:l]]).T + sign * abs * np.array([I[:, 0]]).T
        Qi = I - 2 * (vi @ vi.T) / (vi.T @ vi)
        J = np.eye(l)
        J[i:l, i:l] = Qi
        m = J@m
    return m


texts: OBBs intersection improvement for AABBs-OBBs

texts:
I'm trying to code some intersection codes for Oriented Bounding Boxes (OBBs) and axis-aligned bounding boxes (AABBs). I have the OBB-OBB intersection using the Separating Axis Theorem (SAT) and I'm trying to figure out how can I improve this code to the specific case where I know I'm comparing an OBB with an AABB.

This is the code of my function:

bool Collider::isColliding(OBB * one, OBB * other)
{
    TestManager::collisionTests++;
    glm::vec3 oneCenter = one->m_gameObject->getWorldPosition(); // object's pos = collider center
    glm::mat4 oneTransform = glm::scale(one->m_gameObject->getTransform(), one->m_halfSize); // scaling for halfsize
    glm::vec3 otherCenter = other->m_gameObject->getWorldPosition();
    glm::mat4 otherTransform = glm::scale(other->m_gameObject->getTransform(), other->m_halfSize);

    for (int a = 0; a < 3; a++) {
        glm::vec3 l = glm::vec3(oneTransform[a]); // one axis to project on
        float tl = std::abs(glm::dot(l, otherCenter) - glm::dot(l, oneCenter)); // center distance
        float ra = std::abs(glm::dot(l, glm::vec3(oneTransform[0]))) + std::abs(glm::dot(l, glm::vec3(oneTransform[1]))) + std::abs(glm::dot(l, glm::vec3(oneTransform[2])));
        float rb = std::abs(glm::dot(l, glm::vec3(otherTransform[0]))) + std::abs(glm::dot(l, glm::vec3(otherTransform[1]))) + std::abs(glm::dot(l, glm::vec3(otherTransform[2])));
        float penetration = (ra + rb) - tl;
        if (penetration <= 0) { // no overlap
            return false;
        }
    }
    for (int b = 0; b < 3; b++) {
        glm::vec3 l = glm::vec3(otherTransform[b]); // other axis to project on
        float tl = std::abs(glm::dot(l, otherCenter) - glm::dot(l, oneCenter)); // center distance
        float ra = std::abs(glm::dot(l, glm::vec3(oneTransform[0]))) + std::abs(glm::dot(l, glm::vec3(oneTransform[1]))) + std::abs(glm::dot(l, glm::vec3(oneTransform[2])));
        float rb = std::abs(glm::dot(l, glm::vec3(otherTransform[0]))) + std::abs(glm::dot(l, glm::vec3(otherTransform[1]))) + std::abs(glm::dot(l, glm::vec3(otherTransform[2])));
        float penetration = (ra + rb) - tl;
        if (penetration <= 0) { // no overlap
            return false;
        }
    }
    for (int a = 0; a < 3; a++) {
        glm::vec3 aAxis = glm::vec3(oneTransform[a]);
        for (int b = 0; b < 3; b++) {
            glm::vec3 bAxis = glm::vec3(otherTransform[b]);
            if (aAxis != bAxis) {
                glm::vec3 l = glm::cross(aAxis, bAxis); // has flaw when axis are same, result in (0,0,0), solved by if
                float tl = std::abs(glm::dot(l, otherCenter) - glm::dot(l, oneCenter)); // center distance
                float ra = std::abs(glm::dot(l, glm::vec3(oneTransform[0]))) + std::abs(glm::dot(l, glm::vec3(oneTransform[1]))) + std::abs(glm::dot(l, glm::vec3(oneTransform[2])));
                float rb = std::abs(glm::dot(l, glm::vec3(otherTransform[0]))) + std::abs(glm::dot(l, glm::vec3(otherTransform[1]))) + std::abs(glm::dot(l, glm::vec3(otherTransform[2])));
                float penetration = (ra + rb) - tl;
                if (penetration <= 0) { // no overlap
                    return false;
                }
            }
        }
    }
    return true;
}

Hope you can help me.


texts: Random changes in a list of binary numbers

texts:
I have a list of N integers, e.g. intList=[1,7,3,1,5] with N=5 and all integers have a binary representation of lenght l, e.g. binList=["001","111","011","001","101"] with l=3. Now I want to add random flips from 1->0 & 0->1. Each of the l positions should flip with a probabiliy mu. (mu varies over many magnitudes & N is around 100-100000) This happens over many iterations. Currently my code is
@nb.njit()
for x in range(iterations):
    ...other code...
    for number in range(N):
        for position in range(l):
            if random.random() < mu:
                intList[number] = intList[number] ^ (1 << position)
    ...other code...

The numba decorator is necessary. Since this part takes most of the execution time I just want to make sure that it is already optimal. Thanks for any comment!


texts: Are private extension methods a bad thing to use?

texts:
In C# I have the following two extension methods.

    public static void WaitForMilliseconds(this IWebDriver driver, int milliseconds)
    {
        var timeout = new TimeSpan(0, 0, 0, 0, milliseconds);
        WaitForTimeout(driver, timeout);
    }

    public static void WaitForSeconds(this IWebDriver driver, int seconds)
    {
        var timeout = new TimeSpan(0, 0, 0, seconds);
        WaitForTimeout(driver, timeout);
    }

    private static void WaitForTimeout(IWebDriver driver, TimeSpan timeout)
    {
        try
        {
            new WebDriverWait(driver, timeout).Until(x => false);
        }
        catch (Exception){}
    }

But since the class is static, I can write a private extension method to make the syntax more readable like this.

    public static void WaitForMilliseconds(this IWebDriver driver, int milliseconds)
    {
        var timeout = new TimeSpan(0, 0, 0, 0, milliseconds);
        driver.WaitForTimeout(timeout);
    }

    public static void WaitForSeconds(this IWebDriver driver, int seconds)
    {
        var timeout = new TimeSpan(0, 0, 0, seconds);
        driver.WaitForTimeout(timeout);
    }

    private static void WaitForTimeout(this IWebDriver driver, TimeSpan timeout)
    {
        try
        {
            new WebDriverWait(driver, timeout).Until(x => false);
        }
        catch (Exception){}
    }

Is there any inherently bad code smell about private extension methods? Which would is better to use? The only issue I see is that if the code is later refactored into a class the methods will have to be rewritten.


texts:
I haven't found a good code example for a reactive retry operator with a retry strategy that was good enough for my needs. So I tried to make my own. It seems to work in my tests but I would really appreciate some feedback. (C# 8.0)

using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace Fncy.Helpers
{
    public static class ObeservableHelpers
    {
        public delegate TimeSpan? NextRetryDelay(int previousRetryCount, TimeSpan elapsedTime, Exception retryReason);

        public static IObservable<TSource> RetryAfterDelay<TSource>(
            this IObservable<TSource> source,
            NextRetryDelay retryDelay,
            IScheduler scheduler = null)
        {
            if (retryDelay == null) throw new ArgumentNullException(nameof(retryDelay));
            scheduler ??= Scheduler.Default;
            return source.RetryWhen(errors =>
            {
                var retryStart = scheduler.Now;
                int previousRetryCount = 0;
                return errors.SelectMany(ex =>
                {
                    var delay = retryDelay(previousRetryCount++, scheduler.Now - retryStart, ex);
                    return delay == null
                        ? Observable.Throw<Unit>(ex)
                        : Observable.Return(Unit.Default).Delay(delay.Value, scheduler);
                });
            });
        }
    }
}


texts:
I have some code that calculates the "sentiment" of a Tweet.

The task starts with an AFINN file, that is a tab-separated list of around 2500 key-value pairs. I read this into a dict using the following function:

csv.register_dialect('tsv', delimiter='\t')

def processSentiments(file):
    with open(file) as sentiments:
        reader = csv.reader(sentiments,'tsv')
        return dict((word, int(sentiment)) for word, sentiment in reader)

I'm happy with this code - it's pretty clear and I'm not worried about its speed and memory usage as the file is small.

Using the created dict I now need to process many tweets. Lets say I have 1GB of then in JSON format - from the live stream.

What I need to do is:

read a tweet file, with a JSON tweet on each line
parse each tweet to a dict using json.loads
extract the text field from the tweet - giving the content of the tweet
for each word in the content, check it if has a sentiment
for each sentiment word in the tweet, calculate it's value (from the AFINN dict) and sum across the tweet
store that number

So whilst I have a lot of tweet data, I only need a list of integers. This is obviously much smaller.

I want to be able to stream the data from the file and convert each line to its sentiment value in the most efficient way possible. Here's what I came up with:

def extractSentiment(tweetText, sentimentsDict):
    return sum([sentimentsDict.get(word, 0) for word in tweetText.split()])

def processTweet(tweet, sentimentsDict):
    try:
        tweetJson = json.loads(tweet)
    except ValueError, e:
        raise Exception('Invalid tweet: ', tweet, e)
    tweetText = tweetJson.get('text', False)
    if tweetText:
        return extractSentiment(tweetText, sentimentsDict)
    else:
        return 0

def processTweets(file, sentimentsDict):
    with open(file) as tweetFile:
        return [processTweet(tweet, sentimentsDict) for tweet in tweetFile]

So I am using a for-comprehension over the tweetsfile to map each line in the file to its corresponding number.

So my question is, how would you rewrite the above the maximise speed and minimise memory usage.

Any other comments on the Python would be welcome too.

I realise that I can use a single-producer -> multiple-consumer pattern to speed up the processing of the file, but I would for now like to stick with a single thread.


texts: A recursive program that attempts to solve an extremely large number

texts:
This is my recursive program for the following function:

\$F(x) = G(x) - W(x)\$
\$G(x) = [G(x-1)+G(x-2)]^2\$
\$W(x) = [W(x-1)]^2 + [W(x-2)]^2\$
If x == 0 in either function G or function W, then return 0
If x == 1 in either function G or function W, then return 1

import java.math.BigInteger;
import java.io.PrintWriter;
import java.io.IOException;

public class RecursiveProgram
{
    BigInteger test = BigInteger.valueOf(30);
    BigInteger zero = new BigInteger(Integer.toString(0));
    BigInteger one = new BigInteger(Integer.toString(1));
    BigInteger two = new BigInteger(Integer.toString(2));
    public BigInteger G(BigInteger x)
    {
        if(x.equals(zero))
            return zero;
        if(x.equals(one))
            return one;
        return (G(x.subtract(one)).add(G(x.subtract(two)))).multiply((G(x.subtract(one)).add(G(x.subtract(two)))));
    }

    public BigInteger W(BigInteger x)
    {
        if(x.equals(zero))
            return zero;
        if(x.equals(one))
            return one;
        return ((W(x.subtract(one))).multiply(W(x.subtract(one)))).add((W(x.subtract(two))).multiply(W(x.subtract(two))));
    }

    public void solveForF() throws IOException
    {
        PrintWriter writer = new PrintWriter("C:/Users/my computer/Desktop/f(30).txt");
        writer.println(G(test).subtract(W(test)));
        writer.close();
    }
}

It writes the calculated number to the .txt file on my desktop. I want to improve the recursive program to allow it to calculate F(30). However, I did some math calculations as to how long it would take for the program to complete using the amount of time it took to calculateF(20) and F(21), approximating to 12.35 days. Obviously this is inefficient and I haven't learned a better method to make it more efficient. I've heard of dynamic programming but I'm not sure as how I would use it here.


texts: Directory that lists employee information - follow-up

texts:
Yesterday I posted a question involving multiple nested queries.  The queries pulled information from the database and created a directory listing of all employees.  There are two many-to-many relationships involving 5 tables.  For each employee they can have multiple job titles and multiple departments.

$stmt = $mysqli->prepare("SELECT employeeId, firstName, middleName, lastName, suffix, profilePhoto, GROUP_CONCAT(DISTINCT jobName ORDER BY jobTitleId), GROUP_CONCAT(DISTINCT departmentName ORDER BY departmentId), GROUP_CONCAT(DISTINCT departmentURL ORDER BY departmentId) FROM employee
INNER JOIN employee_has_jobTitle ON employeeId = employee_has_jobTitle.employee_employeeId
INNER JOIN jobTitle ON employee_has_jobTitle.jobTitle_jobTitleId = jobTitleId
INNER JOIN employee_has_department ON employee.employeeId = employee_has_department.employee_employeeId
INNER JOIN department ON employee_has_department.department_departmentId = departmentId
GROUP BY employeeId ORDER By lastName, firstName");

$stmt->execute();
$stmt->store_result();
$stmt->bind_result($employeeId, $firstName, $middleName, $lastName, $suffix, $profilePhoto, $jobName, $departmentName, $departmentURL);

//set up the list
echo "
";

while($stmt->fetch()){

    echo "

";

    $deptName = explode(",", $departmentName);
    $deptURL = explode(",", $departmentURL);
    $jobTitle = explode(",", $jobName);
    echo "$firstName $lastName
";

    $counter = 0;
    foreach($deptName as $name) {
        //echo a preceding comma if not the first department
        if($counter > 0) echo ", ";

        echo "$name";
        $counter++;
    }

    echo "
";

    foreach($jobTitle as $job) {
        echo "$job
";
    }

    echo "

";
}

//close the list
echo "

";

If you check my other question, you can see that this is an improvement.  However, I don't think the query and code are as elegant as they should be.  Is there an obvious way to simplify the code and enhance performance that I'm not seeing?

Screenshot of the ERD for reference:


texts: Nested trial and error in if-else condition

texts:
Using Rails 3.2, I have the following:

g = Geocoder.search(address)

# if no address found, geocode with latitude and longitude
if g.empty?
  g = Geocoder.search(latitude, longitude)
  if g.empty?
    log.info "Geocode failed for #{latitude}, #{longitude}"
  end
else
  ---save---
end

If the first geocoding with address fails, it will try latitude and longitude. If still fails, then it logs error, else it will save.

Is this a good way to write this code?


texts: (php , mysql) Contact us form mysql injection

texts:
I made this anti SQL Injection, I tested if I can still send queries, and it is looks good. could you tell me if you see any problem I missed, before I launch this to the internet? (this is contact us form, no log in)

<?php

if(isset($_POST['submit'])) {

    $name = $_POST['username'];
    $email =  $_POST['email'];
    $text =  $_POST['textt'];

    $connection = mysqli_connect('localhost', 'root', '',  'database1');

    if($name && $email && $text ) {

        echo  "thanks you for contacting us, we will respond within 24 hours.";
    }
    else {
        echo  "Please enter name, email and your message.";

        // echo  $result;
    }

    $name = mysqli_real_escape_string($connection, $name);

    $email = mysqli_real_escape_string($connection, $email);

    $text = mysqli_real_escape_string($connection, $text);

    $query = "INSERT INTO info(username,email,textt) ";
    $query .= "VALUES ('$name', '$email', '$text')";

    mysqli_query($connection, $query);

}

?>


texts: Autofill a table based on the input provided in a userform

texts:
Good morning,

I have the following code:

Option Explicit

 Private Sub CommandButton1_Click()
 Dim LastRowA As Long, LastRowB As Long, LastRowC As Long, lastrowD As Long, LastrowE As Long,
 LastrowF As Long, LastrowG As Long, LastrowH As Long, LastrowI As Long, LastrowK As Long, LastrowL
 As Long
 Dim ws As Worksheet

 Set ws = Sheets("Sheet1")

LastRowA = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row
LastRowB = ws.Range("B" & Rows.Count).End(xlUp).Row + 1
LastRowC = ws.Range("C" & Rows.Count).End(xlUp).Row + 1
lastrowD = ws.Range("D" & Rows.Count).End(xlUp).Row + 1
LastrowE = ws.Range("E" & Rows.Count).End(xlUp).Row + 1
LastrowF = ws.Range("F" & Rows.Count).End(xlUp).Row + 1
LastrowG = ws.Range("G" & Rows.Count).End(xlUp).Row + 1
LastrowH = ws.Range("H" & Rows.Count).End(xlUp).Row + 1
LastrowI = ws.Range("I" & Rows.Count).End(xlUp).Row + 1
LastrowK = ws.Range("K" & Rows.Count).End(xlUp).Row + 1
LastrowL = ws.Range("L" & Rows.Count).End(xlUp).Row + 1

ws.Range("A" & LastRowA).Value = JobID.Text 'Adds the TextBox3 into Col A & Last Blank Row
ws.Range("B" & LastRowB).Value = Surveyor.Text
ws.Range("C" & LastRowC).Value = DateBox.Text
ws.Range("D" & LastRowC).Value = AddressBox.Text
ws.Range("E" & LastrowE).Value = CityBox.Text
ws.Range("F" & LastrowF).Value = PostcodeBox.Text
ws.Range("G" & LastrowG).Value = THPBox.Text
ws.Range("H" & LastrowH).Value = ChamberBox.Text
ws.Range("I" & LastrowI).Value = ORFibreBox.Text
ws.Range("K" & LastrowK).Value = ("=I" & LastrowI & "*5")

 End Sub

which helps me to autofill the table columns based on the user form.

The code is valid, but I am wondering how can I write it smarter. Is it possible at all?


texts: Merge Two Sorted Lists by splicing together the nodes of the first two lists

texts:
I solved this problem:

  Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

How can I improve its execution time and also, if there is any better way of doing it?

public ListNode mergeTwoLists(ListNode listNode1, ListNode listNode2) {
    ListNode headNode = new ListNode(0);
    ListNode node = headNode;
    while (null != listNode1 && null != listNode2) {
        if (listNode1.val < listNode2.val) {
            node.next = listNode1;
            listNode1 = listNode1.next;
        } else {
            node.next = listNode2;
            listNode2 = listNode2.next;
        }
        node = node.next;
    }
    if(null != listNode1) {
        node.next = listNode1;
    }
    if(null != listNode2) {
        node.next = listNode2;
    }
    return headNode.next;
}


texts: Downloading and parsing list of Getcachine CWGs

texts:
I'm building a page that downloads a list of Geocaching CWGs for my country in XML, and then parse it. The structure of the XML looks like this:

<cwgkatalog>
    <cwg>
        <cislo>8245</cislo>
        <id_katalog>8245</id_katalog>
        <kategorie>cwg</kategorie>
        <verze>1</verze>
        <guid>891a8e4d-9dee-4f77-a9c7-8017c5f16b15</guid>
        <jmeno>GarfieldMnHr</jmeno>
        <jpg_oficialni>cwg08245-1.jpg</jpg_oficialni>
        http://cwg.geog.cz/cwg08245-1.jpg
        <odkaz/>
        <komentar/>
        <zarazeno>2013-12-06 00:00:00</zarazeno>
    </cwg>
    <cwg>
...

I have a function that searches for jmeno property and because of that, I have created an array working as an index array for jmeno:

function createAjax() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject('Microsoft.XMLHTTP');
    }
}

function CwgParser(xmlListURL) {
    var httpRequest = createAjax(),
        mainContext = this,
        tree_cwgData = [],
        arr_nameIndex = [];

    this.findDataByName = function(searchedName) {
        var lastIndex = arr_nameIndex.indexOf(searchedName),
            arr_foundIndexes = [lastIndex],
            arr_resultData = [];
        while (lastIndex != -1) {
            lastIndex = arr_nameIndex.indexOf(searchedName, lastIndex + 1);
            arr_foundIndexes.push(lastIndex);
        }
        arr_foundIndexes.splice(-1, 1);

        arr_foundIndexes.forEach(function(value) {
            arr_resultData.push(tree_cwgData[value]);
        });
        return (arr_resultData.length == 0) ? false : arr_resultData;
    };

    this.parseXML = function(xmlData) {
        var _xmlDoc, _parser, _arr_parts, _node_currentNode, _obj_currentNodeData, arr_cwgList = [], nameIndex = [];
        if (window.DOMParser) {
            _parser = new DOMParser();
            _xmlDoc = _parser.parseFromString(xmlData, 'text/xml');
        } else {
            _xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
            _xmlDoc.async = false;
            _xmlDoc.loadXML(xmlData);
        }

        _arr_parts = _xmlDoc.getElementsByTagName('cwg');

        for (var i = 0; i < _arr_parts.length; i++) {
            _node_currentNode = _arr_parts[i];
            _obj_currentNodeData = {};
            for (var j = 1; j < _arr_parts[i].childNodes.length - 1; j=j+2) {
                _obj_currentNodeData[_node_currentNode.childNodes[j].nodeName] = _node_currentNode.childNodes[j].innerHTML;
            }
            nameIndex.push(_obj_currentNodeData.jmeno.trim());
            arr_cwgList.push(_obj_currentNodeData);
        }

        tree_cwgData = arr_cwgList;
        arr_nameIndex = nameIndex;

        mainContext.ondataparse();
    };

    this.loadXML = function () {
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4) {
                mainContext.ondataload();
                mainContext.parseXML(httpRequest.responseText);
            }
        };
        mainContext.onrequeststart();
        httpRequest.open('GET', './fileContentProvider.php?url=' + xmlListURL, true);
        httpRequest.send(null);
    };

    this.onrequeststart = function() {};
    this.ondataload = function() {};
    this.ondataparse = function() {};
}

and I call it like this (LoadingIcon is just a support class that creates overlay, displaying loading .gif and some text):

var xml = new CwgParser('cwg.geog.cz/cwg.xml'),
    loader = new LoadingIcon('./ajax-loader.gif');
xml.ondataparse = function() {
    loader.stop();
    document.getElementById('container').style.display = 'block';
};
xml.ondataload = function() {
    loader.setText('Parsing CWG list...');
};
loader.setText('Loading CWG list...');
loader.start();
xml.loadXML();

Is there any better way of searching and downloading the data?


texts: Reduce code handling start and end datepickers

texts:
I have a select with 3 options and two datepickers, a start and an end date. Based on the option selected, the date end date can either be any future date or limited to a 30 day date range. In the jsFiddle provided below, when Option 1 is selected, the date range is restricted to 30 days. If either Option 2 or Option 3 are selected, the end date can be any future date.

Here is a complete working jsFiddle with the complete code.

I haven't run into any issues with the code below.  I'm just wondering if anyone has any suggestions on how I could go about reducing it as it just seems too "bulky".

$('#startDate, #endDate').datepicker({
    beforeShow: setDateRange,
    dateFormat: "mm/dd/yy",
    firstDay: 1,
    changeFirstDay: false,
    onChange: function() { $(this).valid(); },
    onSelect: function() {
        if (this.id == 'startDate') {
            var date = $('#startDate').datepicker('getDate');
            if (date) { date.setDate(date.getDate() + 1); }
            $('#endDate').datepicker('option', 'minDate', date);
        }
    }
});

function setDateRange(input) {
    var min = null, dateMin = min, dateMax = null, dayRange = 30;
    var opt = $('#select1'), start = $('#startDate'), end = $('#endDate');
    if (opt.val() == '1') {
        if (input.id == 'startDate') {
            if ($('#endDate').datepicker('getDate') != null) {
                dateMax = $('#endDate').datepicker('getDate');
                dateMin = $('#endDate').datepicker('getDate');
                dateMin.setDate(dateMin.getDate() - dayRange);
                if (dateMin < min) { dateMin = min; }
            }
        } else if (input.id == 'endDate') {
            dateMin = $('#startDate').datepicker('getDate');
            dateMax = new Date(dateMin.getFullYear(),
                dateMin.getMonth(), dateMin.getDate() + 30);
            if ($('#startDate').datepicker('getDate') != null) {
                var rangeMax = new Date(dateMin.getFullYear(),
                    dateMin.getMonth(), dateMin.getDate() + dayRange);
                if (rangeMax < dateMax) { dateMax = rangeMax; }
            }
        }
    } else if (opt.val() != '1') {
        if (input.id == 'startDate') {
            if ($('#endDate').datepicker('getDate') != null) {
                dateMin = null;
            }
        } else if (input.id == 'endDate') {
            dateMin = $('#startDate').datepicker('getDate');
            dateMax = null;
            if ($('#startDate').datepicker('getDate') != null) { dateMax = null; }
        }
    }
    return {
        minDate: dateMin,
        maxDate: dateMax
    };
}

I posted this on Stack Overflow a couple months back when I was initially trying to figure out how to get it working. The post goes into a little more detail on the option selections but I have since added on to it some. For example, the code above now includes an onSelect when the datepickers are initialized.

If anyone has any suggestions on how I could go about improving this, please let me know.


texts: Linux background changing daemon in Rust

texts:
I'm working on a program that updates the background of an x11 desktop at a specified interval. However, it eats large amounts of my CPU just sitting idle. I know this is due to the main loop running faster than I want it to. I've used a couple shameful hacks to quell usage down to about 15% but now I am searching for a long-term solution.

Here is the function that contains the main loop:

pub fn run_mapped(&mut self) {
    info!(self.logger, "Running in mapped mode!");
    let wait_d = Duration::new(0,500);
    let long_wait_d = Duration::new(0,750);
    loop {
        if self.img_dir.1.elapsed() > self.reload_time {
            self.img_dir.0.reload();
            self.img_dir.1 = Instant::now();
        }
        let cd = self.x.get_current_desktop();
        // change background if timeout is reached
        if self.since_timeout.elapsed() > self.timeout {
            self.change_backgrounds();
            let ref mut current_bg = self.image_map[cd];
            self.since_timeout = Instant::now();
            self.x.change_background(current_bg);
        }
        match self.x.next_event() {
                Some(_) => {
                    let ref mut current_bg = self.image_map[cd];
                    self.x.change_background(current_bg);
                },
                None => { sleep(wait_d); }
        }
        sleep(long_wait_d);
    }
}

Not shown, but I have additionally set process priority lower to give more important process priority over this one.

I added the sleep calls to prevent >50% CPU usage but it still consumes ~20% which seems a little excessive for what I want this program to do. I'm looking at some of the CPU usage from other programs I'm running in my DE (candybar) and they're nowhere near as resource-hungry as my program.

All that being said, my two questions are:

Why is this? Meaning, why is my program using so much CPU since it is basically 'sleeping' most of the time (in its current state)?
How can I fix this? The only thing I can think of now is scrapping it and abusing cron jobs to the same effect.

The full code can be found on Github.


texts: Certainty of two comparative values (A/B results certainty)

texts:
I'm trying to output the percentage of certainty of two comparatives data.

Here's the resulting code:

/**
 * Original code from https://vwo.com/js/significanceCalculator.js
 */
function calculatePValue (c_t, c_c, v_t, v_c) {
    var d1 = 0.0498673470,
        d2 = 0.0211410061,
        d3 = 0.0032776263,
        d4 = 0.0000380036,
        d5 = 0.0000488906,
        d6 = 0.0000053830;

    var c_p = c_c / c_t;
    var v_p = v_c / v_t;

    var std_error = Math.sqrt((c_p * (1 - c_p) / c_t) + (v_p * (1 - v_p) / v_t));
    var z_value = (v_p - c_p) / std_error;

    var a = Math.abs(z_value);
    var p_value = 1.0 + a * (d1 + a * (d2 + a * (d3 + a * (d4 + a * (d5 + a * d6)))));

    p_value *= p_value;
    p_value *= p_value;
    p_value *= p_value;
    p_value *= p_value;
    p_value = 1.0 / (p_value + p_value);
    if (z_value >= 0)
        p_value = 1 - p_value;

    if (p_value > 0.5)
        p_value = 1 - p_value;

    p_value = Math.round(p_value * 1000) / 1000;
    return p_value;
}

function getPercentage(totalA, convA, totalB, convB) {
    var p = calculatePValue(totalA, convA, totalB, convB);
    if (p < 0,5) {
        return 'B, with certainty of : ' + ((1-p)*100).toFixed(2) + '%';
    } else {
        return 'A, with certainty of : ' + (p*100).toFixed(2) + '%';
    }
}

For example, if you try with:

getPercentage(1000, 120, 500, 90);

you'll get:

  "B, with certainty of : 99.90%"

The code for calculating P was extracted from here. I simply took it as a percentage value to display either A or B is better.

What do you think? Is this ok?


texts: Erlang linter written in Erlang using erl_lint:module

texts:
I've just started learning Erlang. Since my editor of choice doesn't have a syntax checker for Erlang, I decided to use the parser/linter in the standard library to make a standalone script. It works now, but I'd like my code to look cleaner, possibly handle edge cases better, be more ... what's the Erlang equivalent of "pythonic"?

-module(erlint).
-export([main/1]).

main(["--version"]) ->
    io:fwrite("erlint version 0.1.0~n");
main([File]) -> % escript passes in args in an array
    Out = lint(File),
    print(Out);
main([]) -> % no args from escript
    io:fwrite("Usage: erlint filename.erl~n");
main(File) -> % allow callers to pass filename in a bare string
    main([File]).

lint(File) ->
    case epp:parse_file(File,[]) of
        {ok, Forms} ->
            case erl_lint:module(Forms, File) of
                % nothing wrong
                {ok, []} ->
                    [];
                % just warnings
                {ok, [Warnings]} ->
                    [{warning,element(1,Warnings),X} || X <- element(2,Warnings)];
                % errors, no warnings
                {error, [Errors], []} ->
                    [{error,element(1,Errors),X} || X <- element(2,Errors)];
                % errors and warnings
                {error, [Errors], [Warnings]} ->
                    [{error,element(1,Errors),X} || X <- element(2,Errors)] ++
                    [{warning,element(1,Warnings),X} || X <- element(2,Warnings)]
            end;
        {error, _} ->
            "Cannot open file"
    end.

% degenerate case
print([]) ->
    0;
% some errors use a tuple to describe the error
print([{Type,File,{Line,_Module,{ErrT,ErrX}}}|More]) ->
    io:fwrite("~s:~w: ~w: ~w ~w~n",[File,Line,Type,ErrT,ErrX]),
    print(More);
% some errors use a list to describe the error
print([{Type,File,{Line,_Module,[ErrT,ErrX]}}|More]) ->
    io:fwrite("~s:~w: ~w: ~s ~s~n",[File,Line,Type,ErrT,ErrX]),
    print(More);
% some errors use a string to describe the error
print([{Type,File,{Line,_Module,Err}}|More]) ->
    io:fwrite("~s:~w: ~w: ~s~n",[File,Line,Type,Err]),
    print(More);
print(String) ->
    io:fwrite("~s~n",[String]).

Future versions of the script will live at https://github.com/sparr/erlint/blob/master/src/erlint.erl


texts: At most one LocalDate per month in a list

texts:
I'm implementing argument check in a method where one parameter is a List of LocalDate objects (from Joda-Time). I want to make sure that List contains at most one LocalDate per month.

public List<LocalDate> generateAllDates(List<LocalDate> firstYearDates, ...) { }

Thus, for example

Arrays.asList(
    new LocalDate(2012, 3, 25),
    new LocalDate(2012, 4, 30),
    new LocalDate(2013, 3, 26)
)

would be an illegal argument because there are two dates whose month is March.

Currently I have something like this (making use of Guava's Multimap):

Multimap<Integer, LocalDate> monthToDates = HashMultimap.create();
for (LocalDate date : firstYearDates) {
    monthToDates.put(date.getMonthOfYear(), date);
}
for (Integer i : monthToDates.keySet()) {
    if (monthToDates.get(i).size() > 1) {
        throw new IllegalArgumentException(
            "firstYearDates must contain at most one entry per month");
    }
}

Question is, how would you simplify that? Using any API features of JDK 1.6, Guava or Joda-Time is fine.


texts: Miller-Rabin Primality Test Using C++ and GMP

texts:
I'm currently writing a Miller-Rabin primality test using C++ and the GNU MP Bignum Library (GMP). As I've only started learning C++ about a day ago, I'm sure this code is riddled with errors and inefficiencies. I'm looking for several things (in order of importance):

Make the code as fast as possible (really at the expense of anything else)
Make the code more readable
Encapsulating all functions in the miller_rabin() function
Make the length of the code shorter

I'm also looking for any insight into my handling of the GMP code. I know there's a way to reallocate memory but I'm not sure how to do that yet. Any thoughts are greatly appreciated!

Here's the code:

#include <iostream>
#include <gmp.h>
#include <gmpxx.h>

using namespace std;

mpz_class exp_one(mpz_class a, mpz_class b, mpz_class c){
    mpz_class r;
    mpz_powm(r.get_mpz_t(), a.get_mpz_t(), b.get_mpz_t(), c.get_mpz_t());
    return r;
}

mpz_class exp_two(mpz_class a, mpz_class b){
    mpz_class r, c;
    c = 2;
    mpz_powm(r.get_mpz_t(), a.get_mpz_t(), c.get_mpz_t(), b.get_mpz_t());
    return r;
}

mpz_class mr_check_one(mpz_class n){
    if(n % 2 != 0){
        return 0;
    }

    n = n - 1;
    while(n % 2 == 0){
        n = n / 2;
    }
    return n;
}

mpz_class mr_check_two(mpz_class m, mpz_class n){
    mpz_class b, u, j, d;
    u = n - 1;
    j = 0;
    d = 2;

    b = exp_one(d, m, n);

    if(b == u or b == 1){
        return 0;
    }

    while(b != u and j < 7){
        b = exp_two(b, n);
        j++;
    }

    if(b == u){
        return 0;
    } else {
        return 1;
    }
}

mpz_class miller_rabin(mpz_class n){
    mpz_class r;
    r = mr_check_one(n);
    r = mr_check_two(r, n);
    return r;
}

int main(){
    mpz_class n, r;
    n = 2305843009213693951;  //some prime
    r = miller_rabin(n);

    if(r == 0){
        cout << "This number is PRIME!" << endl;
    } else {
        cout << "This number is NOT prime." << endl;
    }
}


texts:
The first line will contain numbers m (number of rows), n (number of columns), and b (number of rotations to be performed).

Suppose I have following 4X4 matrix:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

and b = 1,the output must be:

2 3 4 8
1 7 11 12
5 6 10 16
9 13 14 15

The problem I am facing is 3 test case are timing out and 9 test case successfully passed. Can somebody suggest a way or help me with optimizing my code?

Here is the link to the question.

I need a way to figure out how to minimize b, because some rotations will be useless as it will result in giving us the original array.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class So {
    private static BufferedReader br;
    private static int n,m,b;
    private static int [][]arr;
    public static void main(String[] args)throws IOException {
        int i,j;
        br=new BufferedReader(new InputStreamReader(System.in));
        String []str;
        str=br.readLine().split(" ");
        m=Integer.parseInt(str[0]);
        n=Integer.parseInt(str[1]);
        b=Integer.parseInt(str[2]);
        arr=new int[m][n];
        for(i=0;i<m;++i)
        {
            str=br.readLine().split(" ");
            for(j=0;j<n;++j)
             arr[i][j]=Integer.parseInt(str[j]);
        }
        i=0;
        while(i++<b)
         rotate();
        for(i=0;i<m;++i)
        {
            for(j=0;j<n;++j)
             System.out.print(arr[i][j]+" ");
            System.out.println();
        }
    }
    public static void rotate()
    {
        int sr=0,sc=0,r=m,c=n,i,j,prev,res;
        while(sr<=r-2&&sc<=c-2)
        {prev=arr[sr][sc];
        res=arr[sr+1][sc];
        for(i=sr+1;i<=r-2;++i)
        {
            arr[i][sc]=prev;
            prev=res;
            res=arr[i+1][sc];
        }
        for(i=sc;i<=c-2;++i)
        {
            arr[r-1][i]=prev;
            prev=res;
            res=arr[r-1][i+1];
        }
        for(i=r-1;i>=sr+1;--i)
        {
            arr[i][c-1]=prev;
            prev=res;
            res=arr[i-1][c-1];
        }
        for(i=c-1;i>=sc+1;--i)
        {
            arr[sr][i]=prev;
            prev=res;
            res=arr[sr][i-1];
        }
        arr[sr][sc]=prev;
        sr++;sc++;r--;c--;
    }
    }
 }


texts: Ruby function to surround a word with dashes

texts:
I am new to Ruby on Rails. Can some one please help me with this question?

How would you modify the following to be consistent with Ruby's style?

class Add_dash
def dashesHere(word)
    attachTheDashes = "--" + word + "--"
        return attachTheDashes
   end
end


texts:
I'm trying to brush up on some C basics (it's been ten years since I've programmed in C) and am working on a simple Rot13 program as a Unix filter. Any suggestions on how to improve it would be appreciated. Specifically, I'm curious if the call to fclose at the end of main is necessary or will have bad potential effects since it is possible for stdin to be passed as an argument.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

// input_from_args: returns a FILE* corresponding to the input
// source specified by the user. If no file was specified,
// returns stdin.

FILE* input_from_args(int argc, const char *argv[])
{
    if (argc == 1) {
        return stdin;
    } else {
        return fopen(argv[1], "r");
    }
}

// rot13: returns the rot13 encoding of the specified character

int rot13(int c)
{
    if (('a' <= c && c <= 'm') || ('A' <= c && c <= 'M')) {
        return c + 13;
    } else if (('n' <= c && c <= 'z') || ('N' <= c && c <= 'Z')) {
        return c - 13;
    } else {
        return c;
    }
}

// convert_all: converts all of the characters in src using the
// rot13 encoding writing the results to dest

void convert_all(FILE *src, FILE *dest)
{
    int c;

    while ((c = fgetc(src)) != EOF) {
        fprintf(dest, "%c", rot13(c));
    }
}

int main(int argc, const char *argv[])
{
    FILE *src = input_from_args(argc, argv);
    FILE *dest = stdout;

    if (src == NULL) {
        fprintf(stderr, "%s: unable to open %s\n", argv[0], argv[1]);
        exit(EXIT_FAILURE);
    }

    convert_all(src, dest);

    fclose(src);

    return EXIT_SUCCESS;
}


texts: Linux: Raku script to open files from terminal and ask for deletion

texts:
Raku script to open files from terminal with xdg-open and, with del option, asks for deletion. Happy to receive Raku syntax improvements. Thanks!
use v6;

#| Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion
sub MAIN( $pattern is copy, Str $ext, Str $del? where ( $del ∈ < del nodel > ) = "nodel" ) {

    $pattern = "" if $pattern eq "all";
    my @files = '.'.IO.dir(test => /.*$pattern.*\.$ext/);

    for @files -> $file {
        my @args = 'xdg-open', $file.basename;
        my $command = run @args;
        $command.exitcode == 0 or die "system @args failed: $!";
        if $del eq 'del' {
          my $delete = prompt("\n \n Delete file $file (s/n) ");
          next if $delete ne "s";
          say "mv $file /tmp/$file";
          $file.IO.move("/tmp/$file");
        }
        my $exit = prompt("\n Press 'q' to end, return to continue ");
        last if $exit eq q{q};
    }

    @files = '.'.IO.dir(test => /.*$pattern.*$ext$/);
    say "-" x 60;
    for @files -> $file { $file.Str.say }
    say "-" x 60;
}


texts: Implement code coverage flush function with boiler plate code

texts:
In each shared library that I build, it need to call __gcov_flush but that call should only be made when building the instrumented binaries for code review.
In that case I'm passing

-D__CODE_COVERAGE__

option as a compilation flag.

And in each .so file.

#ifdef __CODE_COVERAGE__

void cscomm_gcov_flush()
{
    __gcov_flush();
}
#endif // __CODE_COVERAGE__

So I'm keeping the same source tree for both code coverage , debug and release.
Is this approach is oky, good or bad ? Can you review?


texts:
For my web application I have written AuthenticationFilter which validates each request to check against CSRF attacks, Browser Checks, Session Validity etc. Instead of putting multiple if else blocks I thought it can be implemented as following.

Please let me know if I can improve this.

public interface IValidator {

    public void validate(Context context) throws ValidatorException;

    public void handleFailure(Context context) throws Exception;

}

public class CSRFValidator implements IValidator, CWSConstants {

    private final Logger LOGGER = LoggerFactory.getLogger(CSRFValidator.class);

    @Override
    public void validate(Context context) throws ValidatorException {
        //some logic to validate request if it contains CSRF token
    }

    @Override
    public void handleFailure(Context context) throws Exception {
        context.getHttpServletResponse().sendError(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
    }
}

public class BrowserCheckValidator implements IValidator, CWSConstants {

    private final Logger LOGGER = LoggerFactory.getLogger(CSRFValidator.class);

    @Override
    public void validate(Context context) throws ValidatorException {
        //if request is not coming from suported browser then throw exception
    }

    @Override
    public void handleFailure(Context context) throws Exception {
        context.getHttpServletResponse().sendError(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
    }
}

public class AuthenticationFilter implements Filter{
    private List<IValidator> requestValidators = new ArrayList<>();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc)
            throws IOException, ServletException {
                            Context context = new Context(httpRequest, httpResponse, session);
        for (IValidator validator : requestValidators) {
            try {
                LOGGER.debug("Validating " + validator.getClass().getName());
                validator.validate(context);
            } catch (ValidatorException e) {
                LOGGER.error("Error while validating " + validator.getClass().getName(), e);
                validator.handleFailure(context);
                return;
            }
        }
        fc.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("Initializing validators");
        requestValidators.add(new CSRFValidator());
    }

}
public class ValidatorException extends Exception {

    private static final long serialVersionUID = 8990146478624920065L;

    public ValidatorException() {
        super();
    }

    public ValidatorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public ValidatorException(String message, Throwable cause) {
        super(message, cause);
    }

    public ValidatorException(String message) {
        super(message);
    }

    public ValidatorException(Throwable cause) {
        super(cause);
    }
}

public final class Context {

    private HttpServletRequest httpServletRequest;
    private HttpServletResponse httpServletResponse;
    private HttpSession httpSession;

    public Context(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            HttpSession httpSession) {
        this.httpServletRequest = httpServletRequest;
        this.httpServletResponse = httpServletResponse;
        this.httpSession = httpSession;
    }

    public HttpServletRequest getHttpServletRequest() {
        return httpServletRequest;
    }

    public HttpServletResponse getHttpServletResponse() {
        return httpServletResponse;
    }

    public HttpSession getHttpSession() {
        return httpSession;
    }

}


texts:
I'm using Axios to fetch data from an API, and don't know if this is the best way to deal with APIs in ReactJS or not. I want to know if anyone can suggest edits or something to make the code more efficient.

api.js

import axios from 'axios';

export const APIendpoint = axios.create({
    baseURL: 'https://1eb19101-0790-406f-90e0-ee35a2ff2d1f.mock.pstmn.io',
    timeout: 2000
});

matchesAction.js

import {FETCH_MATCHES} from './actionTypes';
import {APIendpoint} from '../api/api';

export const fetchMatches = () => dispatch => {
    const matchInstance = APIendpoint.get('/matches');
    matchInstance.then(response =>
        dispatch({
            type: FETCH_MATCHES,
            payload: response.data
        })
    );
};


texts:
I am creating a very small application to demonstrate solid principles and also a brief implementation of a builder pattern, does anyone have any feedback as to how this could be improved or how it breaks the solid principles? The app is a small app that just converts units, e.g. yards to meters, inches to cms.

Interface

public interface IConverter
{
    double ConversionRate { get; set; }
    string[] ConvertedUnits { get; set; }
    string DisplayText { get; set; }

    string[] Convert(string input);
}

Class implementing interface

 public class Converter : IConverter
    {
        public double ConversionRate { get; set; }
        public string[] ConvertedUnits { get; set; }
        public string DisplayText { get; set; }

        public Converter(double conversionRate, string[] convertedUnits, string displayText)
        {
            ConversionRate = conversionRate;
            ConvertedUnits = convertedUnits;
            DisplayText = displayText;
        }

        public string[] Convert(string input)
        {
            if (!input.Contains('\n'))
            {
                double d = double.Parse(input, CultureInfo.InvariantCulture) * ConversionRate;

                string[] array = new string[1];
                array[0] = d.ToString();

                return array;
            }
            else
            {
                double[] doubles = new double[input.Split('\n').Count()];

                for (int i = 0; i < input.Split('\n').Count(); i++)
                {
                    double value = double.Parse(input.Split('\n')[i]);
                    doubles[i] = value;

                    string.Format("{0}", value * ConversionRate);
                }

                string[] strings = new string[doubles.Length];

                for (int i = 0; i < input.Split('\n').Length; i++)
                {
                    strings[i] = string.Format("{0}", doubles[i] * ConversionRate);
                }

                return strings;
            }
        }
    }

Builder (abstract class)

public abstract class ConverterBuilder
    {
        protected double _conversionRate;
        protected string[] _convertedUnits;
        protected string _displayText;

        public ConverterBuilder AddConversionRate(double conversionRate)
        {
            _conversionRate = conversionRate;
            return this;
        }

        public ConverterBuilder AddConversionRate(string[] convertedUnits)
        {
            _convertedUnits = convertedUnits;
            return this;
        }

        public ConverterBuilder AddDisplayText(string displayText)
        {
            _displayText = displayText;
            return this;
        }

        public Converter Build()
        {
            return new Converter(_conversionRate, _convertedUnits, _displayText);
        }

    }

Builder implementing abstract builder class

public class UnitConverterBuilder : ConverterBuilder
{
    public UnitConverterBuilder()
    {

    }
}

Controller

public IActionResult Convert(string text, double conversionRate)
{
    Converter converter = new UnitConverterBuilder()
    .AddConversionRate(conversionRate)
    .Build();

    string output = "";
    for (int i = 0; i < converter.Convert(text).Count(); i++)
    {
        output += converter.Convert(text)[i] + Environment.NewLine;
    }

    return Content(output);

}

View

    Enter values to convert

<form asp-controller="Home" asp-action="Convert" method="post">
    <textarea id="text" name="text" rows="10" cols="40"></textarea>
    <select name="conversionRate">
        <option value="">Please Select</option>
        <option value="0.9144">Yards to Meters</option>
        <option value="2.54">Inches To Centimeters</option>
    </select>
    <button>Convert</button>
</form>

The app is built using .net core, any feedback greatly appreciated :)