texts:
This code is intended to find all possible solutions to a cryptoarithmetic problem.  The description of the problem I was trying to solve is here:

  In cryptoarithmetic problems, we are given a problem wherein the
  digits are replaced with characters representing digits. A solution to
  such a problem is a set of digits that, when substituted in the
  problem, gives a true numerical interpretation.

  Example:

IS
IT
___
OK

  has a solution

{ I = 1; K = 1; O = 3; S = 5; T = 6}

  For each of the below cryptoarithmetic problems, write a program that finds all
  the solutions in the shortest possible time.

IS     I
IT    AM
__    __
OK    OK

I was only able to solve it using brute force, though I believe there are more efficient methods.  I am also hoping to receive feedback on my formatting, naming, and really anything you think could use improvement.

(defun place-value-to-integer (the-list &OPTIONAL place-value)
  (let ((place-value (if place-value place-value 1)))
    (if (= (length the-list) 1) (* place-value (first the-list))
      (+ (* place-value (first (last the-list))) (place-value-to-integer (butlast the-list) (* 10 place-value))))))

(defun fill-from-formula (formula guess)
  (loop for digit in formula collect (gethash digit guess)))

(defun check-answer (augend-formula addend-formula sum-formula guess)
  (let ((augend (fill-from-formula augend-formula guess))
    (addend (fill-from-formula addend-formula guess))
    (sum (fill-from-formula sum-formula guess)))
        (= (place-value-to-integer sum) (+ (place-value-to-integer augend) (place-value-to-integer addend)))))

(defun brute-force-guess(augend-formula addend-formula sum-formula unique-values &OPTIONAL callback guess)
  (let ((guess (if (null guess) (make-hash-table) guess)))
    (loop for digit in '(0 1 2 3 4 5 6 7 8 9) do
      (setf (gethash (car unique-values) guess) digit)
      (if (= (length unique-values) 1)
        (if (check-answer augend-formula addend-formula sum-formula guess) (print-result augend-formula addend-formula sum-formula guess) nil)
        (brute-force-guess augend-formula addend-formula sum-formula (cdr unique-values) callback guess)))))

(defun print-result (augend-formula addend-formula sum-formula guess)
  (format t "One answer is ~a + ~a = ~a ~%"
      (fill-from-formula augend-formula guess)
      (fill-from-formula addend-formula guess)
      (fill-from-formula sum-formula guess)))

(defun find-unique-values (the-list)
  (let ((unique-items ()))
    (loop for sublist in the-list do
      (loop for item in sublist do
          (unless (member item unique-items) (setf unique-items (append (list item) unique-items))))) unique-items))

(let ((problemA (list (list 'I 'S) (list 'I 'T) (list 'O 'K)))
      (problemB (list (list 'I) (list 'A 'M) (list 'O 'K))))
    (brute-force-guess (first problemA) (second problemA) (third problemA) (find-unique-values problemA) #'print-result)
    (brute-force-guess (first problemB) (second problemB) (third problemB) (find-unique-values problemB) #'print-result))


texts: Written numbers to numerical representation

texts:
So I took a stab at this task to begin learning common lisp.

The idea is that you give it a written representation of a number such as "three thousand and forty nine" and it will output 3049.

I was looking for some input on my lisp and where I'm being daft or even what parts are good.

So without further a due, my code:

(defmacro do-push (result value)
 `(if (not (eq ,value 0))
   (progn (setf ,result (append ,result (cons ,value nil)))
      (setf ,value 0))))

(defun should-push (string)
 (or (equalp string "and")) (not (should-multiply string)))

(defmacro sum-list (L)
 `(reduce '+ ,L))

(defun get-input ()
 (princ "Please enter a number: ")
 (read-line))

(defun tokenize (string)
 (loop for i = 0 then (incf j)
       as j = (position #\Space string :start i)
       collect (subseq string i j)
       while j))

(defun should-multiply (string)
 (or (equalp string "hundred") (equalp string "thousand") (equalp string "million")))

(defun get-needed-operation (string)
 (cond ((should-multiply string) (symbol-function '*))
       ((equalp string "and") (symbol-function '+))
       (t nil)))

(defun string-value (string)
 (cond ((equalp string "one") 1)
       ((equalp string "two") 2)
       ((equalp string "three") 3)
       ((equalp string "four") 4)
       ((equalp string "five") 5)
       ((equalp string "six") 6)
       ((equalp string "seven") 7)
       ((equalp string "eight") 8)
       ((equalp string "nine") 9)
       ((equalp string "ten") 10)
       ((equalp string "eleven") 11)
       ((equalp string "twelve") 12)
       ((equalp string "thirteen") 13)
       ((equalp string "fourteen") 14)
       ((equalp string "fifteen") 15)
       ((equalp string "sixteen") 16)
       ((equalp string "seventeen") 17)
       ((equalp string "eighteen") 18)
       ((equalp string "nineteen") 19)
       ((equalp string "twenty") 20)
       ((equalp string "thirty") 30)
       ((equalp string "forty") 40)
       ((equalp string "fifty") 50)
       ((equalp string "sixty") 60)
       ((equalp string "seventy") 70)
       ((equalp string "eighty") 80)
       ((equalp string "ninety") 90)
       ((equalp string "hundred") 100)
       ((equalp string "thousand") 1000)
       ((equalp string "million") 1000000)))

(let ((result '())
      (current 0))
 (loop for word in (tokenize "one million three hundred thousand eighteen thousand six hundred and seventy three") do
  (let ((operation (get-needed-operation word))
        (value (string-value word)))
   (progn (when (and (eq value nil) (eq operation nil))
       (format t "Unexpected token: ~a~c" word #\newline))

      (if (eq operation nil) (setq operation (symbol-function '+)))

      (when (should-push word)
       (do-push result current))

      (when (not (eq value nil))
       (setq current (funcall operation value current)))))
       finally (do-push result current))
 (format t "Result: ~a" (sum-list result)))

My logic is to have a list that contains all the detected "sub-numbers" which are just added together to get the final number.

Certain words (hundred, thousand, etc) imply a multiply operation to the current number such that three hundred becomes 3 * 100 = 300

Certain words (and, one, two, etc) imply an addition operation such that sixty seven becomes 60 + 7 = 67

Some words cause the current number to be pushed to the result list, resetting the current number.


texts: Given a word, find other words in an array with same length and same characters

texts:
I tried solving the problem in the following manner; I am just a beginner and wanted to know my mistakes and a more efficient way with better time complexity (if any).

    public class d3 {
    public static void main(String[] args){
    String Search="loop";
    String[] letters = Search.split("") ;
    int counter;

    String[] words={"pole","pool","lopo","book","kobo"};

    for(int i=0;i<words.length;i++)
    {
        counter=0;
        String ssplit[] = words[i].split("");
        for(int j=0;j<words[i].length();j++)
        {

            if(letters.length==ssplit.length)
            {
            for(int k=0;k<letters.length;k++)
            {
                    if(letters[j].equals(ssplit[k]))
                        {counter++;
                        ssplit[k]="*";
                break;

                        }

            }
            if (counter == 4)
            {
                System.out.println(words[i]);

            }

        }
            }

    }

}
}


texts: Calculate the crc32 of the contents of a file using boost

texts:
I'm computing the crc32 of a given file using boost:

uint32_t crc32(const std::string &fp){
    boost::crc_32_type result;
    std::ifstream is{fp, std::ios::in | std::ios::binary};
    size_t file_size = is.tellg();
    is.seekg(0, std::ios::beg);
    std::vector<char> buf(file_size);
    is.read(&buf[0], file_size);

    result.process_bytes(&buf[0], file_size);
    return result.checksum();
}

I believe this code is correct, but it seems unecssarily verbose, and does 2 passes over the data.

Ideally I'd like to write something like:

uint32_t crc32(const std::string &fp){
    boost::crc_32_type result;
    std::ifstream is{fp, std::ios::in | std::ios::binary};
    size_t file_size = is.tellg();
    result.process_block(std::istreambuf_iterator<char>{is}, {}); //invalid
    return result.checksum();
}

But I'm not sure there's a valid way to convert the iterator to char *.

The final alternative I tried was:

for(uint8_t b : std::istreambuf_iterator<char>{is}){ //invalid
    result.process_byte(b);
}
return result.checksum();

But I'm unclear how to get a range from a istreambuf_iterator.


texts:
I got a word count assignment and the requirements are shown below:

  INPUT

  The input contains words in several lines and in each line
  there could be more than one word. The input only contains English
  words, separated by space or line breaks. Words are case-sensitive.

  OUTPUT

  Print the words in alphabetic order with the corresponding appearance
  count in the text. For each word, please print the result in a single line
  (separate the word and the number with space).

Sample Input:

Computer system
computer design
algorithm design and analysis
quantum computer
computer science Department

Sample Output:

Computer 1
algorithm 1
analysis 1
and 1
computer 3
department 1
design 2
quantum 1
science 1
system 1

I tried something shown below and actually got the same output as the sample but still got marked as wrong answer by the assignment judge system.
Is there anything I did wrong?

#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
using namespace std;

int main() {

    string whole;
    string line;
    string word;

    do {
        getline(cin, line);
        whole += line + ' ';
    } while (!line.empty());

    if (!whole.empty()) {
        istringstream iss(whole);
        vector<string> results((istream_iterator<string>(iss)), istream_iterator<string>());

        int count = 1;
        int size = results.size();
        if (size == 1) cout << results[0] << ' ' << count;
        else {
            sort(results.begin(), results.end());
            for (int j = 0; j < size; j++) {
                if (j != size - 1) {
                    if (results[j] != results[j + 1]) {
                        string word = results[j];
                        cout << word << ' ' << count << endl;
                        count = 1;
                    }
                    else if (results[j] == results[j + 1]) count++;
                }
                else if (j == size - 1) {
                    if (results[j] != results[j - 1]) {
                        string word = results[j];
                        cout << word << ' ' << count << endl;
                    }
                    else if (results[j] == results[j - 1]) cout << results[j] << ' ' << count << endl;
                }
            }
        }
    }
    return 0;
}


texts:
Recently I did an exercise to understand Akka. I implemented a trading system with Akka to process orders with Actors.

My code is like:

Order: Immutable class with acts as the messages in the system.

public final class Order {

    public enum OrderType {
        BUY,
        SELL
    };

    private final int orderId;

    private final OrderType orderType;

    private final String instrument;

    private final double price;

    public Order(int orderId, OrderType orderType, String instrument, double price) {
        this.orderId = orderId;
        this.orderType = orderType;
        this.instrument = instrument;
        this.price = price;
    }

    public int getOrderId() {
        return orderId;
    }

    public OrderType getOrderType() {
        return orderType;
    }

    public String getInstrument() {
        return instrument;
    }

    public double getPrice() {
        return price;
    }
}

Then I created an OrderProcessingActor to process the orders received. For now, the process is an abstract thing which only prints the order received and tells the sender order executed information.

import akka.actor.AbstractActor;
import akka.actor.Props;

public class OrderProcessingActor extends AbstractActor {

    public static Props props() {
        return Props.create(OrderProcessingActor.class, OrderProcessingActor::new);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(
                        Order.class,
                        order -> {
                            processOrder(order);
                        }).build();
    }

    private void processOrder(Order order) {
        System.out.println(String.format("OrderProcessingActor %d %s order received for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()));
        //process order here.
        getSender().tell(String.format("OrderProcessingActor %d %s order processed for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()), getSelf());
    }
}

I also created a TradingSystemSupervisor which is responsible for creating and managing OrderProcessingActor. The orders are received by the TradingSystemSupervisor which are then sent to the OrderProcessingActor.

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;

import java.util.HashMap;
import java.util.Map;

public class TradingSystemSupervisor extends AbstractActor {

    private static Map<String, ActorRef> actorRefMap = new HashMap<>();

    public static Props props() {
        return Props.create(TradingSystemSupervisor.class, TradingSystemSupervisor::new);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(
                        Order.class,
                        order -> {processOrder(order);}).build();
    }

    private void processOrder(Order order) {
        System.out.println(String.format("TradingSystemSupervisor %d, %s order received for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()));
        //process order here.
        if(!actorRefMap.containsKey(order.getInstrument())) {
            ActorRef actorRef = getContext().getSystem().actorOf(OrderProcessingActor.props(), String.format("%s-order-processing-actor", order.getInstrument()));
            actorRefMap.put(order.getInstrument(), actorRef);
        }
        actorRefMap.get(order.getInstrument()).tell(order, getSelf());
    }
}

I am looking for a review of the solution from Java as well as Akka's perspective. Is my solution ok considering the way I have used Akka or can I improve the solution? I am also trying to implement Akka routing to this solution.


texts: Static wcf client to make multiple request with one object

texts:
I want to make a static client to call a wcf because the first time I call the wcf it takes too long, even sometimes it throws time out.

I have the following class:

public class Repository : IRepository
{
    protected static ServiceClient Client { get; set; }

    public Repository()
    {
        if (Client == null)
        {
            Client = new ServiceClient();
        }

        if (Client.ChannelFactory.State != CommunicationState.Opened
            || Client.ChannelFactory.State != CommunicationState.Created)
        {
            Client = new ServiceClient();
        }
    }

    public virtual async Task<Response> GetPersonsFromAddress(string address)
    {
        try
        {
            Request request = new Request();
            request.Address = address;
            Response response = await Client.GetPersonsAsync(request);

            return response;
        }
        catch (Exception ex)
        {
            // ...
            // Handle exception
            // ...
        }
    }
}

And this class calls the method:

public class Conector : IConector
{
    private IRepository Repository { get; }

    public Conector()
    {
        Repository = new Repository();
    }

    public virtual async Task<Response> GetPersonsFromAddress(string address)
    {
        Response response = await Repository.GetPersonsFromAddress(address);
        return response;
    }
}

The object that calls the wcf service is static so I want to know if this is a good practice.

Also if there are a lot of people at the same time using this method, it will return the correct response for each request.


texts: Creating a thumbnail of a PDF using Cairo, Poppler and Rust

texts:
I want to create thumbnails from PDF files – specifically, a thumbnail of the first page. Currently I use pdftocairo on the command line:

$ pdftocairo myfile.pdf -png -singlefile -scale-to-x 400 -scale-to-y -1

but I wanted to see if I could implement this without shelling out to an external tool. I've written a function in Rust that links to poppler, takes the path to a PDF file, and a path to write a thumbnail to. It reads the first page of the PDF, renders it as a PNG, and saves it to the thumbnail path.

The function seems to work in the handful of PDFs I've tested, and I have a larger corpus I can test on if I decide to use this code.

I'd be interested in knowing:

Is this idiomatic Rust, especially the error handling? I don't have much experience writing Rust and I've been doing everything on my own, so my knowledge of what counts as "good" Rust code is quite limited.
Are there any bugs? I think I've covered the happy path and all the errors (thanks Rust!), but I might have missed something less obvious.
Is there a better way of doing this in Rust? I'm not tied to Cairo or Poppler, and if there's a Rust-native PDF library or similar that can do this sort of thing, I'd have a look at that instead.

extern crate cairo;
extern crate glib;
extern crate poppler;

use std::convert::From;
use std::fs::File;
use std::result::Result;

use cairo::{Context, Format, ImageSurface};
use poppler::{PopplerDocument, PopplerPage};

#[derive(Debug)]
pub enum ThumbnailError {
    GlibError(glib::error::Error),
    NoPagesError,
    CairoError(cairo::Status),
    CairoIoError(cairo::IoError),
    IoError(std::io::Error),
}

impl From<glib::error::Error> for ThumbnailError {
    fn from(err: glib::error::Error) -> Self {
        ThumbnailError::GlibError(err)
    }
}

impl From<cairo::Status> for ThumbnailError {
    fn from(status: cairo::Status) -> Self {
        ThumbnailError::CairoError(status)
    }
}

impl From<cairo::IoError> for ThumbnailError {
    fn from(err: cairo::IoError) -> Self {
        ThumbnailError::CairoIoError(err)
    }
}

impl From<std::io::Error> for ThumbnailError {
    fn from(err: std::io::Error) -> Self {
        ThumbnailError::IoError(err)
    }
}

/// Create a JPEG thumbnail from the first page of a PDF.
fn create_thumbnail(pdf_path: &str, out_path: &str) -> Result<(), ThumbnailError> {

    // Assume the PDF is not password protected.
    let doc: PopplerDocument = PopplerDocument::new_from_file(pdf_path, "")?;

    // Note: PDF pages are 0-indexed
    let page: PopplerPage = match doc.get_page(0) {
        Some(p) => p,
        None => return Err(ThumbnailError::NoPagesError),
    };

    let (width, height) = page.get_size();

    let mut surface = ImageSurface::create(
        Format::Rgb24,
        width as i32,
        height as i32)?;

    // Draw a white background to start with.  If you don't, any transparent
    // regions in the PDF will be rendered as black in the final image.
    let ctxt = Context::new(&mut surface);
    ctxt.set_source_rgb(1.0 as f64, 1.0 as f64, 1.0 as f64);
    ctxt.paint();

    // Draw the contents of the PDF onto the page.
    page.render(&ctxt);

    let mut f: File = File::create(out_path)?;
    surface.write_to_png(&mut f)?;

    Ok(())
}

fn main() {
    let pdf_path = "myfile.pdf";
    let out_path = "thumbnail.png";

    match create_thumbnail(pdf_path, out_path) {
        Ok(_) => println!("Created thumbnail of {} at {}", pdf_path, out_path),
        Err(err) => println!("Something went wrong: {:?}", err),
    };
}
```


texts:
I wrote a Python program that can take as argument either a string or a filename, with these options being mutually exclusive:

#!/usr/bin/env python

import argparse
import sys

def parse_command_line():
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--text', dest = 'input_text', help = 'Text')
    parser.add_argument('-f', '--file', dest = 'input_file', help = 'File containing the text')
    return parser

if __name__ == '__main__':
    parser = parse_command_line()
    args = parser.parse_args()

    if args.input_text is not None and args.input_file is None:
        text = args.input_text
    elif args.input_file is not None and args.input_text is None:
        text = open(args.input_file, 'r').read()
    else:
        parser.print_help()
        sys.exit()

    # Program continues ...

The mutually exclusive check is not optimal and will become very ugly in case of three, four, ... options. How can I improve this code?


texts:
I've just started with the basics of OOP. At first it looked complicated, but once I just started with it, it seemed so easy and everything seems to work like a charm, and that's why I'm unsure if I'm doing this right.

I'm creating a system to track actions:

This is the Timer class:

class Timer {

    private $_db;
    public $user_id;

    public function __construct($db, $user_id) {

        $this->_db = $db;
        $this->user_id = $user_id;

    }

    public function checkActiveTimer() {

        $db = $this->_db;

        $query = $db->prepare("SELECT * FROM qrm_logs WHERE `active` = :active");
        $query->execute(array(

            ':active'   =>  1

        ));

        $result = $query->fetchAll(PDO::FETCH_OBJ);

        if (count($result) > 0) {

            return true;

        }

        return false;

    }

    public function getTimerTypes() {

        $db = $this->_db;

        $query = $db->prepare("SELECT * FROM qrm_types WHERE `active` = :active");
        $query->execute(array(

            ':active'   =>  1

        ));

        $types = $query->fetchAll(PDO::FETCH_OBJ);

        if (count($types) > 0) {

            return $types;

        }

        return false;

    }

    public function startTimer() {

        $db = $this->_db;
        $user_id = $this->user_id;

        $date = new Datetime();

        $query = $db->prepare("INSERT INTO `qrm_logs` (`user_id`, `type_id`, `active`, `started_at`) VALUES (:user_id, :type_id, :active, :started_at)");
        $query->execute(array(

            ':user_id'      =>  $user_id,
            ':type_id'      =>  6,
            ':active'       =>  1,
            ':started_at'   =>  $date->format('Y-m-d H:i:s')

        ));

    }

    public function getTime() {

        $db = $this->_db;
        $user_id = $this->user_id;

        $query = $db->prepare("SELECT `started_at` FROM qrm_logs WHERE `active` = :active AND `user_id` = :user_id");
        $query->execute(array(

            ':active'   =>  1,
            ':user_id'  =>  $user_id

        ));

        $result = $query->fetchAll(PDO::FETCH_OBJ);

        if (count($result) > 0) {

            foreach ($result as $time) {

                $date = new Datetime($time->started_at);
                $date2 = new Datetime();

                $difference = $date2->getTimestamp() - $date->getTimestamp();

                return $difference;

            }

        }

        return false;

    }

    public function stopActiveTimer() {

        $db = $this->_db;
        $user_id = $this->user_id;

        $date = new Datetime();

        $query = $db->prepare("UPDATE `qrm_logs` SET `active` = :inactive, `ended_at` = :ended_at WHERE `user_id` = :user_id AND `active` = :active");
        $query->execute(array(

            ':inactive' =>  0,
            ':ended_at' =>  $date->format("Y-m-d H:i:s"),
            ':user_id'  =>  $user_id,
            ':active'   =>  1

        ));

    }

    public function startWhiteSpaceTimer($type_id) {

        $db = $this->_db;
        $user_id = $this->user_id;

        $date = new Datetime();

        $query = $db->prepare("INSERT INTO `qrm_logs` (`user_id`, `type_id`, `active`, `started_at`) VALUES (:user_id, :type_id, :active, :started_at)");
        $query->execute(array(

            ':user_id'      =>  $user_id,
            ':type_id'      =>  $type_id,
            ':active'       =>  1,
            ':started_at'   =>  $date->format('Y-m-d H:i:s')

        ));

    }

}

This is a piece of code I use in an AJAX request:

$timer = new Timer($db, $_SESSION['id']);

if ($timer->checkActiveTimer() !== false) {

    $timer->stopActiveTimer();

}

$timer->startWhitespaceTimer($type_id);

Can you give me some feedback on how I'm currently approaching it (right or wrong), and eventually correct some errors/mistakes?


texts: Full text search for multiple words using Laravel and MySQL

texts:
I'm using Laravel 5.6 and MySQL. I need to search multiple columns for a single word or multiple words (e.g., "camhandle", "cam handle").

The way I was originally doing it was just using column like %$request->keyword% but if I type in "cam handle" it wouldn't return results that were "camhandle" so I had to  search word by word. I came up with this solution but it's messy.

How can I improve this code?

$s = preg_split('/\s+/', $request->keyword, -1, PREG_SPLIT_NO_EMPTY);

$items =   Items
            ::join('ic.itemunits as iu', function($join) {
                $join->on('items.itemcode', '=', 'iu.itemcode');
                $join->on('items.defaultvendorcode', '=', 'iu.vendorcode');
            })
            ->select('items.itemcode', 'items.picturecode', 'items.description')
            ->where(function ($query) use ($s) {
                foreach ($s as $value) {
                    $query->orWhere('items.description', 'like', "%{$value}%");
                    $query->orWhere('items.itemcode', 'like', "%{$value}%");
                    $query->orWhere('iu.itemcode', 'like', "%{$value}%");
                }
            })
            ->get();


texts: Search for a multiword string in a list of strings

texts:
Unlike Perl, you can't to my knowledge match a regular expression inside an if statement in Python and assign the result to a varaible at the same moment. This leads to typical constructs like this:

match = re.search(REGEX, STRING)
if match:
    # do something

So far, so Python. But what if I want to iterate through a file / array of lines, check each line for a few regexes, and fire a catch-all when none has matched? I can't think my way around a rather unwieldy and deeply nested if-else-if-else...-construction:

import re
strings = ["abc zzz", "y", "#comment"]
for s in strings:
    match = re.search("(\S+) (\S+)", s)
    if match:
        print "Multiword: %s+%s" % (match.group(1), match.group(2))
    else:
        match = re.match("y$", s)
        if match:
            print "Positive"
        else:
            match = re.match("n$", s)
            if match:
                print "Negative"
            else:
                # a few more matches possible in real life script,
                # and then the last catch-all:
                print "No match found, line skipped"

Isn't there any way to put this in a much nicer looking elif-construction or something? The following doesn't work in Python, because if-clauses take only expressions, not statements. However, something along these lines would strike me as pythonic, or am I blind to something obvious here?

if match = re.search(" ", s):
    print "Multiword: %s+%s" % (match.group(1), match.group(2))
elif match = re.match("y$", s):
    print "Positive"
else:
    print "No match found, line skipped"


texts:
This simply pulls data from mysql and creates the html to be sent to the page.

class view_html extends database
  {
  function __construct($type)
    {
    parent::__construct();
    switch ($type)
      {
      case "bookmraks":
        $this->bookmarks();
        break;
      case "tweets":
        $this->tweets();
        break;
      default:
        echo "Invalid View Type";
        break;
      }
    }
  private function bookmarks()
    {
    $email = $_SESSION['email'];
    $query_return = database::query("SELECT * FROM bo  WHERE email='$email' ORDER BY name ASC");
    while ($ass_array = mysqli_fetch_assoc($query_return))
      {
      $fav=$this->fav($ass_array['url']);
      echo "$ass_array[name]";
      }
    }
  private function tweets()
    {
    $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7");
    $time = time();
    while ($a = mysqli_fetch_assoc($query_return))
      {
      echo  "
$a[fname] posted

$a[message]

";
      }
    }
  private function fav($url)
    {
    $pieces = parse_url($url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))
      {
      return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico';
      }
      return false;
    }
  }


texts: Method for adding error messages to a dictionary given a key

texts:
I want this method to be completely understandable just from looking at the code and comments only.

def add_error(error_dict, key, err):
    """Given an error message, or a list of error messages, this method
    adds it/them to a dictionary of errors.

    Doctests:
        >>> add_error({}, 'key1', 'error1')
        {'key1': ['error1']}
        >>> add_error({'key1': ['error1']}, 'key1', 'error2')
        {'key1': ['error1', 'error2']}
        >>> add_error({'key1': ['error1', 'error2']}, 'key2', 'error1')
        {'key1': ['error1', 'error2'], 'key2': ['error1']}
        >>> add_error({}, 'key1', ['error1', 'error2'])
        {'key1': ['error1', 'error2']}
        >>> add_error({}, 'key1', [])
        {}
        >>> add_error({'key1': ['error1']}, 'key2', ['error1', 'error2'])
        {'key1': ['error1'], 'key2': ['error1', 'error2']}
        >>> add_error({}, 'key1', 23) # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        TypeError: The error(s) must be a string, or a list of strings.
        >>> add_error({}, 'key1', [23]) # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        TypeError: The error(s) must be a string, or a list of strings.
        >>> add_error({}, 'key1', ['error1', 23]) # doctest: \
        +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        TypeError: The error(s) must be a string, or a list of strings.
    """
    if not isinstance(err, list):
        err = [err]

    if not key in error_dict and len(err) > 0:
        error_dict[key] = []

    for e in err:
        if not isinstance(e, string_types):
            raise TypeError(
                'The error(s) must be a string, or a list of strings.'
            )
        error_dict[key].append(e)
    return error_dict

Hopefully, the code along with the comment does the job well, but I would still appreciate review(s) of this method. One thing I always keep on wondering is whether this is too many doc-tests for such a simple method. Thanks.


texts: Identify MOT Dates which could be in various formats

texts:
I want to significantly tidy this code as its cluttered and repetitive

var myDate = "No MOT"

if ((myData[0]["motTests"][0]["expiryDate"].string) != nil) {

    let theDate=myData[0]["motTests"][0]["expiryDate"].string
    let msYear = theDate!.prefix(4)
    let msMonth = theDate!.suffix(5).prefix(2)
    let msDay = theDate!.suffix(2)
    let mYear = Int (msYear)
    let mMonth = Int (msMonth)
    let mDay = Int(msDay)
    self.motDue = self.convertDate(aYear: mYear!, aMonth: mMonth!, aDay: mDay!)

    myDate=msDay+("/")+msMonth+"/"+msYear
}
if ((myData[0]["motTestExpiryDate"].string) != nil){
    let theDate=myData[0]["motTestExpiryDate"].string

    let msYear = theDate!.prefix(4)
    let msMonth = theDate!.suffix(5).prefix(2)
    let msDay = theDate!.suffix(2)

    let mYear = Int (msYear)
    let mMonth = Int (msMonth)
    let mDay = Int(msDay)
    self.motDue = self.convertDate(aYear: mYear!, aMonth: mMonth!, aDay: mDay!)

    myDate=msDay+("/")+msMonth+"/"+msYear
}

self.myMOT.text=String(myDate)

The code checks to see if the vehicle has an MOT, if it does its sets myDate to the date. If not it checks when the first MOT is due and sets myDate to that's and if not myDate stays set to "No MOT"

It works but needs improving.


texts: Imrpove the following code without if/else

texts:
I want to avoid using multiple if and else condition here

  if (decode) {
                Imagepath = bucket + "/" + key;
                Result.pages.push({
                        Id: Processid,
                        ValidTicket: decode ? true : false
                });
        } else {
                //checking for barcode if qr code is not present
                Quagga.decodeSingle({
                        src: filename,
                        numOfWorkers: 0, // Needs to be 0 when used within node
                        decoder: {
                                readers: ['code_128_reader',
                                        'ean_reader',
                                        'ean_8_reader',
                                        'code_39_reader',
                                        'code_39_vin_reader',
                                        'codabar_reader',
                                        'upc_reader',
                                        'upc_e_reader',
                                        'i2of5_reader'
                                ] // List of active readers
                        },
                }, function (result, error) {
                        //if guaggajs returns the result
                        if (result) {
                                console.log("bar code done");
                                //sometimes result is not empty but codeResult is empty
                                if (result.codeResult) {
                                        var barcode = result.codeResult.code;
                                        var Imagepath = '';
                                        Imagepath = bucket + "/" + key;
                                        Result.pages.push({
                                                Id: Processid,
                                                ValidTicket: barcode ? true : false
                                        });
                                        console.log("final array is" + Result);
                                } else {
                                        var Imagepath = '';
                                        Imagepath = bucket + "/" + key;
                                        Result.pages.push({
                                                Id: Processid,
                                                ValidTicket: false
                                        });

                                }
                        } else {
                                var Imagepath = '';
                                Imagepath = bucket + "/" + key;
                                Result.pages.push({
                                        Id: Processid,
                                        ValidTicket: false
                                });

                        }
                });
        }


texts: Using HikariCP and JDBC to store data for a Minecraft plugin

texts:
I'm creating a plugin for the game Minecraft, and with it I'm using HikariCP and MySQL to store data between server restarts. I've created working code but I'm wanting to improve it.

While the code works fine, I feel there's a simpler way to structure it. I appreciate any suggestions.

HikariFacade.java

public class HikariFacade {

private final HikariConfig hikariConfig;
private final HikariDataSource hikariDataSource;

public HikariFacade(HikariConfig hikariConfig) {
    this.hikariConfig = hikariConfig;
    hikariDataSource = new HikariDataSource(hikariConfig);
}

/**
 * Get a connection from the DataSource
 *
 * @return A connection, or null if one couldn't be obtained
 */
public Connection getConnection() {
    Connection connection = null;
    try {
        connection = hikariDataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}

/**
 * Create a PreparedStatement
 *
 * @param sql The SQL for the PreparedStatment
 * @return A prepared statement
 * @throws SQLException
 */
public PreparedStatement createPreparedStatement(String sql) throws SQLException {
    return getConnection().prepareStatement(sql);
}

/**
 * Run an update, then close the resources
 *
 * @param ps Run a PreparedStatement as an update
 * @return The number of rows effected
 * @throws SQLException
 */
public int update(PreparedStatement ps) throws SQLException {
    int i = ps.executeUpdate();
    close(ps.getConnection(), ps, null);
    return i;
}

/**
 * Run a query, then close the resources
 *
 * @param ps Run a PreparedStatement as a query
 * @return The ResultSet from the query
 * @throws SQLException
 */
public ResultSet query(PreparedStatement ps) throws SQLException {
    ResultSet rs = ps.executeQuery();
    close(ps.getConnection(), ps, rs);
    return rs;
}

/**
 * Close a set of database related objects
 *
 * @param connection A Connection to close
 * @param statement  A Statement to close
 * @param resultSet  A ResultSet to close
 */
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
    try {
        if (connection != null) {
            connection.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (resultSet != null) {
            resultSet.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public HikariDataSource getHikariDataSource() {
    return hikariDataSource;
}
}

DatabaseManager.java

public abstract class DatabaseManager {

protected HikariFacade hikariFacade;

public DatabaseManager(HikariFacade hikariFacade) {
    this.hikariFacade = hikariFacade;
}

}

TownDatabaseManager.java

public class TownDatabaseManager extends DatabaseManager {

public TownDatabaseManager(HikariFacade hikariFacade) {
    super(hikariFacade);
}

public int create(Town town) {
    String sql = "INSERT INTO towns VALUES (?);";
    try {
        PreparedStatement ps = hikariFacade.createPreparedStatement(sql);
        ps.setString(1, String.valueOf(town.getUuid()));
        return hikariFacade.update(ps);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return 0;
}

public List<Town> loadTowns() {
    String sql = "SELECT * FROM towns;";
    try {
        PreparedStatement ps = hikariFacade.createPreparedStatement(sql);
        ResultSet rs = hikariFacade.query(ps);
        List<Town> towns = new ArrayList<>();
        while (rs.next()) {
            UUID townUuid = UUID.fromString(rs.getString("town_uuid"));
            towns.add(new Town(townUuid));
        }
        return towns;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

}

Here's how this is all used in the end:

Main.java

private void testDb() {
    Town newTown = new Town(UUID.randomUUID());

    int i = new TownDatabaseManager(getHikariFacade()).create(newTown);

    new TownDatabaseManager(getHikariFacade()).loadTowns();

}


texts:
I wrote some conditionals for a button component and everything works, but I feel like this is not the right way of writing conditionals. Would appreciate it if anyone could review my code.

import buttonStyles from './Button.module.scss';
import { Link } from "gatsby";

interface Props {
  content: string,
  color: string,
  path?: string,
  type: string
}

export default function Button(props: Props): JSX.Element {
  const availableColors = ['blue', 'grey', 'dark-grey', 'white'];
  const borderColors = [''];

  if(!availableColors.includes(props.color)) {
    console.error(`"${props.color} color key not available for button style`);
    return;
  }

  if(!props.content) {
    console.error(`"${props.content} is not valid as content`);
    return;
  }

  let buttonStyle = buttonStyles[`button--${props.color}`];
  let elementType;

  if(props.type == 'link' || props.type == 'button') {
    if(props.type == 'link') {
      elementType = <Link to={ props.path } className={ buttonStyle }>{ props.content }</Link>
    } else {
      elementType = <button className={ buttonStyle }>{ props.content }</button>
    }
  } else {
    console.error(`"${props.type} is not valid as a type. Use 'link' or 'button'`);
    return;
  }

  return (
    <React.Fragment>
      { elementType }
    </React.Fragment>
  );
}
```


texts: JavaScript implementation of insertion sort

texts:
I just started reading Introduction to Algorithms and the first algorithm introduced is the insertion sort.

Even though the sort seems to work, I thought I'd ask for feedback right at the start since this is a really new topic to me.

This is the JS implementation I came up with based on the pseudo code:

function insertionSort(arr) {
  for (let j = 1; j < arr.length; j++) {
    let key = arr[j]
    let i = j - 1
    while (i >= 0 && key < arr[i]) {
      i--
    }
    arr.splice(i + 1, 0, key)
    arr.splice(j + 1, 1)
    console.log(arr)
  }
}

const arr = [0, 12, 55, 0, 33333, 5, 1, 7, 2, 3, 3]

insertionSort(arr)


texts: Program to shutdown computer after a certain time

texts:
I'm trying to make a program that will shutdown my computer after a certain time that I will input via GUI. I'm wondering if I did it the correct way.

Also, will this slow down my computer while it waits to shut off? Do you see anything wrong with the code?

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class PCShutdown {
    private int minutes;
    private int hours;

    private void setHours(int hoursArg) {
        this.hours = hoursArg;
    }

    private void setMinutes(int minutesArg) {
        this.minutes = minutesArg;
    }

    private void shutDown() {
        Thread shutDownThread = new Thread(new ShutDownThread());
        shutDownThread.start();
    }

    private class ShutDownThread implements Runnable {

        @Override
        public void run() {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    Runtime runtime = Runtime.getRuntime();
                    Process process = null;
                    try {
                        process = runtime.exec("shutdown -s -t 30");
                        System.exit(0);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally { process.destroy();}
                }
            }, (hours * 60 * 60 * 1000) + (minutes * 60 * 1000));
        }
    }
}

Also, I still have to figure out how to kill all open programs except for this one before it shuts down. I'm going to work on that now.

Also, this might be a very dumb question, but will any of these operations harm my computer in any way? Will it be better if I just learn to do this via powershell?


texts:
I created this working sample and the code is below. Any advice on how to make this code; cleaner, more effective, just overall better! The data is coming from an API and I need to parse, select the value in location 0 set the title and then rebuild the drop down control.

can it be done without the JSON.parse(data) or the $.each?

https://dotnetfiddle.net/lfJhGi
      $("#ddlReleaseYears").change(function () {
            $('#toptitle').text('change event');
            //coming from API
            var data = "[2021,2020,2019,2018,2017,2016]";
            var arr = JSON.parse(data);
            $('#toptitle').text(arr[0]);
            var HTML = ""
            $.each(arr, function (index, value) {
                 HTML += "<option value='" +value + "' ";
                 HTML += ">" +value + "</option>"
            });
            $("#ddlReleaseYears").html("");
            $("#ddlReleaseYears").append(HTML);
        })


texts:
This is the problem statement. I have submitted successfully a \$O(n^2)\$ solution and I would like to know if there is a way to improve the running time to, maybe, \$O(n \log n)\$.

  Having dropped out of school because of chemistry, Luka got a job
  driving trucks. One evening he parked his three trucks in a rest area
  which charges for parking in an unusual way – they give a discount on
  quantity.

  When only one truck is parked, the driver pays AA kuna per minute.
  When two trucks are parked, the drivers each pay BB kuna per minute.
  When three trucks are parked, the drivers each pay CC kuna per minute.

  Given the numbers AA, BB and CC, as well as the intervals in which
  Luka’s three trucks are parked, determines how much Luka needs to pay
  the owner of the rest area.

  Input

  The first line contains three integers AA, BB and CC
  (\$1 \le C \le B \le A \le 100\$), the prices of parking as defined above. Each of the following three lines contains two integers each. These are the
  arrival and departure times (in minutes) of one of Luka’s trucks. The
  arrival time will always be earlier than the departure time. All time
  indexes will be between 1 and 100.

  Output

  Output the overall cost of Luka’s parking his three trucks.

Current solution (please note that I use custom I/O which I haven't included):

public class Parking {

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);

        int A = in.readInt();
        int B = in.readInt();
        int C = in.readInt();

        int minArrival = Integer.MAX_VALUE;
        int maxDeparture = Integer.MIN_VALUE;

        Times[] times = new Times[3];

        for (int i = 0; i < 3; ++i) {
            int arrival = in.readInt();
            int departure = in.readInt();

            minArrival = Math.min(minArrival, arrival);
            maxDeparture = Math.max(maxDeparture, departure);
            times[i] = new Times(arrival, departure);
        }

        int result = 0;
        for (int i = minArrival; i <= maxDeparture; ++i) {
            int count = 0;
            for (Times t : times) {
                if (t.arrival <= i && t.departure > i) {
                    count++;
                }
            }

            switch (count) {
                case 1:
                    result += A;
                    break;
                case 2:
                    result += B * 2;
                    break;
                case 3:
                    result += C * 3;
                    break;
                default:
                    break;
            }

        }

        out.print(result);
        out.close();
    }

    private static class Times {
        final int arrival;
        final int departure;

        Times(int arrival, int departure) {
            this.arrival = arrival;
            this.departure = departure;
        }
    }
}


texts: Playing different audio files based on video keyframe

texts:
The general idea of this function is to load a different sound file depending on current time position of the video. I have the following information about audio files:

var samples: [
['00:00:05', 'audio/1.mp3'],
['00:01:00', 'audio/2.mp3']
]

The first element contains the end time for specific audio sample, and the second is the sample. I think we don't need the start time, because the following condition should return a good result:

if( video.currentTime <= endTime ) { ... }

Anyway, here is the code of function I'm using to check which audio file to play (it's executed when the video is paused):

var APP.playAudio = function() {

    var pAudio = samples; // the array above

            for(var i = 0; i < pAudio.length; i++ ) {

                if( video.currentTime < hms_to_s(pAudio[i][0]) ) {
                    pCurrentAudio = pAudio[i][1];
                    break;
                }

            }
}

I'm looking for more tricky and clever way to achieve this. As you see, now we iterate over the pAudio array each time the video is paused.


texts: Function takes a dictionary with list as value, returns the key of the biggest list

texts:
I created a function that takes a dictionary as parameter. This dictionary is expected to have lists as value pair. (i.e. {1: [1, 2, 3], 'a': [4, 'b', 5, 'c']} )
This function has to return the key associated to the biggest list in the dictionary, or None if the dictionary is empty. (considering the above example, it would return 'a' )
I came up with this code:
def biggest(aDict):
    return None if not aDict else [x for x in aDict if len(aDict[x]) == max(len(x) for x in aDict.values())][0]

Can I have some review on this and any ideas on how to further simplify without using external libraries?


texts: How can I reduce the number of nested if statements in this code?

texts:
The application I'm building can accept two types of updates: Application Update and Parameter Updates. If there is an application update, then parameter updates can be ignored. This is the code that I've written, and it's messy.  How can I clean this up?

mContext = this.getApplicationContext();
//experimental();
//check for updates
UpdateMode updateInstallationMode = Parameters.load(mContext).getUpdateMode();
if(updateInstallationMode==UpdateMode.MANUAL)
{
    //User will manually install update - no further action needed to be performed by activity.
    //proceed to next screen.
    gotoNextActivity();
}else
{
    boolean shouldConfirm = (updateInstallationMode == UpdateMode.CONFIRM);

    lblStatus.setText(getString(R.string.checking_for_updates));
    Error outUpdateError = new Error();
    Map<String,String> availableUpdates = checkForUpdates(outUpdateError);

    boolean appUpdatesAvailable = availableUpdates.containsKey("application");
    boolean paramUpdatesAvailable = availableUpdates.containsKey("parameters");
    boolean appUpdatesAccepted = Parameters.load(mContext).getUpdateType()==UpdateType.BOTH
            || Parameters.load(mContext).getUpdateType()==UpdateType.APPLICATION;
    boolean paramUpdatesAccepted = Parameters.load(mContext).getUpdateType() == UpdateType.BOTH
            || Parameters.load(mContext).getUpdateType() == UpdateType.PARAMETERS;

    if(appUpdatesAccepted && appUpdatesAvailable){
        boolean shouldInstall = shouldConfirm? confirmInstallUpdate(UpdateType.APPLICATION):true;
        if(shouldInstall){
            downloadUpdate(UpdateType.APPLICATION,availableUpdates.get("application"));
        }else{
            gotoNextActivity();
        }

    }else if(paramUpdatesAccepted && paramUpdatesAvailable){
        boolean shouldInstall = shouldConfirm? confirmInstallUpdate(UpdateType.PARAMETERS):true;
        if(shouldInstall){
            downloadUpdate(UpdateType.PARAMETERS,availableUpdates.get("parameters"));
        }else{
            gotoNextActivity();
        }
    }else{
        lblStatus.setText(getString(R.string.app_up_to_date));
        gotoNextActivity();
    }
}


texts:
I'm writing a function called unzip that turns:

[(1,2);(3,4);(5,6)]

to

([1;3;5],[2;4;6])

I've got a working implementation right here:

let unzip (data:(int*int) list) : int list * int list =
   match data with
   |(x,y)::tl->(x::traverse (tl,true),y::traverse (tl,false))
   |[]->([],[])
  let rec traverse tree =
    match tree with
    |((x,y)::tl,dir) -> if dir then x::traverse (tl, dir) else y::traverse (tl,dir)
    |([],_) -> [];;

However I'm not sure if this is the cleanest way to do this. As you can see, my traverse function accepts a boolean to know whether or not to go right or left, specifically because of:

(x::traverse (tl,true),y::traverse (tl,false))

Now is there even a way to do this so I only have to call one function, AND it knows where to put the data? or is this an alright way of doing it?

PS: I can't use non-core functions. (Modules, etc.)


texts: Thread-safe "singleton" that destroys object when not used anymore

texts:
I'm working on some legacy code which uses the singleton pattern. The problem I have with the traditional singleton is that the instance lives until the program terminates. This is messing up the order in which things need to get destroyed and makes it difficult to write independent unit tests. Unfortunately, I can't get rid of the singleton by constructing a single instance and passing it around since this would break APIs.

I wrote the following wrapper around a class T that hands out shared pointers to a single instance of T. When the last shared pointer goes out of scope the object gets destroyed.

#include <memory>
#include <type_traits>
#include <mutex>

template <class T>
class refCountedSingleton
{
  static_assert(!std::is_default_constructible<T>::value, "T must have a private/protected constructor to ensure it can only be constructed by refCountedSingleton");
  static_assert(!std::is_copy_constructible<T>::value, "T must have a private/protected copy constructor to ensure instances handed out by refCountedSingleton cannot be copied");
  static_assert(!std::is_copy_assignable<T>::value, "T must have a private/protected copy assignment operator to ensure instances handed out by refCountedSingleton cannot be copied");
  static std::weak_ptr<T> p;
  static std::mutex mu;
public:
  static std::shared_ptr<T> getShared();
};

template <class T>
std::weak_ptr<T> refCountedSingleton<T>::p;
template <class T>
std::mutex refCountedSingleton<T>::mu;

template <class T>
std::shared_ptr<T> refCountedSingleton<T>::getShared()
{
    std::lock_guard<std::mutex> lock(mu);
    std::shared_ptr<T> temp = p.lock();
    if (!temp) {
      temp.reset(new T());
      p = temp;
    }
  return temp;
}

The following class could be used as T:

class obj {
  friend class refCountedSingleton<obj>;
private:
  obj() {}
  obj(obj const&);
  obj& operator=(obj const&);
};

Example use case:

{
  std::shared_ptr<obj> pm1 = refCountedSingleton<obj>::getShared();
  {
    // calling getShared() multiple times yields pointers to the same object
    std::shared_ptr<obj> pm2 = refCountedSingleton<obj>::getShared();
  }
} // instance of obj gets destroyed here
{
   // a new instance of obj gets greated
   std::shared_ptr<obj> pm3 = refCountedSingleton<obj>::getShared();
}

My singleton needs to be thread safe which is why I'm locking the mutex in getShared(). With the traditional singleton pattern performance can be improved by avoiding the expensive locking most of the time by leveraging double-checked locking. I'm wondering if something similar could be done here as well.


texts:
Recently I had someone describe a "Time Machine" service to me; that is, a service that could be used to change how a chunk of code perceives time.

Normally through calls to DateTime.Now and other DateTime statics, time is directly tied to the system clock. A Time Machine service is used instead of the static DateTime calls, and allows external code to change the time it reports. This is especially useful when writing unit tests for services that behave different as time passed due to timers, triggers, etc.

I liked the idea, and decided to implement my own version. Here are the relevant interfaces:

// A service that can travel through time
public interface ITimeTraveler
{
    ITimeMachine TimeMachine { get; set; }
}

// Interface for a Time Machine
public interface ITimeMachine
{
    DateTime Now();
    DateTime UtcNow();
    DateTime Today();
    DateTime UtcToday();
    void TimeTravel(TimeSpan adjustment);
    void TimeTravelTo(DateTime newDateTime);
    void FreezeTime();
    void UnfreezeTime();
    void RevertAllTimeTravel();
    bool IsCurrentlyTimeTraveling();
}

Here is the Time Machine Gist with the full implementation.

This includes two revisions. The first revision was the code I linked to originally, and additional revisions take the feedback here into consideration.

I'm looking for any feedback or suggestions on both the concept of this service and my current implementation.


texts: Searching purchase records, with or without a vendor criterion

texts:
I'm trying to figure out a better way to have one query here. I want to be able to send something to last where statement a wildcard so I can select all vendors. Right now if I don't include that line it doesn't filter by vendor so I essentially get all the purchase requests.

Any thoughts of a cleaner way to do these queries?

 if @vendor == "0" #checks for vendor
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
  else
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
                          .where("purchaseorder.VendorRef_ListID = ?", @vendor)
  end


texts: Filtering a data structure using regex predicates

texts:
Assume we have a data-structure like this:

(def data
     (atom [{:id 1 :first-name "John1" :last-name "Dow1" :age 14}
            {:id 2 :first-name "John2" :last-name "Dow2" :age 54}
            {:id 3 :first-name "John3" :last-name "Dow3" :age 34}
            {:id 4 :first-name "John4" :last-name "Dow4" :age 12}
            {:id 5 :first-name "John5" :last-name "Dow5" :age 24}]))

I want to filter it by specific keys using regex in predicates, so I ended up with this function which works fine, but I guess code is ugly and duplicated. How can I get rid of code duplication?

(defn my-filter [str-input]
  (let [firstname (filter #(re-find (->> (str str-input)
                                         (upper-case)
                                         (re-pattern))
                                    (upper-case (:first-name %)))
                     @data)
        lastname (filter #(re-find (->> (str str-input)
                                        (upper-case)
                                        (re-pattern))
                                   (upper-case (:last-name %)))
                    @data)
        age (filter #(re-find (->> (str str-input)
                                   (upper-case)
                                   (re-pattern))
                              (upper-case (:age %)))
               @data)]
    (if-not (empty? firstname)
      firstname
      (if-not (empty? lastname)
        lastname
        (if-not (empty? age)
          age)))))


texts: Javascript function to return an array that needs to be in a specific order, depending on the order of a different array

texts:
I have an array of objects, reviews which I get from an API endpoint. This object looks like this:
[
  { name: "Facebook", count: 50 },
  { name: "Google", count: 43 },
  { name: "TripAdvisor", count: 67 },
  { name: "Other", count: 130 }
]

I have a chart.js Pie chart that I'm feeding this data to. I'm using the name for the labels and the count for the size of each slice of the pie chart. Now, due to how chart.js works, I have to supply some hexadecimal colors to use as background colors, and the order in which the background color is being defined matters if I want the labels to match the colors properly. For example, if the order of the labels is [A, B, C], an array of colors like [red, green, blue] means that A = red, B = green and C = blue. The problem is that the reviews array comes in a random order every single time from the API (I don't have control over the API and the data it gives me), so I can't just have a simple, predetermined array.
As far as I see, I have two options, I either sort the reviews array in some way, or I iterate over the data I get from the API and return an array based on some simple switch statements. I opted for the 2nd option, as it seems simpler for my usecase.
My current solution looks like this
const chartBackgroundColor = collection => {
  let colorArray = [];
  const itemArray = collection.map(data => data.name);
  itemArray.forEach(item => {
      switch (item) {
        case "TripAdvisor":
          colorArray.push("#00B98B");
          break;
        case "Google":
          colorArray.push("#FFBD00");
          break;
        case "Facebook":
          colorArray.push("#4B6DAA");
          break;
        default:
          colorArray.push("#D9D9D9");
          break;
      }
    }
  )
  return colorArray;
}

The method works fine, but I was just curious whether there was some more elegant way of handling this issue, and whether a switch case is appropriate in this situation rather than a if/ifel/else tree.


texts:
I have written the below code where the server is getting requests from clients on a socket and creating a thread per client. Each client thread is then writing to a file which is common to all the threads. The file has been opened when main starts, so the same fd is being used by each thread. In such a scenario I have tried to achieve locking on file when one thread is writing to it. Since the threads are of same process so flock can't simply lock the file, hence mutex is used.

/*Logging function*/
void write_to_file(int op_fd,char *name)
{
   flock(op_fd,LOCK_EX);
   pthread_mutex_lock(&f_lck);
      write(op_fd,name,20);
   pthread_mutex_unlock(&f_lck);
   flock(op_fd,LOCK_UN);
}

/*Client thread function*/

void *clnt_thread(void * arg)
{
  int this_fd=*(int *)arg;
  /*str is a continuous memory array of the size of the dat_com struct.This will be filled up initially on receive as a normal array
   , but then it'll typecasted to point to struct dat_com object*/
  char str[sizeof(dat_com)],str_send[25];

  memset(&str,'\0',sizeof(str));
  dat_com *incm_dat;    // struct to contain the incoming data from client .

  while(1)
  {
  read(this_fd,str,sizeof(str));
  /*typecast to struct dat_com so that it is ready to be inserted into linked list or file.*/
  incm_dat=(dat_com *)&str;

   if(strncmp(str,"quit",4)==0)
    break;

  /*Call write to file function*/
  write_to_file(o_fd,incm_dat->name);
  fprintf(stderr,"Client said: %s",incm_dat->name);

  /*client wants to close connection?*/

  sprintf(str_send,"%s",incm_dat->name);
  send(this_fd,str_send,sizeof(incm_dat->name),MSG_NOSIGNAL);
  }
close(this_fd);
return 0;
}

This is working as expected at the moment. Is it good practice to lock this way, or is there any other best practice? If I have to put this code into production, what changes should I make that are not standard practice?


texts: Getting paginated data from ajax call and putting the data on the page

texts:
At the moment, it gets the first page worth of data and then each subsequent page when the user scrolls down to the bottom of the page.

My JavaScript/jQuery level is fairly weak, however I have managed to cobble this together and would like to know how I can improve my code.

 var page = 1;

 $(function() {
   getUsers(page);
   page++;
 });

 $(window).scroll(function() {
   if ($(window).scrollTop() + $(window).height() == $(document).height()) {
     getUsers(page);
     page++;
   }
 });

 function getUsers(page) {

   $.ajax({
     url: '/ajax/users?page=' + page
   }).done(function(data) {
     var users = data;
     var user;
     var url = "<?php echo url('profile/') ?>";

     if (page > users.last_page) {
       return true;
     } else {
       $.each(users.data, function(key, value) {
         var image;
         if (value.image[0]) {
           image = value.image[0].name;
         } else {
           if (value.profile.gender == 'male') {
             image = 'maleDefault.png';
           } else {
             image = 'femaleDefault.jpg';
           }
         }
         user = "

";
         $('.panel-body').append(user);
       });
     }
   });
 }


texts: Configuration class in C#, reading an INI file

texts:
This class will load a file with INI configuration elements and cache them, it then has a method to get an item from the cache if it needs to.

internal class ConfigHandler
{
    private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

    private Dictionary<string, string> _configItems;

    public ConfigHandler()
    {
        _configItems = new Dictionary<string, string>();
        LoadConfig("resources/config/pitaya.ini");
    }

    internal void LoadConfig(string configFile)
    {
        try
        {
            if (!File.Exists(configFile))
            {
                Logger.Error("Your config file couldn't be found.");

                Console.ReadKey(true);
                Environment.Exit(0);
            }

            if (CoreUtilities.IsFileLocked(new FileInfo(configFile)))
            {
                Logger.Error("Your config file is already open somewhere.");

                Console.ReadKey(true);
                Environment.Exit(0);
            }

            _configItems = File.ReadLines(configFile).Where(IsConfigurationLine).Select(line => line.Split('=')).ToDictionary(line => line[0], line => line[1]);
        }
        catch (Exception exception)
        {
            Logger.Fatal(exception, "Error while loading config.");

            Console.ReadKey(true);
            Environment.Exit(0);
        }
    }

    private static bool IsConfigurationLine(string line)
    {
        return !line.StartsWith("#") && line.Contains("=");
    }

    internal string GetConfigValueByKey(string key)
    {
        if (!_configItems.TryGetValue(key, out var value))
        {
            Logger.Warn("Missing configuration key `" + key + "`");
        }

        return value;
    }
}


texts:
Successful attempt at the ICPC North America Qualifier 2018 Problem D "Froggie." Any advice and all topical comments on code optimization and performance enhancement is appreciated!

Problem Summary

  You are recreating the classic ‘Frogger’ video game.

  Each level consists of a road with multiple lanes, with cars traveling in both directions. Cars within each lane are evenly-spaced and move at the same speed and in the same direction. Lane directions alternate, with the top lane moving left to right.

  ‘Froggie’ starts below the bottom lane and she travels across the road from the bottom to the top. At each time step, Froggie hops one space in one of four directions: up, down, left, or right. The goal of the game is to get Froggie across the road and above the top lane without her getting hit by a car.

  Goal

  Given a description of the road, car positions and speeds, and Froggie’s starting positions and moves, determine her outcome after the simulation. There are two possible outcomes: safely exiting the top lane or getting squished.

  In order to better plan her travel, Froggie may move left or right before entering the road. Once Froggie has entered the road she may only exit through the top of the road. That is, Froggie’s path never exits the left, right, or bottom lane boundaries.

  Input

  Each input describes one simulation. The first line of input contains two integers separated by a space: \$L\$ and \$W\$. The number of lanes is given by \$L\$ (\$1≤L≤10\$), while \$W\$ (\$3≤W≤20\$) defines the width (in number of cells) of the grid.

  This is followed by \$L\$ lines each describing the car configuration for a lane (from top to bottom). Each line contains three integers: \$O\$, the starting offset of the first car; \$I\$, the interval between cars; and \$S\$, the speed of the cars. The bounds are \$0≤O<I≤W\$ and \$0≤S≤W\$. All offsets should be computed based on the direction of lane movement.

  The final line of input starts with a single integer, \$P\$ (\$0≤P≤W−1\$) followed by a space and then a string of \$M\$ characters (\$1≤M≤L⋅W\$) from the set \$\{U,D,L,R\}\$. \$P\$ defines the starting position of Froggie, starting from the left. The string of characters defines the sequence of moves (up, down, left, right) that Froggie makes during the simulation.

  Output

  If Froggie successfully crosses the road (exiting the road from the top lane), output “safe”. If Froggie is hit by a car, or does not end above the road, output “squish”.

froggie.py

l, w = map(int, input().split())
cars = []
for i in range(l):
  cars.append(list(map(int, input().split())))
  if i % 2 != 0:
    cars[-1][0] = w - cars[-1][0] - 1
pos, moves = input().split()
pos = (l, int(pos))

dirs = { 'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1) }
for i, c in enumerate(moves):
  pos = list(map(sum, zip(pos, dirs[c])))
  row = pos[0]
  if row == -1:
    print('safe')
    exit(0)
  elif row >= l:
    continue
  car = cars[row]
  diff = car[0] + car[2] * (i + 1) if row % 2 == 0 else car[0] - car[2] * (i + 1)
  if (diff - pos[1]) % car[1] == 0:
    print('squish')
    exit(0)
print('squish')


texts:
I have some code that loops through directories named for years (e.g. /2011/, /2012/ etc) which each contain files whose names end with dates in the "yyyyMMdd" format, and builds a list of all the dates in all the directories. But what is the best way to indent this, nothing I've tried is readable:

files = files.Union(
    Directory.GetFiles(year)
             .Select(d => DateTime.ParseExact(
      Path.GetFileNameWithoutExtension(d)
          .Substring(
         Path.GetFileNameWithoutExtension(d)
             .Length - 8),
     "yyyyMMdd",
     null))).ToList();

or

files = files.Union(Directory.GetFiles(year)
                             .Select(d => DateTime.ParseExact(
                                                              Path.GetFileNameWithoutExtension(d).Substring(
                                                                                Path.GetFileNameWithoutExtension(d).Length - 8),
                                                              "yyyyMMdd",
                                                              null)
                                     )
                    ).ToList();

or

files = files.Union(Directory.GetFiles(year)
                             .Select(d => DateTime.ParseExact(
                                                              Path.GetFileNameWithoutExtension(d).Substring(
                                                                                Path.GetFileNameWithoutExtension(d).Length - 8),
                                                              "yyyyMMdd",
                                                              null))).ToList();

or

files = files.Union(Directory.GetFiles(year).Select(d => DateTime.ParseExact(
                    Path.GetFileNameWithoutExtension(d).Substring(
                    Path.GetFileNameWithoutExtension(d).Length - 8),
                    "yyyyMMdd", null))).ToList();


texts:
I'd like a general opinion on my piece of code (which does exactly what I want it to do). I feel like I'm using bad practices, like a DB query within a foreach loop, or grabbing the lowest value in a non-elegant way (sorting, then using the object with an index of 0). I'm also not sure on my usage of the DB queries inside my controller, instead of passing it to the model.

Note this is on Laravel v3:

public function get_predict()
{
    $champions = DB::table('champions')
        ->get(array('id','name','released','price_ip','price_rp'));

    $now = strtotime(date('Y-m-d'));

    foreach($champions as &$champion) {
        $id = $champion->id;
        $champion_sales = DB::table('sales')
            ->where('type','=','1')
            ->where('for','=',$id)
            ->get();
        $champion->sales = $champion_sales;

        foreach($champion->sales as &$sale) {
            $dateout = strtotime($sale->date_out);
            $sale->days_since = floor(($now - $dateout)/(60*60*24));
        }

        usort($champion->sales, function($b, $a) {
            return strcmp($b->days_since, $a->days_since);
        });

        if(isset($champion->sales[0]->days_since)) {
            $champion->most_recent = $champion->sales[0]->days_since;
            $champion->last_sale = date('Y-m-d',strtotime($champion->sales[0]->date_out));
        }
    }

    return View::make('champion.predict')->with('champions', $champions);
}


texts: Solving Robot Paths with Pascal's Triangle

texts:
I wanted to take on the challenge of the classic Robot Path's problem but solve it using Pascal's triangle.  The approach was generate pascal's triangle, then grab the middle element from the row. I saw the following pattern:

//where combos are on pascal's triangle:
// 1x1 grid on the 1st line ===> 1
// 2x2 grid on 3rd line==> 2
// 3x3 grid on 5th line ===> 6
// 4x4 grid on 7th line ===> 20
// 5x5 grid on the 9th line ===> 70
// 6 x6 on the 11th line ===> 252

and so made my getPaths() function accordingly:
     var tri = pascal(n * 2);

function getPaths(n) {

  if (n === 1) {
    return 1;
  }

  if (n === 0) {
    return 0;
  } else {
    var oddElement = (n + (n - 2));
    var mid = Math.floor(tri[oddElement].length / 2);
    // console.log(oddElement);
    return tri[oddElement][mid];
  }

}

Below is the entire function. what could I have done better?

    //Using pascal's triangle to get all unique paths on a board, where only moves are down and to the right:

//generate Pascal's triangle.
function pascal(n) {
  function pascalHelper(n, arr) {
    if (n < 2) {
      return arr;
    }
    var prevTier = arr[arr.length - 1];
    var currTier = [1];
    for (var i = 1; i < prevTier.length; i++) {
      currTier[i] = prevTier[i] + prevTier[i - 1];
    }
    currTier.push(1);
    arr.push(currTier);
    return pascalHelper(n - 1, arr);
  }
  return pascalHelper(n, [
    [1]
  ]);
}

function getPaths(n) {
var tri = pascal(n * 2);
  if (n === 1) {
    return 1;
  }

  if (n === 0) {
    return 0;
  } else {
    var oddElement = (n + (n - 2));
    var mid = Math.floor(tri[oddElement].length / 2);
    // console.log(oddElement);
    return tri[oddElement][mid];
  }

}
//observed pattern: triangle has to be twice as long as the number of paths.
console.log(getPaths(7));
//where combos are on pascal's triangle:
// 1x1 grid on the 1st line ===> 1
// 2x2 grid on 3rd line==> 2
// 3x3 grid on 5th line ===> 6
// 4x4 grid on 7th line ===> 20
// 5x5 grid on the 9th line ===> 70
// 6 x6 on the 11th line ===> 252


texts:
Calculator class:

class Calculator
{
    /**
     * @return array
     */
    function doPowTable ($n)
    {
        $table = array();
        for ($i = 1; $i <= $n; $i++)
        {
            $table[] = array(
                'i' => $i,
                'factor' => pow($i, 2)
            );
        }
        return $table;
    }
}

Formatter class:

class Formatter
{
    /**
     * @return array
     */
    function getAndFormat ($n)
    {
        $table = (new Calculator()).doPowTable ($n);
        return array_map (function($item) {
            $item['i_factor'] = $item['i'].'_'.$item['factor'];
            return $item;
        }, $table);
    }
}

They say it's bad because the helper hard-codes the Calculator. But I think it's how it is supposed to be. It would have been better if I didn't give the $n to it but an array created by the doPowTable() method. Why?


texts: Is it advisable to integrate SQL statements in the JSP pages that are not displayed to the user but handled at the back?

texts:
I have a signup form in which the user has to enter the email address and after some quick asynchronous processing at the backend I have to tell the user that whether the email address is already registered or not.

Below is a sample example of the JSP page that I have created,

<input type="email" id="inputEmail" placeholder="*Email" name="inputEmail" required="true" onchange="checkDuplicate();"
    onpaste="this.onchange();" oninput="this.onchange();" onsubmit="this.onchange();" autocomplete="off"/>

Now the at the backend the check_email.jsp page will be like this,

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<c:set var="email" value="${param['email']}"/>

<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver" user="root"  password="root" url="jdbc:mysql://localhost:3306/ercafe"/>
<sql:query dataSource="${db}" sql="SELECT * FROM user_details" var="result" />

<c:forEach var="row" items="${result.rows}">

    <c:if test="${row.user_email_id eq email}">
        <c:out value="This email is already registered"/>
    </c:if>

</c:forEach>

I know that it is not advisable to include the database interaction in the JSP page but as this page would be handled in the backend without any direct interaction from the user I'm very tempted to use check_email.jsp as above.
Can anyone tell me how to handle the check_email.jsp by the ideal way?


texts: Using pointers and type cast to break up integers into byte array

texts:
Usually I don't start using pointers for a few microseconds here and there.

But with this implementation I started getting results of factor 2.

using System;
class BenchmarkPointers {
    public static void Main() {
#if ALLOW_UNSAFE
        Console.WriteLine("This is safe code");
#else
        Console.WriteLine("This is unsafe code");
#endif

        int bs = 0x100000;
        byte[] buffer = new byte[bs];
        Random rnd = new Random(DateTime.Now.GetHashCode());

        long total = 0;
        long avg = 0;

        int max = 100;

        DateTime start = DateTime.Now;

        for(int i = 0; i <= max; i++) {
            start = DateTime.Now;
            RandomizeBuffer(ref buffer, bs, rnd);
            TimeSpan ts = DateTime.Now - start;
            total += (long)ts.TotalMilliseconds;
            Console.WriteLine("Pass {0} took {1} ms", i, ts.TotalMilliseconds);
        }
        avg = total / max;
        Console.WriteLine("Avarage time for one pass was: {0}ms\nTotal time over {1} passes was {2}ms", avg, max, total);
    }

    public static
#if ALLOW_UNSAFE
    unsafe
#endif
    void RandomizeBuffer(ref byte[] buffer, int bufferSize, Random rnd) {

#if ALLOW_UNSAFE
        fixed(byte * pBuffer = buffer)
#endif
        for(int i = 0; i < bufferSize; i += 4) {
            int k = rnd.Next(int.MinValue, int.MaxValue);

#if ALLOW_UNSAFE
            // One of the rare moments when I like to use pointers (with type casting)
            *((int*)(pBuffer + i)) = k;
#else
            byte[] bits = BitConverter.GetBytes(k);
            buffer[i    ] = bits[0];
            buffer[i + 1] = bits[1];
            buffer[i + 2] = bits[2];
            buffer[i + 3] = bits[3];
#endif

        }
    }
}

Now essentially I need to put the 32bit integers I get from Random.Next into a byte array.

I started implementing the randomizer as

unsafe void RandomizeBuffer(byte **pBuffer, int bufferSize, Random rnd)

Thats why I got the size in the signature and thats also why I first used the 'pointery' approach. (Since then I removed one deref in the method body)

Then I remembered that C# has reference parameters so I refactored... but noticed my code took longer to execute.

Hence the little benchmark here.

I'm wondering whether there is a managed/safe way to break up lot's of ints into bytes.

Of course since results can vary from circumstance to circumstance here my latest results:

csc Benchmark.cs
...
Avarage time for one pass was: 31ms
Total time over 100 passes was 3197ms

and

csc -define:ALLOW_UNSAFE -unsafe benchmark.cs
...
Avarage time for one pass was: 19ms
Total time over 100 passes was 1931ms

Also I noticed with the unsafe execution there is quiet a fluctuation in execution times of the passes. i.E.:

 Pass 85 took 15.6097 ms
 Pass 86 took 15.6251 ms
 Pass 87 took 31.2502 ms
 Pass 88 took 15.626 ms
 Pass 89 took 15.6246 ms

I can only imagine it has something to do with the CPU Pipeline.
But I am no expert in CPU Architecture or Compiler Internals

Any thoughts on this are welcome!

(Yes also those that say: Don't waste your time with this kind of micro management)

Edit:

Using StopWatch and 1000 passes the results are similar, though the fluctuations have been eliminated.

safe -
Avarage time for one pass was: 24ms
Total time over 1000 passes was 24606ms
unsafe -
Avarage time for one pass was: 16ms
Total time over 1000 passes was 16965ms


texts:
I have a class Call and 3 types of calls. Each type of call has a specific rate. So I have created an CallType enum and I will apply the right rate when making a call.

Here is my code so far:

public partial class Devices : Form
{
    public Devices()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var call = new Call(CallType.Regular);
        call.MakeCall();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        var call = new Call(CallType.Important);
        call.MakeCall();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        var call = new Call(CallType.Critical);
        call.MakeCall();
    }
}

public enum CallType
{
    None,
    Regular,
    Important,
    Critical
};

public class Call
{
    private CallType callType;
    const decimal regularRate = 0.25M;
    private decimal ratePerMinute;

    public Call(CallType callType)
    {
        this.callType = callType;
    }

    public void MakeCall()
    {
        switch (callType)
        {
            case CallType.Regular:
                ratePerMinute = regularRate;
                break;
            case CallType.Important:
                ratePerMinute = regularRate * 1.5M;
                break;
            case CallType.Critical:
                ratePerMinute = regularRate * 2.5M;
                break;
        }
    }
}

One of my colleague said that this code is bad: not loosely coupling and not scalable. He suggested to use inheritance instead.

How can I transform this code to respect loose coupling and scalabilty?


texts:
I'm trying to create an Isometric Game in JavaScript.  I think the code is pretty good, but I'd like to know if there is something to improve.

        var CameraX = 0,
            CameraY = 0;

        for(var yChunks = 0; yChunks < NumYChunks; yChunks++)
        {
            var ChunkY = yChunks * HalfChunk,
                ChunkCameraY = yChunks * 4294967296;

            for(var xChunks = 0; xChunks < NumXChunks; xChunks++)
            {

                var FinalyChunk = ChunkY + CameraY;

                var FinalxChunk = xChunks * SizeChunk,
                    ChunkCameraX = xChunks + NumXChunks + CameraX;

                var index = new Number(ChunkCameraY + ChunkCameraX);

                ctx.fillStyle = "black";
                ctx.font = "bold 13px Arial";
                ctx.fillText("ID: " + index, FinalxChunk + 10, FinalyChunk + 20);

                for(var CeldY = 0; CeldY < CeldsYChunk; CeldY++)
                {
                    var yCeld = CeldY * 40;
                    for(var CeldX = 0; CeldX < CeldsXChunk; CeldX++)
                    {
                        var NewCeldX = HalfChunk + FinalxChunk + (CeldX * 40) - yCeld - 40 ,
                            NewCeldY = (CeldX * 20) + (yCeld / 2) + (FinalyChunk) - 10 ;
                        ctx.beginPath();
                        ctx.rect(NewCeldX, NewCeldY, 80, 40);
                        ctx.stroke();
                        ctx.closePath();
                    }
                }
            }
        }


texts: Searching based on a query string and returning JSON ActionResult

texts:
Using a Select2, what's the best way to refactor multiple if statements.

This code returns Json to a select2 based on what information it gets in the query. The action result is used in many places so it has accommodate different parameter being passed.

public ActionResult *********(string query = "", int? id = null, int? accountId = null)
    {
        var empty = new object();

        if (query == "" && accountId == null)
        {
            return Json(empty, JsonRequestBehavior.AllowGet);
        }

        if (query == "" && accountId != null)
        {
            var search = Db.Entities.Find(accountId);
            var suggestions = Db.Entities.Where(
                x => x.Name.Contains(search.Name) && x.EntityId != accountId && !String.IsNullOrEmpty(x.Group.Label))
                .ToList()
                .Select(item => new { id = item.GroupId, text = item.Group.Label });

            return Json(suggestions, JsonRequestBehavior.AllowGet);

        }

        if (id != null)
        {
            var accountGroup = Db.Groups.Find(id);
            if (accountGroup != null)
                return Json(new { id = accountGroup.GroupId, text = accountGroup.Label },
                    JsonRequestBehavior.AllowGet);
            return Json(null, JsonRequestBehavior.AllowGet);
        }
        var list = Db.Groups.Where(
            r => !String.IsNullOrEmpty(query) && query.Length > 2 && (r.StatusId == GroupStatus.Both || r.StatusId == GroupStatus.Customer) && r.Label.ToLower().Contains(query.ToLower())).OrderBy(r => r.Label).Select(item => new { id = item.GroupId, text = item.Label }).ToList();
        if (!list.Any())
        {
            return Json(new List<object>() { new { id = query, text = query } }, JsonRequestBehavior.AllowGet);
        }
        return Json(list, JsonRequestBehavior.AllowGet);
    }


texts: String length calculation implementation in Assembly (NASM)

texts:
I just made a working implementation of calculating a string's length, but I'm not exactly sure it's the most efficient way. I divide the string up in blocks of four bytes each (32 bits), and add 4 to EAX. Once I hit a completely NULL block, I roll back the count of EAX by 4 bytes, and then calculate the final block's size one byte at a time. It only works using ASCII characters, and is limited to 32 bit computing (though that can be easily upgraded to 64 bit soon). I'm using assembly on a Linux maching using NASM. Here's the code:

; Function to compute the length of a string in blocks
; this only works in ASCII, or else it may give the wrong character count.
; input register: EAX - the string

section .data

    BYTE_COUNT equ 4        ;4 bytes = 32 bits
    NULL_TERMINATOR equ 0 ;\0, aka 0

section .text

    global  _strlen ;main entry point

        _strlen:

            push ebp             ; c calling convention: preserve ebp
            mov     ebx, eax  ; mov to ebx the string
            jmp _NextBlock ; go to _NextChar

        _NextBlock:
            cmp     word [eax], NULL_TERMINATOR ; Compare whether or not this block is completely null (e.g. 0)
            jz      _RollbackFinalBlock ; if it is, jump to _RollbackFinalBlock
            ; if not...
            add eax, BYTE_COUNT ; Add to EAX the block size
            jmp     _NextBlock; repeat loop

        _RollbackFinalBlock:

            sub eax, BYTE_COUNT ;Subtract the block size from EAX, because it is null
            jmp _FinalizeFinalBlock ; go to _FinalizeFinalBlock

        _FinalizeFinalBlock:
            cmp     byte[eax], NULL_TERMINATOR ;Compare the characters of the final block to the null byte.
            jz      _Exit ;if this byte is null, proceed to _Exit
            ; if not...
            inc eax ;increment EAX
            jmp     _FinalizeFinalBlock ;repeat loop

        _Exit:

            dec eax ; We will have a null terminator at the end. remove it.
            sub     eax, ebx ; compute difference to get answer, and store result in EAX
            pop     ebp ; load preserved EBP value from the stack
            ret             ; exit this function

You can test this function by linking it with a c program, and calling it from there.

The problem I have is that I have an extra jump to _RollbackFinalBlock and _FinalizeFinalBlock. Is there a way to make this implementation faster and more efficient?


texts: Find all anagrams to a given word from a text file

texts:
This program I made takes a word as an input and prints all the anagrams of the word in a given word base from a txt file. I would like advice for code style, Java specific practices etc as I'm new to to the Java language (about 2 months).

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

public class Anagrams {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new File("bg.txt"));

        ArrayList<String> words = new ArrayList<String>();
        while (s.hasNext()) {
            words.add(s.next());
        }

        HashMap<String, ArrayList<String>> map = new HashMap<>();

        for (String str : words) {
            char[] temp = str.toCharArray();
            Arrays.sort(temp);
            String key = new String(temp).toLowerCase();
            if (map.get(key) != null) {
                map.get(key).add(str.toLowerCase());
            } else {
                ArrayList<String> anagramList = new ArrayList<>();
                anagramList.add(str);
                map.put(key, anagramList);
            }
        }
        Scanner input = new Scanner(System.in);
        String str = input.next();
        char[] key = str.toCharArray();
        Arrays.sort(key);
        str = new String(key).toLowerCase();
        if (!map.containsKey(str)) {
            System.out.print("word not found");
        } else if (map.get(str).size() != 1) {
            for (String p : map.get(str)) {
                System.out.print(p + " ");
            }
        } else {
            System.out.print("No anagrams found");
        }
        s.close();
        input.close();
    }
}


texts:
I have a big collection of MP4 files and an unstable internet connection so I use this batch file to check for the files integrity.

Having posted this primitive code and received valuable reviews, I decided to take into consideration as much as I can, especially not mixing C code unless when using Windows API  and implement the said batch file using that code as the basis.

This program works in CMD it takes a path to MP4 location as argument.

#include <iostream>
#include <string>
#include <windows.h>

#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
#endif

bool DirectoryExists(const std::string& path)
{
   DWORD present = GetFileAttributesA(path.c_str());

   if (present == INVALID_FILE_ATTRIBUTES)
          return false;

   if (present & FILE_ATTRIBUTE_DIRECTORY)
          return true;

   return false;
}

std::string replace (const std::string& path)
{
   std::string in = path;
   std::replace(in.begin(), in.end(), '\\', '/');
   return in;
}

void findVideos (std::string& fspath)
{
   while(*(fspath.rbegin()) =='/')  //to get rid of trailing '/' like a user inputs path/to/file//////\\\
       fspath.pop_back();

   size_t i=1;
   WIN32_FIND_DATA FindFileData;
   std::string destpath = fspath + std::string("/")+ std::string("*.mp4");
   std::string ffmpegPath = "ffmpeg.exe -v error -f null - -i ";

   HANDLE hFind = FindFirstFile(destpath.c_str(), &FindFileData);

   if (hFind != INVALID_HANDLE_VALUE)
   {
        do
          {
            std::string fullpath = std::string(fspath)+std::string("/")+std::string(FindFileData.cFileName);
            std::cout<<i<<"-"<<"Checking "<<fullpath<<" for errors"<<std::endl;
            std::string command = ffmpegPath +std::string("\"")+fullpath+std::string("\"");
            system(command.c_str());
            i++;
          }
        while(FindNextFile(hFind, &FindFileData));
   }
   FindClose(hFind);
}

int main(int argc, char**argv)
{
    const char* path = argv[1];

    if (path == nullptr)
    {
        std::cout<<"No path provided"<<std::endl;
        return 0;
    }
    else
        if ( DirectoryExists(path) )
           std::cout<<"Provided path is: "<<path<<std::endl;
        else
             {
             std::cout<<"Path doesn't exist"<<std::endl;
             return 0;
             }

   std::string fspath;
   fspath = replace(path);
   findVideos (fspath);
   return 0;
}

The code is working, I am open to criticism and any way to improve it especially if I work in a professional company and asked to implement such program.

EDIT: Please forgive my ignorance about indentation and other programming paradigms, I graduated a year ago and failed to get an internship or a job in the domain. I tried to go with the comments as much as I can after reading some articles about indentations.


texts:
I am developing a chat bot with Node.Js. I am trying to find efficient way to parsing sentence.

what do you think about humanity
-> ba bla bla.

what do you think about cats
->I love cats

Right now I am using the intersection technique, but I don't think it's efficient:

var sentence = sentence.split(",")
var inters = intersectionOfArrays(sentence, ["what", "do", "you", "think", "about"])
if(inters.length >= 3) { //we have common words
    keyword = extractionOfarrays(sentence,["what", "do", "you", "think", "about"]) // get question word (humanity, cats etc)
    if(keyword == "cats")
       responseToServer("I love cats")
    if(keyword == "humanity")
       responseToServer("bla bla bla")
}

Is this technique bad? I want to answer thousands of questions so I need to know what is the best method for doing some "AI" magic.


texts: Efficiency of Project Euler 28 - number spiral diagonals

texts:
I have written a solution for Problem 28.

  Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

  $$\begin{array}{rrrrr}
\color{red}{21} &22 &23 &24 &\color{red}{25}\\
20 & \color{red}{7} & 8 & \color{red}{9} &10\\
19 & 6 & \color{red}{1} & 2 &11\\
18 & \color{red}{5} & 4 & \color{red}{3} &12\\
\color{red}{17} &16 &15 &14 &\color{red}{13}\\
\end{array}$$

  It can be verified that the sum of the numbers on the diagonals is 101.

  What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

Since I am a beginner, I am looking for suggestions for improving the efficiency of my program.

from timeit import default_timer as timer
start = timer()
def find_sum(limit):
    limit*=limit
    num=1
    add=2
    result=1
    while num<limit:
        for i in range(4):
            num+=add
            result+=num
        add+=2
    return result
print (find_sum(1001))
elapsed_time = (timer() - start) * 1000 # s --> ms
print ("Found in %r ms." % (elapsed_time))


texts: Eliminating global variables in GUI program

texts:
I'm just getting started on GUI programming using swing in Java, and I would love some critiques on my code. I understand there is a danger in using global variables.  If someone can hint me on how to get rid of my globals (which will be later registered for event handling), I'd really appreciate it.

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public final class Calculator extends JFrame
{
    //initialise various variables for use within the program
    //BUTTONS
    private final JButton additionButton = new JButton("+");
    private final JButton subtractionButton = new JButton("-");
    private final JButton divisionButton = new JButton("/");
    private final JButton multiplicationButton = new JButton("*");

    //PANELS
    private JPanel operatorPanel;
    private JPanel operandPanel;

    //LABELS
    private JLabel operationLabel;

    //constructor to initialise the frame and add components into it
    public Calculator()
    {
        super("Clancy's Calculator");
        setLayout(new BorderLayout(5, 10));
        setResizable(false);
        setSize(370, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);

        //create a message label to display the operation that has just taken place
        operationLabel = new JLabel("YOU HAVE PERFORMED SOME OPERATION", SwingConstants.CENTER);

        add(getOperatorPanel(), BorderLayout.NORTH);
        add(getOperandPanel(), BorderLayout.CENTER);
        add(operationLabel, BorderLayout.SOUTH);

        pack();
    }

    //setter method for the operator panel
    public void setOperatorPanel()
    {
        operatorPanel = new JPanel();
        operatorPanel.setLayout(new FlowLayout());

        operatorPanel.add(additionButton);
        operatorPanel.add(subtractionButton);
        operatorPanel.add(multiplicationButton);
        operatorPanel.add(divisionButton);
    }
    //getter method for the operator panel
    public JPanel getOperatorPanel()
    {
        setOperatorPanel();
        return operatorPanel;
    }

    //setter method for operands panel
    public void setOperandPanel()
    {
        operandPanel = new JPanel();
        operandPanel.setLayout(new GridLayout(3, 2, 5, 5));

        //LABELS
        JLabel operandOneLabel = new JLabel("Enter the first Operand: ");
        JLabel operandTwoLabel = new JLabel("Enter the second Operand: ");
        JLabel answerLabel = new JLabel("ANSWER: ");

        //TEXT FIELDS
        JTextField operandOneText = new JTextField();   //retrieves one operand
        JTextField operandTwoText = new JTextField();   //retrieves another operand
        JTextField answerText = new JTextField();   //displays answer

        answerText.setEditable(false);  //ensure the answer field is not editable

        operandPanel.add(operandOneLabel);
        operandPanel.add(operandOneText);
        operandPanel.add(operandTwoLabel);
        operandPanel.add(operandTwoText);
        operandPanel.add(answerLabel);
        operandPanel.add(answerText);

    }
    //getter method for operand panel
    public JPanel getOperandPanel()
    {
        setOperandPanel();
        return operandPanel;
    }

    /** main method */
    public static void main(String[] args)
    {
        new Calculator();
    }
}


texts:
This project is based on trivia (question/answer quiz). The scenario is simple but I have to improve/optimize my query using these tables:

$query=$this->db->query("SELECT
q.`id`,
q.`topic_id`,
t.`topic`,
q.`question`,
GROUP_CONCAT(a.`answer`) AS `answer`,
GROUP_CONCAT(a.`is_correct`) AS `is_correct`,
GROUP_CONCAT(a.`id`) AS `ans_id`,
q.`answer_type`,
q.`image_url`,
q.`created_date`,
(SELECT ua.`topic_id` FROM usersAnswer ua
WHERE t.`id`= ua.topic_id AND ua.`user_id` = '".$user_id."' LIMIT 1)
AS `userdone_topic`,
(SELECT ua.`answer_id`
FROM usersAnswer ua
WHERE ua.`question_id` = q.`id` AND ua.`user_id`='".$user_id."'
AND ua.`answer_id`
IN
(SELECT a.`id` FROM answers a
WHERE a.`is_correct` != '0' AND a.question_id = q.`id`
)) AS `user_correct_id`
FROM
questions q INNER JOIN topics t ON q.`topic_id`= t.`id`
INNER JOIN answers a ON q.`id`=a.`question_id`
WHERE
(SELECT s.`status`
FROM `status` s
WHERE
s.`month_date`= q.created_date AND s.`status`= 2
$valid)
GROUP BY q.`id`
");
return $query->result();