texts: Exercise 6.1 from ANSI C book - getword function

texts:
I have a following exercise from ANSI C book:

  Exercise 6.1. Our version of getword does not properly handle
  underscores, string constants, comments, or preprocessor control
  lines. Write a better version.

Here's my improved version of getword function and code that test if it works:

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#define BUFSIZE 100
#define MAXWORD 100
#define NKEYS (sizeof keytab / sizeof(keytab[0]))

int buf[BUFSIZE];
int bufp = 0;

struct key {
    char * word;
    int count;
} keytab[] = {
        { "#define", 0 },
        { "#elif", 0 },
        { "#else", 0 },
        { "#endif", 0 },
        { "#error", 0 },
        { "#if", 0 },
        { "#ifdef", 0 },
        { "#ifndef", 0 },
        { "#include", 0 },
        { "#line", 0 },
        { "#pragma", 0 },
        { "auto", 0 },
        { "break", 0 },
        { "case", 0 },
        { "char", 0 },
        { "const", 0 },
        { "continue", 0 },
        { "default", 0 },
        { "do", 0 },
        { "double", 0 },
        { "else", 0 },
        { "enum", 0 },
        { "extern", 0 },
        { "float", 0 },
        { "for", 0 },
        { "goto", 0 },
        { "if", 0 },
        { "int", 0 },
        { "long", 0 },
        { "register", 0 },
        { "return", 0 },
        { "short", 0 },
        { "signed", 0 },
        { "sizeof", 0 },
        { "static", 0 },
        { "struct", 0 },
        { "switch", 0 },
        { "typedef", 0 },
        { "union", 0 },
        { "unsigned", 0 },
        { "void", 0 },
        { "volatile", 0 },
        { "while", 0 },
};

int getword(char *, int);
int binsearch(char *, struct key *, int);
int getch(void);
void ungetch(int);

int main(void) {
    int n,  c;
    char word[MAXWORD];

    while ((c = getword(word, MAXWORD)) != EOF) {
//        printf("getword(word, MAXWORD) = %c %d\n", c, c);
//        printf("word = %s\n", word);
        if (isalpha(word[0]) || word[0] == '_' || word[0] == '#') {
            if ((n = binsearch(word, keytab, NKEYS)) >= 0) {
                keytab[n].count++;
            }
        }
    }
    for (n = 0; n < NKEYS; n++)
        if (keytab[n].count > 0)
            printf("%4d %s\n",
                   keytab[n].count, keytab[n].word);
    return 0;
}

int getch(void) {
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) {
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

int getword(char * word, int lim) {
    int c;
    char * w = word;
    static int last;
    while (isblank(c = getch()))
        ;
    if (c != EOF)
        *w++ = c;
    if (last == '/' && c == '/') {
        while (c = getch() != '\n')
            ;
        return c;
    }
    if (last == '/' && c == '*') {
        x:
        while (c = getch() != '*')
            ;
        if (c = getch() == '/')
            return c;
        else
            goto x;
    }
    if (c == '\'') {
        while (c = getch() != '\'')
            ;
        return c;
    }
    if (c == '\"') {
        while (c = getch() != '\"')
            ;
        return c;
    }
    if (!isalpha(c) && c != '_' && c != '#') {
        *w = '\0';
        last = c;
        return c;
    }
    for ( ; --lim > 0; w++) {
        if (!isalnum(*w = getch()) && *w != '_') {
            ungetch(*w);
            break;
        }
    }
    *w = '\0';
    last = word[0];
    return word[0];
}

int binsearch(char * word, struct key tab[], int n) {
    int cond;
    int low, high, mid;

    low = 0;
    high = n - 1;
    while (low <= high) {
        mid = (low + high) / 2;
        if ((cond = strcmp(word, tab[mid].word)) < 0)
            high = mid - 1;
        else if (cond > 0)
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}

What are your opinions about my solution? Is it a correct approach? Is this code enough fast?


texts: JavaScript function to create a duplicate-free copy of an array

texts:
I've made this function which returns a copy of a given array with no duplicated elements in it.

/**
 * Returns an array with only unique elements. Based
 *  upon an array which might possibly contain duplicates.
 * @param { array } arrayToCheck
 * @return { array }
 * @throws { Error } when given parameter is
 *  detected invalid.
 */

function createArrayWithoutDuplicates(arrayToCheck) {
  'use strict';
  var arrayWithoutDuplicates = [];

  if (!arrayToCheck || !Array.isArray(arrayToCheck)) {
    throw new TypeError('Array expected but ' +
      typeof arrayToCheck + ' found.');
  }

  arrayToCheck.forEach(function(element) {
    if (!arrayWithoutDuplicates.includes(element)) {
      arrayWithoutDuplicates.push(element);
    }
  });

  return arrayWithoutDuplicates;
}

// --------------------------------------------------
// --------- JUST USAGE-DEMO ------------------------
// -- ... not that important, folks! ;) -------------

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 1, 2, 7, 8];
var arr2 = ['a', 'b', 'c', 'd', 'e', 'a', 'b'];

function testCreateArrayWithoutDuplicates(arrayWithDuplicates) {
  let unique = createArrayWithoutDuplicates(arrayWithDuplicates);

  console.log('With duplicates: %o', arrayWithDuplicates);
  console.log('Without duplicates: %o', unique);
  console.log('Array with duplicates: %s', arrayWithDuplicates.length);
  console.log('Array without duplicates: %s', unique.length);
}

testCreateArrayWithoutDuplicates(arr);
console.log('\n');
testCreateArrayWithoutDuplicates(arr2);

As far as I can say: It is doing alright.

But I would like to know:

Is there a better pattern for solving the task of getting a duplicate-free array?

If someone knows a better solution then I would appreciate his/her answer.

Moreover:

- Is my documentation understandable and done in a good way? Or do I have to improve?

- Is my parameter validation done correctly?

Looking forward to read your answers. :)


texts: lodash filter array of objects by array of exclude property values

texts:
I ran into a scenario, I'll simplify the data to user/project, where I needed to take values like:

users: [
  {name: 'bob', project: 1},
  {name: 'sam', project: 2},
  {name: 'ted', project: 3},
];

and given an array of project ids I wish to exclude such as

excludeProjects: [1,3];

I want to return [{name: 'sam', project: 2}];

I was able to do this with a custom filter function:

let usersNotInProject = _.filter(users, function(o) {
    for (var i=0; i<excludeProjects.length; i++){
        if (excludeProjects[i]===o.project){
            return false;
        }
    }
    return true;
});

However, I believe I am missing some more elegant way to do this with lodash. Is a custom function really needed for this scenario?


texts: Elegantly handle github API requests exceptions

texts:
I have this code which creates a team using the github API and returns the team-id(success) or -1(failure).

My problem is with the error handling. When the request responses with an error status code I try to deal with a few different types of failure.  It looks like a mess!

Is there any way to make it more readable/elegant?

I'd also like to know if I am catching all the reasonable exceptions that can be thrown by requests.

def create_team(org,team_name):
    '''
    Try to create a team and return its id
    if already exisits return id
    '''
    try:
        data = {
            "name": team_name,
            "permission": "push"
        }
        headers = {'Authorization': 'token '+OAUTH_TOKEN}

        response = requests.post(GH_API_URL+'orgs/'+org['login']+'/teams',
                                    headers=headers,
                                    data = json.dumps(data))

        response.raise_for_status() #throw exception if request does not retun 2xx

        #http status is 2xx, team must have been created
        json_response = json.loads(response.text)
        return json_response['id'] #get id of new team from response

    except requests.exceptions.HTTPError as e:

        if response.status_code == 422: #Unprocessable Entity
            json_response = json.loads(response.text)
            if json_response['errors'][0]['code'] == 'already_exists': #Unprocessable because already exists
                print(' not created, team already exists!!!')

                #get the id of existing team
                team_id = get_teamID_from_name(org, team_name)

                return team_id
            else:  #Unprocessable for some other reason
                print(' HTTP error: '+str(e))

        else: #other HTTP error != 422
            print(' HTTP error: '+str(e))

    except requests.exceptions.RequestException as e:
        print('Connection error: '+str(e))

    return -1

In case you were wondering why I don't just check for the existence of the team BEFORE trying to create it. That's because the normal case for this function is that the teams do not already exist and the github API is quite slow. As it stands it takes several minutes to process a groups with 50 teams and 100 students. Checking for team existence would add a few more minutes to the runtime.


texts: Fetch an array from API endpoint in async function

texts:
I've been studying javascript for the love of it, I'm currently learning how to use async functions and my code actually works, but I know there is always room for improving.

I'm open to any help regarding my use of async functions and how I use the return of sizeJokesArray() in fetchJokes().

const jokeContainer = document.querySelector('.joke-container');

async function sizeJokesArray() {
  let url = 'https://api.icndb.com/jokes/count';
  let data = await (await fetch(url)).json();
  return data.value;
}

async function fetchJokes() {
  let url = `https://api.icndb.com/jokes/random/${length}`;
  let jokesData = [];
  let data = await (await fetch(url)).json();
  for (jokePosition in data.value) {
    jokesData.push(data.value[jokePosition].joke);
  }
  return jokesData;
}

sizeJokesArray().then(size => (length = size)); // return of sizeJokesArray

jokeContainer.addEventListener('click', event => {
  if (event.target.value === 'Fetch') {
    fetchJokes(length).then(jokesData => (jokesArray = jokesData)).then(jokesData => (console.log(jokesData)));
  }
});

Fetch some jokes bro!!

        <button type="button" value="Fetch">Fetch Jokes</button>

the existing console.log() it's not actually used in my code just used it here to log my results for the question purpose.


texts: Code to ask for user string, then display the output

texts:
# printstring.py
# 7/8/2016

import sys

# ask for user input
s_string = input('Enter a string: ')

# if no string, then exit()
if s_string == '':
    sys.exit()

# display the output
print(s_string)

Also wondering how to get "raw" input and output the text properly formatted with line breaks, etc. Also looking for general feedback and tips for improvement.


texts: API with revealing module pattern in Javascript

texts:
I'm working on a project where I want to create a API that can be used to do some mathmatical calculations.

Here are the important aspects:

I used the revealing module pattern
I added method chaining (sort of like in JQuery)
No Prototypes used (I don't see a advantage here)

My questions are the following:

Is it a mistake to not use prototypes ? I'm sort of thinking about the benefits I could gain by using them but I don't see any.
Is the error handling the correct way or should I do it differently ?
Does the code look viable and suitable for a API ?
Is there a other way of doing the method chaining ?

I'm also open for general suggestion to improve the code further which wasn't mentioned in the questions.

Edit: I haven't mentioned that I don't have a problem with using prototypes, I do understand the prototype inheritance and I also welcome any suggestion that is written with it.

Here is the code

function type(entity) {
  return Object.prototype.toString.call(entity).slice(8, -1);
}

function isNumber(entity) {
  return type(entity) === "Number";
}

let gMath = (function() {
  let currentNumber;
  let gotNumber = false;

  let number = function(number) {
    let numberType = type(number);

    if (isNumber(number) && !gotNumber) {
      currentNumber = gotNumber ? undefined : number;
      gotNumber = true;
    } else if (gotNumber) {
      console.log("Error! Cannot define 2 numbers. Only use .number() once or call .getNumber() to clear the current one.");
    } else if (type(number) === "String") {
      console.log(`This function only accepts Numbers as arguments. You passed in: "${numberType}"`);
    } else{
      console.log(`This function only accepts Numbers as arguments. You passed in: ${numberType}`);
    }
    return this;
  }

  let scatter = function(range) {
    currentNumber = Math.floor((currentNumber + (Math.random() * range * 2) - range) + 1);
    return this;
  }

  let randomize = function(number) {
    currentNumber = Math.floor(Math.random() * currentNumber);
    return this;
  }

  let atleast = function(number) {
    currentNumber = currentNumber < number ? number : currentNumber;
    return this;
  }

  let add = function(number) {
    currentNumber += number;
    return this;
  }

  let subtract = function(number) {
    currentNumber -= number;
    return this;
  }

  let show = function() {
    console.log(currentNumber);
    return this;
  }

  let getNumber = function() {
    gotNumber = false;
    return currentNumber;
  }

  let isCurrentNumber = function() {
    console.log("Currently the gotNumber variable is: " + gotNumber);
  }

  return {
    // chainable
    scatter,
    number,
    atleast,
    randomize,
    add,
    subtract,
    show,

    // non-chainable
    getNumber,
    isCurrentNumber
  }

})();

let a = gMath.number(10)
.scatter(50)
.getNumber();

console.log(a) // --> logs a Number between -40 and 60


texts: How to make this query better (e.g. avoid repeating subquery in a query)?

texts:
Stack Exchange provides access to query their MS SQL databases. They have a table Posts where each post is either a question or an answer (see the schema on right hand side here).
I saw a query for questions answered by more than three 50k users:
SELECT DISTINCT Q.Id AS [Post Link], Q.AnswerCount
FROM Posts Q
JOIN Posts A1 on A1.ParentId = Q.Id
  AND A1.OwnerUserId IN (SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC)
JOIN Posts A2 on A2.ParentId = Q.Id
  AND A2.OwnerUserId IN (SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC)
  AND A1.Id != A2.Id
JOIN Posts A3 on A3.ParentId = Q.Id
  AND A3.OwnerUserId IN (SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC)
  AND A3.Id != A1.Id AND A3.Id != A2.Id
WHERE Q.AnswerCount = 3

I was wondering how to improve the query (balance between efficiency and readability)? For example:

Is it possible to avoid repeating the subquery SELECT TOP ##TopN## Id FROM Users ORDER BY Reputation DESC three times, and instead just have it once?

Will it be more  efficient if switching the order of filtering out questions with less than three answers and checking if  a question is answered by more than three 50k users?


texts: Area under curve and its volume as solid of revolution

texts:
I would like to know if there is some more "elegant" way to write these 3 functions. Any tip or idea is welcome.

open System

module Calculus =
    let area f a b =
        let dx = 0.001
        seq { for x in a .. dx .. b -> (f x) * dx }
        |> Seq.sum

    let rotate f x =
        let y = f x
        y * y * Math.PI

    let volume f =
        area (rotate f)

[<EntryPoint>]
let main args =
    let f x = x * 2.0

    printfn "Running..."

    printfn "%f" (Calculus.area f 1.0 10.0)
    printfn "%f" (Calculus.volume f 1.0 10.0)

    0

Note

I understand the method for integration I am using here is not the best around, but it is not the point here. Let's focus on its implementation.


texts:
Using Rails 6. Here's a piece that I wrote just to display number of stars. Obviously I am disgusted by my own code. How would you refactor?

# application_helper.rb
module ApplicationHelper
  def show_star_rating(rating)
    zero_star_icon_name = "star"
    full_star_icon_name = "star_fill"
    half_star_icon_name = "star_lefthalf_fill"
    total_stars = []
    round_by_half = (rating * 2).round / 2.0
    (round_by_half.to_i).times { total_stars << full_star_icon_name }

    if round_by_half - round_by_half.to_i == 0.5
      total_stars << half_star_icon_name
    end

    if total_stars.size != 5
      (5 - total_stars.size).times { total_stars << zero_star_icon_name }
    end

    total_stars
  end
end

# show.html.erb
<% show_star_rating(agent_review.rating).each do |star| %>
  <i class="f7-icons"><%= star %></i>
<% end %>


texts:
I was tasked with creating a script to be able to rename some files and then move them into different folders based on a code in the filename.

import os
import shutil

path = (r"C:\user\reports")

filelist = [ f for f in os.listdir(path) if f.endswith(".xml") ]

for f in filelist:
    x = os.path.join(path, f)
    os.remove(x)

filelist = [ f for f in os.listdir(path) if f.endswith(".pdf") ]

for f in filelist:
    os.rename(os.path.join(path, f),os.path.join(path, f[31:]))

filelist = [f for f in os.listdir(path) if f.endswith(".pdf")]

for f in filelist:
    if "A" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderA")
    if "B" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderB")
    if "C" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderC")
    if "D" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderD")
    if "E" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderE")
    if "F" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderF")
    if "G" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderG")
    if "H" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderH")
    if "I" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderI")

filelist = [f for f in os.listdir(path) if f.endswith(".pdf")]

for f in filelist:
    x = os.path.join(path, f)
    os.remove(x)

First, it removes any XML files in the folder. Then it strips the first 31 characters (it will always be 31 characters) of the filename, leaving just a name and a code. It then checks if the final 6 characters contain a "code" and then move the file to the correct folder based off that code. After every file has been moved, it will delete every file in the parent folder.

I know my current code could be improved, but it's been a couple of years since I've done Python so I've literally done it the easiest way (from what I could Google) possible. Any improvements or suggestions to what features of Python I should be looking at would be great.


texts:
Exercise 2.31.  Abstract your answer
  to exercise 2.30 to produce a
  procedure tree-map with the property
  that square-tree could be defined as

(define (square-tree tree) (tree-map square tree))

I wrote the following solution:

(define (square x) (* x x))

(define (tree-map f tree)
  (cond ((null? tree) null)
        ((pair? tree)
         (cons (tree-map f (car tree))
               (tree-map f (cdr tree))))
        (else (f tree))))

(define (map-tree-map f tree)
  (map (lambda (subtree)
         (if (pair? subtree)
             (cons (map-tree-map f (car subtree))
                   (map-tree-map f (cdr subtree)))
             (f subtree)))
         tree))

(define (square-tree tree) (tree-map square tree))
(define (map-square-tree tree) (map-tree-map square tree))

(define a (list 1 1 (list (list 2 3) 1 2)))

Can this be improved in any way?


texts:
As an exercise, I limited my self to the man pages. I didn't look for a previous existing implementation because I wanted to see how well I could do on my own. I also tried to handle as many cases as I could think of. I am sure there are weaknesses so feel free to point them out. Where can I improve my usage of the C standard library, etc.

char *
itoa(int i)
{
  short digit_cnt;
  short index;
  void *ret;
  char digit;
  int tmp;

  errno = 0;
  feclearexcept(FE_ALL_EXCEPT);
  if (i == 0) {
    digit_cnt = 1;
  } else {
    tmp = (i == INT_MIN) ? (i + 1) : i;
    digit_cnt = floor(log10(abs(tmp))) + 1;
    if (errno || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
      FE_UNDERFLOW)) {
      return NULL;
    }
  }

  if (i < 0) {
    ++digit_cnt;
  }
  ++digit_cnt; // '\0'

  errno = 0;
  if ((ret = malloc(digit_cnt * sizeof(char))) == NULL || errno) {
    print_error_msg(errno);
    free(ret);
    return NULL;
  }

  // This made debugging easier.
  memset(ret, '0', digit_cnt * sizeof(char));

  index = digit_cnt;
  ((char*)ret)[--index] = '\0';

  tmp = i;
  do {
    digit = (char)((int)'0' + abs(tmp % 10));
    ((char*)ret)[--index] = digit;
    tmp /= 10;
  } while (tmp != 0);

  if (i < 0) {
    ((char*)ret)[--index] = '-';
  }

  return ret;
}


texts:
I wrote a C# program that converts decimal to string. It is not the best but it works. I'm looking for inputs from others on how can it be improved? One aspect that baffled me was how to find out total number of digits after decimal point? Right now I've to pass it as a separate parameter. It is in C#, but I'm open to any programming language. credit goes to all authors that I found online and little bit to me

    static void Main(string[] args)
    {
        string s = decToStr(123456.789M,3);
        Console.WriteLine(s);
        Console.ReadLine();
    }

    static string decToStr(decimal d,double totaldec)
    {
        if (d == 0)
            return "0";
        int i = (int)d;
        decimal fracPart = d - i;
        int fracPartInt = 0;

        StringBuilder strResult = new StringBuilder();
        StringBuilder fracStrResult = new StringBuilder();

        strResult = ProcessInt(strResult,i);
        //not sure how to find total number of digts after decimal point
        fracPartInt = (int)(fracPart * (decimal)Math.Pow(10, totaldec));

        fracStrResult = ProcessInt(fracStrResult, fracPartInt);

        strResult.Append(".").Append(fracStrResult);

        return strResult.ToString();
    }

    static StringBuilder ProcessInt(StringBuilder sb, int i)
    {
        string digits = "0123456789";
        while (i > 0)
        {
            sb.Insert(0, digits[i % 10]);
            i = i / 10;
        }

        return sb;

    }


texts: BFS' shortest path unweighted directed graph

texts:
The code I have is based on BFS and a little bit of Dijkstra and returns the shortest path of an unweighted directed graph as an integer. I was wondering if someone could take a look at my code too see if anything could be changed or improved:

public int bfsshortestpath (V source, V target) {
    Map<V, Integer> dist = new TreeMap<V, Integer>();
    Map<V, V> prev = new TreeMap<V, V>();

    for(V v: adjlist.keySet()){
        dist.put(v, null);
        prev.put(v, null);
    }
    dist.put(source, 0);

    Queue<V> q = new LinkedList<V>();
    q.offer(source);
    while(!q.isEmpty()){
        V u = q.poll();
        if(u == target)
            break;
        q.remove(u);
        for(V neighbor: adjlist.get(u)){
            int a = dist.get(u);
            if(dist.get(neighbor) != null)
                continue;
            //BFS distance
            dist.put(neighbor, a + 1);
            prev.put(neighbor, u);
            q.offer(neighbor);
        }
    }

    List<V> s = new LinkedList<V>();
    V u = target;
    while(prev.get(u) != null){
        s.add(u);
        u = prev.get(u);
    }
    return s.size();
}


texts: Calculate reservation cancellation penalty based on date difference

texts:
The website I'm developing allows customers to book an appointment. They can also cancel their appointment with the following rules:

if the appointment is cancelled between 48 hours and 1 hour in advance, the customer has to pay 50%.
if the appointment is cancelled below 1 hour in advance, the customer should pay 100 %
if the appointment is cancelled above 48 hours in advance, the customer has to pay 0%.

My function to decide this:

decidePercentageToBePayed(cancelledReservation: Reservation) {
    const reservationYear = parseInt(cancelledReservation.getYear(), 10);
    const reservationMonth = parseInt(cancelledReservation.getMonth(), 10);
    const reservationDay = parseInt(cancelledReservation.getDay(), 10);
    const reservationHour = Utils.getTimeSlotHour(Utils.getStartSlot(cancelledReservation.period));
    const reservationMinute = Utils.getTimeSlotMinute(Utils.getStartSlot(cancelledReservation.period));
    const currentYear = parseInt(Utils.getCurrentYear(), 10);
    const currentMonth = parseInt(Utils.getCurrentMonth(), 10);
    const currentDay = parseInt(Utils.getCurrentDay(), 10);
    const currentHour = parseInt(Utils.getCurrentHour(), 10);
    const currentMinute = parseInt(Utils.getCurrentMinute(), 10);

    if (reservationYear > currentYear) {
      if (reservationMonth === 1 && currentMonth === 12) {
        if (currentDay === 30 && reservationDay === 1 || currentDay === 31 && reservationDay === 2) {
          if (currentHour > reservationHour) {
            return 50;
          }
          return 0;
        } else if (currentDay === 31 && reservationDay === 1) {
          return 50;
        }
        return 0;
      }
      return 0;
    } else if (reservationMonth - currentMonth > 1) {
      return 0;
    } else if (reservationMonth - currentMonth === 1) {
      if (currentMonth === 2 && Utils.isLeapYear()) {
        if (currentDay === 27 && reservationDay === 1 || currentDay === 28 && reservationDay === 2) {
          if (currentHour > reservationHour) {
            return 50;
          }
          return 0;
        } else if (currentDay === 28 && reservationDay === 1) {
          return 50;
        }
        return 0;
      } else if (currentMonth === 2 && !Utils.isLeapYear()) {
        if (currentDay === 28 && reservationDay === 1 || currentDay === 29 && reservationDay === 2) {
          if (currentHour > reservationHour) {
            return 50;
          }
          return 0;
        } else if (currentDay === 29 && reservationDay === 1) {
          return 50;
        }
        return 0;
      } else if (Utils.has31Days(currentMonth)) {
        if (currentDay === 30 && reservationDay === 1 || currentDay === 31 && reservationDay === 2) {
          if (currentHour > reservationHour) {
            return 50;
          }
          return 0;
        }  else if (currentDay === 31 && reservationDay === 1) {
          return 50;
        }
        return 0;
      } else {
        if (currentDay === 29 && reservationDay === 1 || currentDay === 30 && reservationDay === 2) {
          if (currentHour > reservationHour) {
            return 50;
          }
          return 0;
        } else if (currentDay === 30 && reservationDay === 1) {
          return 50;
        }
        return 0;
      }
    } else {
      if (reservationDay - currentDay > 2) {
        return 0;
      } else if (reservationDay - currentDay === 2) {
        if (currentHour > reservationHour) {
          return 50;
        }
        return 0;
      } else if (reservationDay - currentDay === 1) {
        return 50;
      } else {
        if (reservationHour - currentHour === 0) {
          return 100;
        } else if (reservationHour - currentHour === 1) {
          if (reservationMinute < currentMinute) {
            return 100;
          }
          return 50;
        }
        return 50;
      }
    }
  }
```


texts: Arduino driver for 7 segment display with bit-shift register

texts:
This code counts down from 30 to -999 on a 7-segment 4-digit display; it works but I don't know if it is a good way to do it or if it follows best practices.  I want to start writing libraries for components that are not specifically made for Arduino.  This is my first attempt.  Please tell me if there are any problems with it or if there is some way for me to improve it.  I am working on also making it able to show decimals but am not done yet.

//This is code to put out any signed integer to a seven segment display using a bit shift register.

int number[12]   = {80,95,50,22,29,148,144,94,16,28,191,16};  //Values 0 through 9 on a 7-segment LED display, negative symbol is 10 and subtract 11 from any number to put a decimal
int shiftPins[3] = {7,8,9};  // (clock pin, data pin, latch pin)
int digitPins[4] = {2,3,4,6}; // (ones, tens, hundreds, thousands)
int show[4]; // (thousands, hundreds, tens, ones)

void setup(){
  pinMode(digitPins[0], OUTPUT);
  pinMode(digitPins[1], OUTPUT);
  pinMode(digitPins[2], OUTPUT);
  pinMode(digitPins[3], OUTPUT);

  pinMode(shiftPins[0], OUTPUT);
  pinMode(shiftPins[1], OUTPUT);
  pinMode(shiftPins[2], OUTPUT);
}

void loop(){

  print2LEDs(30-millis()/1000);

}

void print2LEDs(int number2show){

  if(number2show >= 0){

    show[0] = ((int)number2show/1000);
    show[1] = ((int)number2show%1000)/100;
    show[3] = (((int)number2show%1000)%100)/10;
    show[2] = ((((int)number2show%1000)%100)%10);
    }
  else {
    number2show = -(number2show);
    show[0] = 10;
    show[1] = ((int)number2show%1000)/100;
    show[3] = (((int)number2show%1000)%100)/10;
    show[2] = ((((int)number2show%1000)%100)%10);
  }
  showDigit(show[0],digitPins[0]);
  showDigit(show[1],digitPins[1]);
  showDigit(show[2],digitPins[2]);
  showDigit(show[3],digitPins[3]);
}

void showDigit(int i, int f){

  digitalWrite(shiftPins[2], 0);
  digitalWrite(f, 1);

  shiftOut(shiftPins[1], shiftPins[0], LSBFIRST, number[i]);

  digitalWrite(f, 0);
  digitalWrite(shiftPins[2], 1);
}


texts: Traversing List of Integers and ending on the last index which should be 0

texts:
I have a method that checks if a List is solvable. Solvable in this context means 2 things:

The last index of the list is a 0.
Starting from the first index, each value indicates how many position you should go back or forth in the List. After walking the indexes you should end at the last index.

public class ListSolver {

  public boolean isSolvable(List<Integer> list) {
    if (list == null) {
      throw new IllegalArgumentException("List is null");
    }

    int listSize = list.size();
    int lastIndex = listSize - 1;
    int currentIndexValue;
    for (int i = 0, loopCounter = 0; i < listSize; i = i + currentIndexValue, loopCounter++) {
      try {
        currentIndexValue = list.get(i);
      } catch (IndexOutOfBoundsException e) {
        return false;
      }

      // if traversed to last index and last index is 0
      if (i == lastIndex && currentIndexValue == 0) {
        return true;
      }

      // if infinite loop
      if (loopCounter > listSize) {
        return false;
      }
    }

    return false;
  }

}

public class ListSolverTest {

  private ListSolver listSolver = new ListSolver();

  @Test(expected = IllegalArgumentException.class)
  public void isSolvableGivenNullExpectIllegalArgumentException() {
    listSolver.isSolvable(null);
  }

  @Test
  public void isSolvableGivenListContainingZeroAndZeroExpectFalse() {
    boolean isSolvable = listSolver.isSolvable(Arrays.asList(0, 0));

    assertFalse(isSolvable);
  }

  @Test
  public void isSolvableGivenListContainingOneAndNegOneExpectFalse() {
    boolean isSolvable = listSolver.isSolvable(Arrays.asList(1, -1));

    assertFalse(isSolvable);
  }

  @Test
  public void isSolvableGivenListContainingZeroExpectTrue() {
    boolean isSolvable = listSolver.isSolvable(Collections.singletonList(0));

    assertTrue(isSolvable);
  }

  @Test
  public void isSolvableGivenListContainingOneAndZeroExpectTrue() {
    boolean isSolvable = listSolver.isSolvable(Arrays.asList(1, 0));

    assertTrue(isSolvable);
  }

  @Test
  public void isSolvableGivenListContainingNegOneExpectFalse() {
    boolean isSolvable = listSolver.isSolvable(Collections.singletonList(-1));

    assertFalse(isSolvable);
  }

}

The method was written using TDD, but I'm stuck now.

  How  can I refactor and make it more readable without creating new methods that feel contrived?


texts: Calculating a Score in VBA based on selected ShapeStyle. Is there a better/shorter way to do this?

texts:
I'm calculating a score based on whether or not certain colors shape is selected. Some of the shapes are in groups, some are not. For the shapes which are in groups, only one of them will count towards the score. I have figured out how, as you can see below. However, I have 9 more shapes/scores to add to the Sub. I'm still somewhat new at VBA, and I am wondering if there is a better/shorter way to write this formula. Thanks in advance.

Sub Lead_Score()
With Sheet1

Dim Cust As Integer, Vend As Integer, Sus As Integer, Pros As Integer, RelScore As Integer, Qual As Integer, NonQual As Integer, QualScore As Integer, Score As Integer
Cust = .Shapes("CustomerButton").ShapeStyle
Vend = .Shapes("VendorButton").ShapeStyle
Sus = .Shapes("SuspectButton").ShapeStyle
Pros = .Shapes("ProspectButton").ShapeStyle
Qual = .Shapes("QualifiedButton").ShapeStyle
NonQual = .Shapes("NonQualifiedButton").ShapeStyle

Dim Customer As Long, Vendor As Long, Prospect As Long, Suspect As Long, Qfied As Long, NQfied As Long
Customer = 0
Vendor = 0
Prospect = 15
Suspect = 5
Qfied = 15
NQfied = 0

If Cust = 34 Then
    RelScore = Customer
End If
If Vend = 34 Then
    RelScore = Vendor
End If
If Sus = 34 Then
    RelScore = Suspect
End If
If Pros = 34 Then
    RelScore = Prospect
End If
If Qual = 34 Then
    QualScore = Qfied
End If
If NonQual = 34 Then
    QualScore = NQfied
End If

Score = RelScore + QualScore
    Debug.Print Score

End With
End Sub


texts:
I am trying to implement Dijkstra algorithm. I try to calculate cost of reaching every node from first node. Though I have tried with couple of graphs and results are correct but I have one doubt which leads me to think that something is wrong with my implementation. Here is my implementation

private int[] findShortestPathBetween(int[][] graph, int src) {

    int[] result = new int[graph.length];
    for (int i = 0 ; i < result.length ; i++) {
        result[i] = Integer.MAX_VALUE;
    }

    result[src] = 0;

    boolean[] visited = new boolean[graph.length];

    int i = 0;
   while (true) {
        for (int kk = 0 ; kk < graph.length ; kk++) {
            if (graph[i][kk] != 0 ) { // edge between nodes exists
                int previousCost = result[i];
                if (previousCost == Integer.MAX_VALUE) {
                    previousCost = 0;
                }
                int newCost = previousCost + graph[i][kk];
                newCost = Math.min(newCost, result[kk]);
                if (newCost != result[kk]) {
                    visited[kk] = false; //weight of visited node changed, remove it from visited nodes.
                }
                result[kk] = newCost;
            }
        }
        visited[i] = true;

        int nextNode = -1;
        int nextNodeCost = Integer.MAX_VALUE;

        for (int k = 0 ; k < graph.length ; k++) {
            if (!visited[k]) {
                nextNode = k;
                break;
            }
        }

        if (nextNode == -1) {
            break;
        }

        i = nextNode;
   }
    return result;
}

I think line containing following code should not be required.

visited[kk] = false;

Here I am marking an already visited node as not visited if its cost has changed. Not doing this gives wrong results. As per my understanding this should not be required because if a node has been marked visited it should never be visited again.

I am trying to implement Dijkstra without using any queue (using queue is 2nd part of my implementation).

Please check and confirm whether my implementation has any gaps or this is expected when we are not using queue to implement Dijkstra algorithm.

Assumptions: I have used 2D array to represent my graph. If edge exist between 2 nodes corresponding entry in array is non-zero and if edge does not exist corresponding entry contains 0.


texts:
I have a bunch of processes that are being executed on different virtual machines. All of those processes have a StartDate, EndDate and Resource properties. Resource is a specific virtual machine it was ran on. I generated the actual timeline for items and found out that all of those resources have "holes" in timeline that could fit other processes running on other machines at the same time, which means I could live with less machines. So I am now trying to come up with an algorithm that tries to fit all those processes to timeline. It adds a timeline and first item to timeline, for every next item, it checks if the EndDate of the last item in timeline is greater than current items StartDate, if so Add a new timeline, else put to existing timeline. The current implementation:

public List<TimelineDto> GetOptimizedTimeline()
{
    var allItems = GetInterestingItems().OrderBy(x => x.StartDate).ToList();
    if (!allItems.Any())
    {
        return null;
    }
    // Add the first item to first resource
    var firstitem = allItems.FirstOrDefault();
    var timelineCount = 1;
    var timeline = new List<TimelineDto>
    {
        new TimelineDto
        {
            itemId = firstitem.Id,
            Resource = timelineCount.ToString(),
            StartTime = firstitem.StartDate,
            EndTime = firstitem.EndDate
        }
    };
    allItems.Remove(firstitem);

    foreach (var item in allItems)
    {
        var added = false;
        for (var i = 1; i <= timelineCount; i++)
        {
            // as items are ordered by date, take the last item in current resource and see if the new items "fits" to that resource
            var last = timeline.Last(x => x.Resource.Equals(i.ToString()));
            if (item.StartDate > last.EndTime)
            {
                // Add to existing
                timeline.Add(new TimelineDto
                {
                    itemId = item.Id,
                    Resource = i.ToString(),
                    StartTime = item.StartDate,
                    EndTime = item.EndDate
                });
                added = true;
                break;
            }
        }
        // suitable resource already found, cool.
        if (added)
            continue;
        // Current item did not fit into any existing resource, add a new one.
        timelineCount++;
        timeline.Add(new TimelineDto
        {
            itemId = item.Id,
            Resource = timelineCount.ToString(),
            StartTime = item.StartDate,
            EndTime = item.EndDate
        });
    }
    return timeline;
}

Now this does what I need, but for 100k items it takes minutes to complete. I am processing 1M items daily so it's not that I can't wait several minutes, but it would be great to optimize it. Can I parallelize this?


texts:
I recently began to dabble into the programming world and wrote a Dice Simulator Program. How do I know that I'm writing Good Code? In the sense, is it something similar to how a major Software Developing company would produce code for real problems.

""" This Program is Dice Simulator that produce an Output from 1-6
everytime the User presses Enter. In order to close the Program,
the User has to type "Exit" into the console.
"""

#Imports the random module to generate the random Integers
import random

#Initial Designer Print Statements
print(" Hi! Welcome to Dicey!")
print ("""

   .-------.    _______
  /   o   /|   /\\      \\
 /_______/o|  /o \\  o   \\
 | o     | | /   o\\______\\
 |   o   |o/ \\o   /o     /
 |     o |/   \\ o/  o   /
 '-------'     \\/____o_/

  """)

exit=False      #Set True When User types "Exit" into the console
count=0         #Count to keep track of Iterations/Dice rolls

#The Input is obtained below
enter=(input(("Press Enter to Roll (or) Type 'Exit' to Close.
\n\n")).lower())

#Condition to check wether the user wants to Exit the program without
#Rolling the Dice

if (enter=="exit"):
    exit=True

#Checks for Enter and Produces a random integer using the random module
while(enter=="" or not exit):
  dice_number=random.randint(1,6)
  count = count + 1
  print(f"{count}>You got a {dice_number}")
  enter=(input("Press Enter to Roll Again! \n").lower())

#If User inputs "Exit", Close the program.
if (enter=="exit"):
    exit=True

#If the User inputs anything else other than "Exit" Roll the dice again.
elif(enter is not ""):
    print("\n")
    continue


texts:
This a very simple function to expand the sizes between the given values.

For instance, if the input variable is "S-XL" then the function returns "S, M, L, XL".

Basically I'm not happy with this function.  I think it's too complex for its purpose.

function sizexpander($sizes) {
    $sizearray=Array("XS", "S", "M", "L", "XL", "XXL", "XXXL");
    $size1=array_search(strstrb($sizes, "-"), $sizearray);
    $size2=array_search(substr(strstr($sizes, "-"),1), $sizearray);
    while ($size1 <= $size2) {
        $prodsizes.= $sizearray[$size1].", ";
        $size1++;
    }
    return substr($prodsizes, 0, -2);
}

function strstrb($h,$n){
    return array_shift(explode($n,$h,2));
}


texts:
I want to get a result from the website when I submit a form. There are several things that can go wrong.

In a simple scenario I want to return:

true - when form was submitted

false - when form wasn't submitted

null - when we don't know if form was submitted or not

I did that ugly try, because of NullReferenceException (if form is filled correctly, there would be no summary element, and if form is filled incorrectly, there would be no popup element).

How can I make this more elegant?

public bool? GetResult(TimeSpan timeout)
{
    var deadline = DateTime.Now.Add(timeout);

    do
    {
        // check if success
        try
        {
            var success = new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
        .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("summary")), "Success!"));
            if (success) return true;
        }
        catch (Exception ex)
        {  }

        // check if not enough data
        try
        {
            var notEnoughData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
        .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Not enough data"));
            if (notEnoughData) return false;
        }
        catch (Exception ex)
        { }

        // check if too much data
        try
        {
            var tooMuchData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
        .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Too much data"));
            if (tooMuchData) return false;
        }
        catch (Exception ex)
        { }

        // check if empty data
        try
        {
            var tooMuchData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
        .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Empty data"));
            if (tooMuchData) return false;
        }
        catch (Exception ex)
        { }

    } while (DateTime.Now > deadline);

    return null;
}


texts:
I am using NodeJS and MongoDB for a weather app that takes the weather info from a logger, saves it to a database, and relays the data to the browser in real-time.  It is hosted here with code here which has project details and explanation.

I am saving the weather data to the mongolab cloud-db like so:

// Save to cloud db on MongoLab
mongodb.MongoClient.connect(uri, function (err, cloud_db) {
  cloud_db.collection('raw_data', function(err, collection) {
    if(!err) {
        collection.insert(dbString, function(docs) {
            collection.count(function(err, count) {
                if(!err) {
                    console.log("Saved to mongolab");
                }
            });
        });
     }
  });
});

and the document in db looks like:

{
  "lat": "22.65587",
  "long": "75.82626",
  "date": "2014/08/23",
  "time": "20:10:00.000",
  "temp_c": "25.2",
  "humidity": "86.5",
  "pressure_mbar": "939.0",
  "wind_dir": "85.9",
  "wind_speed_mps": "0.8",
  "rain_mm": "0.0",
  "solar_rad_wpsqm": "-3.8",
  "_id": {
      "$oid": "53f8a7d840ecdfe006b0e3be"
  }
}

I was wondering if this was the best possible schema for storing the data in terms of speed of data retrieval and ease of use.

Another concern is handling the units. I have named the quantities with units in them. Is there any other way this can be handled better ?


texts:
I just wonder whether it is a common approach to hit the third-party API and fetch values within the initialize method?

Ex.

    class BalanceTransaction::Update
      include Service

      attr_reader :offset, :transactions

      def initialize(offset)
        @offset = offset
        @transactions = fetch_transactions
      end

      def call
        transactions.auto_paging_each do |txn|
          type = txn[:type]
          source = txn[:source]

          case type
            when 'charge', 'adjustment' # NOTE: adjustment is something
              invoice = find_invoice(source)
              ac_id = invoice.ac.id
              update_attrs(id: invoice.id, account_id: ac_id, type:'invoice', attrs: txn)
            when 'refund'
              refund = find_refund(source)
              ac_id = refund.invoice.account.id
              update_attrs(id: refund.id, account_id: ac_id, type:'refund', attrs: txn)
          end
        end
      end

   private
      def external_card_balance
        Stripe::BalanceTransaction
      end

      def fetch_transactions
       external_card_balance.all
      end


texts:
I use ruby 1.8.7. I have method wich select records and fill hash. In my opinion the code is not dry. Could somebody help me to refactor it and make it shorter and more elegant?

def fill_attributes()
  if (!$array[:status_id])
            $array[:status_id] = @customer.status_id
             @status_name=Status.find($array[:status_id]).name rescue nil
            $array[:status]=@status_name if @status_name
      end

     if (!$array[:color_id])
            $array[:color_id] = @customer.color_id
            @color_name=Color.find($array[:color_id]).name rescue nil
            $array[:color]=@color_name if @color_name
      end
     .....

  end

My version is:

  map={'model1' => Model1, 'model2' => Model2,'model3' =>Model3}

  map.keys.each do |model|
       key="#{model}_id".to_sym
       value="#{model}.#{model}_id"
     if (!$array[key])
          $array[key] =  #instance_variable_set("@#{value}",eval(value, binding) )
          name=map[model].find($array[key]).name rescue nil
          $array[key]=name if name
      end
   end

But there's a problem, to use instance_variable_set I have to create a class? What is the  best way to refactor it?


texts: Fastest path on a snakes and ladders board

texts:
I am not looking for a detailed review of this code as I am aware it is very inefficient. The main reason for posting this is to see if there is a better way to achieve my goal (I am certain there must be)

I have created code to find the fewest number of dice rolls that would permit someone to move from the first to last square on a snakes and ladders board. The player wins if they land on or go beyond the final square on the board. They start off the board at position -1.

My approach uses recursion so is OK for small boards. The moment the board reaches a size of 30+ it takes far too long to generate the solution.

Is there a better way to solve this problem

"""Module works out fastest way to traverse a snakes and ladders board"""
def roll_dice(position, roll_number, number_squares, snakes, ladders, list_moves=[]):
    """Roll the dice and then work out if the player can climb a ladder / has won"""
    if position in ladders:
        position = ladders[position]
    if position >= number_squares - 1:
        list_moves.append(roll_number)
        return
    for i in range(1, 7): #For each position roll the dice 6 times
        if position + i in snakes:
            continue  # Forbid a dice-roll that lands on a snake
        roll_dice(position + i, roll_number + 1, number_squares, snakes, ladders)
    return list_moves

def minimum_moves(number_squares, snakes={}, ladders={}):
    """Returns the minimum number of moves starting from position 0 for a board of size n
    snakes and ladders are both dictionaries containing the starting point as the key
    and end point as the value"""
    # Initialise board
    # The player starts off the board at position -1
    list_moves = roll_dice(-1, 0, number_squares, snakes, ladders)
    print(f"Board is traversable in {min(list_moves)} moves")

if __name__ == "__main__":
    NUMBER_SQUARES = 25
    SNAKES = {21:0, 19:9, 14: 2, 18:5}
    LADDERS = {2: 21, 4:9, 10:20, 17:23}
    minimum_moves(NUMBER_SQUARES, SNAKES, LADDERS)


texts: Project Euler # 37 Truncatable primes in Python

texts:
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

Here's my implementation in Python, it's very slow(takes like 10 secs to show results. How to make it faster, more efficient?
def is_prime(number):
    """returns True for a prime number, False otherwise."""
    if number == 1:
        return False
    factor = 2
    while factor * factor <= number:
        if number % factor == 0:
            return False
        factor += 1
    return True

def get_truncatable(n):
    """returns truncatable numbers within range n."""
    for number in range(9, n, 2):
        if is_prime(number):
            check = 0
            for index in range(-1, -len(str(number)), -1):
                less_right = str(number)[:index]
                if not is_prime(int(less_right)):
                    check += 1
            if check == 0:
                for index in range(1, len(str(number))):
                    less_left = str(number)[index:]
                    if not is_prime(int(less_left)):
                        check += 1
                if check == 0:
                    yield number

if __name__ == '__main__':
    print(sum(list(get_truncatable(1000000))))


texts:
I have the following code working fine:
rowData is an object and I want to display download button only if the completePathName is not null and hence I did the following which is working fine. I am wondering if I can improve the following code in some manner or the conditional if that I have used is fine?
buttonTemplate = (rowData: any, column: any)  => {
        //if(typeof rowData !=='undefined' && typeof rowData.completePathName !=='undefined'){
        if(rowData.completePathName === null){
            return (

              console.log("Inside first return  - testing rowData:"),
              console.log(rowData),
              console.log(rowData.completePathName),

                            <Button type='button' icon="pi pi-pencil" style={{marginRight: '5px'}} onClick={(e) => this.handleClick(rowData, e)} tooltip='Edit'/>
                            <Button icon="pi pi-trash" style={{marginRight: '5px'}} tooltip='Delete' />

            );

        }
        else {
            return (

                console.log("Inside second return  - testing rowData:"),
                console.log(rowData),
                console.log(rowData.completePathName),

                            <Button type='button' icon="pi pi-pencil" style={{marginRight: '5px'}} onClick={(e) => this.handleClick(rowData, e)} tooltip='Edit'/>
                            <Button icon="pi pi-trash" style={{marginRight: '5px'}} tooltip='Delete' />
                            <Button icon="pi pi-download" tooltip='Download' />

            );

        }

    }


texts:
I'm a beginner programmer and i'm looking for interesting projects to improve my low skills. I tried one day to improve my skills by trying to create a small game in which a user owns a cat, and has to feed it and clean it. My main aim of the game(which yet has many illogical things like the never decreasing happiness and cleanness level) was to try and keep my code as clean and presentable as possible. The game is made in 4 different files, and I will paste them all below. I will be happy if anyone could give me help on understanding where should I improve.
Lets go into the code:
main.cpp
#include "Cat.h"
#include "pet game.h"
#include <iostream>
using namespace std;

int main() {
    //Create the user's profile
    //User();

    //Welcome messages
    cout
            << "Welcome to Unga bonga! Here you buy pets and raise them as your kids, and try to level up, in order to finish the game!"
            << endl;
    showHelp();

    //Command execution
    do {
        commandIdentify();
    } while (true);
}
Cat cat;
//User user;

void showHelp() {
    cout << "The commands in this game are:" << endl
            << "1. to feed your cat, type f" << endl
            << "2. to clean your cat, type c" << endl
            << "3. to check your cat's happiness, type h" << endl
            << "4. to check your cash balance, type m" << endl
            << "5. to check your level status, type l" << endl
            << "6. to display this help message, type ?" << endl
            << "7. to exit, type e" << endl
            << "8. Finally, to play this game, enjoy!" << endl;
}

void commandIdentify() {
    //take input
    cin >> command;
    //identify and execute
    switch (command) {
    case 'f':
        feedCat();
        break;
    case 'c':
        cleanCat();
        break;
        case 'h':
         checkHappiness();
         break;
    case '?':
        showHelp();
        break;
    case 'e':
        exit();
    default:
        cout << "That's not a command -yet (probably)" << endl;
    }
}

void feedCat() {
    cout << "Time for food!!!" << endl;
    cat.feed();
}

void cleanCat() {
    cout << "Let's take a bath!!!" << endl;
    cat.clean();
}

void checkHappiness(){
 cat.checkHappiness();
 }

int exit() {
    exit(0);
    return 0;
}

pet game.h:
    #ifndef PET_GAME_H_
#define PET_GAME_H_

#include <iostream>
#include "Cat.h"
//#include "User.h"

using namespace std;

//Global variables
char command;
int exit();

//functions
void commandIdentify();
void buyNextCat();
void showHelp();
void tutorial();
void feedCat();
void cleanCat();
void checkHappiness();

//functions defined for a future use but they cause problems right now
void checkMoney();
void checkLevel();

#endif /* PET_GAME_H_ */

Cat.cpp:
#include <iostream>
#include <string>
#include "Cat.h"

using namespace std;

Cat::Cat(){
    happiness = 1;
    cleanness = 1;
}

void Cat::feed(){
    cout << "Yummy!!" << endl;
    Cat::happiness = Cat::happiness + 0.2;
}

void Cat::clean(){
    cout << "So soupy!!" << endl;
    Cat::cleanness = Cat::cleanness + 0.2;
}

Cat.h:
#ifndef CAT_H_
#define CAT_H_

#include <iostream>

using namespace std;

class Cat {
private:
    int happiness;
    bool happy = happiness >= 0.6;

    int cleanness;
    bool isClean = cleanness >= 0.6;
public:
    Cat();
    void feed();
    void clean();
    void checkHappiness() {
        cout << "Your cat's happiness is " << happiness*100 << "%" << endl;
    }

};

#endif /* CAT_H_ */

it will be great if you could tell me how to improve code


texts: PreWarmCache for MVC Application with Stopwatch Infinite Loop

texts:
I used the information from the article "Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)" to create a background task that runs on an infinite loop. Ultimately, this program is going to be consuming a REST API to get data from a remote web site and insert records into my database. For the time being, I am just doing a basic insert.

public class PreWarmCache : System.Web.Hosting.IProcessHostPreloadClient
{
    private static BackgroundTaskContext db = new BackgroundTaskContext();
    private static Timer _timer;

    public void Preload(string[] parameters)
    {
        // Perform initialization and cache loading logic here...
        try
        {
            var doStuff = new DoStuff();
            doStuff.DoStuffName = "Test from PRELOAD INIT " + DateTime.Now;
            db.DoStuffs.Add(doStuff);
            db.SaveChanges();
        }
        catch
        {
        }

        var timeInMilliseconds = 0;
        _timer = new Timer(Callback, null, timeInMilliseconds, Timeout.Infinite);

    }

    public static void Callback(Object state)
    {
        var timeInMilliseconds = 5000;
        Stopwatch watch = new Stopwatch();

        watch.Start();

        // Update the database
        try
        {
            var doStuff = new DoStuff();
            doStuff.DoStuffName = "Test from CALLBACK " + DateTime.Now;
            db.DoStuffs.Add(doStuff);
            db.SaveChanges();
        }
        catch
        {
        }

        _timer.Change(Math.Max(0, timeInMilliseconds - watch.ElapsedMilliseconds), Timeout.Infinite);
    }
}


texts:
I want to have a deck of cards that looks like this:

['H1', 'H2', 'H3', 'H4', 'H5', 'H6'...]

For that I wrote the following code:

    import itertools
    kind = 'HCDS'
    value = ['1','2','3','4','5','6','7','8','9','10','J','Q','K','A']
    temp = list(itertools.product(kind,value))

    deck = []
    for i in range(0, len(temp)):
        (a,b) = temp[i]
        deck.append(a+b)
    print(deck)

I was wondering if it could be done easier without the use of this temp variable or the for loop.


texts:
I need the most efficient way to calculate when the Collatz Conjecture of two numbers, a and b respectively, are the same. Here is my algorithm, which is too slow:

while(true) {
        int a = sc.nextInt();
        int b = sc.nextInt();

        if(a == 0 && b == 0) {
            break;
        }

        TreeMap<Integer, Integer> visited = new TreeMap<>();
        visited.put(a, 0);

        int A = a;
        int Acount = 0;

        while(A != 1) {
            Acount++;

            if(A % 2 == 0) {
                A /= 2;
            } else {
                A = A * 3 + 1;
            }

            if(!visited.containsKey(A)) {
                visited.put(A, Acount);
            }
        }

        int B = b;
        int Bcount = 0;

        while(B != 1) {
            if(visited.containsKey(B)) {
                out.println(a + " needs " + visited.get(B) + " steps, " + b + " needs " + Bcount + " steps, they meet at " + B);
                break;
            }

            if(B % 2 == 0) {
                B /= 2;
            } else {
                B = B * 3 + 1;
            }

            Bcount++;
        }

    }

After looking around on Github, I found this, and it worked, although it's essentially the exact same thing.

Original problem

How do I fix my Java code to make it more efficient? I tried it literally at least four times.


texts:
for some fun, I decided to start working on something that let me work with Money calculations. I realise there are libraries out there like Joda Money, but I'm doing this mainly for fun.

I was hoping to get a review on the way I've started to construct the library.

GitHub

private def calculate(that: Money)(f: (BigDecimal, BigDecimal) => BigDecimal): Either[String, Money] = (this.currency, that.currency) match {
case (c, c1) if c == c1 => new Right(this.copy(this.currency, f(this.amount, that.amount)))
case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

private def compare(that: Money)(f: (BigDecimal, BigDecimal) => Boolean): Either[String, Boolean] = (this.currency, that.currency) match {
    case (c, c1) if c == c1 => new Right(this.amount > that.amount)
    case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

These two methods are incredibly similar except for the return type. Could someone suggest a way to improve this?


texts:
I have received this question during an interview I did earlier, but I found that my solution might not be correct. And I would like to know whatever there is a better way to solve this.

Question:

  Lots of people are making a reservation for appointments

  Writes a function to let people make appointments reservation before
  attending the appointment. When a time-slot is reserved
  (already booked), do not let any user double-book and make overlap         reservation in the same time-slot.

  Reservation takes (as an example)

  personA: 9:00 -> 11:00 tomorrow -> successful
  personB: 9:00 -> 10:00 tomorrow -> fail
  personC: 13:00 -> 14:00 tomorrow -> successful
  personA: 17:00 -> 18:00 tomorrow -> fail because personA already made reservation once

  Few notes:

  Assuming reservation only for 1 specific day, 24-hrs only
  Assuming the clock is 24-hrs with only integers

  Additions - v1.1 After launching v1.0, more than half of the users do not attend their appointments. Allow a user to reserve appointments
  twice in the same time intervals

ALLOW_MULTIPLE_RESERVATIONS = 2

users = {
    'alice': '1',
    'bob': '2',
}

appointments = [[9, 12], [9, 12], [13, 17]]
reservations = {}

def print_error(user, time):
    print('Cannot make reservation for user {} at {}'.format(user, time))
    return False

def reserve(user, time):

    # this case is for double reservation for the same interval
    if user in reservations:
        user_reservation = reservations[user]
        user_count = reservations[user]['count']
        user_time = reservations[user]['time']
        if user_count < ALLOW_MULTIPLE_RESERVATIONS:
            if user_time[0] == time[0] and user_time[1] == time[1]:
                reservations[user] = {
                    'time': time,
                    'count': user_count + 1,
                }
            return True
        else:
            print_error(user, time)
            return False

    # this is for first time reservation
    for t in appointments:
        if user not in reservations:
            if (time[0] >= t[0] and time[1] <= t[1]):
                t[0] = time[1]
                t[1] = t[1]
                reservations[user] = {
                    'time': time,
                    'count': 1,
                }

    # end-for

    # when we cannot find any available time interval for reservation, we simply just return False
    if user not in reservations:
        print_error(user, time)
        return False
    return True

reserve(user='alice', time=[9, 10])
reserve(user='alice', time=[9, 10]) # v1.1 this should pass
reserve(user='alice', time=[9, 10]) # v1.1 this should fail
reserve(user='bob', time=[9, 10])

print(reservations)
print(appointments)


texts: pos+ (value added to position) - ex 3.5 in “ANSI Common Lisp” (p57)

texts:
The problem is to take a list of integers and map them to another list containing those integers added to their respective position in the list.

Example runs with required outputs:

> (pos+ '(1 1 1 1))
(1 2 3 4)
> (pos+ '(7 5 1 4))
(7 6 3 7)

We are required to develop three alternate solutions. One using recursion, one using iteration, and one using mapcar.

I present my solutions below and seek comments on style, best coding conventions & habits to adopt. Also the question of which solution is preferred for this particular case arises, including justification for the choice.

Observations (on which I seek discussion) are included as comments in the code.

;;; (1) Using recursion
(defun pos+ (lst)
  (pos-helper lst 0))
(defun pos-helper (lst n)
  (if (null lst)
      nil
      (cons (+ (first lst) n)
            (pos-helper (rest lst) (+ n 1)))))
;; Elegant, as recursion often is, but not a tail call (cant abandon stack frame),
;; hence less efficient at scale (which may not matter).

;;; (2) With iteration
(defun pos+2 (lst)
  (do ((i 0 (+ i 1)))
      ((>= i (length lst)) lst)
      (setf (nth i lst) (+ (nth i lst) i))))
;; Fewer lines, but i have a feeling of disappointment to be learning lisp
;; and not be using a functional style. Q. Is that intuition well-placed?

;;; (3) With mapcar
(defun pos+3 (lst)
  (mapcar #'(lambda (x y) (+ x y))
          lst
          (range (length lst))))

;; This would be my 'most beautiful' solution except for one problem.
;; Could not find any built in range function. I found range [footnote 1]
;; and pasted it here. The syntax doesn't look anything like CL to me!
(defun range (max &key (min 0) (step 1))
   (loop for n from min below max by step  ;; did the lisp alien write this?! :)
      collect n))

link to range function used above


texts:
My task is:

Write a program that reads integers until 0 is entered. After input terminates, the
program should report the total number of even integers (excluding the 0)
entered, the average value of the even integers, the total number of odd integers
entered, and the average value of the odd integers.

But I had to use switch for this...

My code is:

#include <stdio.h>

int main(void)

{
    int oddIndex = 0, evenIndex = 0, evenTotal = 0, evenSum, oddTotal = 0, oddSum;
    int userInput;
    int oddArray[oddIndex], evenArray[evenIndex];

    printf("please enter some numbers: \n");
    while (((scanf("%d", &userInput)) == 1) && (userInput != 0))
    {

        switch (userInput%2)
        {
            case 0:
                evenArray[evenIndex] = userInput;
                evenIndex++;
                evenTotal++;
                evenSum += userInput;
                break;

            default:
                oddArray[oddIndex] = userInput;
                oddIndex++;
                oddTotal++;
                oddSum += userInput;
                break;
        };
    }
    if (evenTotal > 0)
    printf("even total: %d, even average: %d\n", evenTotal, evenSum/evenTotal);
    else
        printf("there is no even numbers!\n");
    if (oddTotal > 0)
    printf("odd total: %d, odd average: %d", oddTotal, oddSum/oddTotal);
    else
        printf("there is no odd numbers!");
}

Is this code ok?


texts: Having single DAO parent class in an EJB application

texts:
I have the following DAOParent class that I use to put connect/disconnect code in one place. Each DAO class in the application is an EJB that extends DAOParent (note that I don't use JPA):

public class DAOParent {

    private InitialContext context = null;
    private DataSource ds = null;
    private Connection conn = null;

    protected Connection getConnFromPool(String pool) throws DAOException {

        try {
            context = new InitialContext();
            ds = (DataSource)context.lookup(pool);
            conn = ds.getConnection();
            return conn;
        }
        catch (NamingException e) {
            throw new DAOException(e.getMessage());
        }
        catch (SQLException e) {
            throw new DAOException(e.getMessage());
        }
    }

    protected void releaseConn() {
        try {
            if (conn != null)
                conn.close();
        }
        catch (SQLException e) {}

        try {
            if (context != null)
                context.close();
        }
        catch (NamingException e) {}
    }
}

And the DAO class:

@Stateless
public class DAOChild extends DAOParent {

    public void someMethod() throws DAOException {

        Connection conn = getConnFromPool("some/jndi/path");

        try {

            // use the connection
        }
        finally {
            releaseConn();
        }
    }
}

The DAOChild class is then injected in an EJB to access the data.

Questions: (1) is there a problem with this approach? (2) If I have DAOChild1 and DAOChild2 injected in the same EJB, is there a conflict in the connection lookup?

I run this on Wildfly 14 application server/container.


texts:
I'm trying to increase the speed of my application at the moment. My inserting/updating methods were opening every time a new connection which took too much time. I read that it's better to create a connection object and pass it to different methods. It worked fine but I'm just curious if this is a good practice.

This is a part of my code I wrote:

public class BusinessRuleUpdaterDaoImplV2 extends OracleBaseDao implements BusinessRuleUpdaterDaoV2 {

    @Override
    public boolean updateBusinessRule(BusinessRule businessRule) {
        try(Connection con = super.getConnectionConfigDb()) {
            con.setAutoCommit(false);
            if (updateTableBusinessRule(con,businessRule)){
                return true;
            } else {
                con.rollback();
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean updateTableBusinessRule(Connection con, BusinessRule businessRule){
        String queryBr = "UPDATE BUSINESSRULE SET ERRORMESSAGE = ?, SQLCODE = ?, CUSTOMNAME = ?, OPERATOR_ID = ? WHERE BUSINESSRULE_ID = ?";
        try(PreparedStatement pstmtBr = con.prepareStatement(queryBr)) {
            pstmtBr.setString(1,businessRule.getErrorMessage());
            pstmtBr.setString(2,businessRule.getSqlQuery());
            pstmtBr.setString(3,businessRule.getName());
            pstmtBr.setInt(4,businessRule.getOperatorID());
            pstmtBr.setInt(5,businessRule.getBusinessRuleID());
            pstmtBr.executeUpdate();
            pstmtBr.close();
            return updateTableTargetTable(con,businessRule);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean updateTableTargetTable(Connection con, BusinessRule businessRule){
        String queryTt = "UPDATE TARGETTABLE SET NAME = ? WHERE TABLE_ID = ?";
        for (int i = 0 ; i < businessRule.getTableListSize() ; i++) {
            try (PreparedStatement pstmtTt = con.prepareStatement(queryTt)) {
                pstmtTt.setString(1,businessRule.getListOfTables().get(i).getName());
                pstmtTt.setInt(1, businessRule.getListOfTables().get(i).getId());
                pstmtTt.executeUpdate();
                pstmtTt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }

        return false;
    }

    private boolean updateTableAttribute(Connection con, BusinessRule businessRule){
        // return updateTableValue(con, businessRule)
        return false;
    }

    private boolean updateTableValue(Connection con, BusinessRule businessRule){
        //return updateTableStack(con, businessRule)
        return false;
    }

    private boolean updateTableStack(Connection con, BusinessRule businessRule){
        return false;
    }
}

As you can see in the first method, updateBusinessRule(), I'm opening a connection and passing it to the next method. If one of the methods returns false, it will make a roll back in the first method.

I'm also curious about why intellij is telling me that pstmtTt.close() is redundant.


texts: Reading and updating an XML address file

texts:
I have some code that reads from an XML file and updates if needed. I want to move some of the stuff around. Here is the code overall:

 priv.refAddUpdate = function(addressDoc, addressLine, value)
{
  if(!S(value).isEmpty())
  {
     var found = $(addressDoc).find('addressLines').find(addressLine);

     if(found.length > 0)
     {
        found.text(value);
     }
     else
     {
        $(addressDoc).find('addressLines').append('<addressLine>' + value + '</addressLine>');
     }
  }
  else
  {
     $(addressDoc).find(addressLine).remove();
  }
   };
   priv.updateAddress = function(addressDoc, address)
   {
  if(addressDoc)
  {
     priv.addUpdate(addressDoc, 'firstName', address.firstName);
     priv.addUpdate(addressDoc, 'middleName', address.middleName);
     priv.addUpdate(addressDoc, 'lastName', address.lastName);
     priv.addUpdate(addressDoc, 'companyName', address.companyName);
     priv.refAddUpdate(addressDoc, ':nth-child(1)', address.address);
     priv.refAddUpdate(addressDoc, ':nth-child(2)', address.ref1);
     priv.refAddUpdate(addressDoc, ':nth-child(3)', address.ref2);
     priv.addUpdate(addressDoc, 'city', address.city);
     priv.addUpdate(addressDoc, 'state', address.state);
     priv.addUpdate(addressDoc, 'zip', address.zip);
     $(addressDoc).find('countryCode').text(address.country);
     $(addressDoc).find('shipMethod').text(address.shipMethod);
     priv.addUpdate(addressDoc, 'phoneOne', address.phoneOne);
     priv.addUpdate(addressDoc, 'phoneTwo', address.phoneTwo);
     priv.addUpdate(addressDoc, 'email', address.email);
     }
  };

the big thing is I want to move the :nth-child(1)||:nth-child(2)||:nth-child(3) up into this so that way I can just call perhaps a 1 2 or 3 based on the child instead of how it is now.

priv.refAddUpdate = function(addressDoc, addressLine, value)
    {
  if(!S(value).isEmpty())
  {
     var found = $(addressDoc).find('addressLines').find(addressLine);

     if(found.length > 0)
     {
        found.text(value);
     }
     else
     {
        $(addressDoc).find('addressLines').append('<addressLine>' + value + '</addressLine>');
     }
  }
  else
  {
     $(addressDoc).find(addressLine).remove();
  }
  };

Perhaps it would look like this:

 priv.refAddUpdate(addressDoc, '(1)', address.address);

Or something close to that. Any advice would be awesome!


texts:
As a 'trying to learn Python' project, I am using ffmpy to stitch together a timelapse from a series of still images. I'd like the script to output a couple of formats for web use.

This is what I have:

#!/usr/bin/env python3

import datetime
import ffmpy
import os

now = datetime.datetime.now()
ydr = now.strftime('%Y')
mdr = now.strftime('%m')
ddr = now.strftime('%d')

ipath = str(os.path.dirname(os.path.abspath(__file__))) + '/images/' + ydr + '/' + mdr + '/*/*.jpg'
opath1 = str(os.path.dirname(os.path.abspath(__file__))) + '/videos/' + ydr + mdr + '.mp4'
opath2 = str(os.path.dirname(os.path.abspath(__file__))) + '/videos/' + ydr + mdr + '.webm'

ff = ffmpy.FFmpeg(
    inputs={ipath: '-loglevel info -pattern_type glob -framerate 18 '},
    outputs={opath1: '-c:v libx264 -vf "scale=1280:-1,hqdn3d=luma_spatial=1" -pix_fmt yuv420p'}
)
ff.run()

ff = ffmpy.FFmpeg(
    inputs={ipath: '-loglevel info -pattern_type glob -framerate 18 '},
    outputs={opath2: '-c:v libvpx -vf "scale=1280:-1,hqdn3d=luma_spatial=1" -b:v 1M -c:a libvorbis'}
)
ff.run()

It works, but it's kinda ugly and I'm pretty sure there's a more efficient and 'Pythonic' way of doing this. Any pointers?


texts:
I am writing a Tornado app in which a user can maintain his products wishlist. There are two collections, users and products. As the names imply, the users collections will contain users info and the products collections will contain the URLs.

Typically a user document in users collection will contain the following fields:

email_id
name
tracked_products

The tracked_products here is a list which maintains the wishlist. It contains the ObjectId mapped to URLs in products collection. To make it clear, when two users add the same product URL, in their respective user documents instead of containing the URL, they will have the ObjectId of this URL, which is the ID of the URL in the products collection.

To find tracked_products of a specific user:

    search_user = user_db.find_one({'email_id': user_email})
    search_user['tracked_products']

above will return to me list of ObjectIds.

To add a product URL to the user's wishlist:

product_doc = product_db.find_one({'url': url})
if not product_doc:
    # code needs to be added here to get product name from url
    product_id = str(product_db.insert({'product_name': 'iPad', 'url': url})
else:
    product_id = product_doc['_id']
user_db.update({'email_id': user_email}, {'$addToSet': {'tracked_products': ObjectId(product_id)}})

The following is the code when user wants to remove a URL from his wishlist. Do note that he will send the ObjectId instead of the URL, he intends to remove. This may seem less intuitive. The user will actually never know the ObjectIds, but the page rendered to him which displays the wishlist, will make call when user wants to delete the URL (am I clear here?):

user_db.update({'email_id': user_email}, {'$pull': {'tracked_products': ObjectId(product_id)}})

And here is my actual Tornado app code. I am not using any templating as of now, will add that later. Also ignore the repeated user_db = self.application.db.users statement which is present in all handlers (which should not, may app can have this variable). And one more thing: I access the current logged in user's email ID every time by a cookie.

Is there any way to avoid this? Can I have some global variable which stores user email ID every time the user is logged in?

class ProductsDisplayHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        user_email = self.get_secure_cookie('trakr')
        user_db = self.application.db.users
        search_user = user_db.find_one({'email_id': user_email})
        self.write(str(search_user.get('tracked_products', None)))

class ProductAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, url):
        user_email = self.get_secure_cookie('trakr')
        user_db = self.application.db.users
        product_db = self.application.db.products
        product_doc = product_db.find_one({'url': url})
        if not product_doc:
            product_id = str(product_db.insert({'product_name': 'iPad', 'url': url}))
        else:
            product_id = product_doc['_id']
        user_db.update({'email_id': user_email}, {'$addToSet': {'tracked_products': ObjectId(product_id)}})

class ProductDelHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, product_id):
        user_email = self.get_secure_cookie('trakr')
        user_db = self.application.db.users
        user_db.update({'email_id': user_email}, {'$pull': {'tracked_products': ObjectId(product_id)}})
        self.redirect('/products')
        return


texts:
I am trying to write an algorithm to solve a variation of the N queens problem. There are only 2 queens on an N x N board. I simply need to find the number of solutions, don't need to know what the solutions are.

Below is the code I have so far, and it works fine for N < 100000. However I need to solve it for N > 130456789 so I'm looking for feedback on how to make it more efficient.

public class Chess {

    long size;
    long n;
    long board;
    long cRow;
    long cCol;
    long maxRow;
    long maxCol;
    long safes = 0;

    public static void main(String[] args) {
        Chess a = new Chess(6);
        a.calculateMoves();
    }

public Chess(long n) {
        size = n * n;
        this.n = n;
        maxRow = n - 1;
        maxCol = n - 1;
    }

    public void calculateMoves() {
        iterate();
    }

    public void iterate() {
        for (long i = 0; i < n; i++) {
            for (long j = 0; j < n; j++) {
                cRow = i;
                cCol = j;
                calculateSafePlaces();
            }
        }
        System.out.println(safes/2);
    }

    private void calculateSafePlaces() {
        long notSafePlaces = (2 * n) - 1;

        notSafePlaces += Nw();
        notSafePlaces += Ne();
        notSafePlaces += Se();
        notSafePlaces += Sw();

        safes += (n * n) - notSafePlaces;
    }

    public long Nw() {
        long x = cRow;
        long y = cCol;

        if (x == 0) {
            return 0;
        }

        if (y == 0) {
            return 0;
        }

        if (x == y) {
            return x;
        }

        if (x > y) {
            return y;
        }

        if (y > x) {
            return x;
        }
        return 0;
    }

    public long Ne() {
        long x = cRow;
        long y = cCol;

        long count = 0;
        boolean condition = true;

        if (x == 0 || y == maxCol) {
            return 0;
        }

        long distance_to_east = maxCol - y;
        long distance_to_north = x;
        if (distance_to_north > distance_to_east) {
            return distance_to_east;
        }

        if (distance_to_east > distance_to_north) {
            return distance_to_north;
        }

        if (distance_to_north == distance_to_east) {
            return distance_to_east;
        }
        return 0;
    }

    public long Se() {
        long x = cRow;
        long y = cCol;

        if (x == maxRow) {
            return 0;
        }

        if (y == maxCol) {
            return 0;
        }

        long distance_to_south = maxRow - x;
        long distance_to_east = maxCol - y;

        if (distance_to_south > distance_to_east) {
            return distance_to_east;
        }

        if (distance_to_east > distance_to_south) {
            return distance_to_south;
        }

        if (distance_to_south == distance_to_east) {
            return distance_to_south;
        }
        return 0;
    }

    public long Sw() {
        long x = cRow;
        long y = cCol;

        long count = 0;
        boolean condition = true;

        if (x == maxRow) {
            return 0;
        }

        if (y == 0) {
            return 0;
        }

        long distance_to_south = maxRow - x;
        long distance_to_west = y;

        if (distance_to_south > distance_to_west) {
            return distance_to_west;
        }

        if (distance_to_west > distance_to_south) {
            return distance_to_south;
        }

        if (distance_to_south == distance_to_west) {
            return distance_to_west;
        }
        return 0;
    }
}


texts: Reordering a list in python so that no neighboring elements are equal

texts:
Basically I need to order a list, so that an element is not the same as the element that comes after or before it.

For example [1,2,2,3,1,3,3] should come out as [3,1,2,3,1,2,3], [3,2,3,1,2,3,1] or [2,1,3,1,3,2,3] and so on.

I searched for a solution but couldn't find one so I wrote this function myself.

def unorder(alist):
    multi_lvl_list = []
    unord_list = []

    alist.sort()

    # makes a new list that holds lists where same elements
    # are grouped together
    start = 0
    for i in range(len(alist)):
        if i == len(alist)-1:
            if alist[i] != alist[i-1]:
                multi_lvl_list.append([alist[i]])
            else:
                multi_lvl_list.append(alist[start:])
        elif alist[i] != alist[i+1]:
            multi_lvl_list.append(alist[start:i+1])
            start = i+1
        i += 1

    multi_lvl_list.sort(key=len)

    '''
    goes over every list and pops out one element to a third list
    if there are many same elements they will be put
    to the end of the list
    '''
    while len(multi_lvl_list) > 0:
        for idx, val in enumerate(multi_lvl_list):
            unord_list.append(val.pop())
            if len(val) == 0:
                del multi_lvl_list[idx]

    '''
    go over the list in reverse. if x == x-1 try to put x in the
    beginning of the list. becourse there are
    more likely different elements
    '''
    for i in range(len(unord_list)-1, -1, -1):
        if unord_list[i] == unord_list[i-1]:
            for j in range(len(unord_list)):
                if j == 0:
                    if unord_list[i] != unord_list[0]:
                        unord_list.insert(0, unord_list[i])
                        del unord_list[i+1]
                elif unord_list[i] != unord_list[j] and unord_list[i] != unord_list[j+1]:
                    unord_list.insert(j+1, unord_list[i])
                    del unord_list[i+1]
        else:
            break

    return unord_list

It seems to work in cases where it's possible to make such a list, but I'm pretty sure there is a more efficient way and the code can be optimized.


texts: Speed up counting sort algorithm in Ruby

texts:
I'm attempting this simple HackerRank counting sort problem but testcase #3, which has 100,000 test cases, is timing out.

Is there something particularly inefficient about this code?

input = []
$stdin.each do |line|
  input << line
end
input.shift

arr = input.map { |line| line.split(' ')[0].to_i }

answer = (0..99).map do |i|
  counter = 0
  arr.uniq.each do |j|
    counter += arr.count(j) if j <= i
  end
  counter
end

puts answer.join ' '


texts:
I have an API endpoint to modify a race car, which supports the PUT method:

PUT /api/racecars/{racecarId}

Since PUT must be idempotent it works as a full replacement of an entity:

[Route("api/racecars/{racecarId}")]
public class RacecarsController : Controller
{
    private readonly IRaceCarsAppService racecarsAppService;

    public RacecarsController (IRaceCarsAppService racecarsAppService)
    {
        this.racecarsAppService = racecarsAppService;
    }

    [HttpPut]
    public IActionResult Put(int racecarId, [FromBody] Racecar model)
    {
        if (model == null)
        {
            return BadRequest("Racecar model is not specified");
        }

        try
        {
            racecarsAppService.Update(racecarId, model.NextServiceDate, model.CrashesCount);

            return Ok();
        }
        catch (DomainRuleViolationException e)
        {
            return Forbidden(e.Message);
        }
    }

    protected IActionResult Forbidden(string errorMessage)
    {
        return StatusCode((int)HttpStatusCode.Forbidden, errorMessage);
    }
}

public class DomainRuleViolationException : Exception
{
    public DomainRuleViolationException(string message) : base(message)
    {
    }
}

public class Racecar
{
    public int RacecarId { get; set; }
    public int CrashesCount { get; set; }
    public DateTime NextServiceDate { get; set; }
}

public interface IRaceCarsAppService
{
    void Update(int racecarId, DateTime nextServiceDate, int crashesCount);
}

However, our customers fairly asked to introduce partial updates for the racecar entity. Here is what I've come up with so far. First we need to introduce the Patch model with nulls:

public class RacecarPatch
{
    public int RacecarId { get; set; }
    public int? CrashesCount { get; set; }
    public DateTime? NextServiceDate { get; set; }
}

And the Patch method of the controller:

    [HttpPatch]
    public IActionResult Patch(int racecarId, [FromBody] RacecarPatch model)
    {
        if (model == null)
        {
            return BadRequest("Racecar model is not specified");
        }

        try
        {
            if (model.CrashesCount.HasValue)
            {
                racecarsAppService.UpdateCrashesCount(racecarId, model.CrashesCount.Value);
            }

            if (model.NextServiceDate.HasValue)
            {
                racecarsAppService.UpdateNextServiceDate(racecarId, model.UpdateNextServiceDate.Value);
            }

            return Ok();
        }
        catch (DomainRuleViolationException e)
        {
            return Forbidden(e.Message);
        }
    }

public interface IRaceCarsAppService
{
    void Update(int racecarId, DateTime nextServiceDate, int crashesCount);

    void UpdateCrashesCount(int racecarId, int crashesCount);

    void UpdateNextServiceDate(int racecarId, DateTime nextServiceDate);
}

I know this is a pretty straightforward approach, so I'd be glad to know if there are any alternative options.


texts: Printing right triangles recursively in Haskell

texts:
I've implemented a simple program to print out 4 right triangles oriented in different ways to learn Haskell. I'm sure there are more efficient ways of doing what I have done, and I just want some feedback.

All feedback related to the efficiency or quality of my code is welcome.

The four different triangle orientations are listed below

A Top Left Triangle of size 4 would look like:

****
***
**
*

A Bottom Left Triangle of size 4 would look like:

*
**
***
****

A Top Right Triangle of size 4 would look like:

****
 ***
  **
   *

A Bottom Right Triangle of size 4 would look like:

   *
  **
 ***
****

Here is my implemented solution to the problem:

module Main (main) where

import Prelude

-- MARK: Pure section --

makeTopLeftTriangle :: Char -> Int -> [String]
makeTopLeftTriangle c n
    | n < 1     = []
    | otherwise = makeTriangleRow c n : makeTopLeftTriangle c (n-1)
  where
    makeTriangleRow :: Char -> Int -> String
    makeTriangleRow c n
        | n < 1     = []
        | otherwise = c : makeTriangleRow c (n-1)

makeBottomLeftTriangle :: Char -> Int -> [String]
makeBottomLeftTriangle c n = makeBottomLeftTriangleHelper c 1 n
  where
      makeBottomLeftTriangleHelper :: Char -> Int -> Int -> [String]
      makeBottomLeftTriangleHelper c x n
          | x > n     = []
          | otherwise = makeTriangleRow c x : makeBottomLeftTriangleHelper c (x+1) n
        where
            makeTriangleRow :: Char -> Int -> String
            makeTriangleRow c x
                | x <= 0    = []
                | otherwise = c : makeTriangleRow c (x-1)

makeTopRightTriangle :: Char -> Int -> [String]
makeTopRightTriangle c n = [(replicate n c)]
                           ++ zipWith (++) (makeBottomLeftTriangle ' ' (n-1))
                                           (makeTopLeftTriangle c (n-1))

makeBottomRightTriangle :: Char -> Int -> [String]
makeBottomRightTriangle c n = zipWith (++) (makeTopLeftTriangle ' ' (n-1))
                                           (makeBottomLeftTriangle c (n-1))
                              ++ [(replicate n c)]

makeTriangle :: Char -> Int -> Int -> [String]
makeTriangle c triangleType = case triangleType of
    1 -> makeTopLeftTriangle c
    2 -> makeBottomLeftTriangle c
    3 -> makeTopRightTriangle c
    4 -> makeBottomRightTriangle c

-- MARK: Non-pure section --

printTriangle :: [String] -> IO ()
printTriangle []     = return ()
printTriangle (x:xs) = do
    putStrLn x
    printTriangle xs

getTriangleType :: IO String
getTriangleType = do
    putStrLn "What type of triangle do you want to print? (1, 2, 3, or 4)"
    putStrLn "1) Top Left"
    putStrLn "2) Bottom Left"
    putStrLn "3) Top Right"
    putStrLn "4) Bottom Right"
    getLine

main :: IO ()
main = do
    i_triangleType <- getTriangleType
    i_n <- getLine

    let triangleType = read i_triangleType :: Int
    let n = read i_n :: Int

    printTriangle $ makeTriangle '*' triangleType n


texts: Functional way to have two toggles that turn each other off

texts:
I have two sets of toggles that need to "uncheck" each other. This is my current solution which is working.  Can it somehow get more functional/elegant?

let unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar];
let availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar];

flipToggles(firstToggles, secondToggles)
flipToggles(secondToggles, firstToggles)

function flipToggles(firstToggles, secondToggles) {
    firstToggles.forEach(function (toggle) {
        on(toggle, "change", function () {
            secondToggles.forEach(function(element) {
                element.checked = false
            })
        })
    })
}


texts: Evaluate whether string is in alphabetical order or reverse alphabetical order

texts:
Purpose

This problem comes from this question on the dailyprogrammer subreddit.

Basically, the task is to write an implementation that identifies if the characters in a String are in

Alphabetical order (A to Z)
Reverse Alphabetical order (Z to A)
Neither Alphabetical nor Reverse Alphabetical order ("abba")
Both Alphabetical and Reverse Alphabetical order (only one distinct character in String)

Implementation

public class StringCharactersInAlphabeticalOrderEvaluatorImpl implements StringCharactersInAlphabeticalOrderEvaluator {
  private final List<Character> charactersFromAtoZ;

  public StringCharactersInAlphabeticalOrderEvaluatorImpl(final List<Character> charactersFromAtoZ) {
    this.charactersFromAtoZ = charactersFromAtoZ;
  }

  @Override public AlphabeticalOrderState evaluateAlphabeticalOrderOfCharacters(final String candidate) {
    final char[] stringChars = candidate.toUpperCase().toCharArray();
    int index = 0;
    boolean fromAtoZ = true;
    boolean fromZtoA = true;
    while (index < stringChars.length - 1) {
      if (charactersFromAtoZ.indexOf(stringChars[index]) > charactersFromAtoZ.indexOf(stringChars[index + 1])) {
        fromAtoZ = false;
      }

      if (charactersFromAtoZ.indexOf(stringChars[index]) < charactersFromAtoZ.indexOf(stringChars[index + 1])) {
        fromZtoA = false;
      }

      index++;
    }

    if (!fromAtoZ && !fromZtoA) {
      return AlphabeticalOrderState.IN_NEITHER_ALPHABETICAL_NOR_REVERSE_ALPHABETICAL_ORDER;
    }

    if (fromAtoZ && fromZtoA) {
      return AlphabeticalOrderState.IN_BOTH_ALPHABETICAL_AND_REVERSE_ALPHABETICAL_ORDER;
    }

    if (fromAtoZ) {
      return AlphabeticalOrderState.IN_ALPHABETICAL_ORDER;
    }

    if (fromZtoA) {
      return AlphabeticalOrderState.IN_REVERSE_ALPHABETICAL_ORDER;
    }

    throw new RuntimeException("unexpected character string");

  }
}

Feedback

I'd like feedback on my implementation, specifically

Am I missing any corner cases? Am I over-specifying my cases (for example, the BothAlphabeticalAndReverseAlphabetical case)?
Is this the most efficient way of implementing a solution? Is there a better implementation technique (particularly when it comes to my if statements, which I'm not in love with).


texts:
I have a class LoanAccount that contains an attributes creationDate and  loanAmount.

  I want to implement a Comparator that sorts the accounts by loan amount in descending order.
  When the loan amounts are the same, sorts the accounts
  ascending by date.

The code look like this:

Class

public class LoanAccount {
    private String id;
    private Date creationDate;
    private BigDecimal loanAmount;
}

Comparator

public class LoanAccountAmountComparator implements Comparator<LoanAccount> {

    @Override
    public int compare(LoanAccount o1, LoanAccount o2) {
        if (o1 == null) {
            if (o2 == null) {
                return 0;
            }
            return -1;
        }
        if (o2 == null) {
            return 1;
        }
        if (o1.getLoanAmount() == null) {
            if (o2.getLoanAmount() == null) {
                return 0;
            }
            return -1;
        }
        if (o2.getLoanAmount() == null) {
            return 1;
        }

        int comparedLoanAmount = o2.getLoanAmount().compareTo(o1.getLoanAmount());
        if (comparedLoanAmount == 0) {
            if (o1.getCreationDate() == null) {
                if (o2.getCreationDate() == null) {
                    return 0;
                }
                return -1;
            }
            if (o2.getCreationDate() == null) {
                return 1;
            }
            return o1.getCreationDate().compareTo(o2.getCreationDate());
        } else {
            return comparedLoanAmount;
        }
    }
}

Objects o1, o2 can be null. Fields creationDate and loanAmount can be null.

I want to ask you if there are better ways to handle null pointer exception in compareTo method.

For me it looks like there are too many if conditions


texts:
One thing lead to another and eventually I wanted to know the "proper" way of writing the permutation generating function in C#. Below is my code for generating permutations. This will go into an internal library, so the calling context is really generic. Expected calling is in a single-threaded context

/// <summary>
/// Generate all possible permutations of all elements in the list taken r at a time
/// Permutations: Choose 'r' letters from 'n' possible letters to form a word (sequence is important).
/// Formula for counting: nPr = n! / (n - r)!
/// </summary>
/// <param name="list">The list whose permutations are needed</param>
/// <param name="startPos">The position of first element of interest in the list</param>
/// <param name="r">Number of items required in the permuted list</param>
/// <returns>An enumeration containing a permutation of the original list</returns>
public static IEnumerable<IList<T>> GetPermutations<T>(this IList<T> list, int r, int startPos = 0) {
    for (int i = startPos; i < list.Count; ++i) {
        if (r > 1) {
            list.Swap(startPos, i);
            foreach (var permute in GetPermutations(list, r - 1, startPos + 1))
                yield return new List<T>().AddRange(list[startPos].AsEnumerable(), permute);
            list.Swap(startPos, i);
        } else
            yield return new List<T>() { list[i] };
    }
}

The Utils class has the extensions used in the GetPermutations function

public static class Utils {
    public static bool Swap<T>(this IList<T> list, int i1, int i2) {
        if (i1 == i2)
            return false;
        var tmp = list[i1];
        list[i1] = list[i2];
        list[i2] = tmp;
        return true;
    }

    public static IEnumerable<T> AsEnumerable<T>(this T item) {
        yield return item;
    }

    public static List<T> AddRange<T>(this List<T> list, params IEnumerable<T>[] collections) {
        foreach (var collection in collections)
            list.AddRange(collection);
        return list;
    }

}

The code will be invoked as below

var items = new [] { 'a', 'b', 'c', 'd'};
foreach (var permutation in items.GetPermutations(3))
    Console.WriteLine(string.Join(", ", permutation));

Couple of things on which I would like to get feedback are:

yield return in a recursive function.
Generation of new Lists to be yield returned, given that we will have a really large number of permutations with small increase in the input set


texts: Finding first recurring letter in each string of a given set

texts:
First input is the number of strings ex: 5
Second input is a set of strings ex: hello world how are you

Output the letter in the string ex: 'l' in string 1

Below is my code:

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

void find_first_recurring_letter(char **str,int r,int c);

int main()
{
    int r,i;
    printf("Enter the number of strings to be entered");
    scanf("%d",&r);
    /*dynamic allocation for str*/
    char **str=(char**)malloc(r*sizeof(char*));
    for(i=0;i<r;i++)
        str[i]=(char*)malloc(50*sizeof(char));
    for(i=0;i<r;i++)
    {
        printf("Enter the string %d",i+1);
        gets(str[i]);
    }
    for(i=0;i<r;i++)
        printf("%s\n",str[i]);
    find_first_recurring_letter(str,r,50);
    for(i=0;i<r;i++)
       free(str[i]);
    return 0;
}

void find_first_recurring_letter(char **str,int r,int c)
{
    char *ptr,*sptr,ch[r];
    int indx[r];
    int i;
    for(i=0;i<r;i++)
    {
        indx[i]=0;
        ch[i]='\0';
        for(ptr=&str[i][0];*ptr!='\0';ptr++)
        {
            for(sptr=&ptr[1];*sptr!='\0';sptr++)
            {
                if(*ptr==*sptr)
                    ch[i]= *ptr;
                    indx[i]=1;
            }
        }
    }
    for(i=0;i<r;i++)
    {
        if(ch[i]!='\0')
            printf("'%c' in string %d\n",ch[i],indx[i]+1);
    }

}