texts:
Please suggest how I can improve my code (like memory leakage, which pattern to use etc.). I have to parse a book XML in two ways: first from an FTP file and second from the REST API. I implemented the methods in one class.

public void GetBooksFromApi(int bookId, int bookNumber = 0)
    {
        string ApiBookIDPrefix = ConfigurationManager.AppSettings["ApiBookIDPrefix"].ToString();
        string key = ConfigurationManager.AppSettings["BookApiKey"].ToString();
        string apiBookIdValue = $"{ApiBookIDPrefix}{bookId}";
        string restApiBookUrl = $"{ApiDownloadUrl}?BookID={apiBookIdValue}&key={key}&bookNumber={bookNumber}&limit=1";
        string bookName = String.Empty;
        string clientFolderPath = String.Empty;
        string bookContent = String.Empty;

        try
        {//here to get response, parse xml and creating files process
            using (Stream xmlResponseStream = GetRestApiResponse(restApiBookUrl))
            {
                IEnumerable<XElement> xmlRecords = ParseBookXml(xmlResponseStream);
                if (xmlRecords == null)
                    throw new NullReferenceException($"No Book found to parse from rest api xml");

                foreach (var xmlRecord in xmlRecords)
                {
                    if (xmlRecord.Element("BookError") == null)
                    {
                        bookName = GetBookName(xmlRecord, bookId);
                        clientFolderPath = $@"{BaseFolder}\{bookId}";
                        bookContent = xmlRecord.ToString();

                        if (!string.IsNullOrEmpty(bookContent))
                            CreateFile(clientFolderPath, bookName, bookContent);

                    }

                }

            }

        }
        catch (Exception ex)
        {
            log.Error($"Unable to retrieve Book for {bookId.ToString()} with URL", ex);
            throw ex;
        }

    }

    public IEnumerable<XElement> ParseBookXml(Stream response)
    {
        IEnumerable<XElement> bookRecords = null;
        try
        {

            XDocument bookDoc = new XDocument();
            bookDoc = XDocument.Load(response);
            bookRecords = bookDoc.Root.Elements("bookReport").ToList();

            return bookRecords;
        }
        catch (Exception ex)
        {
            log.Error($"Unable to load  XML response from Rest Api Url .", ex);
            return bookRecords;

        }

    }

     public string GetBookName(XElement bookXmlRecord, int bookId)
    {
        string bookName = string.Empty;
        string bookNumberString = String.Empty;

        string bookNumberVal = bookXmlRecord.Element("bookNumber")?.Value;
        DateTime bookDateVal = now(); // today date
        bool validBookDate = DateTime.TryParse(bookXmlRecord.Element("BookDate")?.Value, out bookDateVal);

        if (!validBookDate)
            throw new InvalidCastException($"Unable to parse Book Date from rest api xml");

        bookNumberString = GetBookNumberString(int.Parse(bookNumberVal));

        bookName = $"Book-{bookId.ToString().PadLeft(4, '0')}-{reportDate:yyyyMMdd}{bookNumberString}.xml";

        return bookName;

    }

    public bool CreateFile(string clientFolder, string fileName, string xmlResponse)
    {
        try
        {
            string filePath = $@"{clientFolder}\{fileName}";
            if (!Directory.Exists(clientFolder))
                Directory.CreateDirectory(clientFolder);

            File.WriteAllText(filePath, xmlResponse);
            return true;
        }
        catch (Exception ex)
        {
            log.Error($"Unable to create book in path {clientFolder}.", ex);
            return false;

        }

    }


texts: Wrapper for dynamically-allocated memory block

texts:
I have built a single header-only memory class (just a C++ wrapper around a dynamically-allocated pointer and a size) that supports copy and move semantics (I hope I implemented them correctly) for a game I'm building. Its use case is to wrap the raw contents of assets imported (from any source) before processing them. So there is:

#include <cstdint>
#include <algorithm>

class Memory
{
    uint8_t *ptr;
    size_t size;

public:
    inline Memory() : ptr(nullptr), size(0) {}
    inline Memory(size_t size) : ptr(new uint8_t[size]), size(size) {}
    inline Memory(const Memory &other) : Memory(other.size)
    {
        std::copy(other.ptr, other.ptr+size, ptr);
    }
    inline Memory(Memory &&other) : Memory() { swap(*this, other); }

    inline Memory& operator=(Memory other)
    {
        swap(*this, other);
        return *this;
    }

    inline ~Memory() { delete[] ptr; }

    inline const void* get_ptr() const { return ptr; }
    inline void* get_ptr() { return ptr; }
    inline size_t get_size() const { return size; }

    friend inline void swap(Memory &m1, Memory &m2)
    {
        using std::swap;
        swap(m1.ptr, m2.ptr);
        swap(m1.size, m2.size);
    }
};

Is there something I forgot to add? Are there any errors? Can it be improved in any way?


texts: Java client that consumes a RESTful web service created using Jersey 2

texts:
I'm learning web services using Java. I just don't know which method has what advantage over another, like which one is more secure? Which one will be more faster?

POST resource is as follows:

@POST
@Path("postactivity")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String createActivity(
        @QueryParam("id") int id,
        @QueryParam("description") String description,
        @QueryParam("duration") int duration,
        @QueryParam("name")String name)
{
    //My code that creates Activity object from QueryParams is here.
}

Now I've created a client which is a Java application. I'm consuming the REST service in the following two ways:

Method 1 - using HTTPURLConnection

private static void doPost(){
    QueryString qs = new QueryString("id", "123"); //QueryString is a class created to build query, not important to the question.
    qs.add("duration", "12");
    qs.add("description", "This is description");
    qs.add("name", "This is Name");
    String url = "http://localhost:8080/webservices/webapi/activities/activity?" + qs;

    URL obj;
    try {
        obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestProperty("Content-Type","application/json");
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla 5.0");
        con.setDoOutput(true);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        Activity activity = GSON.fromJson(response.toString(), Activity.class); //This is for checking if i'm getting correct data back which I'm sending.

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
 }

Method 2 - using WebTarget available via Jersey

private static void doPost(){
Response entity = webTarget
        .path("activities/postactivity")
        .queryParam("id",2204)
        .queryParam("description","Foo")
        .queryParam("duration",100)
        .queryParam("name", "Bar")
        .request()
        .post(null);
String entityRead = entity.readEntity(String.class);

System.out.println(entityRead);
Activity activityRead = GSON.fromJson(entityRead, Activity.class);
}


texts: Send multiple REST requests at the same time. (node)

texts:
Below is a (very) simplified version of a function I made that creates multiple REST requests to gather needed information.
Things to note:

One of the REST calls is dependent upon the output of another.
I want to send off multiple requests at the same time when possible
If any rest responses inform us that the user is logged out, null should be returned.

async function gatherUserInfo(userId) {
  try {
    // Don't await yet, so this request can be sent at the same time as future requests.
    const groupsRequest = getGroups(userId)

    const {username, name} = await getProfile(userId)
    return {
      username,
      name,
      statusText: await getStatusText(username),
      groups: await groupsRequest,
    }
  } catch (err) {
    if (err instanceof NotLoggedInError) {
      return null
    }
    throw err
  }
}

I found the above code to be a very elegant solution to the problem. However, I recently realized that it won't actually work in node, because node will give warning or stop execution (depending on version) if an uncaught error happens in a promise. In the example above, the getGroups() call would send off a request (but not await it). Then, this function execution will pause on getProfile(). In the meantime, getGroups() will come back with the NotLoggedInError, which will result in the process being terminated, because that promise has not been awaited yet, (the try-catch can't catch the error until the await happens, which does happen later in the function execution).
So, I reluctantly trashed my old design and coded this up instead:
async function gatherUserInfo(userId) {
  const requests = [];

  requests.push(
    getGroups(userId)
    .then(groups => ({groups}))
  )

  requests.push(
    getProfile(userId)
    .then(async ({username, name}) => {
      const statusText = await getStatusText(username)
      return {username, name, statusText}
    })
  )

  let responses
  try {
    responses = await Promise.all(requests)
  } catch (err) {
    if (err instanceof NotLoggedInError) {
      return null
    }
    throw err
  }

  return Object.assign({}, ...responses)
}

This is much harder to follow or understand, but it's the best I could come up with. How can this code be improved?
Here's some stub methods and test cases that can be paired with the examples above to execute them:
// Mocks //

async function getGroups(userid) {
  await wait(50)
  if (userid !== 12) throw new NotLoggedInError('User not logged in')
  return ['group A', 'group B'];
}

async function getProfile(userid) {
  await wait(30)
  if (userid !== 12) throw new NotLoggedInError('User not logged in')
  return { username: 'grinchMaster135', name: 'The Grinch' };
}

async function getStatusText(username) {
  await wait(30)
  return 'away'
}

class NotLoggedInError extends Error {}

const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

// TEST //

;(async function() {
  console.log('Grinch info:', await gatherUserInfo(12)) // Grinch info: { username: 'grinchMaster135', name: 'The Grinch', groups: [ 'group A', 'group B' ], statusText: 'away' }
  console.log('Non-logged in user info:', await gatherUserInfo(13)) // Non-logged in user info: null
})()
```


texts: Program to top-up phone with conditions in Python

texts:
I am fairly new to Python. I wrote a program to take the user inputs which are service, the top-up time, the top-up amount, and exit or stay on the program.
Please review my code. And, can my code be organized? I think it looks a bit messy, maybe it can be shorter?

First, I wrote everything under function, so I can restart the program later on.
Second, I want to take user input about the service that they want to top up by limiting the choice of service to only 3 which are Green, Blue, or Red. If none of it, display "Try Again!, Wrong Service" otherwise, "Welcome to Top-up Service".
Third, after passed service versification, the user can top up but limit to only 50,100,300,500,1000. Also, the user can only choose "How many times they want to top-up".
Forth, after top-up, the list of top-up and sum of top-up is presented.
Last, the user can choose to stay or exit the program. If stay, the program is restarted, if exit, the program is terminated.

Here is the code that I wrote
  def main():
# Letting user choose a service
    service = None
    while service not in {"Green", "Blue", "Red"}:
        service = input("Please enter Green, Blue or Red: ")
    # Now service is either Green, Blue or Red
        if service in {"Green", "Blue", "Red"}:
            print("Welcome to Top-up Service")
        else:
            print("Try Again!, Wrong Service")

# Doing Top up(s)
    top_list = []
    n=int(input("How many times do you want to top up? "))
    for i in range(1,n+1):
        top_up = None
        while top_up not in {50,100,300,500,1000}:
            top_up = int(input("Please enter 50,100,300,500 or 1000: "))
    # Now top_up is either 50,100,300,500 or 1000"
            if top_up in {50,100,300,500,1000}:
                top_list.append(top_up)
            else:
                print("Try Again!, Wrong Top-up")

# Show all top up(s) information & Sum all top up(s)
    print("Top up(s) information : ", top_list)
    print("Total top up(s): ", sum(top_list))

# Letting user choose to stay or exit
    restart = input("Do you want to start again?,Y or else ").upper()
    if restart == "Y":
        main()
    else:
        print("Thank you for using our service")
        exit()
main()

This is the example of output
Please enter Green, Blue or Red: o
Try Again!, Wrong Service
Please enter Green, Blue or Red: Blue
Welcome to Top-up Service
How many times do you want to top up? 2
Please enter 50,100,300,500 or 1000: 20
Try Again!, Wrong Top-up
Please enter 50,100,300,500 or 1000: 50
Please enter 50,100,300,500 or 1000: 500
Top up(s) information :  [50, 500]
Total top up(s):  550
Do you want to start again?,Y or else n
Thank you for using our service


texts:
For my web application I have to generate a sequence of following format:

<year><sometext><month><sequence>

For example:

2014TOYS11000001 -> for first sequence of month of November this year. If month has changed, we have to reset the sequence to 1.

The application is Spring-based, and I have used NoSQL (Mongodb) to persist the sequence. NoSQL because we already have Mongodb usage in the application and this sequence that is generated is not used to refer anything in the backend database(Oracle).

Here is my implementation: an API of String nextVal() backed by a HashMap maintained in Mongodb.

import my.dao.MongoDao;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public final class MySequence {
    private final String SEQUENCE_TEXT = "TOYS";
    private final String SEQUENCE_FORMAT = "%d%s%02d%010d";

    private static final String KEY_ID = "id";
    private static final String KEY_MONTH = "month";
    private static final String KEY_SEQNB = "seq_nb";

    private static Map<String, String> seqData;

    @Autowired
    private MongoDao mongoDao;

    public MySequence() {
    }

    public String nextVal() {
        synchronized(seqData){
            seqData = mongoDao.findById(HashMap.class, SEQUENCE_TEXT);

            if (seqData == null) {
                //create new hash map with starting values and persist.
                seqData = new HashMap<String, String>(3);
                initSequenceDataMap(seqData);
                //save new map with "id" map field as the id to use in DB
                mongoDao.addObject(seqData, KEY_ID);
            } else {
                int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
                int monthInDb = Integer.parseInt(seqData.get(KEY_MONTH));
                if (currentMonth != monthInDb) {
                    //reset sequence for the month
                    initSequenceForMonth(seqData, currentMonth);
                } else {
                    incrementSequenceNumber(seqData);
                }

                mongoDao.update(seqData);
            }
        }
        return mapToString(seqData);
    }

    private void incrementSequenceNumber(Map<String, String> seqData) {
        int seqNum = Integer.parseInt(seqData.get(KEY_SEQNB));
        seqNum++;
        seqData.put(KEY_SEQNB, seqNum + "");
    }

    private void initSequenceDataMap(Map<String, String> seqData) {

        seqData.put(KEY_ID, SEQUENCE_TEXT);
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        initSequenceForMonth(seqData, month);
    }

    private void initSequenceForMonth(Map<String, String> dataMap, int month) {
        dataMap.put(KEY_MONTH, month + "");
        dataMap.put(KEY_SEQNB, "1");
    }

    private String mapToString(Map<String, String> seqData) {
        return String.format(SEQUENCE_FORMAT, Calendar.getInstance().get(Calendar.YEAR),SEQUENCE_TEXT,
                Integer.valueOf(seqData.get(KEY_MONTH)),
                Integer.valueOf(seqData.get(KEY_SEQNB)));
    }

    public GenericMongoDao getGenericMongoDao() {
        return mongoDao;
    }

    public void setGenericMongoDao(MongoDao mongoDao) {
        this.mongoDao = mongoDao;
    }
}

Concerns:

Is this thread-safe even when two separate beans can be created?
Is there a way to achieve less ceremonious call such as
`MySequence.nextVal() using spring?
Any other improvements?


texts: Optimization of a Qt QByteArray conversion

texts:
I wrote a function to convert a hexadecimal string representation (like 0x00) of some binary data to the data itself.

How can I improve this code?

QByteArray restoreData(const QByteArray &data, const QString prepender = "x")
{
    QByteArray restoredData = data;

    return QByteArray::fromHex(restoredData.replace(prepender, ""));
}


texts: Conditional parsing, non-standard approach

texts:
Conditional parsing (aka read some tokens and return true or false).

As a solution to this SO question, I wrote following code:

bool nectar_loader::resolve_conditional( const std::function<bool(const string&)> &config_contains )
{
    bool result = true;
    // My very own recursive implementation
    /*
      - each set of parenthesis is handled recursively
      - logical AND: +
      - logical OR:  |
      - logical NOT: !
      - two bools: "result" and "current"
      - "result" keeps global result, and is modified by "+"
      - "current" keeps results for "|" and "!"
      - syntax checking for invalid
    */
    bool previous_was_operator = true;
    bool current = false; // keep track of current state
    string token;
    while( next_token(token) )
    {
        conditional_operator op;
        if( map_value(conditional_operator_map, token, op) )
        {
            if( previous_was_operator )
            {
                if( op == conditional_operator::not_op )
                    current ^= current; // negate next
                else
                {
                    syntax_error( "Conditional operators \'+\', \'|\', \')\', and \'(\' must be followed by a CONFIG string." );
                    break;
                }
            }
            else
            {
                switch(op)
                {
                    case conditional_operator::right_parenthesis:
                        // TODO: allow conditionals without outer parenthesis of the form (a+b)|(c)
                        return result;
                    case conditional_operator::left_parenthesis: // recurse
                        return resolve_conditional( config_contains );
                    case conditional_operator::plus_op:
                        result = result && current; // "current" -> "result"
                        if( !result ) // negative when an element of a "+" expression
                        current = false; // reset "current"
                        break;
                    case conditional_operator::or_op: // combine with "current"

                    case conditional_operator::not_op: // unreachable
                        throw runtime_error( "Internal logic error in nectar_loader::resolve_conditional" );
                }
            }
            previous_was_operator = true;
        }
        else if( !previous_was_operator )
        {
            syntax_error( "In a conditional all CONFIG strings must be seperated by a conditional operator \'+\', \'|\', \')\', or \'(\'." );
            break;
        }
        else // previous was operator, so now we have a CONFIG string
        {
            // check CONFIG string, and perform a logical OR
            // TODO: check effect of "!"
            current = current || config_contains(token);
        }
    }
    return result;
}

next_token() reads the next token, and returns false if this fails. syntax_error sets a global error status with message which is checked after calling this function. map_value returns true if the token can be converted to an enum class value (so if it is a conditional operator as defined by me). This algorithm is more flexible than a shunting yard (due to my future plans).

I have not tested this extremely well, but what do you think?


texts:
I just finished working through Exercise 16 of Learn Python The Hard Way.
To further study, I wanted to create a script that will read and display a file's contents on screen, and then have the user re-write the file with three lines.

Can my code be written in a much cleaner, pythonic way?

from sys import argv

script, filename = argv

print "The name of the script is: %r" % script

# open txt file and display on screen
text1 = open(filename, 'r')
print text1.read()
text1.close()

# ask user to overwrite the file
print "To overwrite this file, hit <enter>."
print "Otherwise, CTRL-C to escape."
raw_input('> ')

# open the txt file again; overwrite it with different data
# have user input new data for each line
text2 = open(filename, 'w')
print "Write three lines to the file."
line1 = raw_input('line 1: ')
line2 = raw_input('line 2: ')
line3 = raw_input('line 3: ')

text2.write('\n'.join([line1, line2, line3, '']))
text2.close()

# read and display reconstructed file
text3 = open(filename, 'r')
print text3.read()
text3.close()


texts:
I decided to learn a Lisp-ish language and I am  discovering a very weird and new syntax. The obligatory first program, that also uses all the fundamentals, is the number guessing game.

Did I define too few or too many constants?
Is my code properly spaced and indented?
Is there a cleaner way to exit the loop than error?
Is it too imperative? Is it even possible to write the number guessing game functionally?
Is it OK to define null and set!?

#lang racket

(define NUM 12)
(define TRIES 6)
(define CORRECT "Correct! Well guessed!")
(define TOO_LOW "... Too Low ...")
(define TOO_HIGH "... Too high ...")

(define (num_message player_num)
  (if (= player_num NUM)
      CORRECT
       (if (> player_num NUM)
          TOO_HIGH
          TOO_LOW
      )
    )
  )

(define (number-guessing-game)
  (define out null)
  (for ([i (range TRIES)])
    (set! out (num_message (read)))
    (print out)
    (when (equal? out CORRECT)
        (print "You won")
        (error "Exiting")
    )
  )
  (print "Too many attempts")
)

(number-guessing-game)


texts:
I have code that reduces an array until all remaining elements are the same. It takes a first line which contains an integer n, the number of elements in the array, and a second line which contains space-separated integers, the proper array. For instance with the sample input:
5
3 3 2 1 3

It should return 2, as we only need to remove 2 and 1.
As it looked like an oriented graph I implemented Astar:
#!/bin/python3

import math
import os
import random
import re
import sys

class Node:
    def __init__(self, arr):
        self.value = len(set(arr))
        self.arr = arr
        self.parent = None
        self.H = 0
        self.G = 0

def children(arr):
    s = list(set(arr))
    children = []
    for deleted_element in s:
        arr_copy = list(arr)
        arr_copy.remove(deleted_element)
        child = Node(arr_copy)
        children.append(child)
    return children
    # return [Node([x for x in arr if x!= deleted_element]) for deleted_element in s] # issue

def astar(start, goal):
    # the open and closed sets
    openset = []
    closedset = []
    # current point is the starting point
    current = start
    #add the starting point to the openset
    openset.append(current)
    # while the openset is not empty
    while openset:
        current = min(openset, key=lambda o:o.G + o.H)
        # if it is the item we want retrace the path and return it
        if len(set(current.arr)) == goal:
            print("inside, current.arr: " + str(current.arr))
            path = []
            while current.parent:
                print("path in while: " + str([x.arr for x in path]))
                path.append(current)
                current = current.parent
            print("path: " + str([x.arr for x in path]))
            path.append(current)
            print("path: " + str([x.arr for x in path]))
            return path[::-1]
        # remove the item from the openset
        openset.remove(current)
        # add it to the closed set
        closedset.append(current)
        # loop through the node's children and siblings
        print("current.arr: " + str(current.arr))
        for node in children(current.arr):
            #If it is already in the closed set, skip it
            if node in closedset:
                continue
            #Otherwise if it is already in the open set
            if node in openset:
                # check if we beat the G score
                new_g = current.G + 1
                if node.G > new_g:
                    # if so, update the node to have a new parrent
                    node.G = new_G
                    node.parent = current

            else:
                # if it isn't in the openset, calculate the G and H score for the node
                node.G = current.G
                node.H = len(set(current.arr))
                #Set the parent to our current item
                node.parent = current
                #add it to the set
                openset.append(node)
    # thow an error if path is not found
    raise ValueError('No Path Found')

def equalizeArray(arr):
    startNode = Node(arr)
    path = astar(startNode,1)
    path.pop(-1)
    print("path: " + str(path))
    return len(path)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    result = equalizeArray(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

It works but for some arrays it seems to take too much time. I am not able to find what is the threshold from which my algorithm lacks performance but it does for examples like:
78
24 29 70 43 12 27 29 24 41 12 41 43 24 70 24 100 41 43 43 100 29 70 100 43 41 27 70 70 59 41 24 24 29 43 24 27 70 24 27 70 24 70 27 24 43 27 100 41 12 70 43 70 62 12 59 29 62 41 100 43 43 59 59 70 12 27 43 43 27 27 27 24 43 43 62 43 70 29

So how can I improve its performance? I am eager to learn and improve my programming skills.


texts: Count numbers whose digits are only increasing or decreasing

texts:
The goal is described here: basically, it is to compute the number of numbers below \$10^n\$ such that its digits are either increasing or decreasing (like 112 or 211, but not like 121).

The original version:

-- f computes the number of numbers with increasing digits.
-- digits >= k and the number of digits is n

f :: (Num t1, Num t, Eq t1, Eq t, Enum t) => t -> t1 -> t
f k 0 = 1
f k 1 = 10 - k
f 9 n = 1
f k n = foldl (\sum i -> sum + f i (n-1)) 0 $ enumFromTo k 9

-- h computes the number of numbers with decreasing digits.
-- digits <= k and the number of digits is n

h :: (Num t1, Num t, Eq t1, Eq t, Enum t) => t -> t1 -> t
h k 0 = 1
h 0 n = 1
h k 1 = k + 1
h k n = foldl (\sum i -> sum + h i (n-1)) 0 $ enumFromTo 0 k

-- The main function is g

g :: (Num t1, Num t, Eq t1, Eq t, Enum t) => t1 -> t
g 0 = 1
g 1 = 10
g n = g (n-1) + foldl (\sum i -> sum + g1 i (n-1)) 0 (enumFromTo 1 9)

-- g1 computes the number of numbers with either increasing or decreasing digits.

g1 :: (Num t1, Num t, Eq t1, Eq t, Enum t) => t -> t1 -> t
g1 0 n = f 0 n -- only increasing
g1 9 n = h 9 n -- only decreasing
g1 k 0 = 1     -- necessary for recursion
g1 k n = g1 k (n-1) + s1 + s2
  where
  s1 = foldl (\sum i -> sum + f i (n-1)) 0 $ enumFromTo (k+1) 9
  s2 = foldl (\sum i -> sum + h i (n-1)) 0 $ enumFromTo 0 (k-1)

The problem is it is too slow, and basically g n needs two times of the time needed by g (n-1).

I think maybe I need to memorize the functions, but don't know how to achieve this. Perhaps a list of lists?

The version using a list of lists follows:

total n  = case n of
  0 -> 1
  _ -> foldl (\sum k -> (sum + incg k n + decg k n) - 1) 0 [1..9] + total (n - 1)

incg k n = incgs !! n !! k
decg k n = decgs !! n !! k

incgs :: [[Integer]]
incgs =  [] : take 10 (repeat 1) : rest
  where
  rest = map (reverse . scanl1 (+) . reverse) $ tail incgs

decgs :: [[Integer]]
decgs =  [] : take 10 (repeat 1) : rest
  where
  rest = map (scanl1 (+)) $ tail decgs


texts:
Is the below program written in the most efficient way possible? I am new to Java Script and am just trying to make something basic so I can practice as I learn more.

The way I wrote it the program does work (except it keeps wanting to run again after it's over?) but is there a better way I could have accomplished this?

var charName = prompt("Hello Lost Stranger, Tell us your name!");
alert("Welcome " + charName + " we have been waiting for someone who can challenge this dragon!");
alert("A rather small but still intimidating dragon appears; it does not look happy.");

var charHP = 3000;
var mobHP = 3000;
var userAttack = "What type of attack will you use?(Choices: Sword, Charge, Spell)";

var diceOne = Math.floor(Math.random() * 100) + 1;
var diceTwo = Math.floor(Math.random() * 100) + 1;
var diceThree = Math.floor(Math.random() * 100) + 1;

function report() {
    alert("You have " + charHP + " remaining and the dragon has " + mobHP + " remaining.");
}

function attack() {
    function report() {
        alert("You have " + charHP + " remaining and the dragon has " + mobHP + " remaining.");
    }
    var attackType = prompt(userAttack);
    function evaluateAttack() {
        if (attackType.toLowerCase() === "sword") {
            mobHP = mobHP - diceOne - diceTwo - diceThree;
            alert("You slash at the dragon three times drawing blood!");
        } else if (attackType.toLowerCase() === "charge") {
            mobHP = mobHP - (3 * diceOne);
            alert("You charge the dragon at full speed drawing blood!");
        } else if (attackType.toLowerCase() === "spell") {
            mobHP = mobHP - (4 * diceTwo);
            alert("You close your eyes and summon the fires of hell on the dragon");
        }
    }
    if (mobHP > 0) {
        report();
        evaluateAttack();
    } else {
        alert("The dragon is dead! You have won!");
    }
}

do {
    attack();
} while (mobHP > 0);


texts:
I've done this simple c++ assignment. The homework was "Design a Tree class that allows insertion of nodes and visit of the graph".

What do you think of the style/design I used? I chose to store in the STL container the pointers of sub trees.

Is it memory efficient?

Is it sufficiently readable?

Did I chose the right STL container?

Thanks a lot for any tips about problems or bad practices!

What do you think of the style/design I used? I chose to store in the STL container the pointers of sub trees.

Is it memory efficient?

Is it sufficiently readable?

Did I chose the right STL container?

Thanks a lot for any tips about problems or bad practices!

#include <set>
#include <deque>
#include <iostream>
  using namespace std;

template < typename T >
class Tree {

struct compare {
  bool operator()(const Tree * t1,
    const Tree * t2) const {
    return t1 -> GetContent() < t2 -> GetContent();
  }
};

typedef typename std::multiset < Tree * , typename Tree::compare > NodeSet;

private:
  NodeSet children;
T content;

public:

  Tree& AppendNode(const T& node) {
    Tree *t = new Tree(node);
    AttachTree(t);
    return *t;
  }
void Clear() {
  typename NodeSet::iterator it = children.begin();
  while (children.end() != it) {
    children.erase( *it);
    delete *it;
    it++;
  }

}
const T& GetContent() const {
  return content;
}
Tree(const T& root) {
  content = root;
}
void AttachTree(Tree* t) {
  children.insert(t);
}
void Visit(std::deque <T>& exp) const {
  exp.push_back(content);
  typename NodeSet::iterator it = children.begin();
  while (it != children.end()) {
    (*it) -> Visit(exp);
    it++;
  }
}
Tree() {}
Tree(Tree & c) {
  c.DeepCopyTo(this);
}
T & operator = (const Tree & b) {
  b.DeepCopyTo(this);
}
~Tree() {
  Clear();
}
void DeepCopyTo(Tree* dest) const {
  dest -> content = content;
  typename NodeSet::iterator it = children.begin();
  while (it != children.end()) {
    Tree* t = new Tree();
    (*it)->DeepCopyTo(t);
    dest->AttachTree(t);
    it++;
  }
}

 };

https://ideone.com/62Ggwu


texts:
var romanArray = [];
var toRoman = {

    analyze: function(number){
        romanArray = [];
        if (number >= 1000) {
            return this.thousands(number);
        }else if (number >= 100){
            return this.hundreds(number);
        }else if (number >= 10) {
            return this.tens(number);
        }else{
            return this.last_number(number);
        }
    },

    thousands: function(number){
        var remainder = number % 1000;
        var thousands = Math.floor(number / 1000);
        for(var e = 0; e < thousands; e++) {
            romanArray.push('M');
        }
        return this.hundreds(remainder);
    },

    hundreds: function(number){
        var remainder = number % 100;
        var hundreds = Math.floor(number / 100);
        if (hundreds === 4){
            romanArray.push('CD');
        }else if(hundreds === 9){
            romanArray.push('CM');
        }else if(hundreds >= 5 && hundreds < 9){
            romanArray.push('D');
            for(var i = 0; i < (hundreds % 5); i++) {
                romanArray.push('C');
            }
        }else if (hundreds > 0 && hundreds < 4){
            for(var e = 0; e < hundreds; e++) {
                romanArray.push('C');
            }
        }else{

        }
        return this.tens(remainder);
    },

    tens: function(number){
        var remainder = number % 10;
        var tens = Math.floor(number / 10);
        if (tens === 4){
            romanArray.push('XL');
        }else if(tens === 9){
            romanArray.push('XC');
        }else if(tens >= 5 && tens < 9){
            romanArray.push('L');
            for(var i = 0; i < (tens % 5); i++) {
                romanArray.push('X');
            }
        }else if (tens > 0 && tens < 4){
            for(var e = 0; e < tens; e++) {
                romanArray.push('X');
            }
        }else{

        }
        return this.last_number(remainder);
    },

    last_number: function (number){
        if (number === 4){
            romanArray.push('IV');
        }else if(number === 9){
            romanArray.push('IX');
        }else if(number >= 5 && number < 9){
            romanArray.push('V');
            var remainder = number % 5;
            for(var i = 0; i < remainder; i++) {
                romanArray.push('I');
            }
        }else if (number > 0 && number < 4){
            for(var e = 0; e < number; e++) {
                romanArray.push('I');
            }
        }else{

        }
        return romanArray.join('');
    }
};

console.log(toRoman.analyze(1000));
console.log(toRoman.analyze(2999));
console.log(toRoman.analyze(2555));

I'm wondering if this JavaScript can be refactored using some sort of base/template function.
For Example:

base_function: function (number, four, nine, five, one){
    if (number === 4){
        romanArray.push(four);
    }else if(number === 9){
        romanArray.push(nine);
    }else if(number >= 5 && number < 9){
        romanArray.push(five);
        var remainder = number % 5;
        for(var i = 0; i < remainder; i++) {
            romanArray.push(one);
        }
    }else if (number > 0 && number < 4){
        for(var e = 0; e < number; e++) {
            romanArray.push(one);
        }
    }else{

    }
    return romanArray;
},

How can I improve this code?


texts: Project Euler #10 (sum of primes less than two million) in Clojure

texts:
I'm new to Clojure and using some Project Euler problems to familiarize myself with the language's capabilities. Problem #10 asks to find the sum of all primes less than two million.

I wanted to solve this problem by building a generalized Sieve of Eratosthenes, then adding up all the primes:

(defn sieve [size]
  (-> (reduce (fn [prev i]
                (if (prev i)
                  (vec (reduce #(assoc %1 %2 false)
                               prev
                               (range (+ i i) size i)))
                  prev))
              (vec (repeat size true))
              (range 2 (-> size Math/sqrt int inc)))
      vec
      (assoc 0 false)
      (assoc 1 false)))

(time
 (let [limit 2000000
       s (sieve limit)]
   (reduce #(+ %1 (if (s %2) %2 0))
           0 (range limit))))

That works, but takes over 14 seconds when run from an already "hot" REPL. For comparison, I did a simple Java implementation:

import java.util.Arrays;
import java.lang.Math;

public class P10 {
  public static void main(String[] args) {
    int size = 2000000;

    boolean[] sieve = new boolean[size];

    Arrays.fill(sieve, true);
    sieve[0] = false;
    sieve[1] = false;

    for (int i = 2; i < (1 + Math.sqrt(size)); i++) {
      if (sieve[i]) {
        for (int j = i + i; j < size; j += i) {
          sieve[j] = false;
        }
      }
    }

    long sum = 0;
    for (int i = 0; i < size; i++) {
      if (sieve[i]) sum += (long) i;
    }

    System.out.println(sum);
  }
}

Which runs in about 0.7 seconds from the command line. (Incidentally, my Java experience isn't very deep either--does that include JVM startup?)

So I thought maybe the problem with the "pure" (?) Clojure version is the creation/reliance on Clojure's vectors. So my idea was to rework the Clojure version to use Java's mutable array:

(defn sieve [size]
  (-> (let [ar (to-array (repeat size true))]
        (dorun (map (fn [i]
                      (when (aget ar i)
                        (dorun (map (fn [j] (aset ar j false))
                                    (range (+ i i) size i)))))
                    (range 2 (-> size Math/sqrt int inc))))
        ar)
      vec
      (assoc 0 false)
      (assoc 1 false)))

But that takes more than 3.5 seconds.

At this point, I'm not so interested in implementing fancy things like bit-packing, I'm just trying to reach performance parity with the "traditional" Java implementation. What am i doing "wrong" in my Clojure that makes it "non-competitive" with the Java version?

Also, any other tips/hints/criticisms regarding Clojure style?


texts:
In an effort to complete this month's code challenge, I've started off with the basics. Below I have for review, a class that I can call to create the square/button a user would click to mark a spot on a Tic Tac Toe board. I haven't done any game logic, so I could very easily be forgetting something my buttons need to have.

Would this package stand up to any future additions?
How is my objected orientation here?
Is there anything I can do to compact it?
Am I following common practices?

package
{

    import flash.display.MovieClip;
    import flash.events.MouseEvent;

    public class SquareSpace extends MovieClip
    {

        public static const SQUARE_LENGTH:int = 30;
        public static const PLAYER_A_OWNED_SQUARE:int = 0;
        public static const PLAYER_B_OWNED_SQUARE:int = 1;
        public static const NEUTRAL_SQUARE:int = 2;
        public static const AVAILABLE_SQUARE:int = 3;
        public static const STATE_COLORS:Array = [0xFF3333,0x3333FF,0xDDDDDD,0x33FF33];

        private var _state:int = AVAILABLE_SQUARE;
        private var _square:MovieClip;

        public function SquareSpace(boxX:int, boxY:int)
        {
            _square = formSquare();
            _square.x = boxX;
            _square.y = boxY;
            _square.buttonMode = true;
        }

        public function addSquare():MovieClip
        {
            _square.addEventListener(MouseEvent.CLICK, sendClick);
            return _square;
        }

        private function sendClick(event:MouseEvent):void
        {
            dispatchEvent(new MouseEvent(MouseEvent.CLICK));
        }

        public function changeSquareState(sqrState:int):void
        {
            if (sqrState >= PLAYER_A_OWNED_SQUARE && sqrState <= AVAILABLE_SQUARE) {
                _state = sqrState;
                _square.graphics.beginFill(STATE_COLORS[sqrState]);
                _square.graphics.drawRect(0,0,SQUARE_LENGTH,SQUARE_LENGTH);
                _square.graphics.endFill();
            } else {
                throw new ArgumentError('State not acceptable.');
            }
        }

        public function getState():int
        {
            return _state;
        }

        private function formSquare():MovieClip
        {
            var mvclp:MovieClip = new MovieClip();
            mvclp.graphics.beginFill(STATE_COLORS[NEUTRAL_SQUARE]);
            mvclp.graphics.drawRect(0,0,SQUARE_LENGTH,SQUARE_LENGTH);
            mvclp.graphics.endFill();
            return mvclp;
        }
    }
}

Here is some calling code. I dispatch that click event (sendClick()) so my actual SquareSpace variable can handle clicks, rather than having the event listeners for the movieclip square outside of the class.

private function setUpBlankSubBoard (xOffset:int, yOffset:int, topBoard:int):void
        {
            for (var boxIndX:int = 1; boxIndX <= BOARD_LENGTH; boxIndX++) {
                for (var boxIndY:int = 1; boxIndY <= BOARD_LENGTH; boxIndY++) {
                    var newSqr:SquareSpace = new SquareSpace(
                     xOffset + (SquareSpace.SQUARE_LENGTH * 1.2) * boxIndX,
                     yOffset + (SquareSpace.SQUARE_LENGTH * 1.2) * boxIndY);
                    newSqr.addEventListener (MouseEvent.CLICK, squareChosen); // Called an unrelated function
                    addChild (newSqr.addSquare());
                }
            }
        }


texts: Count the number of ways an integer can be represented as a sum of consecutive positive integers

texts:
I am trying to count the number of ways an integer can be represented as sum of 2 or more consecutive positive integers.  My Code is working in under 1 second for small inputs (\$\le 10^7\$) but after that it's taking too long. How can I lower the time complexity of the solution?

import java.io.*;

//sum needs to contain atleast 2 elements
public class IntegerRepresentedAsSumOfConsecutivePositiveIntegers
{
    public static long count = 0;
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        long num = Long.parseLong(br.readLine()); //Enter a number( <=10^12)
        //driver(num);
        func(num);
        System.out.println("count = " + count);
    }

    public static void func(long num)
    {
        long temp,i,j;
        long limit = (num / 2);
        for(i = 1 ; i <= limit ; i++)
        {
            temp = num;
            j = i;
            while(j < temp)
            {
                temp = temp - j;
                j++;
            }
            if(j == temp)
            {
                count++;
            }
        }
    }

}


texts: Is this a correct Factory Method implementation?

texts:
I'm learning about design pattern and I tried to implement a Factory Method example, based on the GoF book.

Can I say that this is a correct implementation of it ? If not I will be glad to find out what are the pitfalls.

#include <iostream>
#include <vector>
using namespace std;

class Widget {
public:
    virtual void draw() = 0;
};

class Win7Widget : public Widget {
public:
    void draw() { cout << "Win 7 widget" << endl; }
};

class Win8Widget : public Widget {
public:
    void draw() { cout << "Win 8 widget" << endl; }
};

class Factory {
public:
    virtual Widget* Create() = 0;
    virtual ~Factory() {}
};

class Win7Factory: public Factory {
public:
    Widget* Create() { return new Win7Widget; }
};

class Win8Factory: public Factory {
public:
    Widget* Create() { return new Win8Widget; }
};

int main()
{
    unique_ptr<Factory> win7fact(new Win7Factory);
    unique_ptr<Factory> win8fact(new Win8Factory);

    vector<Widget*> widgets;
    widgets.push_back(win7fact->Create());
    widgets.push_back(win8fact->Create());

    for(const auto& f : widgets)
    {
        f->draw();
    }

    return 0;
}


texts: Given a sequence of words, print all anagrams together

texts:
Given an array of words, print all anagrams together. For example, if
  the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
  may be “cat tac act dog god”.

My idea is to sort individual words firstly. And then sort the array of words.
In this way, the anagrams will be together. The following is my code:

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

typedef struct word_with_ind
{
    char* word;
    int ind;
}*word_with_ind_ptr;

int comp_char(const void* x, const void* y)
{
    char* c1 = (char*)x;
    char* c2 = (char*)y;

    return *c1 - *c2;
}

int comp_str(const void* x, const void* y)
{
    const word_with_ind_ptr w1 = (word_with_ind_ptr)x;
    const word_with_ind_ptr w2 = (word_with_ind_ptr)y;

    return strcmp(w1->word, w2->word);
}

void destroy(word_with_ind_ptr x, int size)
{
    for(int i = 0; i < size; ++i)
    {
        free(x[i].word);
    }
    free(x);
}

void print_anagrams_together(char* word[], int size)
{
    //make a copy of the original word array. And sort
    //the individual words
    word_with_ind_ptr x = (word_with_ind_ptr)malloc(sizeof(struct word_with_ind)*size);
    for(int i = 0; i < size; ++i)
    {
        x[i].ind = i;
        x[i].word = (char*)malloc(sizeof(char)*(strlen(word[i])+1));
        strcpy(x[i].word, word[i]);
        qsort(x[i].word, strlen(x[i].word), sizeof(char), comp_char);
    }

    //sort the array of words
    qsort(x, size, sizeof(struct word_with_ind), comp_str);

    //print result
    for(int i = 0; i < size; ++i)
    {
        printf("%s\n", word[x[i].ind]);
    }

    //free memory
    destroy(x, size);

}

int main()
{
    char* word[] = {"cat", "dog", "tac", "god", "act"};
    int size = sizeof(word)/sizeof(word[0]);
    print_anagrams_together(word, size);

    getchar();
    return 0;
}


texts: Map operation to update data | Hazelcast IMap returns clone object

texts:
I have a nested hazelcast distributed map:

Map<CountryId, Map<CityCode, Map<data_key,data_value>>>

where "data_key" is "population", "literacy_rate" and "gender_ratio".
Below is the class where I have implemented a method which adds new city data to a specified country.

import java.util.HashMap;
import java.util.Map;
import net.sf.oval.constraint.Min;
import net.sf.oval.constraint.NotNull;
import net.sf.oval.guard.Guarded;
import com.hazelcast.core.IMap;

/**
 * Provides CacheOperation implementation for CountryRepository.
 *
 * @author Praveen.Puskar
 * Created: 12:27:37 PM, Apr 13, 2015
 */
@Guarded
public class CountryCacheOperation extends
        AbstractCacheOperation<Integer, Map<String, Map<String, Object>>> {

    /**
     * Instantiates a CountryCacheOperation.
     *
     * @param cache the cache
     */
    public CountryCacheOperation(
            @NotNull IMap<Integer, Map<String, Map<String, Object>>> cache) {
        super(cache);
    }

    /**
     * Add city to country.
     *
     * @param countryID id of the country to which city will be added.
     * @param cityCode cityCode to which data is required to be associated.
     * @param data a map containing city data :
     *

     *
litracy_rate

     *
population

     *
gender_ratio

     *

     */
    public void addCityToCountry(@Min(1) int countryID,@NotNull String cityCode,@NotNull Map<String, Object> data) {
        cache.lock(countryID);
        try {
            cache.putIfAbsent(countryID, new HashMap<>());
            Map<String, Map<String, Object>> map = cache.get(countryID);//cache.get(..) returns clone of data.
            map.put(cityCode, data);
            cache.put(countryID, map);
        }
        finally {
            cache.unlock(countryID);
        }
    }

}

Kindly review the logic to add new city to any country. Point to consider:

cache.get(KEY) returns clone of the object so it is required to put the updated data again to cache.


texts: Ensuring user input is an integer in a range

texts:
I have isolated a little bit of code that was causing a small debate between myself and another user.  I have taken some of the things that he said and meshed it with the code that was being reviewed in the first place here.

Original Code

while (!validInput)
{
    var playerChoice = -1;
    Console.WriteLine("Please choose your Gesture ");
    gameSetup(listOfGestures);
    try
    {
        playerChoice = Convert.ToInt32 (Console.ReadLine());
    }
    catch (FormatException e)
    {
        validInput = false;
    }

    if (playerChoice > 0 && playerChoice <= listOfGestures.Count)
    {
        playerGesture = listOfGestures[playerChoice - 1];
        validInput = true;
    }
    else
    {
        validInput = false;
    }
}

Here is what I came up with based on our conversation.

New Code

var validInput = false; //forgot this part
while (!validInput)
{
    var playerChoice = -1;
    Console.WriteLine("Please choose your Gesture ");
    gameSetup(listOfGestures);
    validInput = int.TryParse(Console.ReadLine(),out playerChoice);
    if (playerChoice > 0 && playerChoice <= listOfGestures.Count)
    {
        playerGesture = listOfGestures[playerChoice - 1];
        validInput = true;
    }
}

Do I need to create a new method to sort out user input and whether or not it is an integer inside the min and max bounds?


texts: Improving the code to turn a string into an array of numbers?

texts:
I have a string of numbers, like "31654918562314", and I want to convert it into an array of integers. The code I've written is:

string source = "31654918562314";
int[] numbers = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
    numbers[i] = Convert.ToInt32(source.Substring(i, 1));
}

What improvements can I apply on this code? Is it the best ultimate code I can get to?

Note: I'm using C#. However, I also should implement this code in JavaScript.


texts:
I have a worksheet that contains values, and I need to match one of the values to a lookup worksheet. This syntax works like it should, however, it takes roughly 10 minutes to fully execute. This could be due to the size of the worksheets: Sheet1 has roughly 18,000 rows and Sheet2 has roughly 20,000 rows.

Is there any optimization that can take place in this syntax?

Function TwoMatches()
Dim wSheet As Worksheet: Set wSheet = Sheets("Sheet2")
Dim lookupSheet As Worksheet: Set lookupSheet = Sheets("Sheet1")
Dim lr As Long: lr = wSheet.Cells(wSheet.Rows.Count, "A").End(xlUp).Row
Dim destSheet As Worksheet: Set destSheet = Sheets("Sheet2")
Set lookupRange = Sheets("Sheet1").Range("$A:$C")
Dim Found As Range

'Add a column at the beginning to Trim() and Remove Hyphens
Columns("A:A").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

'Add Clean Sheet1 Name As Header Text
ActiveWorkbook.Sheets("Sheet2").Range("A1").Value = "Clean Sheet1 Name"

'This is the worksheet formula that I want to use for the used range
With wSheet
    lr = .Cells(.Rows.Count, "D").End(xlUp).Row
    form = "=TRIM(SUBSTITUTE(D2,""-"", """"))"
    .Range("A2:A" & lr).Formula = form
End With

'Get the Last Column With Data
ActiveWorkbook.Sheets("Sheet2").Range("P1").Value = "LookupVal"

For i = Range("A" & Rows.Count).End(3).Row To 2 Step -1
    'Pulling value where column O is not null
    If Not IsEmpty(Cells(i, "O").Value) Then
    With Sheets("Sheet1")
        'Filter criteria one is where column B IS NOT NULL
        .Range("$A:$C").AutoFilter Field:=2, Criteria1:="<>"

        Set Found = .Range("A:A").Find(What:=wSheet.Cells(i, "A").Value, _
                               LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                               MatchCase:=False)

        If Not Found Is Nothing Then
            wSheet.Cells(i, "P").Value = Found.Offset(, 2).Value
        End If
    End With
    'Pulling value where column O is null
    Else
    With Sheets("Sheet1")
        'Filter criteria one is where column B IS NULL
        .Range("$A:$C").AutoFilter Field:=2, Criteria1:="="
        Set Found = .Range("A:A").Find(What:=wSheet.Cells(i, "A").Value, _
                               LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                               MatchCase:=False)

        If Not Found Is Nothing Then
            wSheet.Cells(i, "P").Value = Found.Offset(, 2).Value
        End If
    End With
    End If
Next i
'Removing the column added for the Clean Match
Range("A:A").Delete
End Function


texts: Eloquent methods to calculate the average rent of apartments

texts:
I am working on a Laravel 5.1 website where I am counting the average rent of apartments in a specific area. Besides of that I want to get the average rent by amount of rooms in the apartment. The functionality itself isn't anything that hard, but then I want to be able to get the average rent for apartments with e.g. two rooms by a variable.

How would you be able to do this in a cleaner way? I am going to have attributes for up to about 10 rooms, that would mean 20 new methods. Have to be a better way to do this?

public function average_rent($rooms, $timespan = '6 months', $fromDate = null)
{
    if ($fromDate === null) $fromDate = date('Y-m-d');

    $query = DB::select(
        "SELECT COUNT(id) as amt, SUM(rent) AS total_rent
          FROM " . env('DB_PREFIX', '') . "apartments
          WHERE
           rooms = " . $rooms . " AND rent > 0 AND
           formatted_address LIKE '% " . $this->query_params . ", Sverige%' AND
           created_at BETWEEN '" . date('Y-m-d', strtotime('-' . $timespan)) . "' AND '" . $fromDate . "'");

    $avgRent = null;
    $avgAmount = $query[0]->amt;
    if ($avgAmount >= 10) $avgRent = round($query[0]->total_rent / $avgAmount, 0) . ' kr';

    return [$avgRent, $avgAmount];
}

public function getOneRoomAvgRentAttribute()
{
    return $this->average_rent(1)[0];
}

public function getTwoRoomAvgRentAttribute()
{
    return $this->average_rent(2)[0];
}

public function getOneRoomAmtAttribute()
{
    return $this->average_rent(1)[1];
}

public function getTwoRoomAmtAttribute()
{
    return $this->average_rent(2)[1];
}


texts: Hex-string representation of a byte array

texts:
I have a legacy method toHex(byte[]) used in my application since the beginning of time to store a hexadecimal representation of a byte[] into the database. The byte[] buffer is a SHA256 checksum of a file, which is computed consistently.

Since this method is embodied as private method in a class, in order to compare the SHA256 of two files I could either copy the implementation to my other class or use a library-provided implementation. In fact I found org.apache.cxf.common.util.StringUtils.toHexString

This is CXF code:

/*     */   public static String toHexString(byte[] bytes) {
/* 215 */     StringBuilder hexString = new StringBuilder();
/* 216 */     for (int i = 0; i < bytes.length; ++i) {
/* 217 */       hexString.append(Integer.toHexString(0xFF & bytes[i]));
/*     */     }
/* 219 */     return hexString.toString();
/*     */   }

This is my code:

private static String toHex(byte[] checksumArray)
{
    StringBuilder result = new StringBuilder();
    for (byte checksumByte : checksumArray)
    {
        String hex = Integer.toString((checksumByte & 0xff) + 0x100, 16).substring(1);
        result.append(hex);
    }
    return result.toString();
}

I can see the two implementations are different, but I am not understanding in what they differ.

This is example data returned by the two implementations:

CXF : 99dd29352b873ccb7f17e43984c0c984288a397a308cd63b47537968eee991
Me  : 99dd29352b873ccb7f17e43984c00c9804288a397a308cd63b47537968eee991
Diff: 99dd29352b873ccb7f17e43984c0^c98^4288a397a308cd63b47537968eee991

As you can see "my" hex string is longer because of a couple of zeroes.
If I use the same implementation of toHexString to compare the SHA256 stored in database with the actual SHA256 of a file, I get consistent result. But if I try to use an authoritative implementation (assuming people at Apache Foundation write good code) I get a different result.

Is it a bug in my code? Unfortunately I don't know anything about that implementation, I just inherited the code.
Can someone explain me the algorithm behind my implementation compared with CXF's implementation?

In the meantime, can somebody recommend an "official" reference implementation of the conversion from byte[] to hex string?


texts:
I'm coding a small web app with no real functionality. It's like a pilot program for something bigger. What I want is construct a program that works as a clock on/off for a restaurant. Actually I'm just trying to simulate one. What I'v done is working but I would like to know whether there is any java class that I can use in a session to calculate the difference between the clock on and off.

Index.jsp

<%@page import="javax.media.jai.operator.EncodeDescriptor"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Project</title>

Employees

        <form action=<%= response.encodeURL("CheckUser") %> method="get">
            <input type="hidden" name="userId" value="1">
            <input type="submit" value="Diogo">

        </form>

CheckUser

public class CheckUser extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userId = request.getParameter("userId");
        User user1 = new User();
        user1.setUserId(userId);

        HttpSession session = request.getSession();
        session.setAttribute("userId", userId);

        Hours h1 = (Hours) session.getAttribute("hours");

        if (h1 == null){
        h1 = new Hours(user1);
        }

        Calendar cal = new GregorianCalendar();

        h1.setMinutes(cal.get(Calendar.MINUTE));

        request.setAttribute("hours", h1);
        String url = "/show.jsp";

        session.setAttribute("hours", h1);

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);

    }

show.jsp

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <%@ page import="Business.*, process.*" %>

        <%
            String userId = (String) session.getAttribute("userId");
            Hours h = (Hours) session.getAttribute("hours");
            String actualMinute = h.getMinutes();
            String calcMinute = h.getCalMinutes();
        %>

<%= userId %>

<%= h.getMinutes() %> minuto atual

        <%
        if(!actualMinute.equalsIgnoreCase(calcMinute) || calcMinute == "0")
           {
        %>

<%= h.getCalMinutes() %> minutes

        <%
        }else
           {
        %>

It is working

<%= h.getCalMinutes() %>

        <%
           }
        %>

        <form action="<%= response.encodeURL("index.jsp") %>" method="get">
            <input type="submit" value="return">
        </form>


texts: Determining if a string is a palindrome of a permutation

texts:
I wrote code to determine if a string is a palindrome of a permutation. This exercise was taken from Cracking the Coding Interview. I'm looking for any tips on improving it.

#include <iostream>
#include <string>

/*
*   Determine if a string is a palindrome of a permutation.
*   For simplicity, assume each string contains ONLY alphabetical characters.
*/

//strip string of non-alphabetical characters
std::string strip_junk(std::string s){
    std::string output("");
    for(char& c : s)
        if(isalpha(c)){
            c = tolower(c);
            output += c;
        }
    return output;
}

//determine how many times each character appears in the string
int *get_char_counts(std::string input){
    static const int ascii_sub = 97;
    static int counters[26]{0};
    for(char c : input){
        counters[c - ascii_sub]++; //if c='a', c-ascii_sub = 0. if c='z', c-ascii_sub = 25
    }
    return counters;
}

//check if more than one character appears an odd number of times
bool check_chars(std::string input){
    int *char_counter = get_char_counts(input);
    bool flag = false;
    for(int i = 0; i < 26; ++i){
        if(*(char_counter + i) % 2 != 0){ //if number is odd, check if it appeared twice
            if(flag)
                return false; //it appeared twice, return false
            flag = true;
        }
    }
    return true;
}

//check if string is a palindrome of a permutation
bool palindromePermutation(std::string input){
    input = strip_junk(input);
    return check_chars(input);
}

int main(void){
    std::string input;
    std::getline(std::cin, input);
    std::cout << (palindromePermutation(input) ? "True" : "False") << std::endl;
}


texts: Loading items into array from SQL Server

texts:
The program we are working at has the following function:

function loadItem(arrayValues,arrayNames) {
    var j=document.getElementById('itemSelect').options.length;
    for(var i=0;i<arrayValues.length;i++) {
        if(!existsElement(document.getElementById('itemSelect'),arrayValues[i])) {
            document.getElementById('itemSelect').options[j]=new Option(arrayValues[i]+" - "+arrayNames[i],arrayValues[i],null);
            j++;
        }
    }
}

This fills a list that is later used to filter a search.

It was originally designed for small arrays (up to 25 elements) and it worked perfectly.

Now, I'm trying to use it to fill with the whole contents of a SQL table (about 9500 elements), I take the data from the DB with Java, transfer it to Javascript via AJAX and parse that List into two arrays that can be used with this function. That takes about a second, but then this function takes about 20 seconds to complete.

Why is it that slow, and what can I do to improve it?


texts:
In this assignment, I'm supposed to split a string using strtok. (The assignment consists of the comment and the function definition; I fill in the function body.)

It works as far as I've tested. But it seems a little ugly to me. Perhaps it's my Java background, but somehow this just doesn't feel right. Specific concerns:

Is this easily readable to a more experienced C programmer?
Can this be made more idiomatic somewhere?
Is it feasible to split this into several functions? Where would you split it?
Any corner cases where it might break? Does it leak memory?

/* Parses a string into tokens (command line parameters) separated by space.
 * Builds a dynamically allocated array of strings. Pointer to the array is
 * stored in variable pointed by argv.
 *
 * Parameters:
 * argv: pointer to the variable that will store the string array
 * input: the string to be parsed (the original string can be modified, if needed)
 *
 * Returns:
 * number of space-separated tokens in the string */
int parse_cmdline(char ***argv, char *input)
{
    char *token;
    int len, num;

    len = 4;
    *argv = malloc(len * sizeof(char *));
    if (*argv == NULL) {
        return 0;
    }
    for (num = 0;; num++, input = NULL) {
        token = strtok(input, " ");
        if (token == NULL) {
            break;
        }
        if (num >= len) {
            char **temp;

            len *= 2;
            temp = realloc(*argv, len * sizeof(char *));
            if (temp == NULL) {
                for (int i = 0; i < num; i++) {
                    free((*argv)[i]);
                }
                free(*argv);
                *argv = NULL;
                return 0;
            }
            *argv = temp;
        }
        (*argv)[num] = strdup(token);
        if ((*argv)[num] == NULL) {
            for (int i = 0; i < num; i++) {
                free((*argv)[i]);
            }
            free(*argv);
            *argv = NULL;
            return 0;
        }
    }
    return num;
}


texts: Generating packing slips depending on product type

texts:
My abstract class. Product will have multiple child classes those will be different types of Product
 public abstract class Product
            {
                private int productId;
                public int ProductId
                {
                    get
                    {
                        return productId;
                    }
                    set
                    {
                        productId = value;
                    }
                }

                private double cost;
                public double Cost
                {
                    get
                    {
                        return cost;
                    }
                    set
                    {
                        cost = value;
                    }
                }
                protected IPayment payment;
                protected IEmail email;
                public string DoPayment()
                {
                    return payment.MakePayment();
                }

                public void setDifferentPaymentMethod(IPayment payment)
                {
                    this.payment = payment;
                }
            }

Concrete implementation of Product Class . How can I avoid instantiating PackingSlip here. Shall I create a factory?
 public class PhysicalProduct:Product
    {
        public PhysicalProduct()
        {
            payment = new PackingSlip();
        }
    }

Concrete implementation of Product Class
public class BookProduct:PhysicalProduct
    {
        public BookProduct():base()
        {
            payment = new DuplicatePackingSlip();
        }
    }

Strategy class
 internal class DuplicatePackingSlip : IPayment
    {
        public string MakePayment()
        {
            return "Generating Duplicate Packing SLip for Royalty Department";
        }
    }

Strategy.
 internal class PackingSlip : IPayment
        {
            public string MakePayment()
            {
                return "Generating Packing Slip";
            }
        }

Is this the right way to implement if we want to have open/closed principle?


texts: Updates or creates an entity based on if a value is present in an Optional

texts:
I need to get car info from a 3rd party web service and persist the data in my application DB. If my DB already has the car, I only update property values that may have changed. Otherwise, I create and save the car:
@Transactional //Spring Transaction
void saveCars() {

   //get CarInfo from a webservice
   List<CarInfo> carInfos = getCarInfo();

   // now get each Car from my application DB
   // that correspond to each CarInfo.
   Set<Car> cars = mySpringCarRepo.findByCarInfoIdIn(
       carInfos.stream().map(c -> c.getId())
           .collect(Collectors.toSet());

   for (CarInfo carInfo : carInfos) {

      // If a car for the carInfo
      // is already in my application
      // just update it if some carInfo has changed.
      // If a car is not there, create and save it to DB.
      Car car = cars
                 .stream()
                 .filter(c -> c.getCarInfoId().equals(carInfo.getId())
                 .findAny()
                 .map(c -> updateCar(carInfo, car))
                 .orElseGet(() -> createCar(carInfo);

       mySpringCarRepo.save(car);
   }
}

I have the following questions / concerns about this code:

Is this an inappropriate use of Optional's map method? I'm not mapping to a new object but rather just returning the same car with some properties potentially updated.
The save method is really only required to be called for cars created in the orElseGet. Due to being in a transaction, the updates to the car will be persisted without the save call. It seems redundant and perhaps confusing to call save.

Effective Java 3rd edition states that many uses of isPresent can profitably be replaced by other Optional methods. So that has led me to the path of using map & orElseGet and the fact that Java 8 does not have a ifPresentOrElse method on Optional.


texts: Novice implementation of TicTacToe in Haskell

texts:
I want to learn Haskell and figured the best way to do it is to write a simple TicTacToe implementation. However the result feels very inelegant and I think it might be the best playground for your rants and give me an opportunity to learn some lessons.

{-|
TODO: -filter symmetric states from game tree
|-}

module Tictactoe  where

import Data.List

initialBoardStr = "         "

data Tree a = Node a [Tree a]  deriving (Show)

type Board = String
type Points = Int
type Pos = Int

expandGameTree :: Board -> Tree Board
expandGameTree state = Node state $ succesors state
        where succesors cur_state = [Node s (succesors s)
                | s <- indicateAllowedMoves cur_state, s /= []]

evalBoard :: Board -> Points
evalBoard board
        | win && nextSymb board == "X" = 100
        | win && nextSymb board == "O" = (-100)
        | otherwise = 0
        where win = winingBoard board

evalState :: Tree Board -> Points
evalState (Node a []) = evalBoard a
evalState (Node a (x:xs)) = (minimax a) [evalState b | b <- (x:xs)]

minimax board
    | nextSymb board == "X" = minimum
    | nextSymb board == "O" = maximum

nextMove = (makeNextMove . expandGameTree)

numerate :: Board -> Board
numerate board
    | length (findIndices (==' ') board) == 0 = board
    | otherwise = numerate $ replace board (idx board) (show (idx board))
        where idx board = (findIndices (==' ') board) !! 0

makeNextMove (Node a (x:xs)) = getBoardFromTree ((x:xs) !! (maxIndex (rates (x:xs))))
    where maxIndex xs = head $ filter ((== maximum xs) . (xs !!)) [0..]
          rates (x:xs) = [evalState c | c <- (x:xs)]

getBoardFromTree (Node a (x:xs)) = a
getBoardFromTree (Node a []) = a

showBoard :: Board -> String
showBoard board =  "|" ++ (row 0) ++ "|\n|" ++ (row 1) ++ "|\n|" ++ (row 2) ++ "|\n"
           where numeratedBoard = numerate board
                 row i = takeRange numeratedBoard [3*i..(3*i)+2]

indicateAllowedMoves :: Board -> [Board]
indicateAllowedMoves board
        | winingBoard board = []
        | otherwise = [replace board i symb | i <- [0..8], board !! i == ' ']
        where symb = nextSymb board

replace :: String -> Pos -> String -> String
replace str idx char = take idx str ++ char ++ drop (idx+1) str

isAllowedMove :: Board -> Pos -> Bool
isAllowedMove board pos = elem next allowed
        where next = insertInBoardStr board pos
              allowed = indicateAllowedMoves board

winingRow :: String -> Bool
winingRow row
    | row == "XXX" || row == "OOO" = True
    | otherwise = False

rows :: Board -> [String]
rows board = row ++ cols ++ diag
    where row = [takeRange board [i..(i+2)] | i <- [0,3,6]]
          cols = [takeRange board $ map (+i) [0,3,6] | i <- [0..2]]
          diag = [takeRange board [0,4,8]] ++ [takeRange board [2,4,6]]

winingBoard :: Board -> Bool
winingBoard board = any winingRow $ rows board

--takeRange :: String -> [Int] -> String
takeRange str range = [str !! i | i <- range]

insertInBoardStr :: Board -> Pos -> Board
insertInBoardStr board pos = replace board pos symb
        where symb = nextSymb board

nextSymb :: Board -> String
nextSymb board
    | countLetters board 'X' ==  countLetters board 'O' = "X"
    | otherwise = "O"
    where countLetters str c = length $ filter (== c) str

curSymb :: Board -> String
curSymb board
    | nextSymb board == "X" = "O"
    | otherwise = "X"

isEquivivalent :: String -> String -> Bool
isEquivivalent row1 row2
        | row1 == row2 = True
        | row1 == reverse row2 = True
        | otherwise = False

play board = do
    putStr "\ESC[2J"
    putStrLn $ showBoard board
    if (winingBoard board) == True then
        putStrLn ("Player: " ++  (curSymb board) ++ " wins")
     else
        putStrLn "Make your move: "
    input <- getLine
    let pos = (read input :: Int)
    if (isAllowedMove board pos) == True then
        play (nextMove (insertInBoardStr board pos))
     else
        play board

main = play initialBoardStr


texts: Making a script file to perform maintenance

texts:
I wish to make a file to click on to do the 'usual' tasks I would do to clean/perform maintenance on my mother's computer when I'm not present.  I made a script file and took a few command lines from Google.  Am I on the right path?

<job>
<script language="VBScript">
Option Explicit
On Error Resume Next
Dim WshShell
Dim retVal
set WshShell=CreateObject("WScript.Shell")
WshShell.run "CCleaner.exe /AUTO"

WshShell.run "WiseRegCleaner.exe /AUTO"

WshShell.run "Cleanmgr /sagerun:1"

WshShell.run "Defrag volume c:"

wshshell.run "WiseDiskCleaner.exe /AUTO"

wshshell.run "mbam.exe /fullscanterminate"

WScript.Quit
</script>
</job>


texts: Optimizing digit sum and product with GMP

texts:
I have a bottleneck in my program at the point where I calculate the digit sum and product of a number. I am using GMP because I have to work with numbers that follow \$1e8 < n < 1e80\$.

To calculate the sum/product of a number, I initially used strings, thinking the division/modulo method would result in an improvement later on.

However, when I later implemented this it turned out that this did not give me a performance improvement.

mpz_class num = 1120390317;
mpz_class sum = 0;
mpz_class pro = 1;

while(num != 0) {
    mpz_class rem = (num % 10);
    sum += rem;
    pro *= rem;
    num = num / 10;
}

Instead of:

mpz_class num = 1120390317;
mpz_class sum = 0;
mpz_class pro = 1;

const std::string strNum = num.get_str();
for (auto c : strNum) {
    int res = c - '0';
    sum += res;
    pro *= res;
}

In the actual program the values of num are actually in the before mentioned range. But they provide results about equal to this test case.

The test case and the program shows me (with or without optimizations) using the first method is 3x as slow. How can I improve the modulo version to run faster than the string version? Or should I use the string version?  If so, can that be optimized?


texts: MongoDB Per-Module Reusable DB Object With Reconnection Handled

texts:
This implementation was derived from the following requirements. I would like to learn that whether the implementation is clean enough, without memory leak and performance hit.

Requirements

Always return either ready to be used DB object, or error if not available.
Reconnect automatically (passive), even in the event of explicit call of db.close() occurred.
Unessential implementation of a express.js compatible middleware to inject the DB object into request object. This may be ignored while reviewing.

Possible issues

Possible memory leak on registering error and close events handler (not sure since my understanding of the once interface is that it would immediately unregister the handler after being invoked).
Possible "race condition" on async calls of the get() function which would cause unexpected creation of connections.

For the "race condition" one, how do I safely and elegantly solve it? Also, if there're already proper implementations available that fits the requirement and doesn't exhibit any of the concerns and known issues, I'd be appreciated to learn as well.

Module implementation

/*
  Mongo helper, exposes access to Mongo DB object as req.mongo, as well as a
  get() method for similar effect. Reconnection is wrapped and handled within.
*/
var MongoClient = require('mongodb').MongoClient;
var logger = require('tp-logger')();

module.exports = function() {
  // arguments to be forwarded to MongoClient.connect()
  var _args = arguments;
  // reused db
  var _db;
  // connected flag
  var _connected = false;
  // DB error/close events handler
  var _onClose = function(err) {
    if (err) {
      if (_db) _db.close();
      logger.error('MongoDB closed on error', err.stack);
    } else {
      logger.log('MongoDB closed');
    }
    _connected = false;
  };

  function _get(callback) {
    // already connected
    if (_connected) return callback(null, _db);
    // reset connection
    MongoClient.connect.apply(MongoClient, _args).then(function(db) {
      _connected = true;
      _db = db;
      _db.once('close', _onClose).once('error', _onClose);
      return callback(null, _db);
    }).catch(function(err) {
      _connected = false;
      return callback(err);
    });
  }

  return {
    // express.js compatible middleware
    middleware: function(req, res, next) {
      _get(function(err, db) {
        if (err) return next(err);
        req.mongo = db;
        return next();
      });
    },
    get: _get
  };
};


texts:
This is a complete rewrite of the code posted for review in this question. The question is identical.
def render(digits):

    '''This function converts its input, a string of decimal digits, into a
    barcode, using the interleaved 2 of 5 format. The input string must not
    contain an odd number of digits. The output is an SVG string.

    Wikipedia [ITF Format]: http://en.wikipedia.org/wiki/Interleaved_2_of_5
    '''

    top = '<svg height="58" width="{0}" style="background:white">'
    bar = '<rect x="{0}" y="4" width="{1}" height="50" style="fill:black"/>'
    barcode = [top.format(len(digits) * 14 + 24)]

    byte_map = {
        '0': (2, 2, 4, 4, 2), '1': (4, 2, 2, 2, 4),
        '2': (2, 4, 2, 2, 4), '3': (4, 4, 2, 2, 2),
        '4': (2, 2, 4, 2, 4), '5': (4, 2, 4, 2, 2),
        '6': (2, 4, 4, 2, 2), '7': (2, 2, 2, 4, 4),
        '8': (4, 2, 2, 4, 2), '9': (2, 4, 2, 4, 2)
        }

    byte = lambda i: byte_map[digits[i]]

    def encode(bits, i=0):

        '''Encodes a string of decimal digits. The output's a binary string,
        but as a list of ints, all 2s and 4s, rather than zeros and ones, as
        the bars in the SVG barcode are rendered 2px wide for zeros, 4px for
        ones.'''

        if i == len(digits): return bits

        for b, w in zip(byte(i), byte(i+1)): bits.extend([b, w])

        return encode(bits, i+2)

    def svg(bits, i=0, x=4):

        '''Converts the list of ints returned by `encode` to a list of SVG
        elements that can be joined to form an SVG string.'''

        if i == len(bits): return barcode + ['</svg>']

        b, w = bits[i:i+2]
        barcode.append(bar.format(x, b))

        return svg(bits, i+2, x+b+w)

    # The call to `encode` passes in the itf start code, and the itf end
    # code's added to the list that `encode` returns. The complete list
    # is passed to `svg`, which returns a list of SVG element strings
    # that're joined with newlines to create the actual SVG output.

    return '\n'.join(svg(encode([2, 2, 2, 2]) + [4, 2, 2, 0]))

The use of recursive functions to implement what appear to be simple iterators does make sense. It avoids the need to try and assign xrange to range for Python2, as we don't need the range function now. As well, neither function can be replaced with a generator expression, so you end up with a couple of fairly crufty loops and more temporary variables otherwise.
Note: This works in both Python 2 and Python 3


texts: Find the common element in two int arrays

texts:
I am preparing for a interview for a junior level c# position.  I take two arrays and find the common int between both of them.  Let me know if you have any feedback.

using System;
using System.Collections.Generic;

namespace CommonElement
{
    class MainClass
    {
        static void EnterArray1IntoHashSet (int[] array1, HashSet<int> hs){
            foreach (int num in array1)
            {
                if (!hs.Contains (num))
                {
                    hs.Add (num);
                }
            }
        }

        static int FindCommonInt(int[] array2, HashSet<int> hs){
            foreach (int num in array2)
            {
                if (hs.Contains (num))
                {
                    return num;
                }
            }
            return -1;
        }

        public static void Main (string[] args)
        {
            int[] array1 = new int[7]{ 5, 6, 7, 8, 1, 2, 3 };
            int[] array2 = new int[7]{ 13, 22, 3, 45, 67, 73, 85};
            HashSet<int> hs = new HashSet<int> ();
            EnterArray1IntoHashSet (array1, hs);
            int commonElement = FindCommonInt(array2, hs);
            if (commonElement != -1)
            {
                Console.WriteLine (commonElement);
            }
            else
            {
                Console.WriteLine ("No Common Element");
            }
        }
    }
}


texts: Calling Web API from MVC generic way of approach

texts:
Our Project architecture is AngularJS + MVC + WebAPI.  Angular JS would call MVC action and MVC action further calls API methods. Below are some of the action methods we used for calling api  methods.
Note that our project is in its final stage, and as such we cannot modify the existing architecture. We have to use AngularJS + MVC + WebAPI.

We are having lot of controllers and each controller contains lot of get/post methods.   I need suggestion about below part of code. because similar to below piece of code only we are using across all the controllers with different method names. Is there any other better way/  Generic way to call webapi from MVC.

    public async Task<ActionResult> GetStates()
                {

                    httpClient = HttpContext.Items["httpclient"] as HttpClient;
                    HttpResponseMessage response = await httpClient.GetAsync(httpClient.BaseAddress + "api/Admin/GetStates");
                    if (response.IsSuccessStatusCode)
                    {
                        string stateInfo = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(stateInfo))
                        {
                            return new ContentResult { Content = stateInfo, ContentType = "application/json" };
                        }
                    }

                    return new JsonResult();
                }
                public async Task<ActionResult> ClientsInfo()
                {

                    httpClient = HttpContext.Items["httpclient"] as HttpClient;
                    HttpResponseMessage response = await httpClient.GetAsync(httpClient.BaseAddress + "api/Admin/GetClients");
                    if (response.IsSuccessStatusCode)
                    {
                        string roleInfo = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(roleInfo))
                        {
                            return new ContentResult { Content = roleInfo, ContentType = "application/json" };
                        }
                    }

                    return new JsonResult();
                }

                public async Task<ActionResult> GetRoles()
                {
                    httpClient = HttpContext.Items["httpclient"] as HttpClient;
                    HttpResponseMessage response = await httpClient.GetAsync(httpClient.BaseAddress + "api/Roles");
                    if (response.IsSuccessStatusCode)
                    {
                        string roleInfo = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(roleInfo))
                        {
                            return new ContentResult { Content = roleInfo, ContentType = "application/json" };
                        }
                    }

                    return new JsonResult();
                }
...........
//for post and delete actions similarly


texts: Capitalizing the first letter of every word in a string (with arbitrary spacing)

texts:
I solved the following question

You are asked to ensure that the first and last names of people begin
with a capital letter in their passports. For example, alison heck
should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, S.
Constraints

0 < len(S) < 1000
The string consists of alphanumeric characters and spaces.

Note: in a word only the first character is capitalized.
Example 12abc when capitalized remains 12abc.
Output Format:
Print the capitalized string, S.

Here's my code:
#!/bin/python

import math
import os
import random
import re
import sys

# Complete the solve function below.
def solve(s):
    ls = s.split(" ")
    new_word = ""
    new_name = ""
    for word in ls:
        if len(word) > 1:
            new_word = new_word + word[0].title() + word[1:] + " "
        else:
            new_word = new_word + word.title() + " "
    new_name = new_name.join(new_word)
    return new_name

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = raw_input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

I think I used a very long approach and would appreciate more efficient techniques to do the same.
The primary problem which I faced is handling arbitrary spaces and hence I went with this approach but the code smells bad. One things I can think of is reducing variables but that wouldn't be very helpful and make it less readable I think
EDIT : The question is  this question from HackerRank however the solution to this problem on the website does not include test cases where capitalize() and title() fail. The failing of these and more methods have also been discussed here


texts: Displaying markers for local attractions on a Google map

texts: I have created a page that displays markers for local attractions on a Google map.  There are a few functions that do similar tasks and I have tried to reduce these by incorporating them into one function, but to no avail. Any suggestions on how to go about doing this?


texts:
Background

I've recently made a contribution to an open source project, ledger-autosync, which is a CLI "to pull down transactions from your bank and create ledger transactions for them".

Most of the functions are fairly stand alone which means passing configuration values from the argument parser to the function where it is actually used can be very tedious. For example, in the contribution I made, of 62 lines added, about 55 or so were updating function calls and signatures to pass the new parameter along.

I submitted a pull request to use a module to manage the configuration global which I think will simplify things and am seeking a review on the approach used.

My Solution

The approach is to use a config module as a namespace for command line argument values.  Then functions that use argument values can access them as attributes of config instead of declaring them in their signature and needing them to be passed along.

My Concerns

I'm worried this global approach will cause issues in ways I can't foresee. One issue I already ran into was the need to update the test suite in order to clear all attributes of config between tests.

I'm also worried this approach will make it unclear what command line arguments control a given function, which could make writing tests and understanding the code difficult.

The Code

Below is a working representation of the code.  The project this is a part of is quite large and I'm not sure of another coherent way to present everything here.

config.py

# no content

cli.py

import argparse
import datetime as dt
import config

def run():
    parser = argparse.ArgumentParser()
    parser.add_argument("--date-format")

    args = parser.parse_args(namespace=config)

    print_transactions()

def print_transactions():
    transactions = [(dt.date(2020, 5, 1), 10), (dt.date(2020, 5, 2), 100)]
    for t in transactions:
        print(format_transaction(t))

def format_transaction(transaction):
    return f"{transaction[0]:{config.date_format}}:\t {transaction[1]}"

if __name__ == "__main__":
    run()

Example usage:

python cli.py --date-format '%Y/%m/%d'

Example output:

2020/05/01:  10
2020/05/02:  100


texts: How to reduce this archive detection function and make it supports wildcards

texts:
The function below is called to determine if a given file is the archive of another file. I'm also looking for a way to supports wildcards. For example if the original log file is serverw3c.log and we type serverw3c*.log, it returns true for the following:

serverw3c.log.2011-02-04
serverw3c.log
serverw3c.log.20110204_120132
serverw3c_20110204.log

The code:

/// <summary>
/// Check if a given file is an archive of an original file.
/// The check is performed on the names of the files only.
/// </summary>
/// <param name="originalFile">The original file.</param>
/// <param name="archivedFile">The file which is supposed to be an archive of the original one.</param>
/// <returns>True if the file is an archive, False otherwise.</returns>
public bool IsArchive(string originalFile, string archivedFile)
{
    // We assume that an archived file has the name of the original
    // concatenated with a timestamp '.YYYYMMDD_HHMMSS'
    Regex exp = new Regex(string.Concat(originalFile, ".", "[0-9][0-9][0-9][0-9][0-1][0-9][0-9][0-9]_[0-2][0-9][0-5][0-9][0-5][0-9]"));
    if (exp.IsMatch(archivedFile))
        return true;

    exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile), "_", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]", Path.GetExtension(".log")));
    if (exp.IsMatch(archivedFile))
        return true;

    exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile), "_", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]", "_", "[0-9][0-9][0-9]", Path.GetExtension(".log")));
    if (exp.IsMatch(archivedFile))
        return true;

    exp = new Regex(string.Concat(originalFile, ".", "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]"));
    if (exp.IsMatch(archivedFile))
        return true;

    return false;
}


texts: Change functions based on jQuery plugin {options}

texts:
I'm developing my first legitimate jQuery plugin, and I'm trying to keep it very modular. To do this, I'm writing many individual functions, which is fine, but I need a clean way to determine what functions to fire based on the plugin options provided by the user.

Right now, I'm using a .on('click',...) event with a switch statement. That method is ok and I just have a feeling that there is a better, time-tested method of changing what function is fired based on plugin {options}. A better method that is used by professional JavaScript developers and has been proven to work reliably.

Again, I'm trying to be as modular and professional as possible, but I'm self taught, so there's really no one to say if I'm doing it the "right" way, or the "best" way for future maintainability.

JSFiddle

(function($){

$.fn.showDateTime = function(options) {

    // variables and settings
    var d;
    var $button = $(this);
    var defaults = {
        date: "all"
    };
    var settings = $.extend({}, defaults, options);

    // event handlers
    $button.on('click', function(){
        d = new Date();
        switch(settings.date){
            case "all": showDate();
                        break;
            case "date only": showDateOnly();
                              break;
            case "time only": showTimeOnly();
                              break;
            default: showDate();
        }
    });

    // functions
    function showDate(){
        alert(d.toString());
    }
    function showDateOnly(){
        alert(d.toDateString());
    }
    function showTimeOnly(){
        alert(d.toLocaleTimeString());
    }
};
})(jQuery);

$('#button').showDateTime({date:"date only"});


texts:
I have written the following routine to clean an html raw code and extract the text.

It works, but the code is not very well written. Any ideas how to solve this faster and with fewer lines of code?

Thanks a lot for your help!

import re
def cleanhtml(raw_html):
    cleanr = re.compile('<.*?>')
    cleantext1 = re.sub(cleanr, ' ', raw_html)
    cleanr = re.compile('&amp;')
    cleantext2 = re.sub(cleanr, '&', cleantext1 )
    cleanr = re.compile('\n')
    cleantext3 = re.sub(cleanr, ' ', cleantext2)
    cleanr = re.compile('&nbsp;')
    cleantext4 = re.sub(cleanr, ' ', cleantext3)
    cleanr = re.compile('&#8217;')
    cleantext5 = re.sub(cleanr, '\'', cleantext4)
    cleanr = re.compile('&#8230;')
    cleantext6 = re.sub(cleanr, '...', cleantext5)
    cleanr = re.compile('&#8216;')
    cleantext7 = re.sub(cleanr, '\'', cleantext6)
    cleanr = re.compile('&#8221;')
    cleantext8 = re.sub(cleanr, '\'', cleantext7)
    cleanr = re.compile('&#8220;')
    cleantext9 = re.sub(cleanr, '\'', cleantext8)
    cleanr = re.compile('&#8211;')
    cleantext10 = re.sub(cleanr, '\'', cleantext9)
    cleanr = re.compile('&#8212;')
    cleantext11 = re.sub(cleanr, '\'', cleantext10)
    cleanr = re.compile('&#38;')
    cleantext12 = re.sub(cleanr, '&', cleantext11)
    cleanr = re.compile('&#2026;')
    cleantext13 = re.sub(cleanr, '...', cleantext12)
    cleanr = re.compile('&#160;')
    cleantext14 = re.sub(cleanr, ' ', cleantext13)
    cleanr = re.compile('&#038;')
    cleantext15 = re.sub(cleanr, '&', cleantext14)
    return cleantext15.strip()


texts: Check a string to see if it is a palindrome

texts:
I have written two code pieces  to check if a given string is a palindrome:

public static bool FirstMethod(string str)
{
    int i = 0;
    int j = str.Length - 1;

    while (i<j)
    {
        if (str[i] != str[j])
            return false;

        i++;
        j--;
    }

    return true;
}

public static bool SecondMethod(string myString)
{
    string first = myString.Substring(0, myString.Length / 2);
    char[] arr = myString.ToCharArray();
    Array.Reverse(arr);
    string temp = new string(arr);
    string second = temp.Substring(0, temp.Length / 2);
    return first.Equals(second);
}

Please tell me which one is better.

Is there a better method than this?


texts:
I've looked at multiple examples of Java AES CBC mode encryption but I couldn't find a proper solution that's safe to use. I ended up writing my own utility class. My questions is: Is this code safe to use? I've read some stuff about padding oracle attacks but I don't really understand how they work.

I've tested the code and it seems to work properly:

CryptoUtils.removeCryptoRestriction();

String string = "Hello world! This is a test string. Have a nice day!";
byte[] iv = CryptoUtils.generateIv();
byte[] key = CryptoUtils.generateKey();

byte[] encrypted = CryptoUtils.doCrypto(Cipher.ENCRYPT_MODE, key, iv, string.getBytes("UTF-8"));
System.out.println(new String(encrypted));

byte[] decrypted = CryptoUtils.doCrypto(Cipher.DECRYPT_MODE, key, iv, encrypted);
System.out.println(new String(decrypted));

Output:

��zI Fğ��O>��_�@3�ܷ+|ZI�m���M�4�;���ygr8G�ܪ8�6u���M
Hello world! This is a test string. Have a nice day!

Here's the util code:

public static byte[] doCrypto(int mode, byte[] keyBytes, byte[] ivBytes, byte[] bytes) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
    cipher.init(mode, secretKeySpec, ivParameterSpec);
    return cipher.doFinal(bytes);
}

public static void doCrypto(int mode, byte[] keyBytes, byte[] ivBytes, File in, File out) throws GeneralSecurityException, IOException {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
    cipher.init(mode, secretKeySpec, ivParameterSpec);

    try (FileInputStream fileInputStream = new FileInputStream(in); FileOutputStream fileOutputStream = new FileOutputStream(out)) {
        byte[] buffer = new byte[1024];

        for (int i = 0; i != -1; i = fileInputStream.read(buffer)) {
            byte[] updateBytes = cipher.update(buffer, 0, i);
            if (updateBytes != null) fileOutputStream.write(updateBytes);
        }
        byte[] finalBytes = cipher.doFinal();
        if (finalBytes != null) fileOutputStream.write(finalBytes);
    }
}

public static byte[] generateIv() {
    SecureRandom secureRandom = new SecureRandom();
    byte[] iv = new byte[16];
    secureRandom.nextBytes(iv);
    return iv;
}

public static byte[] generateKey() throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(256);
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}

public static void removeCryptoRestriction() {
    Security.setProperty("crypto.policy", "unlimited");
}

The file encryption works too.

Thanks in advance!


texts: Writing values from JSON on image and display image

texts:
This is a script I made that opens img.png, downloads the JSON data from the API, writes it on image and displays it. It currently is a community ad over Arqade.

<?php
header('Content-type: image/png'); //setting header to png so it will display as an image
$donationImage = imagecreatefrompng("img.png"); //loading the donation image's base from the file img.png
$white = imagecolorallocate($donationImage, 255, 255, 255);

$json = json_decode(utf8_encode(file_get_contents("http://www.mariomarathon.com/rest/partners/arqade.com")));
$total = round($json->total); //Rounding the total amount because it uses floats
$byus = $json->domainTotal;

imagettftext($donationImage,30,0,60,450,$white,'arial.ttf',"$".$total); //writing the total count to x:60 y:450
imagettftext($donationImage,30,0,370,450,$white,'arial.ttf',"$".$byus); //writing the donations by arqade.com to x:370 y:450
imagepng($donationImage); //displaying image
imagedestroy($donationImage); //removing image from memory
?>

Code and additional resources are available at GitHub. This file is the one named mariobeta.php.

How can I improve this code? I'm not that good with PHP but I think that the code doesn't have any major issues.