texts:
This is some of the code I have:

[window setLevel:kCGScreenSaverWindowLevel];
[window setOpaque:NO];
[window setStyleMask:0];
[window setBackgroundColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.3]];
[window setAlphaValue:0];

[window setFrame:[window frameRectForContentRect:[[window screen] frame]] display:YES animate:YES];

[window makeKeyAndOrderFront:self];
[[window animator] setAlphaValue:1.0];

I was just wondering if there was any way to compact it, all of those commands to my window. Any ways to improve it too?


texts:
http://jsfiddle.net/xkuZF/6/

function func() {
    document.body.scrollTop++;
}

window.onmouseover = function() {
    clearInterval(interval);
};

window.onmouseout = function() {
    interval = setInterval(func);
};

var interval =  setInterval(func);

Do you think that there are any better ways of doing this code?

Better:

More options
Less code


texts:
I am working on a project in Java which includes a lot of database related tasks. For instance, I would have to insert, update, retrieve data so many times within the application. To use code reusability, I've just written this abstraction for my database class. I'm planing to call its methods where ever its needed to perform database related tasks within the code. Please review my code. Are there any bad practices?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.teamincredibles.settings.Settings;

public class Database {

    private Connection connection;

    public void connect() {
        try {
            Class.forName(Settings.getDatabaseDriver());
            connection = DriverManager.getConnection(Settings.getJdbcUrl(), Settings.getDBUserName(), Settings.getDBPassword());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean prepareStatement(String query, String choice1) {
        boolean flag = false;
        try {
            PreparedStatement ps = connection.prepareStatement(query);
            ps.setString(1, choice1);
            ResultSet rs = ps.executeQuery();
            flag = rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean prepareStatement(String query, String choice1, String choice2) {
        boolean flag = false;
        try {
            PreparedStatement ps = connection.prepareStatement(query);
            ps.setString(1, choice1);
            ps.setString(2, choice2);
            ResultSet rs = ps.executeQuery();
            flag = rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public void executeUpdate(String query) {
        try {
            Statement statement = connection.createStatement();
            statement.executeUpdate(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean execute(String query) {
        boolean result = false;
        try {
            Statement statement = connection.createStatement();
            result = statement.execute(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultSet executeQuery(String query) {
        ResultSet result = null;
        try {
            Statement statement = connection.createStatement();
            result = statement.executeQuery(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void disconnect() {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


texts:
This simply creates a table using the items passed in. I would like to make this function shorter and/or more efficient. What I have seems pretty redundant.

def apriori_creator(items, k):
    """Function that creates apriori table using supported candidates"""
    table = []
    the_length = len(items)
    new_k = k-2 # first k-2 items as described in algorithm in book for 'apriori gen'
    for x in range(the_length):
        next = x + 1
        for y in range(next, the_length):
            combined = items[x].union(items[y]) # merge
            l_sub_one = list(items[x])
            l_sub_one.sort()
            l_sub_two = list(items[y])
            l_sub_two.sort()
            first = l_sub_one[:new_k] # getting the first k-2 items of the set
            second = l_sub_two[:new_k]
            if first == second:
                table.append(combined)
    return table


texts: Design considerations for classes/methods using JDBC to ensure resources closed correctly

texts:
In reviewing code in our application, I see a tension between what makes a convenient design for methods accessing database data versus coding to ensure that the JDBC resource objects are closed properly.

An example problem:

// Application.java: Singleton class for objects which want to execute SQL queries

/**
 * Execute a query and return the Result. Provide a common point of
 * connection/statement handling
 *
 * @param sql
 *            SQL to execute
 * @return a ResultSet
 */
public ResultSet executeQuery(String sql) throws Exception {
    DBConnectionObj connectionObj = dbPoolMgr.getConnection();
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("StateServer.executeQuery(): executing query=" + sql);
        }
        return connectionObj.executeQuery(sql);
    } catch (Exception e) {
        LOG.error("executeQuery(): error executing SQL=" + sql);
        throw e;
    } finally {
        dbPoolMgr.putConnection(connectionObj);
    }
}

// DBConnectionObj.java: JDBC Connection wrapper used in a connection pool

public ResultSet executeQuery(String sql, Connection connection) {
  try {
    if (Log4jUtils.isDebugLevel(LOG)) {
            LOG.debug("executeQuery(): " + sql);
        }
        return connection.createStatement().executeQuery(sql);
  } catch (SQLException e) {
        UnsuccessfulSQLExecutionResult result = new UnsuccessfulSQLExecutionResult(e, sql);
        LOG.error("executeQuery(): exception executing query. SQL info=" +        result.getContents());
        e.printStackTrace();
        return null;
  }
}

With above helper functions, other application classes can just pass the specific SQL and get back a reference to the ResultSet:

    ResultSet rs = Application.getInstance().executeQuery(getSql());
    while (rs.next()) {
            // process data
    }
    rs.close();

The problem with the DBConnectionObj.executeQuery() method, is that it creates a temporary Statement to execute the query, and this temporary object is never closed.  But also, because the method returns the ResultSet to the caller, it can't close the Statement until the caller is ready to close the ResultSet.  (The code doesn't need to close the Connection object, because it stays open for the lifetime of the application, and is part of a pool of open database connections.)

One solution would be to make sure every caller to the executeQuery() method, always does this:

rs.close();
rs.getStatement().close();

So the question is this: for usefulness, having a method which takes a SQL string for input and returns a ResultSet feels like a good design.  However, it imposes requirement that callers make sure to close both the ResultSet and the Statement, and it can't take advantage of the safer Java 7 try-close feature:

try(ResultSet rs = Application.getInstance().executeQuery(getSql())) {
    while (rs.next()) {
        // process data
    }
}  // rs is automatically closed, but not the Statement object

Any comments or suggestions on a better design are appreciated.


texts: GroupBy over a clustered iterator in Scala

texts:
Here's a solution for a lazy groupBy when the iterator contents are assumed to be clustered (repeated elements next to each other) over the key:

def clusteredGroupBy[B](h: Iterator[B])(f: B => _): Stream[Iterator[B]] = {
  if (h.hasNext) {
    val firstValue = h.next()
    val projection = f(firstValue)
    val (head, tail) = h.span(f(_) == projection)

    (Iterator(firstValue) ++ head) #:: clusteredGroupBy[B](tail)(f)
  } else Stream.empty
}

Any suggestions on how to improve this? Is there anything more native to Scala that does the same?


texts:
I understand and apply the DRY principle but I have a hard time getting this DRYer than it is right now.

/**
 * The Caller class is used to translate method calls to rest calls.
 *
 * It uses a low level AsyncHttpClient to execute the actual calls.
 *
 * It uses callbacks which are executed when the response is received.
 */

public class Caller {

    // the (rest) base url to where the calls must be directed
    private static final String baseUrl = "http://very.secret.domain.org:1337/";

    // singleton
    private static final Caller instance = new Caller();

    // the client which does the actual (low level) calls
    private static AsyncHttpClient client = new SyncHttpClient();

    // the (rest) method part of the url
    private static final String registerUrl = baseUrl + "createUser/";
    private static final String verifyUrl = baseUrl + "searchUser/";

    // singleton
    private Caller() {
    }

    synchronized static Caller getInstance() {
        return instance;
    }

    // creates a user with given parameters
    synchronized void getUser(final ShareActivity activity, // the activity which calls this method
                                                            // and expects the result (asynchronously)
                              String idToken, String name, String email) {

        //arguments
        Map map = new HashMap();

        map.put("token", idToken);
        map.put("name", name);
        map.put("email", email);

        //casted
        RequestParams params = new RequestParams(map);

        // call to get
        get(registerUrl,
                params,
                new JsonHttpResponseHandler() {//the handler

                    // when response recieved
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject user) {

                // pass the (json) User object to the (calling and passed) activity
                activity.handleUser(user);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray array) {

                // should not happen (the rest endpoint doesn't produce arrays)
                throw new RuntimeException("array in stead of object");
            }
        });
    }

    // more or less the same as above (except for added comments)
    synchronized void getUser(final ShareActivity activity, final String idToken) {

        // the same map again with the same first (and here only) parameter
        // I really think this can be done DRYer
        Map map = new HashMap();

        map.put("token", idToken);

        RequestParams params = new RequestParams(map);

        // same call
        get(verifyUrl, params,
                new JsonHttpResponseHandler() { // other handler

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject user) {

                // this call (with different url,
                // more or less the same map
                // does other work in the same activity)
                // that's to much of same in the same sentence I suspect ;-)
                if(user!=null){
                    activity.handleUser(user);
                }else {
                    activity.registerUser();
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray array) {

                // shouldn't happen either
                throw new RuntimeException("array in stead of object");
            }
        });
    }

    // the lowlevel call
    private static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.get(url, params, responseHandler);
    }
}

As can be seen, the getUser() is overloaded. There are two different use cases which differ in URL, the content of map and the handler.

The get method on the bottom is reused but I was wondering whether it is possible to get this code cleaner (or DRYer in any case...).


texts:
I am new to Python and recently started exploring web crawling. The code below parses the S&P 500 List Wikipedia page and writes the data of a specific table into a database.

While this script is hardcoded and I would certainly be interested in some thoughts on performing the same task in a slightly more generic way (perhaps with beautifulsoup), this is not my primary concern. What I really wondered was if there is a less verbose or more "pythonic" way of doing it.

import urllib.request
import re
import pymysql

# Open Website and get only the table on the page with the relevant data. In this hardcoded case
table = urllib.request.urlopen("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies#S.26P_500_Component_Stocks").read().decode("utf-8")
table = table.split("
(.+)<\/a>	'
cigs_grab = '^(.+)	'

ticker, exchange, names, cigs, cigs_sub = ( [] for i in range(5))
match = False

# Parse HTML output and write relevant td data to lists.
# The list is "hardcoded", meaning after each match of either NASDAQ or NYSE ident,
# the matching  as well as the next, the fourth and fifth  after that one get parsed.

for i in range(len(table)):
    if bool(re.search(pattern = tick_ident_nasdaq, string = table[i])):
        ticker.append(re.search(pattern = name_grab, string = table[i]).group(1))
        exchange.append("NASDAQ")
        match = True

    elif bool(re.search(pattern = tick_ident_nyse, string = table[i])):
        ticker.append(re.search(pattern = name_grab, string = table[i]).group(1))
        exchange.append("NYSE")
        match = True

    if match == True:
        names.append(re.search(pattern = name_grab, string = table[i + 1]).group(1))
        names[-1] = re.sub(pattern = "&amp;", repl = "&", string = names[-1])
        cigs.append(re.search(pattern = cigs_grab, string = table[i + 3]).group(1))
        cigs[-1] = re.sub(pattern = "&amp;", repl = "&", string = cigs[-1])
        cigs_sub.append(re.search(pattern = cigs_grab, string = table[i + 4]).group(1))
        cigs_sub[-1] = re.sub(pattern = "&amp;", repl = "&", string = cigs_sub[-1])
        match = False

# Format Data in tuple format for database export
company_data = zip(ticker, exchange, names, cigs, cigs_sub)

# Establish database connection, empty companies table and rewrite list data to table
try:
    conn = pymysql.connect(host = "localhost", user = "root", passwd = "pw", db = "db", charset = "utf8", autocommit = True, cursorclass=pymysql.cursors.DictCursor)
    cur = conn.cursor()
    cur.execute("DELETE FROM companies")
    cur.executemany("INSERT INTO companies (tickersymbol, exchange, name, cigs, cigs_sub) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\")", (company_data))
finally:
    cur.close()
    conn.close()


texts:
The original question is as follows:

Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found in the given array. (Efficiency is not a priority.)
maxSpan([1, 2, 1, 1, 3]) → 4
maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6
maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6

Here is my implementation of the maxSpan function.
public int maxSpan(int[] nums) {
  Map<Integer, List<Integer>> spans = new HashMap<>();
  for (int i = 0; i < nums.length; i++) {
    if (!spans.containsKey(nums[i])) {
      List<Integer> position = new ArrayList<>();
      position.add(i);
      spans.put(nums[i], position);
    } else {
      List<Integer> position = spans.get(nums[i]);
      position.add(i);
    }
  }
  int globalMaxSpan = 0; // empty set has maxSpan = 0
  for (List<Integer> value : spans.values()) { //iterating over values only
      int localMaxSpan = 0;
      if (value.size() > 1) {
        localMaxSpan = value.get(value.size() - 1) - value.get(0) + 1;
      } else localMaxSpan = 1;
      if (localMaxSpan > globalMaxSpan)
        globalMaxSpan = localMaxSpan;
  }
  return globalMaxSpan;
}

Here is another implementation of the same algorithm I found on GitHub implemented by others.
public int maxSpan(int[] nums) {
    int max = 0;
    for(int i = 0; i < nums.length; i++) {
        int j = nums.length - 1;
        while(nums[i] != nums[j])
            j--;
        int span = j - i + 1;
        if(span > max)
            max = span;
    }
    return max;
}

Although my implementation is O(n) runtime but it is more complicated than the below implementation. Please give comments to my code in different aspects. Thanks.


texts:
My daughter, nine, recently had some homework looking at number palindromes. Part of the assignment was to take a number, reverse it, add the two together and repeat until she got a palindrome and to do this for several different numbers.

While helping her with this it struck me it'd be a nice simple idea for a computer program. She & I have messed about in Scratch a bit, but this sounded like a nice problem to do in a more commercial language. Thought I could write it and then show her how it worked.

So I did. It turned out to be not quite as child-friendly as I'd imagined.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace CheckNumberPalindrome
{
    class Program
    {
        static void Main(string[] args)
        {
            string rollingSum;
            int iterations = 1;

            if(IsNumeric(args[0]) == false)
            {
                Console.WriteLine("You did not enter a numeric value");
            }

            rollingSum = RecurseUntilPalindrome(args[0], ref iterations);
            Console.WriteLine(string.Format("The final palindrome is {0}, which took {1} steps.", rollingSum, iterations));
        }

        private static bool IsNumeric(string s)
        {
            long result;
            return Int64.TryParse(s, out result);
        }

        private static string RecurseUntilPalindrome(string s, ref int iterations)
        {
            long rollingSum = AddToPalindrome(s);

            if(IsPalindrome(rollingSum.ToString()))
            {
                return rollingSum.ToString();
            }

            iterations++;
            return RecurseUntilPalindrome(rollingSum.ToString(), ref iterations);
        }

        private static long AddToPalindrome(string s)
        {
            string reversedString = ReverseString(s);
            long result = Convert.ToInt64(s) + Convert.ToInt64(reversedString);
            Console.WriteLine(string.Format("Adding {0} to {1} = {2}", s, reversedString, result));
            return result;
        }

        private static string ReverseString(string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

        private static bool IsPalindrome(string s)
        {
            return s.SequenceEqual(ReverseString(s));
        }
    }
}

There are two questions here:

How could I make this better or cleaner or more efficient or any of the other things that CR does so well?
What could I do (beside hiding some of the functions in pre-compiled code elsewhere) to make this more child-friendly, or better for teaching/explaining some basic code concepts?


texts:
I've adapted an Instagram widget from this example so that it now appends 8 images to their respective IDs using an Instagram username. I want my widget implementation to be better and more efficient.  I'm very new to this so I'm sure there are parts that are no longer needed or that could be greatly improved.

var accessToken = ''; // Access token
var instagram = function () {
  return {
    getUserIDByUsername: function (strUser) { // By username
      var getUserURL = 'https://api.instagram.com/v1/users/search?q=' + strUser + '&access_token=' + accessToken + ''
      $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: getUserURL,
        success: function (data) {
          var getUserID = data.data[0].id;
          instagram.getUserDetailsByUserID(getUserID);
        }
      });
    },
    getUserDetailsByUserID: function (userID) { // By userid
      $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: "https://api.instagram.com/v1/users/" + userID + "/?access_token=" + accessToken + "",
        success: function (data) {
          if (data.meta && data.meta.code == "200") {
            //console.log(data);
            instagram.loadImages(userID);
          } else if (data.meta && data.meta.code == "400" && data.meta.error_message) {
            console.log(data.meta.error_message);
          }
        }
      });
    },
    loadImages: function (userID) { // Get user photos
      var getImagesURL = "https://api.instagram.com/v1/users/" + userID + "/media/recent/?access_token=" + accessToken + ""
      $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: getImagesURL,
        success: function (data) {
          console.log(data);
          size = data.data[0].images.standard_resolution.url;
          $("#insta-1").append("");
          size = data.data[1].images.standard_resolution.url;
          $("#insta-2").append("");
          size = data.data[2].images.standard_resolution.url;
          $("#insta-3").append("");
          size = data.data[3].images.standard_resolution.url;
          $("#insta-4").append("");
          size = data.data[4].images.standard_resolution.url;
          $("#insta-5").append("");
          size = data.data[5].images.standard_resolution.url;
          $("#insta-6").append("");
          size = data.data[6].images.standard_resolution.url;
          $("#insta-7").append("");
          size = data.data[7].images.standard_resolution.url;
          $("#insta-8").append("");
        }
      });
    }
  }
}();
$(document).ready(function () {
  var strUser = "saturdaysnyc"; // Instagram username
  if (isNaN(strUser)) {
    instagram.getUserIDByUsername(strUser);
  } else {
    instagram.getUserDetailsByUserID(strUser);
  }
});


texts: Welford's online variance calculation algorithm for vectors

texts:
I'm developing a face recognizing application using the face_recognition Python library.

The faces are encoded as 128-dimension floating-point vectors. In addition to this, each named known person has a variance value, which is refined iteratively for each new shot of the face along with the mean vector. I took the refining formula from Wikipedia.

I'm getting some false positives with the recognized faces, which I presume is because the library was developed primarily for Western faces whereas my intended audience are primarily Southern-Eastern Asian. So my primary concern with my code, is about whether or not I had gotten the mathematics correct.

Here's my refining algorithm in Python

import sys
from functools import reduce
from math import hypot

# fake testing data.

# new reference face.
refenc = (0.2, 0.25, 0.4, 0.5) * 32

# previous face encoding and auxiliary info.
baseenc = (0.2, 0.3, 0.4, 0.5) * 32
v = 0.01         # variance
n = 3            # current iteration

n = min(n, 28)   # heuristically limited to 28.

vnorm = lambda v: reduce(hypot, v)
vdiff = lambda u, v: list(map(lambda s,t:s-t, u, v))

delta1 = vdiff(refenc, baseenc)
if( vnorm(delta1) > 0.4375 and n > 1 ):
    sys.exit() # possibly selected wrong face.
    pass
newenc = [ baseenc[i] + delta1[i] / n for i in range(128) ]

delta2 = vdiff(delta1, newenc)
v = v*(n-1)/n + vnorm(delta1)*vnorm(delta2)/n

print(repr((newenc, v, n)))

Irrelevant note
: I used struct.(un)pack to serialize in binary to save space, because the repr of the data is too big.


texts:
I have snapshots (photos) that I load off my camera's memory card, and store in a folder. Sometimes I have videos, and occasionally plain audio too (the camera can record just sound).

Additionally, my wife, and kids have their point-and-shoots too.

I have a workflow where I dump the photos on to a designated folder on a linux samba share, and then run this script which identifies the photos, auto-rotates the portrait picturs, and renames them according to the date and time the picture was taken (rather than a sequential number from the camera).

This way, assuming the various cameras have the correct clock-time set, the different cameras all have photos that are named similar things (and can be sorted alphabetically to get them in chronological order too.

Notes:

the jhead program the script calls will rename/rotate the photos, and the name will become something like: Img20140217-164850.20.jpg
the jhead also identifies that some pictures may have 'raw' partners, for example, my Nikon camera takes a picture called DSC1234.JPG and simultaneously the picture DSC1234.NEF (the raw photo). The command jhead -aNEF -ft -autorot -n DSC*.JPG will identify the JPG photo, strip the .JPG extensions, and, because there is also the -aNEF argument, will rename the matching NEF file to the same base-name (Img*) as the JPG.... in other words, for the files DSC1234.JPG and DSC1234.JPG, the jhead program will produce, for example, both Img20140217-164850.20.jpg and Img20140217-164850.20.NEF
the script deals with both Canon, and Nikon raw files (RW2 and NEF respectively)

The script is relatively simple, but has a fair amount of repetition. Any suggestions for how to improve it?

#!/usr/bin/tcsh -f

#cd /valuable/picxfer

# Do the .jpg first because the jhead program will write .jpg even for .JPG input.
echo 'Checking DSC*.jpg'
if ( `tcsh -f -c "ls -1 DSC*.jpg >& /dev/null" && echo yes` == "yes" ) then
  jhead -anef -ft -autorot -n DSC*.jpg
else
  echo no Nikon jpg files
endif

echo 'Checking DSC*.JPG'
if ( `tcsh -f -c "ls -1 DSC*.JPG >& /dev/null" && echo yes` == "yes" ) then
  jhead -aNEF -ft -autorot -n DSC*.JPG
else
  echo no Nikon JPG files
endif

echo 'Checking *.jpg'
if ( `tcsh -f -c "ls -1 p*.jpg >& /dev/null" && echo yes` == "yes" ) then
  jhead -arw2 -ft -autorot -n p*.jpg
else
  echo no Canon jpg files
endif

echo 'Checking *.JPG'
if ( `tcsh -f -c "ls -1 P*.JPG >& /dev/null" && echo yes` == "yes" ) then
  jhead -aRW2 -ft -autorot -n P*.JPG
else
  echo no Canon JPG files
endif

echo Setting permissions
chmod ugo=r Img*


texts:
For anyone who's unfamiliar with this grading system.

I'd like a general review of my code, and I have a few questions:

Are plain types okay for the letter grades and credit hours, or could they be public typedefs?
Should operator<< need to call calculateGPA(), or should I create a private accessor and have that called?  In order to maintain encapsulation, I'll need to keep operator<< as a friend.
Is the for-loop in calculateGPA() ideal for this purpose, or are there one or more STL functions that can do the same thing but more cleanly?

GPA.h

#ifndef GPA_H
#define GPA_H

#include <iosfwd>
#include <vector>
#include <utility>

class GPA
{
private:
    std::vector<std::pair<unsigned, unsigned> > grades;
    double calculateGPA() const;

public:
    void add(char, unsigned);
    friend std::ostream& operator<<(std::ostream&, GPA const&);
};

unsigned convertLetterGrade(char);

#endif

GPA.cpp

#include "GPA.h"
#include <ostream>
#include <stdexcept>

void GPA::add(char letterGrade, unsigned creditHours)
{
    unsigned numericalGrade = convertLetterGrade(letterGrade);
    grades.push_back(std::make_pair(numericalGrade, creditHours));
}

double GPA::calculateGPA() const
{
    unsigned sumGradePoints = 0;
    unsigned sumCreditHours = 0;

    for (auto iter = grades.cbegin(); iter != grades.cend(); ++iter)
    {
        sumGradePoints += iter->first * iter->second;
        sumCreditHours += iter->second;
    }

    double totalGPA = static_cast<double>(totalGradePoints) / sumCreditHours;
    return totalGPA;
}

unsigned convertLetterGrade(char letterGrade)
{
    switch (letterGrade)
    {
        case 'a':
        case 'A': return 4;
        case 'b':
        case 'B': return 3;
        case 'c':
        case 'C': return 2;
        case 'd':
        case 'D': return 1;
        case 'f':
        case 'F': return 0;
        default: throw std::logic_error("Invalid Letter Grade");
    }
}

std::ostream& operator<<(std::ostream& out, GPA const& obj)
{
    return out << obj.calculateGPA();
}

Main.cpp

#include "GPA.h"
#include <cstddef>
#include <iostream>

int main()
{
    std::cout << "# Classes: ";
    std::size_t numClasses;
    std::cin >> numClasses;

    GPA gpa;

    for (std::size_t i = 0; i < numClasses; ++i)
    {
        std::cout << "\n(" << i+1 << ") Letter Grade: ";
        char letterGrade;
        std::cin >> letterGrade;

        std::cout << "    Credit Hours: ";
        unsigned creditHours;
        std::cin >> creditHours;

        gpa.add(letterGrade, creditHours);
    }

    std::cout << "\n*** Total GPA: " << gpa;
}


texts:
After taking a break and reviewing the comments on my first attempt at creating a fixed-size memory pool, this is my second attempt.

The memory pool should allocate each block correctly aligned in memory, so that when I call placement new on the returned memory, it isn't misaligned.
This is my main goal with this implementation.

The pool is implemented as a free-list, with each block looking something like this in memory:

    -------------------------------------------
   | Next Block Index | Padding | Object Data |
    -------------------------------------------

Here's my .h

#include <cstdint>
class FixedSizeMemoryPool
{
public:
    FixedSizeMemoryPool(const uint32_t objectSize, const uint32_t nObjects);
    ~FixedSizeMemoryPool();

    FixedSizeMemoryPool(const FixedSizeMemoryPool&)=delete;
    FixedSizeMemoryPool&operator=(const FixedSizeMemoryPool&)=delete;
    FixedSizeMemoryPool(FixedSizeMemoryPool&&)=delete;
    FixedSizeMemoryPool&operator=(FixedSizeMemoryPool&&)=delete;

    uint8_t* Alloc();
    void Free(void* data);

    const uint32_t GetCapacity() const;
    const uint32_t GetFreeBlockCount() const;
private:
    const uint32_t GetIndex(void* data) const;
    const uint32_t CalculatePadding(const uint32_t objectSize) const;
    uint32_t m_nFreeBlocks;
    uint32_t m_Capacity;
    uint32_t m_BlockSize;
    uint32_t m_PaddingSize;
    uint32_t m_NextFreeBlock;
    uint8_t* m_pData;
};

And the .cpp:

  FixedSizeMemoryPool::FixedSizeMemoryPool(const uint32_t objectSize,
                                         const uint32_t nObjects)
 : m_pData(nullptr), m_BlockSize(0), m_PaddingSize(0),
   m_Capacity(nObjects), m_nFreeBlocks(nObjects), m_NextFreeBlock(0)
{
    const uint32_t headerSize = sizeof(uint32_t);
    const uint32_t totalObjectSize = headerSize + objectSize;

    m_PaddingSize = CalculatePadding(totalObjectSize);
    m_BlockSize = totalObjectSize + m_PaddingSize;

    m_pData = new uint8_t[m_BlockSize * nObjects];

    //Set up the next free block
    for(unsigned int i = 0; i < nObjects; ++i)
    {
        uint8_t* hPtr = m_pData + (i * m_BlockSize);
        *((uint32_t*)hPtr) = i + 1;
    }
}

FixedSizeMemoryPool::~FixedSizeMemoryPool()
{
    delete[] m_pData;
}

uint8_t *FixedSizeMemoryPool::Alloc()
{
    if(m_NextFreeBlock == m_Capacity)
    {
        return nullptr;
    }

    uint8_t* ptr = m_pData + (m_NextFreeBlock * m_BlockSize);
    m_NextFreeBlock = *((uint32_t*)ptr);

    ptr += sizeof(uint32_t);
    ptr += m_PaddingSize;

    --m_nFreeBlocks;
    return ptr;
}

void FixedSizeMemoryPool::Free(void* data)
{
    uint8_t* pData = (uint8_t*)data - m_PaddingSize - sizeof(uint32_t);
    *((uint32_t*)pData) = m_NextFreeBlock;
    m_NextFreeBlock = GetIndex(data);
    ++m_nFreeBlocks;
}

const uint32_t FixedSizeMemoryPool::GetIndex(void *data) const
{
    return ((uint8_t*)data - m_pData) / m_BlockSize;
}

const uint32_t FixedSizeMemoryPool::CalculatePadding(
    const uint32_t objectSize) const
{
    //Check the object size is a power of 2
    if((objectSize & (objectSize - 1)) != 0)
    {
        //Get next highest power of 2
        uint32_t paddingSize = 0;
        paddingSize  = objectSize - 1;
        paddingSize  |= m_PaddingSize >> 1;
        paddingSize  |= m_PaddingSize >> 2;
        paddingSize  |= m_PaddingSize >> 4;
        paddingSize  |= m_PaddingSize >> 8;
        paddingSize  |= m_PaddingSize >> 16;
        ++paddingSize ;

        paddingSize  = paddingSize  - objectSize;
        return paddingSize;
    }
    return 0;
}

const uint32_t FixedSizeMemoryPool::GetCapacity() const
{
   return m_Capacity;
}

const uint32_t FixedSizeMemoryPool::GetFreeBlockCount() const
{
    return m_nFreeBlocks;
}


texts:
This is a project I came up just as an exercise with to familiarize myself with Python syntax and data types. I am just learning how to code and would like to avoid establishing bad habits. On the other hand, I wanted this program to function so when I found something that worked, I left it as is, even if I suspected that there might be a better way. Any suggestions on how to improve the code would be greatly appreciated.

import feedparser
import nltk
import random

# idea is to scrape headlines from RSS feed and make new headlines
# using words from original headlines and mimicking the syntax of original headlines

#scrape titles into scrptitles list

scrptitles=[]
data = feedparser.parse('http://rss.cnn.com/rss/cnn_topstories.rss')
for entry in data.entries:
   data = entry.title
   scrptitles.append(data)

#tokenize and tag

toks = [(nltk.pos_tag(nltk.word_tokenize(title))) for title in scrptitles]

# create list of dictionaries from list of tuples
# [{'Word':'TAG',...headline structure...},]

d_list = [dict(toks[1]) for toks[1] in toks]

# remove unwanted characters from d_list ['``',"''",'>','.',',','']

nonetype_list = ['``',"''","'",'>',',','.','|','(',')','-   ','_','=','+','<','@','#','$',"%",'^','*','[',']','{','}',":",";"]

for dicts in d_list:
    for item in nonetype_list:
        if item in dicts:
            del dicts[item]

    # create list of tags perserving headline structure

tags_list =  [dict.values() for dict in d_list]

    # get a clean version of the tags list

tags_list = [[element for element in dict_values] for dict_values in tags_list]

    # reverse dictionaries inside of list of dictionaries
    # inv_map = {TAG: [list of words]}

inv_map = {}
for dct in d_list:
    for k, v in dct.items():
        inv_map[v] = inv_map.get(v,[])
        inv_map[v].append(k)

    # grab a headline_pattern, choose random words from dictionary values,
    # print out new headline

headline_pat = (random.choice(tags_list))

new_headline = [random.choice(inv_map[item]) for item in headline_pat]

for item in new_headline:
   print(item.upper(), end=' ')

 ### ----> 2 WAYS TO REFINANCE CREDIT IN WHITESPLAINING


texts:
I created a class to operate with concrete table and I want to generalize this code to develop more universal class.

Here is one method of this class:

public void FillColumns(DataTable table, OracleDataReader reader)
{
  if (reader != null)
    if (reader.HasRows)
    {
      table.Rows.Clear();
      while (reader.Read()) table.Rows.Add
          (
            reader["ColumnName1"],
            reader["ColumnName2"],
            reader["ColumnName3"],
            reader["ColumnName4"]
          );
    }
}

How can I refactor this concrete method, to make concrete column names as input parameters (even independing of number of columns)?


texts: Generic wrapper for Alamofire Request's function jsonResponse wrapper

texts:
I am trying to wrap a responseJSON function of a Request class of Alamofire because when I send an API request I get a response in a specific pattern. I have achieved this, but I am still not satisfied with it. I can see much code repeated in both "handle" functions. One is for handling an array of Mappable type and the other is just a single Mappable type. How can I make this code better?

//
//  AlamofireRequestExtension.swift
//  DartsCool
//
//  Created by Dari on 11/22/16.
//  Copyright © 2016 Ekbana Solutions Pte. Ltd. All rights reserved.
//

import Foundation
import ObjectMapper
import Alamofire
import SwiftyJSON

extension Request {
    func handle<T: Mappable>(completion: (T, Pagination?) -> Void, failure: NSError -> Void) {
        self.validate(statusCode: 200 ..< 411).responseJSON { (response) in
            switch response.result {
            case .Success(let value):
                switch response.response?.statusCode {
                case 200?:
                    let json = JSON(value)
                    if let data: T = json["data"].map() {
                        let pagination: Pagination? = json["pagination"].map()
                        completion(data, pagination)

                    }
                default:
                    break
                }
                break

            case .Failure(let error):
                failure(error)
                break

            }
        }
    }

    func handle<T: Mappable>(completion: ([T], Pagination?) -> Void, failure: NSError -> Void) {
        self.validate(statusCode: 200 ..< 411).responseJSON { (response) in
            switch response.result {
            case .Success(let value):
                switch response.response?.statusCode {
                case 200?:
                    let json = JSON(value)
                    if let data: [T] = json["data"].map() {
                        let pagination: Pagination? = json["pagination"].map()
                        completion(data, pagination)
                    }
                default:
                    break
                }
                break

            case .Failure(let error):
                failure(error)
                break

            }
        }
    }

}

extension JSON {
    func map<T: Mappable>() -> [T]? {
        let json = self.arrayObject
        let mapped = json?.map{Mapper<T>().map($0)!}
        return mapped
    }

    func map<T: Mappable>() -> T? {
        return Mapper<T>().map(self.object)
    }
}


texts: Review: Finished router class for custom mini framework

texts:
I have finished my router and would like your thoughts on anything that may be inefficient of could be done better!:

class Router {

public $start_page = 'Dashboard' ; // Change to your home/default page.
public $staticRoutes = array(
    'alias' => 'ActualController',
) ;

function __construct()
{
    $url = substr(rtrim($_SERVER['REQUEST_URI'], '/'), 6) ;
    if($url)
    {
        $components = explode('/', $url, 3) ;
        if(array_key_exists($class, $this->staticRoutes))
        {
            $class = $this->staticRoutes[$class] ;
        } else {
            $class = preg_replace('/[^a-z-]/', '', $components[0]) ;
        }

        if(class_exists($class))
        {
            if(isset($components[1])) // has method...
            {
                $method = preg_replace('/[^a-z-]/', '', $components[1]) ;
                if(method_exists($class, $method))
                {
                    if(isset($components[2])) // has params...
                    {
                        $params = explode('/', $components[2]) ;
                        call_user_func_array(array($class, $method), $params) ;
                    } else {
                        $controller = new $class ;
                        $controller->$method() ;
                    }
                } else {
                    $e = 'Method '.$components[1].' does not exist.' ;
                    new Error(array('msg' => $e), 'Method Error') ;
                }
            } else { // No method so just go to default index if exists...
                $controller = new $class ;
                if(method_exists($controller, 'index'))
                {
                    $controller->index() ;
                } else {
                    $e = 'Class '.$class.' has no default index method.' ;
                    new Error(array('msg' => $e), 'Class Index Error') ;
                }
            }
        } else {
            $e = 'Class '.$components[0].' does not exist.' ;
            new Error(array('msg' => $e), 'Class Error') ;
        }
    } else {
        $controller = new $this->start_page ;
        $controller->index() ;
    }
}

}

Note that I have not implements the static routes functionality yet.


texts: Count of category occurances (multiple cateogries can fall under each row)

texts:
I want to get a count of each of the category occurrences (in how many rows did it show up in under the taxonomy column). The taxonomy column has a list of categories and I have several thousand rows, and I want to get a count of the number of times the categories shows up. Please note that there could be multiple categories per row but the same category will not be repeated in the same cell.

Is there a way to condense or clean the following code when running through a dataframe? I want to combine the if statements somehow without losing the logic.

for index, row in df.iterrows():
    for key in (row['taxonomy'] ) :

        if key in technical_issues_list:
            technical_issues += 1

        if key  ==    'technical_issues' :
            technical_issues_specific += 1

        if key == 'product_not_available':
            product_not_available += 1

        if key == 'site_performance':
            site_performance += 1

        if key in checkout_list:
            checkout += 1

        if key == 'unable_to_checkout':
            unable_to_checkout += 1

        if key == 'unable_to_add_or_remove_products':
            unable_to_add_or_remove_products += 1

        if key == 'promotions':
            promotions += 1

        if key == 'payment_options':
            payment_options += 1

        if key == 'paypal':
            paypal += 1

        if key == 'shipping_cost':
            shipping_cost += 1

        if key == 'order_total_wrong':
            order_total_wrong += 1

        if key == 'backorder':
            backorder += 1

        if key == 'address_not_fitting_or_incorrect':
            address_not_fitting_or_incorrect +=1

        if key in fulfillment_list:
            fulfillment += 1

        if key == 'where_is_my_order':
            where_is_my_order += 1

        if key == 'BOPIS':
            BOPIS += 1

        if key == 'delivery_issues':
            delivery_issues += 1

        if key == 'no_communication_or_delays':
            no_communication_or_delays += 1

        if key == 'damaged_product':
            damaged_product += 1

        if key == 'unassembled_assembly_issues':
            unassembled_assembly_issues += 1

        if 'customer service' == key:
            customer_service += 1
        if 'long-wait_times' == key:
            long_wait_times +=1
        if 'contact_issues' == key:
            contact_issues +=1
        if 'canada_related'  == key:
            canada_related +=1
        if 'product + info' == key:
            product_info += 1
        if 'design issues' == key:
            design_issues += 1
        if 'gift_wrapping' in key:
            gift_wrapping +=1
        if  'stores' == key:
            store += 1
        if  'email' == key:
            email += 1
        if  'suggestions' == key:
            suggestions +=1
        if 'rewards' == key:
            rewards +=1
        if  'registry' == key:
            registry += 1
        if  'returns_cancellations' in key:
            returns_cancellations +=1


texts: Should i throw exceptions in the service layer or repository, and catch it on the controller?

texts:
I read some answers here on stack exchange, but none really "hits the nail on the head" about where to throw exceptions, where I shouldn't and where to catch them.
the idea that an exception should be thrown in exceptional cases is very vague, for example, if I can't find a user in my data source (repository) I can't continue the flow of my code, can this be considered exceptional?
I also understand that there are caveats about flow control with exceptions, for me it does not seem right to use try/catch within the service, to catch all the exceptions that a repository/adapter/whatever may throw to control what to do next.
based on this, a code example with a "service" and a controller calling the service and catching all of the service exceptions:
Service:
class CheckUserUltraSecretInformation
{

    public function __construct(
        private CachedUserDataRepository $cachedDataRepository,
    )
    {
    }

    public function handle(string $document)
    {
        $cachedUserData = $this->cachedDataRepository->findByDocument($document);

        if (empty($cachedUserData)) {
            throw new CachedUserDataNotFoundException('User Cached information not found, cannot proceed');
        }

        if ($cachedUserData->hasExpired()) {
            throw new CachedUserDataHasExpiredException('Cached user data is expired');
        }
        // return ultra secret information
    }
}

Controller:
class UserSecretInformationController
{

    public function __construct(
        private CheckUserUltraSecretInformation $checkUserUltraSecretInformation)
    {
    }

    public function checkUserInformation(Request $request)
    {
        $document = $request->input('document');

        try {
            $userUltraSecretInformation = $this->checkUserUltraSecretInformation->handle($document);
        } catch (CachedUserDataNotFoundException $exception) {

            // return json response with http code 400

        } catch (CachedUserDataExpiredException $exception) {
            //returns json response with http code 500
        }
    }
}

Is it "correct" that my repository does not throw exceptions, and only returns null/false when it cannot return an entity? if not, what is the problem?

if my repository throws exceptions, should my service capture them and re-launch them as service exceptions? is this considered flow control?

Are the outer layers the "most correct" to capture and handle exceptions? in my example the controller is used, can It know the name of the services/use-cases exceptions?


texts: JMS configuration -- client exclusive messages

texts:
I am SURE this is somehow easy but reading the docs isn't bringing it to light.

The problem: I am trying to setup a JMS message listener and what I need is for the first client to have exclusive message processing rights.

That is: Until a single client acknowledges the message the server will not notify any other consumers of the message.

I believe this is correct but I am looking for some verification. The whole 'transacted' part is throwing me off

As an aside: I posted it to regular SOF and got told to repost here.

  public class QueueMessengerMessageListener implements MessageListener {

    protected Logger log = LoggerFactory.getLogger(getClass());

    private Connection connection;

    @Autowired
    private Queue q;

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private DWHService dwhService;

    @PostConstruct
    private void listen() throws JMSException {
        connection = connectionFactory.createConnection();
        Session jmsSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = jmsSession.createConsumer(q);
        consumer.setMessageListener(this);
        connection.start();
    }

    @PreDestroy
    public void destroy() throws JMSException {
        connection.close();
    }

    @Override
    @Transactional
    public void onMessage(Message m) {
        BytesMessage jmsMessage = (BytesMessage) m;
        MyObject userMessage = null;
        try {
            byte[] in = new byte[(int) jmsMessage.getBodyLength()];
            jmsMessage.readBytes(in);
            ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(in));
            userMessage = (MyObject) inStream.readObject();
            dwhService.addDwhEntry(userMessage);
            m.acknowledge();

        }
         catch (Exception e) {
            /* I normally wouldn't catch *all* exceptions, but the JMS tutorial says Thou Shalt Not throw
             * a RuntimeException from this method. */
             log.error("Error sending message {}",  e.getMessage());
        }
    }
}


texts: Create Excel file multiple times with different names

texts:
I want to create a new Excel files from an Apache POI object. The filename should contain the standard name, the current date and a counter, if necessary, to prevent collisions. I have a working solution here:

private File createFile() throws FileNotFoundException, IOException {
    LOG.debug("Create File");
    DateFormat df = new SimpleDateFormat("ddMMyyyy");
    Date d = new Date(System.currentTimeMillis());
    while (true) {
        File f = new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + ".xlsx");
        File f2 = new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + " ("
                + fcounter + ").xlsx");
        if (!f.exists()) {
            try (FileOutputStream outputStream = new FileOutputStream(
                    "C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + ".xlsx")) {
                wb.write(outputStream);
                outputStream.close();
                wb.close();
                return f;
            } catch (Exception e) {
                LOG.debug(e.toString());
            }
        } else if (!new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + " ("
                + fcounter + ").xlsx").exists()) {
            try (FileOutputStream outputStream = new FileOutputStream("C:\\Users\\" + filepath
                    + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + " (" + fcounter + ").xlsx")) {
                wb.write(outputStream);
                outputStream.close();
                wb.close();
                return f2;
            } catch (Exception e) {
                LOG.debug(e.toString());
            }
        }
        fcounter++;
    }
}

Is there an existing solution or a shorter way to do it? I think my code is very long for such a task.


texts:
So this is the code I wrote for hangman in python. I want to know of can shorten this code more further and make it look more professional

# importing random function
import random, hanged
from word_meaning import meanings

# Dictionary of random words
word_dict = '''whistle,
park,
picayune,
attach,
grubby,
gusty,
neck,
necessary,
day,
compete,
memory,
interfere,
sophisticated,
lumpy,
spiky,
frail'''.split(',\n')

# System chooses a random word
rand_word = word_dict[random.randint(0, len(word_dict)-1)]

print('Welcome to HANGMAN.\nGuess correct letters to complete the hidden word, Else hangman will be Hanged')

n = len(rand_word)
hidden_word = ((n-1)*'*')
hidden_word_1 = hidden_word.split('*')
print(f'Hidden Word: {hidden_word}*')
print(f'Hint: {meanings[str(rand_word)]}')
#This is the dictionary imported from another file. it gives the meaning of the hidden word as a hint

chances = 10

def user_lose():
    global chances
    print(f'Oops wrong guess\n Chances Left : {chances - 1}')
    if chances > 1:
        chances -= 1
        user_guess()
    else:
        hanged.hangman()
#hanged.Hangman() this is the function which shows pic of hangman. imported from another file

def user_guess():
    global chances
    if '' in hidden_word_1:
        user_input = str(input('\nGuess a letter: ')[0]).lower()
        if user_input in rand_word:
            if user_input in hidden_word_1:
                user_lose()
            else:
                if chances > 0:
                    letter_index = rand_word.index(user_input)
                    letter_index_r = rand_word.rindex(user_input)
                    hidden_word_1[letter_index] = user_input
                    hidden_word_1[letter_index_r] = user_input
                    print(hidden_word_1)
                    user_guess()

        else:
            user_lose()

    else:
        print('Hurrah, You saved Hangman')

user_guess()

hanged.py file

def hangman():
    print('''You could not save hangman\n
                                   -------------------
                                   |         |
                                   |         |
                                   |         |
                                   |      ( ` ` )
                                   |         |
                                   |        /|\\
                                   |       / | \\
                                   |         |
                                   |        / \\
                                   |       /   \\
                                   |
                                   |
                                   |
                                   |                 ''')


texts:
I was recently working on a project, something jQuery-related for WP-Admin area.

I enable post-formats and create metaboxes for these post-formats, so at the end I tried to hide these metaboxes until the user checks the radio button. I just want to know if there is a better way I can write this code.

// hide the metabox at start
$('#gallery-box').hide();

// fetch the id name of checked post-format
var idName = $('input.post-format:checked').attr('id');

// display the metabox if the fetched value matched
if ( idName === 'post-format-gallery' ) {
    $('#gallery-box').show();
}

// show or hide
$('.post-format').click(function(){
    idName = $(this).attr('id');
    if ( $(this).is(':checked') ) {
        if ( idName === 'post-format-gallery' ) {
            $('#gallery-box').show();
        } else {
            $('#gallery-box').hide();
        }
    }
});


texts: Fractional Knapack as asked in an interview

texts:
Description:

  Given the Knapsack capacity and the weight and value of some items,
  find a way to maximize the value in the given Knapsack.

Code:

/* Name of the class has to be "Main" only if the class is public. */
class Main
{
    public static float KnapSack(float capacity, PriorityQueue<Pair> queue) {
        float val = 0;
        while (queue.size() > 0) {
            if (capacity == 0) return val;
            Pair max = queue.poll();
            float a = Math.min(max.weight, capacity);
            val += a * (max.value / max.weight);
            if (max.weight - a > 0) // to prevent division by zero
                queue.add(new Pair(max.value, max.weight - a));
            capacity -= a;
        }
        return val;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Comparator<Pair> comparator = new FractionComparator();
        PriorityQueue<Pair> queue   = new PriorityQueue<Pair>(3, comparator);
        queue.add(new Pair(20, 4));
        queue.add(new Pair(18, 3));
        queue.add(new Pair(14, 2));
        System.out.println(KnapSack(7, queue));
    }
}

// Degenerate value class
class Pair {
    final float value;
    final float weight;

    Pair(float value, float weight) {
        this.value  = value;
        this.weight = weight;
    }
}

class FractionComparator implements Comparator<Pair>
{
    @Override
    public int compare(Pair p1, Pair p2)
    {
        if ((p2.value / p2.weight) < (p1.value / p1.weight)) return -1;
        if ((p2.value / p2.weight) > (p1.value / p1.weight)) return  1;
        return 0;
    }
}

Question:

From interview perspective what may raise eyebrows of an interviewer?

Having said that personally I am interested in readability and reducing code redundancy, the one thing where I am feeling uncomfortable is Pair class although I made it for readability but for changing even a field name I have to d changes in many places.

Last but not the least I think some knowledge about scope and visibility would be good.


texts:
In order to perform form validation, I have created a custom object:

define(["jquery", "validate", "activities/new/common/components/BaseFormdata"],
    function($, Validate, BaseFormData){

    var FormData = function(options){

        this.defaults = {
            name: "",
            privacy: "",
            price: "",
            short_description: "",
            long_description: ""
        };

        //Constraints to be used by the validation library
        this.constraints = {
            name: {
                presence: true,
                length: { maximum: 100, minimum: 1 }
            },
            privacy: {
                presence: true
            },
            short_description: {
                short_description: true,
                length: { maximum: 20 }
            },
            max_description: {
                length: { maximum: 1000 }
            }
        };

        this.formData = $.extend({}, this.defaults, options);

    };

    //Inherit from the BaseFormData component
    FormData.prototype = new BaseFormData();

    return FormData;
});

The base FormData object:

define(["underscore", "validate"], function(_, Validate){

    //Defines a Base FormData object that modules can use to inherit from
    function BaseFormData(){};

    /*@param:
     * object containing to be validated properties
     * @return:
     * Success returns false (no error), Error returns an error object
     */
    BaseFormData.prototype.validateProperties = function(objToValidate){

        var constraints = this.getConstraints(objToValidate);

        var status = validate(objToValidate, constraints, {format: "detailed"});
        if(status === undefined){
            //There is no error
            for(var key in objToValidate){
                if (this.formData.hasOwnProperty(key)) {
                    //Set the value on the this.formData object
                    this.setProperty(key, objToValidate[key]);
                };
            };
            //Return no error
            return false;

        } else {
            //An error object is returned
            return status;
        }
    };

    //Set property on object
    BaseFormData.prototype.setProperty = function(key, value){
        this.formData[key] = value;
    };

    //Get relevant constraints from constraints object
    BaseFormData.prototype.getConstraints = function(objToValidate){
        //Get keys in array
        var arrKeys = _.allKeys(this.constraints);
        var constraints = {};
        _.each(arrKeys, _.bind(function(key){
            if(objToValidate.hasOwnProperty(key)){
                constraints[key] = this.constraints[key];
            };
        }, this));

        return constraints;
    };

    return BaseFormData;
});

Is it bad practice to set the form properties immediately on the FormData object? Currently, I have per form one custom FormData object that inherits from the Base FormData object, for which I have set custom properties depending on the form components.

I wonder if it would be better to inject the form fields as a collection of objects in a single FormData object (instead of creating one for each form); this would allow me to define only the base FormData object, but it would require the calling function to also send the constraints along (which is in my case a presenter object that coordinates between the different views that manage the form).

Which is the best approach architectural-wise?


texts: Creating a PowerPoint in vba by calling "slide" subroutines

texts:
I am creating a powerpoint in VBA, but there are a lot of slides in it.

I was thinking I could create a macro that calls a lot of subroutines. Within those subroutines, the actual "slide code" would run. However, I have only created powerpoints where all of the code was in the same subroutine.

I took a shot at it and the below code creates what I want.

My question is, Public and Private variables and the use of "Dim". Would it be bad code if I put all of this in one module and use a bunch of subroutines? Or should I separate over modules? I would prefer to do that so I do not have to define each variable such as ppSlide and ppPres, but open to any suggestions. I am mainly looking for ideas on how to set this up.

Public ppApp As PowerPoint.Application
Public ppPres As PowerPoint.Presentation
Public ppSlide As PowerPoint.Slide

sub CreatePres()
Dim ppTextbox As PowerPoint.Shape
Dim slidesCount As Long
Set ppApp = New PowerPoint.Application
ppApp.Visible = True
ppApp.Activate

Set ppPres = ppApp.Presentations.Add
slidesCount = ppPres.Slides.Count
Set ppSlide = ppPres.Slides.Add(slidesCount + 1, ppLayoutTitle)
ppSlide.Shapes(1).TextFrame.TextRange.Text = "Hello world"
ppSlide.Shapes(2).TextFrame.TextRange.Text = Date
slidesCount = slidesCount + 1

Call slide2(slidesCount)

End Sub

Sub slide2(i As Integer)
'Insert CPR speeds Chart and Table --- slide 2
Set ppSlide = ppPres.Slides.Add(i+ 1, ppLayoutBlank)
ppSlide.Select
Worksheets("Sheet1").Activate
ActiveSheet.Range(Cells(1, 4), Cells(2, 9)).Copy
ppSlide.Shapes.Paste.Select
ppSlide.Shapes(1).Width = _
    (ppPres.PageSetup.SlideWidth / 2)
ppSlide.Shapes(1).Left = _
    (ppPres.PageSetup.SlideWidth / 4)
ppSlide.Shapes(1).Top = _
    4 * (ppPres.PageSetup.SlideHeight / 5)

ActiveSheet.ChartObjects("Chart1").Activate
ActiveChart.ChartArea.Copy
ppSlide.Shapes.Paste.Select
ppSlide.Shapes(2).Height = _
    3 * (ppPres.PageSetup.SlideHeight / 5)
ppSlide.Shapes(2).Width = _
    5 * (ppPres.PageSetup.SlideWidth / 7)
ppSlide.Shapes(2).Left = _
    (ppPres.PageSetup.SlideWidth / 7)
ppSlide.Shapes(2).Top = _
    (ppPres.PageSetup.SlideHeight / 10)

End sub


texts: Querying the probability of choosing even or odd elements in a subarray

texts:
I have written a code where I have an array and I need to print the probability of picking an even/odd number in the given range in the array.

If probability is 0 or 1, I have to print so. And if the probability is say 2/4, I have to reduce it to minimal form and print the output as "1 2" which means 1/2. I have written the below code which handles all these perfectly. But it is taking more than 3 seconds to execute so it is resulting in a timeout as the given time limit is 3 seconds for this.

How do I optimize this further?

#include<stdio.h>
int gcd(int u,int v)
{
int shift;
if(u==0) return v;
if(v==0) return u;
shift = __builtin_ctz(u | v);
u >>= __builtin_ctz(u);
do {
    v >>= __builtin_ctz(v);
    if(u>v) {
        unsigned int t=v;
        v=u;
        u=t;
    }
    v = v-u;
} while(v!=0);
return u << shift;
}
void query(char *arr, int qtype, int l, int r, char v)
{
int q=r-l+1;
int g1=1,g2=1;

int peven=0,podd=0;
for(int i=l-1;i<r;i++)
{
    if(qtype==2 && v)
        arr[i]=(arr[i]^v);
    if(qtype == 1)
    {
        if(arr[i])
        podd++;
    }
    else if(qtype == 0)
    {
        if(!(arr[i]))
        peven++;
    }
}

switch(qtype)
{
case 0:
{
    if(peven == 0)
        printf("0\n");
    else if(peven == q)
        printf("1\n");
    else
    {
        g1=gcd(peven,q);
        if(g1!=1)
        {
            peven/=g1;
            q/=g1;
        }
        printf("%d %d\n",peven,q);
    }
    break;
}

case 1:
{
    if(podd == 0)
        printf("0\n");
    else if(podd == q)
        printf("1\n");
    else
    {
        g2=gcd(podd,q);
        if(g2!=1)
        {
            podd/=g2;
            q/=g2;
        }
        printf("%d %d\n",podd,q);
    }
    break;
}
default:
    break;
}

}

int main()
{
int T;

scanf("%d",&T);

while(T--)
{
    int arr_size;
    scanf("%d",&arr_size);

    int q;
    scanf("%d",&q);

    char *arr=(char *)malloc(arr_size * sizeof(char));
    for(int i=0; i<arr_size;i++)
    {
        int x;
        scanf("%d",&x);
        arr[i]=(char)(x&1);

    }
    while(q--)
    {
        int qtype,l,r;
        char v;

        scanf("%d%d%d",&qtype,&l,&r);

        if(qtype==2)
        {
            int y;
            scanf("%d",&y);
            v=(char)(y&1);

        }

        query(arr,qtype,l,r,v);
    }
    free(arr);
}
return 0;
}

  Format of the input file:

  First line : T i.e Number of testcases.
  For each testcase:

  First line : Two space separated integers N and Q.
  Second line : N space separated integers denoting the array.
  Next Q lines ; Space separated integers representing a query.

  Queries can be:

  0 L R :- You have to find and print the probability of choosing an even number from the segment [L,R] (both Inclusive).
  1 L R :- You have to find and print the probability of choosing an odd number from the segment [L,R] (both Inclusive).
  2 L R K :- You have to add number K to all the elements in the range, changing the values for subsequent queries

  Format of the output file:

  Output the answer to each query in a separate line.

  Constraints:

  1<= N,Q,K <= 1000000

  Sample input;

1
5 3
6 5 2 1 7
0 2 2
2 2 5 3
1 2 5

  Sample Output:

0
1 4

  Explanation: For query 3 numbers in the range [2,5] are {8,5,4,10}
  Hence probability of choosing a odd number is 1/4.


texts: Jquery field add code - Improvements in readability, compactness or efficiency

texts:
I've worked hard on this code and it functions exactly as I wanted, but I've been told it is a little bit unreadable. My focus is to get the code as clean as possible, and have things as efficient as possible.

This is the code I am working with:
http://jsfiddle.net/xT5X5/6/

//latest
var maxFields = 10;

$('.form').on('click', '.add', function () {
      var value_src = $(this).prev();
       var container = $(this).parent().prev();
    if ($.trim(value_src.val()) !== '') {
        if (container.children().length < maxFields) {
            var value = value_src.val();
            var html = '
' +
                '<input class="accepted" type="text" value="' + value + '" />' +
                '<input type="button" value="X" class="remove" />' +
                '
';

            $(html).appendTo(container);
            value_src.val('');
        } else {
            alert("You tried to add a field when there are already " + maxFields);
        }
    } else {
        alert("You didn't enter anything");
    }

})
    .on('click', '.remove', function () {
       $(this).parents('.line').remove();
});

$(".current").keyup(function(e) {
    if (e.which == 13) {
        $(this).next("input").trigger("click");
    }
});

$(document).on("keyup",".accepted",function(e) {
    if (e.which == 13) {
        $(this).closest('.copies').next().find(".current").focus();
    }
});

Can anyone give me any pointers on how I've done, and if there are any improvements that you can spot. Any feedback would be much appreciated!

Thank you.


texts: Ensuring non-expired token before every request

texts:
I'm developing an iOS application where data is fetched from a third-party REST API. Each request must contain an authorization token.

In order to implement this, I've written a fetchToken withCompletionBlock:(void (^)(ASToken*) token,NSError * error) method in AppDelegate:

-(void) fetchTokenWithCompletionBlock:(void (^)(ASToken * token, NSError * error)) completionBlock
{
    if (!_token) {
        _token = [self retrieveTokenFromKeychain];
    }

    if (!_token || _token.isExpired) {
        [ASMyApi loadTokenWithcompletionBlock:^(ASToken *token, NSError*  error) {

            if (token) {
                _token = token;
                [self saveTokenToKeychain: token];
            }else{
                completionBlock(nil,&error);
            }

        }];
    }else{
        completionBlock(_token,nil);
    }
}

Before every requests that requires Authorization, fetchToken withCompletionBlock:(void (^)(ASToken*) token,NSError ** error) is called to retrieve the token. Here's an example:

-(IBAction) loadCategories
{
    [self.refreshControl beginRefreshing];
    [((AppDelegate *)[UIApplication sharedApplication].delegate) fetchTokenWithCompletionBlock:^(ASToken *token, NSError *error) {

        if (token) {
            [ASMyApi loadCategories:token.token completionBlock:^(NSArray *categories, NSError *error) {

                [self.refreshControl endRefreshing];

                if (categories){

                    self.categories = categories;

                }else{

                    [self monitorNetworkReachability];

                }

                [self updateUI];

            }];

        }else{

            [self.refreshControl endRefreshing];
            [self monitorNetworkReachability];
        }

    }];
}

I'm not happy with this code for the following reasons:

The nested nature of the callbacks makes it look ugly and somewhat unreadable
Too much repetition: The code to get the token is verbose and must be called before each request. The failure code is also repeated.

What I do like about this approach is that it ensures that there's always a valid token before sending the request (as opposed to having the request fail, and then requesting a new token).

I'd appreciate a second-opinion on this design and input on how it might be refactored.


texts:
This is a simulation of animal skins, like a cellular automat. I'd like it improved.

#Create Matrix with random numbers 0/1 with a 50% chance
createMatrix <- function(br,gen) {
mat <- matrix(rbinom(br*gen,1,0.5),br,gen)
    return(mat)
}

nextMatrix <- function(mat,w) {

    #Make that Matrix continuous
    wideMatrix <- cbind(mat,mat,mat)
    bigMatrix <- rbind(wideMatrix,wideMatrix,wideMatrix)

    newMat <- mat

    for(j in 1:nrow(mat)){
        for(i in 1:ncol(mat)){
            act <- sum(bigMatrix[(197+j):(203+j),(197+i):(203+i)]) #radius of 3
            inh <- sum(bigMatrix[(195+j):(206+j),(195+i):(206+i)])*w #radius of 6
            if(act>inh) { newMat[j,i] <- 1 }
            if(act<inh) { newMat[j,i] <- 0 }
        }
    }
    return(newMat)
}

x<- createMatrix(200,200)

for(i in 1:5) {
    x <- nextMatrix(x,0.33)
}

image(x, axes=FALSE,col = c("black","darkgoldenrod"))

In particular, the part where I sort out the part with the radius within a matrix:

 act <- sum(bigMatrix[(197+j):(203+j),(197+i):(203+i)])
 inh <- sum(bigMatrix[(195+j):(206+j),(195+i):(206+i)])*w

Is there any package I could use to get a "real radius" (it is a quadrat in my example)?


texts: Partial Function composability in Haskell

texts:
Below is my solution for the CTFP chapter 4 challenges which essentially involves composing partial functions (that don't have defined outputs for all possible inputs i.e. returning a Maybe).
The challenge is to implement composition, identity(to satisfy category requirements) and try it out with 2 partial functions. As I'm relatively new to Haskell, I was hoping to get a general code review with suggestions on better idioms and testing I could follow. Link to Code
import Test.HUnit

module Main where

-- Given
safeRoot :: Double -> Maybe Double
safeRoot x
  | x < 0     = Nothing
  | otherwise = Just (sqrt x)

-- Q1: Identity and composition
partialFnId :: a -> Maybe a
partialFnId x = Just x

partialFnCompose :: (b -> Maybe c) -> (a -> Maybe b) -> (a -> Maybe c)
partialFnCompose g f = \x -> case (f x) of
                          Just value -> g value
                          Nothing -> Nothing

-- Testing Q1
testPartialFnMeetsCategoryRequirements1 = TestCase $ assertEqual "Id should pass through inputs" (Just 3) (partialFnId 3)
testPartialFnMeetsCategoryRequirements2 = TestCase $ assertEqual "Composition with identity is noop(1)" (Just 2.0) ((partialFnCompose partialFnId safeRoot) 4)
testPartialFnMeetsCategoryRequirements3 = TestCase $ assertEqual "Composition with identity is noop(2)" (Just 2.0) ((partialFnCompose safeRoot partialFnId) 4)

-- Q2: Implement safeReciprocal
safeReciprocal :: Double -> Maybe Double
safeReciprocal x
  | x == 0    = Nothing
  | otherwise = Just (1 / x)

-- Q3: Implement safeRootReciprocal via composing the above 2.
safeRootReciprocal :: Double -> Maybe Double
safeRootReciprocal = partialFnCompose safeRoot safeReciprocal

-- Testing Q3
testSafeRootReciprocal1 = TestCase $ assertEqual "Provides root of reciprocal for valid inputs" (Just 2.0) (safeRootReciprocal 0.25)
testSafeRootReciprocal2 = TestCase $ assertEqual "Provides Nothing on invalid inputs(1)" Nothing (safeRootReciprocal 0.0)
testSafeRootReciprocal3 = TestCase $ assertEqual "Provides Nothing on invalid inputs(2)" Nothing (safeRootReciprocal (-0.25))

main = do
  runTestTT $ TestList [testPartialFnMeetsCategoryRequirements1,
                        testPartialFnMeetsCategoryRequirements2,
                        testPartialFnMeetsCategoryRequirements3,
                        testSafeRootReciprocal1,
                        testSafeRootReciprocal2,
                        testSafeRootReciprocal3]


texts: Remove all occurrences of a digit from a number

texts:
I need to remove all occurrences of a digit from a number in a recursive function with this prototype:

unsigned rem(unsigned num, unsigned dig);

This is my solution:

#include <stdio.h>

// just returns 10 to the power of n
int power(int n)
{
    if (n==0)
        return 1;

    int res=1;

    for (int i=0; i<n; i++)
        res *= 10;

    return res;
}

static int i=0;

unsigned rem(unsigned num, unsigned dig)
{
    int tmp = power(i);

    if (num == 0)
        return 0;
    else
    {
        if (num%10 != dig)
        {
            i++;
            return (num%10)*tmp + rem(num/10, dig);
        }
        else
            return rem(num/10, dig);
    }

}

int main()
{
    unsigned n, res;

    scanf("%u", &n);

    res = n;

    for (int j=2; j<10; j+=2)
    {
        res = rem(res, j);
        // reset
        i=0;
    }

    printf("%u without even numbers: %u\n", n, res);
    return 0;
}

It works but I've read a lot about how a global static variable is not a good solution, so I was thinking if there is a way without it.

I've had other solutions (with a local static variable), but all fail when I need to call the function more than once.

Also, the only reason for using a static variable, is to keep tract of what the weight of the next digit of the result.


texts:
beginner web dev here.
I created a custom list component (with edit feature) in plain JS/HTML.

I have few questions on which I would like to get an answer (besides the normal feedback that you folks do here on the site):

is this a standard/right way to create and use components when using plain JS?
if I can create and use objects like this, what is the benefit of creating such component using say react.js?

ListComponent.js

///////
//
// ListComponent is a class which lets you create a list component
// dynamically using JS and DOM. The list component also has some features
// out of the box - e.g. editing items when clicked.
//
function ListComponent(type) {

    // Model data of the list.
    this.data = [{ name: "mona", id: 0 }, { name: "dona", id: 1 }, { name: "jona", id: 2 }],

    // Create a list component.
    this.create = function () {
        let list = document.createElement(!type ? "ul" : type);
        list.id = "customList";
        document.body.appendChild(list);
        this.draw();
    },

    this.remove = function () {
        // Remove our list component from DOM
        var elem = document.getElementById("customList");
        return elem.parentNode.removeChild(elem);

    }

    ///
    // draw
    //  Appends items to the list component.
    //  Deletes any child items first if there are any.
    //
    this.draw = function () {
        let that = this;

        // First delete all items of the list.
        let list = document.getElementById("customList");
        while (list.firstChild) {
            list.removeChild(list.firstChild);
        }

        // Now, append new items.
        that.data.forEach(function (item) {
            let listItem = document.createElement("li");

            // Listen to click event on this list item.
            listItem.addEventListener("click", function () {
                let newName = prompt("Enter item name", item.name);
                if (newName == null || newName.length == 0)
                    return;

                // Make change in the list model data.
                for (let i = 0; i < that.data.length; i++) {
                    if (that.data[i].id == item.id) {
                        that.data[i].name = newName;
                        break;
                    }
                }

                // Redraw the list.
                that.draw();
            }, false);

            listItem.innerHTML = item.name;
            listItem.id = item.id;
            list.appendChild(listItem);

        });
    }
}

index.html

<!doctype html>

<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Demo site</title>
    <!-- Import our list component -->
    <script src="ListComponent.js"></script>
</head>

<script>

    document.addEventListener("DOMContentLoaded", function (event) {
        // Run this code when DOM is loaded.
        let list = new ListComponent("ol");
        list.create();
    });

</script>

</body>

</html>


texts: Rock Paper Scissors Lizard Spock in JQuery

texts:
I wrote a little Javascript rock/paper/scissors/lizard/spock game and when the user clicks the button to make their choice from the five options, I choose the computer's randomly  and then compare the two to find a winner and output the result. It works, but I have the feeling that the findWinner function can be a lot shorter or more elegant. I'm trying to improve my Javascript and jQuery and was hoping for someone to help me with next steps here:.

function findWinner(choiceA,choiceB) {
  if (choiceA == choiceB) {
    return "It's a tie!";
  }

  if (choiceA == 'Rock') {
    if (choiceB == 'Lizard' || choiceB == 'Scissors') {
      return "You win!";
    }
    else if (choiceB == 'Spock' || choiceB == 'Paper') {
      return choiceB;
    }
  }
  else if (choiceA == 'Paper') {
    if (choiceB == 'Rock' || choiceB == 'Spock') {
      return "You win!";
    }
    else if (choiceB == 'Scissors' || choiceB == 'Lizard') {
      return "Computer wins :( ";
    }
  }
  else if (choiceA == 'Scissors') {
    if (choiceB == 'Paper' || choiceB == 'Lizard') {
      return "You win!";
    }
    else if (choiceB == 'Spock' || choiceB == 'Rock') {
      return "Computer wins :( ";
    }
  }
  else if (choiceA == 'Lizard') {
    if (choiceB == 'Paper' || choiceB == 'Spock') {
      return "You win!";
    }
    else if (choiceB == 'Rock' || choiceB == 'Scissors') {
      return "Computer wins :( ";
    }
  }
  else if (choiceA == 'Spock') {
    if (choiceB == 'Rock' || choiceB == 'Scissor') {
      return "You win!";
    }
    else if (choiceB == 'Paper' || choiceB == 'Lizard') {
      return "Computer wins :( ";
    }
  }
}

This just seems very repetitive, but I'm not sure where to go next with it.


texts: Conditional statements relating to hospital management

texts:
It works just fine, but is there any other way to write this shorter?

Nurses are only available to intensive care patients (room I) and TV's and telephones are only available to non intensive care patients (room D or room P). Also, X_COST has a value of 0.

if (room.equals("I")) { // if (room.equals("I"))

    roomCost = 395 * (double)days;
    //System.out.println(roomCost);
    TVCost = X_COST;
    //System.out.println(TVCost);
    phoneCost = X_COST;
    //System.out.println(phoneCost);

    if (nurse.equals("X"))

        nurseCost = X_COST;
        //System.out.println(nurseCost);

    else if (room.equals("N"))

        nurseCost = 250 * (double)days;
        //System.out.println(nurseCost);

    else

        nurseCost = 275 * (double)days;
        //System.out.println(nurseCost);

} // if (room.equals("I"))

else if (room.equals("P")) { // else if (room.equals("P"))

    roomCost = 350 * (double)days;
    //System.out.println(roomCost);
    nurseCost = X_COST;
    //System.out.println(nurseCost);

    if (TV.equals("V")) { // if (TV.equals("V"))

        TVCost = 40 * (double)days;
        //System.out.println(TVCost);

        if (phone.equals("T"))

            phoneCost = 15 * (double)days;
            //System.out.println(phoneCost);

        else

            phoneCost = X_COST;
            //System.out.println(phoneCost);

    } // if (TV.equals("V"))

    else { // else !(TV.equals("V"))

        TVCost = X_COST;
        //System.out.println(TVCost);

        if (phone.equals("T"))

            phoneCost = 15 * (double)days;
            //System.out.println(phoneCost);

        else

            phoneCost = X_COST;
            //System.out.println(phoneCost);

    }  // else !(TV.equals("V"))

} // else if (room.equals("P"))

else { // else

    roomCost = 310 * (double)days;
    //System.out.println(roomCost);
    nurseCost = X_COST;
    //System.out.println(nurseCost);

    if (TV.equals("V")) { // if (TV.equals("V"))

        TVCost = 40 * (double)days;
        //System.out.println(TVCost);

        if (phone.equals("T"))

            phoneCost = 15 * (double)days;
            //System.out.println(phoneCost);

        else

            phoneCost = X_COST;
            //System.out.println(phoneCost);

    } // if (TV.equals("V"))

    else {  // else !(TV.equals("V"))

        TVCost = X_COST;
        //System.out.println(TVCost);

        if (phone.equals("T"))

            phoneCost = 15 * (double)days;
            //System.out.println(phoneCost);

        else

            phoneCost = X_COST;
            //System.out.println(phoneCost);

    }  // else !(TV.equals("V"))

} // else


texts: Rails and Redis: how should I handle validation here?

texts:
I'm new to rails.  I am using Redis instead of something backed w/ ActiveRecord.  I need to validate the presence of location, categories, start_date, and end_date.  I then need to check that start_date and end_date are valid dates, that start_date comes before end_date.  And that location matches a regex [A-Za-z_].  And that categories.length > 0.  Since the start_date and end_date parameters in my model's setters are Date objects, should I check for valid dates and convert them in my controller.  Then have my model's setters take care of the rest of the validation?

I just don't know where to put the validations:  in my model or controller?

Model:

class MyThingie
  def self.set_x(location, categories, start_date, end_date, value)
    updates = {}
    for date in (start_date .. end_date)
      # ...
    end

    $redis.mset(*updates.flatten)
  end

  def self.set_y(location, categories, default)
    updates = {}
    for category in categories
      # ...
    end

    $redis.mset(*updates.flatten)
  end

  def self.set_z(location, categories, start_date, end_date, block)
    if block
      updates = {}
      for date in (start_date .. end_date)
        # ...
      end

      $redis.mset(*updates.flatten)
    else
      deletes = []
      for date in (start_date .. end_date)
        # ...
      end

      $redis.del(*deletes)
    end
  end
end

Controller:

class MyThingieController < ApplicationController
  # ...

  def create
    begin
      method = params[:method]
      location = params[:location]
      categories = params[:categories]
      s_start_date = params[:start_date]
      s_end_date = params[:end_date]

      if method == "normal"
        value = params[:value]

        start_date = Date.strptime(s_start_date, "%m/%d/%Y")
        end_date = Date.strptime(s_end_date, "%m/%d/%Y")

        MyThingie.set_x(location, categories, start_date, end_date, value)
      elsif method == "default"
        default = params[:default]

        MyThingie.set_y(location, categories, default)
      elsif method == "block"
        block = params[:block]

        start_date = Date.strptime(s_start_date, "%m/%d/%Y")
        end_date = Date.strptime(s_end_date, "%m/%d/%Y")

        MyThingie.set_z(location, categories, start_date, end_date, block)
      else
        raise "Invalid form submit"
      end
    rescue Exception => e
      errors = [e.message]
      respond_to do |format|
        format.json do
          json = Jsonify::Builder.new
          json.errors errors
          a = json.compile!
          render :status => 400, :json => a
        end
      end
    else
      respond_to do |format|
        format.json do
          json = Jsonify::Builder.new
          json.msg "Update successful."
          a = json.compile!
          render :json => a
        end
      end
    end
  end

Here the keys are like

mythingie:location:date = value

mythingie:location:default = default

mythingie:location:date:z = "true"


texts: Algorithm that creates in a systematic form, matrix with zero-one elements

texts:
I'm working on Rcpp and I wrote the following code
#include <RcppArmadilloExtensions/sample.h>
using namespace Rcpp;

// [[Rcpp::export]]

arma::mat SIZA(int K){

  arma::mat P;
  P.ones(K,K);
  P = trimatu(P);

  for(int idx=1; idx<K; ++idx){
  arma::mat W;
  arma::mat Hlp;

  W.ones(K-idx,K-idx);
  W = trimatu(W);
  W = join_horiz(W,Hlp.zeros(K-idx,idx));

  P = join_vert(P,W);
  }

  return P;
}

Essentially it creates matrices of the following form
SIZA(2)
     [,1] [,2]
[1,]    1    1
[2,]    0    1
[3,]    1    0

SIZA(3)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    0    1    1
[3,]    0    0    1
[4,]    1    1    0
[5,]    0    1    0
[6,]    1    0    0

SIZA(4)
      [,1] [,2] [,3] [,4]
 [1,]    1    1    1    1
 [2,]    0    1    1    1
 [3,]    0    0    1    1
 [4,]    0    0    0    1
 [5,]    1    1    1    0
 [6,]    0    1    1    0
 [7,]    0    0    1    0
 [8,]    1    1    0    0
 [9,]    0    1    0    0
[10,]    1    0    0    0

What I'm curious and interested in is finding a way to make this chunk of code quicker. But from my knowledge, I do not see an obvious way to achieve that. What I'm thinking is to avoid using the FOR LOOP but it seems to be necessary.
Any ideas would be great!


texts: Extract HTML tags and its content from a string

texts:
Goal

I want to extract HTML tags and its content from a string. The content (input) is queried from WordPress database.

Sample data (input)

I extract this dummy data from my WordPress database: https://www.phpliveregex.com/p/tan
I believe this should cover all the needed tags to parse.

Expectation (output)

Accepting a HTML-format string as input.
The output should be able to return a string which could be any of these:

The HTML element string itself
Attributes string of the HTML element
Text nodes, child nodes string of the HTML element

My concern

Which solutions take less execution time?
Which solutions save more server memory?
Security vulnerable of each solutions.

Solutions

I've come up with a 2 solutions by myself. It works fine, but I don't know which one is good for my case.

Regex pattern

$el = 'li'; // Ex
$match = []; // Reserving for results

/**
 * Regex - extract HTML tag and its content
 * Array map:
 * x[0] = everything
 * x[1] = open tag
 * x[2] = attributes
 * x[3] = content & end tag
 * x[4] = content only
 *
 * Note for content: including text node + children node
 */
$reg = '/(<'.$el.'(.*?)>)((\n*?.*?\n*?)<\/'.$el.'>|)/';

if (preg_match($reg, $html_str, $match)) { echo 'Moving onward!';}

Result: see demo of regex

DOM object

$dom = new DomDocument();
$content = mb_convert_encoding(
    get_the_content(null, true), # WordPress func, it gives input str
    'HTML-ENTITIES',
    'UTF-8'
);
$dom->loadHTML($content);

$el = $doc->getElementsByTagName('li');

Result: returning a DOMNodeList and I have to do few more tasks to print it to a string which can be used.


texts:
Here is my code I'm working with:

$('#slider_1').click( function change_slider(){
  $('#slider_1').addClass('current_tab').siblings('.current_tab').removeClass('current_tab')
  $('#cart_slider_1').show().siblings().hide();
  $('#cart_slider_1').addClass('current').siblings('.current').removeClass('current');
  numItems = $('.current .cart_slide').length;
  sliderwidth = numItems * swidth;
  $('.cart_slides').css({'left': 0, 'width': sliderwidth});
  numloop = numItems-1;
  last_slide = sliderwidth - swidth;
  i=0;
});

$('#slider_2').click( function change_slider(){
  $('#slider_2').addClass('current_tab').siblings('.current_tab').removeClass('current_tab')
  $('#cart_slider_2').show().siblings().hide();
  $('#cart_slider_2').addClass('current').siblings('.current').removeClass('current');
  numItems = $('.current .cart_slide').length;
  sliderwidth = numItems * swidth;
  $('.cart_slides').css({'left': 0, 'width': sliderwidth});
  numloop = numItems-1;
  last_slide = sliderwidth - swidth;
  i=0;
});

It repeats 6 more times, with incrementing #slider numbers and #cart_slider numbers.

I want to make this into one set, and run the variable sets through it. #slider_1, #slider_2, #slider_3, etc... and #cart_slider_1, #cart_slider_2, #cart_slider_3, etc...

The current code works fine; I just want to simplify / condense it.


texts: Applying multiple php FilterIterator instances in a cascading fashion

texts:
I wrote an implementation of php FilterIterator objects that allows me to apply them in a "cascade" way, so I can finally obtain an array of objects which is the result of all those filters.

It works fine, but - being new to SPL objects - I'm wondering if there is a better way to achieve the same results with FilterIterators et similia.

My implementation

I have a Factory class holding an array of objects in a static property:

class Factory {

    /**
     * @var Reservation[]
     */
    public static $reservations;

    public function __construct(){
        self::$reservations = $this->get_all();
    }

    private function get_all(){
        // Queries the database...
        return $results; // array of Reservation objects
    }

    // other unrelated things...
}

As I need the ability to filter such array by some criteria on-demand, I defined a bunch of FilterIterator sub-classes. The following is byOrder, others (byService, byProvider etc.) are defined in a similar way:

class byOrder extends FilterIterator {

    protected $order;

    public function __construct(Iterator $iterator, $order){
        parent::__construct($iterator);
        $this->order = $order;
    }

    public function accept(){

        /** @var $current Reservation */
        $current = $this->current();

        return $current->order() === $this->order;
    }
}

In order to apply just one filter to the array (I need it to stay as array) wherever in my application I can do:

// somewhere else...
$factory = new Factory();
// later on...
$reservations = new ArrayObject(Factory::$reservations);
$iterator = $reservations->getIterator();
$filteredReservation = iterator_to_array(new byOrder($iterator, 'ORDER_ID'));

To be able to apply multiple filters in a "cascade" way, I created the following helper class:

class Select {

    /**
     * @var ArrayIterator
     */
    private $reservations;

    public function __construct(array $reservations)
    {
        $obj = new ArrayObject($reservations);
        $this->reservations = $obj->getIterator();
    }

    public function get(){
        return iterator_to_array($this->reservations);
    }

    public function byOrder($order){
        $this->reservations = new byOrder($this->reservations, $order);

        return $this;
    }

    public function byService($service){
        $this->reservations = new byService($this->reservations, $service);

        return $this;
    }

    // ... and so on
}

It is instantiated on-demand through a method inside the Factory class:

class Factory {

    // All the previously defined content, plus:
    public function select() {
        return new Select(self::$reservations);
    }
}

So I'm able to apply multiple cascading filters like this:

// somewhere else...
$factory = new Factory();
// later on...
$filtered = $factory->select()
    ->byOrder('ORDER_ID')
    ->byService('SERVICE_NAME')
    ->get();


texts:
Inspired by my merge sort in Scheme, I thought I'd try my hand at implementing other sorting algorithms, starting with simple ones (like insertion sort) and working my way up. So, here we go:

(define (insertion-sort lst (lt? <))
  (fold-right (lambda (item sorted)
                (let-values (((lhs rhs) (span! (cut lt? <> item) sorted)))
                  (append! lhs (cons item rhs))))
              '() lst))

Tested with Racket and Guile; requires SRFIs 1, 11, and 26. (If you want to use this for Guile, you will need to adjust the syntax used for optional arguments.)

What I'm looking for

I'd like to get critique on my code for better style (from the perspective of a seasoned Schemer) and performance, with the understanding that:

Insertion sort is O(n²) worst case, and there are obviously more scalable sorting algorithms around.
I'm trying to make this a pure-functional implementation, so that you can pass in a literal list datum without invoking undefined behaviour.

All the nodes in the sorted list are ultimately created using cons, so I can safely use span! and append! on sorted nodes without undefined behaviour.

Things I've considered

I originally implemented this using a left-fold instead of a right-fold. However, SRFI 1 explains that it's usually better to use right-folding when the left-folding version requires reversing afterwards due to better cache locality.

A left-folding implementation requires building the sorted list in reverse order in order to maintain the "fast if mostly sorted" property.

Update: coredump asked if the output list could share cons cells with the input list where possible. Here's one possible implementation; the code is somewhat more longwinded than the original implementation, so any suggestions for improvement are welcome here too:

(define (insertion-sort lst (lt? <))
  (pair-fold-right (lambda (pair sorted)
                     (define item (car pair))
                     (if (and (eq? (cdr pair) sorted)
                              (or (null? sorted)
                                  (not (lt? (car sorted) item))))
                         pair
                         (let-values (((lhs rhs) (span (cut lt? <> item) sorted)))
                           (append! lhs (cons item rhs)))))
                   '() lst))


texts: Creating a simple windows instance capable of rendering Direct3D graphics

texts:
I've just started to learn recently about Direct3D, when I've learned to create a simple window I started wondering if I could automate this process, so whenever I would need to create a window I would just need to call for a function with my configs already setup. This is the essential part of the code I've come out:
void CreateWindow(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
//Inside this function is the code used to create a simple window.
{
HWND hWnd;
WNDCLASSEX(wc);
ZeroMemory(&wc, sizeof(WNDCLASSEX));

wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"D3D11Class";
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;

RegisterClassEx(&wc);

hWnd = CreateWindowEx(NULL, L"D3D11Class", L"WINDOW", WS_OVERLAPPEDWINDOW, 50, 50, 1080, 720, NULL, NULL, hInstance, NULL);
ShowWindow(hWnd, nCmdShow);
Init3D(hWnd);
}

int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
//The main function where the CreateWindow function was called, also used a loop to keep it running.
{
std::atexit(CleanD3D);
CreateWindow(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
MSG msg;
while (true)
{
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
        if (msg.message == WM_QUIT)
        {
            break;
        }
    }
    RenderFrame();
}
return msg.wParam;
}

Some of the functions I've used wasn't pasted here because I think they were irrelevant to what I want to be reviewed. Everything seems to be running fine when I execute the application, but I don't have sure this is the right way of doing things as I'm just a beginner, so if anyone which is more experienced on DirectX coding could advise me I would be thankfull.


texts: Monitor Downloads folder and sort files as they are downloaded

texts:
I have written my first shell script that uses inotify-tools to monitor my Downloads directory. What I intend to do with the script is that, as soon as a file is downloaded, it moves that file to a folder named after its extension. For example: if it is test.pdf it will be moved to a folder named pdf.

The script is here:

#!/bin/bash

cd ~/
basepath=Downloads/InternetDownloads/
while true ; do
filename=$(inotifywait -e create --format "%f" Downloads/InternetDownloads)
arr=(${filename//./ })
if [ ! -d ${arr[1]} ];
    then mkdir ${basepath}${arr[1]}
fi

separator='/'

newpath=${arr[1]}
mv $basepath${filename} $basepath$newpath${separator}
done

The program is working correctly, but I am having trouble ending it elegantly. I have obtained a solution for working here. I want to know if my code is correct since the normal procedure to end scripts of this sort is just to fine the process if and using kill pid


texts:
I made a tumbler thingy...
Do you see possible bugs in the code or any improvements I could do?

var text = "0000 ASCII (Listeni/ˈæski/ ass-kee), abbreviated from American Standard Code for Information Interchange,[1] is a character-encoding scheme (the IANA prefers the name US-ASCII[2]). ASCII codes represent text in computers, communications equipment, and other devices that use text. Most modern character-encoding schemes are based on ASCII, though they support many additional characters. ASCII was the most common character encoding on the World Wide Web until December 2007, when it was surpassed by UTF-8, which includes ASCII as a subset.[3][4][5]";

// Returns a random integer between min and max.
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function tumbler(text) {
  var length = text.length;
  var tumbleText = "";

  function tumble() {
    var code, i, newTumbleText = "",
      rand;

    // Test if we're done.
    if (text === tumbleText) {
      return document.body.style.color = "white";
    }

    for (i = 0; i < length; i++) {
      // Compare the two chars.
      if (text[i] !== tumbleText[i]) {
        code = text.charCodeAt(i);
        rand = getRandomInt(code - 10 < 0 ? 0 : code - 10, code + 10);
        newTumbleText += String.fromCodePoint(rand);
      } else {
        newTumbleText += text[i];
      }
    }

    tumbleText = newTumbleText;
    document.body.textContent = tumbleText;
    window.setTimeout(tumble, 60);
  }

  tumble();
}

tumbler(text);
body {
  background: black;
  color: lime;
  font-family: Courier, monospace;
}