texts: Improve efficiency for finding word frequency in text

texts:
Premise: Write a program that counts the frequencies of each word in a text, and
output each word with its count and line numbers where it appears. We
define a word as a contiguous sequence of non-white-space characters.
Different capitalizations of the same character sequence should be
considered same word (e.g. Python and python). The output is formatted as
follows: each line begins with a number indicating the frequency of the word,
a white space, then the word itself, and a list of line numbers containing this
word. You should output from the most frequent word to the least frequent.
In case two words have the same frequency, the lexicographically smaller
one comes first. All words are in lower case in the output.

Solution:

# Amazing Python libraries that prevent re-invention of wheels.
import re
import collections
import string
from operator import itemgetter

# Simulate work for terminal
print 'Scanning input for word frequency...'

# Text files
input = open('input.txt', 'r')
output = open('output.txt', 'w')

# Reads every word in input as lowercase while ignoring punctuation and
# returns a list containing 2-tuples of (word, frequency).
list = collections.Counter(input.read().lower()
       .translate(None, string.punctuation).split()).most_common()
# Sorts the list by frequency in descending order.
list = sorted(list, key=itemgetter(0))
# Sorts the list by lexicogrpahical order in descending order while maintaining
# previous sorting.
list = sorted(list, key=itemgetter(1), reverse=True)

# Gets the lines where each word in list appears in the input.
for word in list:
  lineList = []
  # Reads the input line by line. Stores each text line in 'line' and keeps a
  # counter in 'lineNum' that starts at 1.
  for lineNum, line in enumerate(open('input.txt'),1):
    # If the word is in the current line then add it to the list of lines
    # in which the current word appears in. The word frequency list is not
    # mutated. This is stored in a separate list.
    if re.search(r'(^|\s)'+word[0]+'\s',
                 line.lower().translate(None, string.punctuation),
                 flags=re.IGNORECASE):
      lineList.append(lineNum)
  # Write output with proper format.
  output.write(str(word[1]) + ' ' + word[0] + ' ' + str(lineList)+'\n')

# End work simulation for terminal
print 'Done! Output in: output.txt'

How can I get the line numbers without re-reading the text? I want to achieve sub-O(n^2) time complexity. I am new to Python so feedback on other aspects is greatly appreciated as well.


texts: Task Scheduler for small interval and one number of start

texts:
Scenario:

I want a task scheduler that enables my application to schedule some tasks in small time interval. I want to use it in my socket server application. For example, when the user connects to the socket application schedule some task in 15 seconds to disconnect user if no actions were made.

Queuing task for specific time
Ability to stop scheduled jobs
Running jobs in separate thread

So, I've decided to create my own Task Schedule. It can schedule tasks. It use System.Timers.Timer to find tasks to run. I want you to review my decision, may be solution has architecture errors etc.

public abstract class ScheduleJob
{
    //Date when task must be executed
    public DateTime DateTrigger { get; set; }

    //Task Id (for search and cancel)
    public string TaskId { get; set; }

    //For logs
    public abstract string TaskName { get; }

    //Main task method
    protected abstract void OnStart();

    //Default task class delay (for example 15 seconds)
    public abstract TimeSpan ScheduleTo { get; }

    private bool _isRunning = false;

    public void Start()
    {
        _isRunning = true;

        var s = new Stopwatch();
        s.Start();

        try
        {
            //run task in separated thread
            Task.Factory.StartNew(OnStart).ContinueWith(t =>
            {
                s.Stop();
                _isRunning = false;

                //if (t.Exception != null)
                //{
                //TODO work with exceptions
                //}
            });
        }
        catch (Exception ex)
        {
            //TODO work with exceptions
        }
    }
}

Manager to work with jobs

public sealed class ScheduleManager : IDisposable
{
    private static ScheduleManager _instance = new ScheduleManager();

    public static ScheduleManager Instance { get { return _instance; } }

    private List<ScheduleJob> _jobs;
    private object _lock = new object();

    private Timer _timer;

    private ScheduleManager()
    {
        _jobs = new List<ScheduleJob>();
        _timer = new Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += TimerOnElapsed;
        _timer.Start();
    }

    private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
    {
        lock (_lock)
        {
            var tasks = _jobs.Where(x => x.DateTrigger <= DateTime.Now).ToList();

            foreach (ScheduleJob scheduleJob in tasks)
            {
                scheduleJob.Start();
                _jobs.Remove(scheduleJob);
            }
        }
    }

    public void Schedule(ScheduleJob job)
    {
        lock (_lock)
        {
            job.DateTrigger = DateTime.Now + job.ScheduleTo;
            _jobs.Add(job);
        }
    }

    public void Remove(string taskId)
    {
        lock (_lock)
        {
            _jobs.RemoveAll(x => x.TaskId.Equals(taskId, StringComparison.OrdinalIgnoreCase));
        }
    }

    public void Dispose()
    {
        if (_timer != null)
        {
            _timer.Stop();
            //todo stop or cancel jobs
            _timer = null;
        }
    }
}

Example of job UserShouldSendAuthTokenAfterConnectToSocketTask

public class UserShouldSendAuthTokenAfterConnectToSocketTask : ScheduleJob
{
    private string _connectionId;

    public UserShouldSendAuthTokenAfterConnectToSocketTask(string connectionId)
    {
        _connectionId = connectionId;
        TaskId = GenerateTaskId(_connectionId);
    }

    public static string GenerateTaskId(string connectionId)
    {
        return $"UserShouldSendAuthTokenAfterConnectToSocketTask_{connectionId}";
    }

    public override string TaskName { get { return "User should auth to socket"; } }

    protected override void OnStart()
    {
        SocketServer.Instance.SendMessage(new UserShouldSendAuthTokenAfterConnectToSocket(), _connectionId);
    }

    public override TimeSpan ScheduleTo
    {
        get
        {
            return TimeSpan.FromSeconds(GameConfig.SecondsUserShouldSendAuthTokenAfterConnectToSocket);
        }
    }
}


texts: Using Python to remove blank lines and comments in Assembly code

texts:
I made this little script to help a friend. He studies computer engineering and is doing a project where he has to make assembly files with comments and some formatting for presentation, but, as he is making a compiler. He explained to me that he needs all their assembly codes without spaces, blank lines or comments and that the other people from his group couldn't find a small and fast solution yet to convert that.

I came up with a simple solution to it using Python:

The script gets the filename or path
Opens it and creates an output file (can be changed to another input for the user to type the output file name)
Then it iterates all the lines from the file and for each line it does the following:
Split the line when it has a comment that is identified by //
Then it gets the first element of the split line which is everything that comes before any comment
Now it replaces every space " " with "". This will get rid of all blank spaces.
If the line had a script the end of the line will be at the second element of the list, this means that the first part will not have a "\n" at the end, do we test if the list has more than one element and if it has we add a "\n" at the end.
I then used rstrip() function to check if the line is not empty, and, if it isn't we write it on the output file.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Made by Iago Sousa.
# fciagsousa@gmail.com
# https://github.com/iagsousa/python/blob/master/scripts/removerComentariosAssembly.py

f = raw_input("Insert file name or path: ")
finput = open(f, "r")
foutput = open("saida.txt", "w")
for line in finput:
    l = line.split("//")
    l[0] = l[0].replace(" ", "")
    if len(l) > 1:
        l[0] += "\n"
    if l[0].rstrip():
        foutput.write(l[0])

Input example:

Output example:

Are there any steps that I could've taken to improve my code? Is is optimal for what's intended? Those are my only questions.


texts:
I'm parsing an XML file and searching for a child value.

As I'm familiar with this XML file structure, I know that the final value is a child of a child, and so I wrote the following code section:

/*Parse XML file and find device friendlyName*/
pxUpnp = ezxml_parse_file(XML_FILE_PATH);

pxUpnpChild = ezxml_child(pxUpnp, "device");

/*Looking for friendlyName sub-child*/
pxUpnpSubChild = ezxml_child(pxUpnpChild, "friendlyName");

This code works, but I wander if there is a better or more elegant method to parse a 'child of a child' value using ezxml library?

Thank you all in advance!


texts: Parsing SOAP messages from a web service

texts:
I'm consuming an ASMX service with SOAP messages. Since Xamarin doesn't support SOAP 1.2, I'm writing the Web requests manually. I'm sending a user/password to retrieve the user ID.

A successful response may look like this:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ns="link-to-namespace">
  <soap:Body>
    <ns:User>
      <ns:UserId>123</ns:UserId>
    </ns:User>
  </soap:Body>
</soap:Envelope>

An error response may look like this:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Body>
    <soap:Fault>
      <soap:Code>
        <soap:Value>InvalidUsernameAndPassword</soap:Value>
      </soap:Code>
    </soap:Fault>
  </soap:Body>
</soap:Envelope>

What's the best way to parse the response? And how to check if there is an error?

Currently I just look for the presense of the <Fault> element.

WebService class handles the request and returns the SOAP envelope as an XDocument:

class WebService
{
    // Returns the SOAP envelope as an XDocument.
    public XDocument Invoke(string soapAction, string method, Dictionary<string, string> parameters)
    {

UserApi class acts as a proxy towards the service.

class UserApi
{
    // Sends user/pwd to server to retrieve user id.
    public string GetUserId(string username, string password)
    {
        var soapAction = "link-to-soap-action";
        var method = "GetUserId";
        var parameters = new Dictionary<string, string>
        {
            { "Username", username },
            { "Password", password}
        };
        var service = new WebService();
        var result = service.Invoke(soapAction, method, parameters);

        XNamespace nsSoap = "http://www.w3.org/2003/05/soap-envelope";
        XNamespace ns = "link-to-namespace";

        // Look for the "Fault" element in the response. If present, there was an error.
        var fault = result.Root.Element("{" + nsSoap + "}Body").Element("{" + ns_soap + "}Fault");
        if (error != null)
        {
            var codeWithNs = error.Element("{" + nsSoap + "}Code").Element("{" + ns_soap + "}Value").Value;
            var codeSplit = codeWithNs.Split(':');
            var code = codeSplit.Length == 2 ? codeSplit[1] : codeSplit[0];
            if (code == "InvalidUsernameOrPassword")
            {
                throw new InvalidUsernameOrPasswordException();
            }
            else
            {
                throw new Exception("Something went wrong.");
            }
        }

        return userId = result.Descendants(ns + "UserId").First().Value;
    }

    public async Task<string> GetUserIdAsync(string username, string password)
    {
        return await Task.Run(() =>
        {
            return GetUserId(username, password);
        });
    }
}

Currently it works, at least under optimal conditions. But my solution looks dense and fragile. If I should go with deserialization, here's some pseudo code of what I'm thinking:

try
{
    var serializer = new XmlSerializer(typeof(UserEnvelope));
    var user = serializer.Deserialize(response);
}
catch (InvalidOperationException)
{
    var serializer = new XmlSerializer(typeof(ErrorEnvelope));
    var error = serializer.Deserialize(response);
    if (error.Code == "InvalidUsernameOrPassword")
    ...etc
}


texts: Relational schema and query for multiplayer tabletop game

texts:
As an exercise, I was asked to design a database schema (for MS SQL Server) for a tabletop game. The requirements were simple: players compete in matches and there are specific match types (e.g. 1v1 or 2v2). A hypothetical web site that would make use of this database would include things like player match history, a scoreboard page, and a leaderboard page.

My initial design had some flaws and inconsistencies, but after thinking more on it, I came up with the following schema:

create table Players (
    Id int identity(1, 1) primary key,
    PlayerName nvarchar(50) not null
);

create table MatchTypes (
    Id tinyint primary key,
    Name nvarchar(50) not null
);

create table Matches (
    Id int identity(1, 1) primary key,
    MatchTypeId tinyint not null references MatchTypes(Id),
    IsComplete bit not null,
    CompletionDate datetime2 null
);

create table Teams (
    Id int identity(1, 1) primary key,
    MatchId int not null references Matches(Id),
    Score smallint not null,
    IsWinningTeam bit null
);

create table PlayerTeams (
    PlayerId int not null references Players(Id),
    TeamId int not null references Teams(Id)
);

Although the design is fairly simple, I'm sure I've made sub-optimal design decisions. What could be improved on?

In addition, I went ahead and wrote a SQL query to extract data for a hypothetical "Player Match History" page. The goal is something like the following:

Player: Foo
Matches:
  Against Bar                  ... Won!
  Against Quux                 ... Lost
  With Baz, against Bar & Quux ... Lost
  With Bar, against Quux & Baz ... Won!

Essentially, given a player, select all matches that the player participated in, and display them with opponents/teammates.

Here's the query, although I feel like it may be unnecessarily complex.

select pm.MatchId,
    t.Id as TeamId,
    p.Id as PlayerId,
    p.PlayerName,
    case when t.Id = pm.TeamId then 1 else 0 end as IsTeammate,
    pm.Won
from (
    select m.Id as MatchId,
        m.CompletionDate,
        t.Id as TeamId,
        t.IsWinningTeam as Won
    from Players p
    inner join PlayerTeams pt
        on p.Id = pt.PlayerId
    inner join Teams t
        on pt.TeamID = t.Id
    inner join Matches m
        on t.MatchId = m.Id
    where m.IsComplete = 1 and p.Id = 1
) pm
inner join Teams t
    on pm.MatchId = t.MatchId
inner join PlayerTeams pt
    on t.Id = pt.TeamId
inner join Players p
    on pt.PlayerId = p.Id
where p.Id != 1
order by pm.CompletionDate desc


texts:
I was working on a subtype of list in python that acts as a list that should never raise an IndexError (every key you input that's greater than the length of the list gets wrapped around). I was having quite a few problems however implementing it properly for slices, who have a LOT of base cases. I wrote the following code to handle slices the way I want to (with example slices commented out);

class Cycle:

    def __getitem__(self, key):
            _self = self._container
            n = len(self)
            if isinstance(key, slice):
                s = key.start
                e = key.stop
                stp = key.step
                r = False
                if stp is None:
                    stp = 1
                elif stp == 0:
                    raise ValueError()
                elif stp < 0:
                    r = True
                    stp = abs(stp)
                if s and not e:
                    sliced = []
                    _len = n - s #[3:]
                    if s < 0:
                        #[-1:]
                        _len = abs(s)
                    elif s >= n:
                        #[7:]
                        _len = n - s % n
                    for i in range(0, _len, stp):
                        index = (i + s) % n
                        sliced.append(_self[index])
                elif e and not s:
                    sliced = []
                    _len = e #[:4]
                    if e <= 0:
                        #[:-1]
                        _len = n - abs(e) % n
                    for i in range(0, _len, stp):
                        index = i % n
                        sliced.append(_self[index])
                elif s and e:
                    sliced = []
                    if s <= e:
                        if s < 0 and e < 0:
                            #[-3:-1]
                            #[-7:-1]
                            _len = abs(s) - abs(e)
                        elif s < 0 and 0 <= e:
                            #[-1:3]
                            #[-7:8]
                            if n + s % n > e:
                                _len = e - s
                            else:
                                _len = e - (n + s)
                        elif 0 <= s and 0 <= e:
                            #[1:3]
                            #[7:19]
                            _len = e - s
                    elif s > e:
                        if s < 0 and e < 0:
                            #[-1:-3]
                            raise ValueError()
                        elif s >= 0 and e < 0:
                            if n + e < s:
                                #[4:-3]
                                raise ValueError()
                            _len = (n + e) - s #[1:-1]
                        elif 0 <= s and 0 <= e:
                            if s >= n:
                                if s % n <= e:
                                    #[7:1]
                                    _len = e - s % n
                                else:
                                    #[7:3]
                                    _len = n - s % n + e
                            else:
                                #[4:2]
                                _len = (n - s % n) + e
                    for i in range(0, _len, stp):
                        index = (i + s) % n
                        sliced.append(_self[index])
                elif not (s or e):
                    sliced = _self[::stp]
                if r:
                    sliced = sliced[::-1]
                return sliced
            else:
                key %= n
                return _self[key]

I can't think of any other more compact way to test for all the different cases that can occur. Can someone help me out please?


texts: Eliminate for loops in numpy implementation

texts:
I have the following dataset in numpy

indices | real data (X)    |targets (y)
        |                  |
0   0   | 43.25 665.32 ... |2.4      } 1st block
0   0   | 11.234           |-4.5     }
0   1     ...               ...      } 2nd block
0   1                                }
0   2                                } 3rd block
0   2                                }
1   0                                } 4th block
1   0                                }
1   0                                }
1   1                       ...
1   1
1   2
1   2
2   0
2   0
2   1
2   1
2   1
...

Theses are my variables

idx1 = data[:,0]
idx2 = data[:,1]
X = data[:,2:-1]
y = data[:,-1]

I also have a variable W which is a 3D array.

What I need to do in the code is loop through all the blocks in the dataset and return a scalar number for each block after some computation, then sum up all the scalars, and store it in a variable called cost. Problem is that the looping implementation is very slow, so I'm trying to do it vectorized if possible. This is my current code. Is it possible to do this without for loops in numpy?

IDX1 = 0
IDX2 = 1

# get unique indices
idx1s = np.arange(len(np.unique(data[:,IDX1])))
idx2s = np.arange(len(np.unique(data[:,IDX2])))

# initialize global sum variable to 0
cost = 0
for i1 in idx1s:
    for i2 in idx2:

        # for each block in the dataset
        mask = np.nonzero((data[:,IDX1] == i1) & (data[:,IDX2] == i2))

        # get variables for that block
        curr_X = X[mask,:]
        curr_y = y[mask]
        curr_W = W[:,i2,i1]

        # calculate a scalar
        pred = np.dot(curr_X,curr_W)
        sigm = 1.0 / (1.0 + np.exp(-pred))
        loss = np.sum((sigm- (0.5)) * curr_y)

        # add result to global cost
        cost += loss

Here is some sample data

data = np.array([[0,0,5,5,7],
                 [0,0,5,5,7],
                 [0,1,5,5,7],
                 [0,1,5,5,7],
                 [1,0,5,5,7],
                 [1,1,5,5,7]])
W = np.zeros((2,2,2))
idx1 = data[:,0]
idx2 = data[:,1]
X = data[:,2:-1]
y = data[:,-1]


texts:
Recently, I've noticed that my code looks so ugly because there were a bunch of functions and global variables.  So, I started reading a little bit about design patterns. Now I come with something that's working for me, but I am not sure if it's good practice.

Anyway, I would like you to take a look at the code and tell me what can I improve.  I'd also like to know a better way to start using modular pattern in JavaScript.  Finally, I'd like suggestions on material for learning about modular pattern and JavaScript.

var responsiveModule = {

    settings: {
        device: false,
        button: $(".responsive-btn"),
        target: $("nav ul"),
        mobileClass: "toggle-menu",
        bgImage: '<img class="background-image" src="img/background.jpg" alt="">',
        bgImageSelector: $(".background-image"),
        windowWidth: $(window).width(),

    },

    init: function(){
        responsiveModule.checkDevice();
        responsiveModule.replaceImages();
        responsiveModule.bindFunctions();
        responsiveModule.listenResize();
    },

    checkDevice: function(){
        if(this.settings.windowWidth > 992){
            this.settings.device = "desktop";

        } else {
            this.settings.device = "mobile";
        }
    },

    bindFunctions: function(){
        var buton = this.settings.button,
            muelleBtn = this.settings.muelleBtn;
        buton.on("click touchstart", function(e){
            e.preventDefault();
            responsiveModule.animateMenu(responsiveModule.settings);
        });
    },

    animateMenu: function(settings){
        var device = settings.device,
            target = settings.target,
            mobileAnimation = settings. mobileClass;

        if(device == "mobile"){
            target.toggleClass(mobileAnimation);
        }
    },

    replaceImages: function(){
        var bgContainer = $("#main-content"),
            bgImage = responsiveModule.settings.bgImage,
            device = responsiveModule.settings.device,
            backgroundSelector = $(".background-image");

        if(device == "desktop" && backgroundSelector.length == 0){
            bgContainer.append(bgImage);
        }else if(device == "mobile" && backgroundSelector.length == 1){
            backgroundSelector.remove();
        }
    },

    listenResize: function(){
        $(window).on("resize", function(){
            responsiveModule.checkDevice();
            responsiveModule.replaceImages();
            responsiveModule.settings.windowWidth = $(window).width();
        });
    }

}

var tooltipModule = {

    settings: {
        tooltipState: false
    },

    init: function(){
        tooltipModule.bindUIfunctions();
    },

    bindUIfunctions: function(){
        var device = responsiveModule.settings.device;
        if(device == "mobile"){
            $(".ship").on("click", function(e){
                e.preventDefault();
                tooltipModule.manageTooltip(e);
            });
        }else{
            $(".muelle-item").addClass("desktop");
        }
    },

    manageTooltip: function(e){
        var tooltip = $(e.currentTarget).next(),
            tooltips = $(".tooltip");

        tooltips.removeClass("display");
        tooltip.addClass("display");
    }

}

$(document).on("ready", function(){
    responsiveModule.init();
    tooltipModule.init();
});


texts: Calculating the number of primes between 3 and another number

texts:
This is a simple program that gets a number from a user and calculates the number of primes between 3 and the user's number. I'm just curious if I'm using too many variables. I'm only asking since I'm used to not needing to initialize iterator variables before a loop.

#include <iostream>
using namespace std;
int isPrime(int);
int main() {
    int userValue;
    int b;
    int x;
    char c;
    cout<< "Enter a number : "<< flush;
    cin >> userValue;
    for (x = 3; x <= userValue; x= x+2){
        a = isPrime(x);
        if (a == 1){
        b +=1;
        }
    }
    cout << "There is, " << b << " number of primes from 3 to "<< userValue << endl;
    cout << "hit enter to terminate..."<< flush;
    cin.get();
    cin.get();
}

int isPrime(int number){
    int i;
    for(i=2; i<number; i++){
    if (number % i == 0 && i != number) return 0;
    }
    return 1;
}


texts:
If I was at an interview, and wrote this code, what would you think? Please be brutal.

Time it took to wrote it: 13 minutes

Problem:

  Write an efficient algorithm that searches for a value in an m x n
  matrix. This matrix has the following properties:

  Integers in each row are sorted from left to right. The first integer
  of each row is greater than the last integer of the previous row. For
  example,

  Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

  Given target = 3, return true.

 public boolean searchMatrix(int[][] matrix, int target) {
    int lastCol = matrix[0].length-1;
    int row=0;
    while(row!=matrix.length && lastCol>=0){
        if(matrix[row][lastCol]==target){
            return true;
        }
        if(matrix[row][lastCol]>target){
            lastCol--;
            if(binarySearch(matrix[row], 0, lastCol, target)!=-1){
                return true;
            }
        }
        row++;
    }
    return false;
}
public int binarySearch(int[] arr, int low, int high, int target){
    while(low<=high){
        int mid = (low + high)/2;
        if(arr[mid]==target){
            return mid;
        }
        else if(arr[mid]<target){
            low = mid+1;
        }
        else if(arr[mid]>target){
            high = mid-1;
        }
    }
    return -1;
}

Space complexity = O(1)
Time Compexity = O(log(n!))


texts: Inserting products scraped from the web into a database

texts:
I am trying to speed up the runtime of my program as the API can make calls.  However after adding the inserts to a database 3 mins turns in 7 mins after 180 API calls, which can be one a second.  How can I further improve the inserts into the DB?

I am using mysql database, but potentially could change if it will increase performance

url = getSignedUrl(params)
resp = requests.get(url)
responseSoup=BeautifulSoup(resp.text)

#EXTRACT FROM XML
quantity = ['' if product.amount is None else product.amount.text for product in responseSoup.findAll("offersummary")]
price = ['' if product.lowestnewprice is None else product.lowestnewprice.formattedprice.text for product in responseSoup.findAll("offersummary")]
prime = ['' if product.iseligibleforprime is None else product.iseligibleforprime.text for product in responseSoup("offer")]

#UPDATE DB
for zz in zip(asins.split(","), price,quantity,prime):
    cursor = conn.cursor()

    if zz[1] == "Too low to display":
        print "Scraping..."
        zz = scrapeTooLow(zz[0])

    dat = [zz[0], zz[1], zz[2], zz[3]]
    if zz[1] != "":
        priceFormat = float(zz[1].replace("$", "").replace(",", ""))
        mep = round(priceFormat*1.35, 2)
        dp = round(priceFormat*1.38, 2)
        fp = round(priceFormat*1.17, 2)
    else:
        priceFormat = ""
        mep = ""
        dp = ""
        fp = ""
    dat.extend([mep,dp,fp])
    print dat
    try:
        cursor.execute("""INSERT INTO data VALUES (%s,%s, %s, %s, %s, %s, %s)""",dat)
        conn.commit()
    except:
        conn.rollback()
print count, i


texts: Using both setInterval and setTimeout for simple image carousel

texts:
I have a really basic image carousel that I just wrote.

Basically I'm trying to keep it as small and light weight as possible, but I get the feeling that I've gotten way off the beaten path of how these things normally work.

function hide(element, index, array) {
  if (index > 0) {
    slides[index].setAttribute('style', 'opacity:0;');
  }
}

var carousel = document.getElementById("carousel"),
  slides = carousel.getElementsByTagName('li'),
  counter = 0,
  liList = Array.prototype.slice.call(slides);

setInterval(function() {
  slides[counter].setAttribute('style', 'opacity:1;');
  counter++;

  if (counter == slides.length) {
    counter = 0;
    setTimeout(function() {
      liList.forEach(hide);
    }, 3000); // setTimeout
  }
}, 3000); // setInterval
#carousel {
  padding: 0;
  margin: 0;
  position: relative;
  width: 315px;
  height: 177px;
}
#carousel li {
  opacity: 0;
  list-style: outside none none;
  width: 315px;
  position: absolute;
  background: #fff;
  transition: opacity 1s;
}

Could this be trimmed down further, is this a bad way to go about something this simple, or am I just over thinking it?


texts:
This is my sample code to convert a integer into string.

Is it very costly to do the multiple loops of [NSMutableString stringWithFormat:..]?

I.e should I just use appendString and get the NSString in reverse order and then do one for loop to reverse this "reverse string".

Is there any other faster/more elegant way?

NSString * intToString(NSInteger numberToConvert)
{
    BOOL isNegative = (numberToConvert < 0);
    if (isNegative)
    {
        numberToConvert = -1*numberToConvert;
    }

    NSMutableString *convertedString = [[NSMutableString alloc] init];

    while(numberToConvert != 0)
    {
        convertedString = [NSMutableString stringWithFormat:@"%ld%@",numberToConvert%10,convertedString];
        numberToConvert = numberToConvert/10;
    }

    if (isNegative)
    {
        convertedString = [NSMutableString stringWithFormat:@"-%@",convertedString];
    }

    return convertedString;
}


texts:
I just completed K&R (2nd Ed.) ex 1-18.  I'm fairly new to C, but have had experience in other languages (Perl, C++, Java, Common Lisp, PHP, etc) and really want to learn the C idiom as opposed to translating the idioms I already know.

What do you think about this approach to 1-18?

/*
   Exercise 1-18 in K&R 2nd Edition
   Removes trailing blanks & tabs & blank lines from each line of input
   Written by Z. Bornheimer (provided as is without warranty).
*/

#include <stdio.h>
#define MAXLINE 1000

/* removes trailing blanks and tabs...deletes null lines */
main()
{
    int len; /* current line length */
    int i = -1, j; /* two counters */
    int c; /* current char */
    char line[MAXLINE]; /* current input line */

    while ((c=getchar()) != EOF) {
        line[++i] = c;
        if (c == '\n') {
            j = i + 1;
            while (line[--j] == ' ' || line[j] == '\n' || line[j] == '\t')
                line[j] = '\0';

            printf("%s", line);

            for (j = 0; j <= i; j++)
                line[j] = '\0';

            i = -1;
        }
    }
    return 0;
}

https://github.com/zachbornheimer/programming-exercises/blob/master/c/1-18.c

Thank you for your help!


texts: Storing JWT in client side and putting tokens in all the future request

texts:
I have started using NodeJS with Express JS and PassportJS and JWT for User Authentication. I am able to authenticate the user and generate JWT Token. I am using Bootstrap for my front-end.

By using Postman I am able to get the token and put it in the next request header and it is working fine.

But how do I do this in HTML Pages using JavaScript?

JavaScript to get response body or response headers
JavaScript to set request header with JWT Token

Here is the snippet to store data in SessionStorage:

sessionStorage.setItem('token', 'token-abcd1234');
var token = sessionStorage.getItem('token');

I have a mechanism to invalidate the token on logout by putting them in a DB.

Let me know if I am missing any pattern or missing anything.

Note: I am using login.html which has a form with a username and password. AJAX is not used.

Login Page

Login

    <form class="form-horizontal" action="/login" method="POST">

      Email:

        <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">

      Password:

        <input type="password" class="form-control" id="password" placeholder="Enter password" name="password">

        <button type="submit" class="btn btn-default">Submit</button>

    </form>

NodeJS Route

router.get('/login', function(req, res, next) {
  res.render('login');
});

router.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      return next(err);
    }

    if (!user) {
      return res.status(401).json({
        err: info
      });
    }

    req.logIn(user, function(err) {
      if (err) {
        console.log(err);
        return res.status(500).json({
          err: 'Could not log in user'
        });
      }

      var token = Verify.getToken(user);
      res.status(200).json({
        status: 'Login successful!',
        success: true,
        token: token
      });
    });
  })(req,res,next);
});


texts:
This is my first program in Python that I have coded and I am relatively happy with how it turned out. I would like to know how I could make my code shorter and more efficient.

def one_round(player):
    #Distinguish player 1 from player 2
    if player == "p1":
       p = "Player 1"
    elif player == "p2":
         p = "Player 2"

    pin = raw_input("%s move (a/b/c for row | 1/2/3 for column):" % (p)) #receive input for player from console
    #separating row from column
    row = pin[0].lower()
    col = int(pin[1]) - 1

    if row == "a": #changing the row letter into a digit for the index of board
       row = 0
    elif row =="b":
         row = 1
    elif row == "c":
         row = 2

    while (row > 2 or col > 2) or (board[row][col] == 'X' or board[row][col] == 'O'):
          if row > 2 or col > 2:
             print "Oops, these co-ordinates are off of the board, please try again"

          elif board[row][col] == 'X' or board[row][col] == 'O':
               print "Oops this spot has been taken, please pick another"

          pin = raw_input("%s move (a/b/c for row | 1/2/3 for column):" % (p)) #receive input for player from console
          #separating row from column
          row = pin[0].lower()
          col = int(pin[1]) - 1
          if row == "a": #changing the row letter into a digit for the index of board
             row = 0
          elif row =="b":
               row = 1
          elif row == "c":
               row = 2

    if player == "p1": #Determining whether to use X or O
       x = 'X'
    elif player == "p2":
         x = 'O'

    del board[row][col] #Swapping out the dashes for a symbol
    board[row].insert(col, x)

    print str(" ".join(board[0])) + '\n' + str(" ".join(board[1])) + '\n' + str(" ".join(board[2])) #Printing board

    if board[0] == [x, x, x] or board[1] == [x, x, x] or board[2] == [x, x, x] or (board[0][0] == x and board[1][0] == x and board[2][0] == x) or (board[0][1] == x and board[1][1] == x and board[2][1] == x) or (board[0][2] == x and board[1][2] == x and board[2][2] == x) or (board[0][0] == x and board[1][1] == x and board[2][2] == x) or (board[0][2] == x and board[1][1] == x and board[2][0] == x): #Checking for winner
          print '%s wins!' % (p) + '\n' + 'Game Over!'
          return True
    elif board[0][0] != '-' and board[0][1] != '-' and board[0][2] != '-' and board[1][0] != '-' and board[1][1] != '-' and board[1][2] != '-' and board[2][0] != '-' and board[2][1] != '-' and board[2][2] != '-': #Checking for draw
          print 'Draw!' + '\n' + 'Game Over!'
          return True
    else:
          return False
#---------------------------------------------------------------------------------------------------------------------
"""Tic tac toe game. (Noughts and crosses)"""
print "Welcome to Tic Tac Toe!" + "\n" + " Find a friend and start the game by typing coordinates for a 3x3 grid labelled with the letters a,b,c from top to bottom along the vertical axis and with 1,2,3 from left to right along the horizontal axis." + "\n" + "Have Fun!"
#initialising board and players
board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
p1 = False
p2 = False
row = 0
col = 0
while (p1 == False and p2 == False): #running game
      p1 = one_round("p1")
      if p1 == True:
         break
      p2 = one_round("p2")


texts:
I am currently working in a project (I have simplified it for the sake of question) that requires a container to store students and retrieve them as fast as possible or access them with \$O(1)\$ if possible. I will also be deleting students from any place but always adding them at the end of the queue.

I have three structs: Student, Class and University.

Student: has name and age
Class: has name of course and array of shared pointers of size 2
University: has deque of Students and deque of class

#include <memory>
#include <deque>
#include <string>
#include <iostream>

constexpr size_t SIZE = 150;

struct Student{
    std::string name;
    size_t age;

    Student(std::string n, size_t a){
        name = n;
        age = a;
    }
    ~Student(){
        std::cout << __func__ << std::endl;
    }
};

struct Class{
    // Lets assume that each class has 2 student for the sake of argument
    // and exactly 2.
    std::shared_ptr<Student> my_class[2];
    std::string course;

    Class(std::string c, std::shared_ptr<Student> n0, std::shared_ptr<Student> n1){

        course = c;
        my_class[0] = n0;
        my_class[1] = n1;
    }
};

struct University{

    std::deque<std::shared_ptr<Student>> student_deq;
    std::deque<std::shared_ptr<Class>> class_deq;

    void add_student(std::string n, size_t a){
        student_deq.push_back(std::make_shared<Student>(n, a));
    }

    void add_class(std::string c, size_t i, size_t j){
        class_deq.push_back(std::make_shared<Class>(c, student_deq[i], student_deq[j]));
    }
};

int main(){

    University u;

    for(size_t i = 0; i < SIZE; i++){
        u.add_student("Xyz", i);
    }

    for(size_t j = 0; j < SIZE; j++){
        if(j+1 == SIZE)
            u.add_class("abc", j, 0);
        else u.add_class("abc", j, j+1);
    }
    std::cout << u.student_deq[9]->name << std::endl;
return 0;
}

I have some questions:

Do you think my choice of deque as a data structure (container) is appropriate?

I want the retrieve (from anywhere) / add (to end)/ remove (from anywhere) to be \$O(1)\$. I use deque because unlike vector it does not have to copy all the data from beginning of the array in case the memory grows and have to allocate new slab of contiguous memory. Since deque is made of small chunks of contiguous memory not all chunks need to be copied (at least that is what I think of). Also the retrieve and add to end is \$O(1)\$ in case of deque. I know remove is \$O(n)\$: \$n\$ being size of one of the chunk of contiguous memory the item reside in.

I think I could also use HashMap (unordere_map) but I read somewhere that hash_map does not necessarily give \$O(1)\$ because of collision when data gets huge and also my student number will definitely grow hugely (e.g. 100,000 and up also for sake of argument). I also heard that implementing hash function to avoid collision is complex.

I also think I can't use std::map since retrieval is \$O(ln)\$.
Do you think the use of shread_ptr inside the deque for memory management is a good design choice?

I used sharad_ptr so that I don't have to do the manual delete of the allocated memory. I also make the class store the shared_ptr rather than a copy of the student because the Student class may contain other information that might be costly to copy. Also a student can be in more then one class ( This way instead of creating multiple copy shared_ptr will only increase the count - Here also I am not sure is it really necessary to increase count because since there will only be one copy I was also thinking about passing by const ref so that we dont have the overhead of increasing the count itself)
Is there a container which gives \$O(1)\$ for retrieval, adding to the end and removal from anywhere in the container (of-course except hash map as I discussed about it above) or anything that is close enough that provide these features?


texts: Finding the smartest set from an array of numbers

texts:
Is there any way to make this program run in better time ? While running, it is taking 1 second for the sample test case to pass and 5-10 seconds for the rest of the test cases.

Problem statement

  A smart-set is a set of distinct numbers in which all the elements have the same number of 1s in their binary form. The set of all smallest elements from each smart-set
  that can be formed from a given array of distinct positive numbers is known as the smartest-set.

  So given an array of distinct numbers, outline the elements of the smartest-set in ascending sorted order.

Example

  Let the array be {6 , 2 , 11 , 1 , 9 , 14 , 13 , 4 , 18}.

  In binary form the set is {110, 010, 1011, 0001, 1001, 1110, 1101, 0100, 10010}.

  The smart-sets are {1, 2, 4}, {6, 9, 18}, {11, 13, 14}.

  The smartest-set is {1,6,11} as each element is the smallest element from each smart-set.

Input Format

The first line of input consists of an integer t. This is the number of test cases. For each test case,
the first line of input contains an integer n. Here n is the number of elements in the array. The next line contains n space separated distinct integers which are the elements
of the array.

Output Format

The output will space separated integer elements of the smartest-set in ascending order.

Constraints

0 < t < 1000 (This is the number of test cases )
2 < n < 10000 (This is the number of integer elements of the array)
1 < Xi < 100000 (This is the size of each element of the array)

SAMPLE STDIN 1
3
9
6 2 11 1 9 14 13 4 18
3
7 3 1
3
1 2 4
SAMPLE STDOUT
1 6 11
1 3 7
1

Code

test_case=input()
for case_num in range(int(test_case)):
    num_of_elements=input()
    arr=input()
    dictn={}
    #print (num_of_elements,arr)
    for bin_values in list(map(int,arr.split())):
        count=0
        for occurence in [int(x) for x in list('{0:0b}'.format(bin_values))]:
               if occurence==1:
                 count=count+1
        dictn[bin_values]=count
    v = {}

    for key, value in sorted(dictn.items()):
        v.setdefault(value, []).append(key)

    lst=[]
    for key,value in (v.items()):
        x=min(value)
        lst.append(str(x))
    s= ' '
    s = s.join(lst)
    print (s)


texts:
I recently wrote a python code for matrix exponentiation.

Here's the code:

from typing import List
Matrix = List[List[int]]

MOD = 10 ** 9 + 7

def identity(n: int) -> Matrix:
    matrix = [[0] * n for _ in range(n)]

    for i in range(n):
        matrix[i][i] = 1

    return matrix

def multiply(mat1: Matrix, mat2: Matrix, copy: Matrix) -> None:
    r1, r2 = len(mat1), len(mat2)
    c1, c2 = len(mat1[0]), len(mat2[0])

    result = [[0] * c2 for _ in range(r1)]

    for i in range(r1):
        for j in range(c2):
            for k in range(r2):
                result[i][j] = (result[i][j] + mat1[i][k] * mat2[k][j]) % MOD

    for i in range(r1):
        for j in range(c2):
            copy[i][j] = result[i][j]

def power(mat: Matrix, n: int) -> Matrix:
    res = identity(len(mat))

    while n:
        if n & 1:
            multiply(res, mat, res)

        multiply(mat, mat, mat)

        n >>= 1

    return res

def fib(n: int) -> int:
    if n == 0:
        return 0

    magic = [[1, 1],
             [1, 0]]

    mat = power(magic, n - 1)

    return mat[0][0]

if __name__ == '__main__':
    print(fib(10 ** 18))

I would mainly like to improve this code performance wise, but any comments on style is also much appreciated.

Thanks!


texts: How can I make this userform timer faster?

texts:
I have a userform that displays a goal time for workers to shoot for when completing a task. It also has a stopwatch on it that is controlled by a start, stop, and reset button on the userform. If the stopwatch time reaches the goal time and goes over, then there is a box called "extra time" that starts counting up. It just displays how much extra time the employees are taking to complete a task. The code runs insanely slow, and I think it's just because it is continuously runs a do until statement.

Is there anything I could do to make Excel not freeze up as much when I run this?

Dim StopTimer As Boolean
Dim Etime As Single
Dim Etime0 As Single
Dim LastEtime As Single
Dim goal As Single
Dim Etime1 As Single
Dim Etime2 As Single
Dim LastEtime2 As Single

Public Sub btnReset_Click()
StopTimer = True
Etime = 0
Etime0 = 0
LastEtime = 0
Etime1 = 0
Etime2 = 0
LastEtime2 = 0
lblTime.Caption = "00:00:00"
lblExtra.Caption = "00:00:00"
End Sub

Public Sub btnStart_Click()
goal = 86400 * (Sheets("Input").Range("C2"))    'goal time in seconds
StopTimer = False
Etime0 = Timer()
Etime1 = Timer() + goal
Do Until StopTimer

If Etime < goal Then
    Etime = Int((Timer() - Etime0) * 100) / 100
    If Etime > LastEtime Then
        LastEtime = Etime
        lblTime.Caption = Format(Etime / 86400, "hh:mm:ss")
        DoEvents
    End If
Else
    Etime2 = Int((Timer() - Etime1) * 100) / 100
    If Etime2 > LastEtime2 Then
        LastEtime2 = Etime2
        lblExtra.Caption = Format(Etime2 / 86400, "hh:mm:ss")
        DoEvents
    End If
End If

Loop
End Sub

Public Sub btnStop_Click()
StopTimer = True
End Sub

Public Sub ComboBox1_Change()
Dim cotime As Single
'Dim lookup As String
'lookup = Application.WorksheetFunction.c
'cotime = application.WorksheetFunction.IF(ISERROR(VLOOKUP(Combobox1&Combobox2,AvgFor12to14,2,FALSE)),"N/A",VLOOKUP(Combobox1&Combobox2,AvgFor12to14,2,FALSE)/1440))

Sheets("Input").Range("A2") = Me.ComboBox1.Value
'Me.AvgTime.Value = Format(cotime, "hh:mm:ss")
Me.AvgTime.Caption = Format(Sheets("Input").Range("C2"), "hh:mm:ss")

End Sub

Public Sub ComboBox2_Change()

Sheets("Input").Range("B2") = Me.ComboBox2.Value
Me.AvgTime.Caption = Format(Sheets("Input").Range("C2"), "hh:mm:ss")

End Sub

Private Sub UserForm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Application.Visible = True
End Sub

Private Sub UserForm_Initialize()
ComboBox2 = ""
ComboBox1 = ""
End Sub


texts: Length of the longest common sub sequence bottom up

texts:
Could I get some feedback on this code? I included a test case as well.

This code computes the longest common sub sequence given paired data, it was not part of any challenge I just did it to learn about dp.

To my understanding it runs in \$\mathcal{O}(m*v)\$ where \$m\$ is length str1 and \$v\$ len str2.

def lcs(word1, word2):

  x = len(word1)
  y = len(word2)
  return _lcs(word1, word2, x, y)

def _lcs(word1, word2, x, y):

  matrix = [[-1]*(x) for val in range (0,y)]

  for i in range(0, y):
    for j in range(0, x):

      if word1[j] == word2[i]:
        if i-1 < 0 or j-1 < 0:
          matrix[i][j] = 1
        else:
          matrix[i][j] = 1 + matrix[i-1][j-1]

      else:
        val1 = 0
        val2 = 0
        if i-1 >= 0:
          val1 = matrix[i-1][j]
        if j-1 >= 0:
          val2 = matrix[i][j-1]
        matrix[i][j] = max(val1,val2)

  return matrix[y-1][x-1]

a = 'ABC'
b = 'ABCD'
print(lcs(a,b))


texts: Constructing and initializing global objects

texts:
I have a script for a web page that has to initialize a lot of complex event handlers on page load. Because of the large number of events and DOM elements that these events should fire for, I want to construct a global object containing all the initialization logic.

var Global =
    {
        button1Handler: function () {
            return {
                button1: $("#button1"),
                init: function () {
                    this.button1.on("click", function () { alert("button1 clicked"); });
                }
            };
        },
        button2Handler: function () { /* */},
        init: function () {
            this.button1Handler().init();
            this.button2Handler().init();
            // ...
        }

    };

$(function () {
    Global.init();
});

But as I'm quite new to JavaScript, I have no idea whether this is the most simple or correct way to do this. And I'm not sure I like these chain function calls: button1Handler().init().

Is there a better way to write this piece of code?


texts: Replace CASE WHEN statement with something more sensible

texts:
While checking my SPs today I found that I have,

SELECT  COUNT(*)
,CASE WHEN ISNULL(MIN(COALESCE(MP.NewPrice, MP.Price, 2147483647)),0) = 2147483647 THEN 0 ELSE ISNULL(MIN(COALESCE(MP.NewPrice, MP.Price, 2147483647)), 0) END
FROM    MerchantsProducts MP

I need to replace this with something which make more sense. Can someone please review this?


texts:
This Haskell program just aligns the text lines on the given substrings.

I took inspiration from here, but my code is not golfed.

import Data.Function
import Data.Ord
import Data.List
import Data.List.Split

alignOn :: String -> [String] -> [String]
alignOn char lines = map padline lines
  where
    partBeforechar = head . splitOn char
    longestLengthBeforeChar = maximum $ map (length . partBeforechar) lines
    padline line = replicate offset ' ' ++ line
      where
        offset = longestLengthBeforeChar - (length (partBeforechar line))

main = do
  mapM putStrLn $ alignOn "," ["Programming, Puzzles", "And, Code Golf"]
  mapM putStrLn $ alignOn ", " ["Code, Review", "And Other, improvements"]
  mapM putStrLn $ alignOn "abc" ["Example abc bar", "foo abc Example"]

Output:

Programming, Puzzles
        And, Code Golf

     Code, Review
And Other, improvements

Example abc bar
    foo abc Example


texts: Simple calculator (going H.A.M with defining functions)

texts:
I am toying around and playing a lot with defining a function. I'm trying to get extremely comfortable with it. The code I have wrote works fairly well, but definitely is not perfect. Also, the function I made called playagain is having some errors. When I type in "Yes" for the input I'm getting a strange TypeError. If you can fix that, please explain to me how, in the simplest way possible.

import sys

OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"]

def userinput():
    while True:
        try:
            number = int(input("Number: "))
            break
        except ValueError:
            print("NOPE...")
    return number

def operation():
    while True:
        operation = input("Multiply/Divide/Add: ")
        if operation in OPTIONS:
            break
        else:
            print("Not an option.")
    return operation

def playagain():
    while True:
        again = input("Again? Yes/No: ")
        if again == "Yes" or again == "yes":
            break
        elif again == "No" or again == "no":
            sys.exit(0)
        else:
            print("Nope..")

def multiply(x,y):
    z = x * y
    print(z)

def divide(x,y):
    z = x / y
    print(z)

def add(x,y):
    z = x + y
    print(z)

def subtract(x,y):
    z = x - y
    print(z)

while True:
    operation = operation()
    x = userinput()
    y = userinput()
    if operation == "add" or operation == "Add":
        add(x,y)
    elif operation == "divide" or operation == "Divide":
        divide(x,y)
    elif operation == "multiply" or operation == "Multiply":
        multiply(x,y)
    elif operation == "subtract" or operation == "Subtract":
        subtract(x,y)

    playagain()

I tried defining as much functions as possible to make it simpler and easier to fix and debug. Please let me know what you think.

NOTE: I am not making this program to actually be a beneficial program. I am simply using it to help myself with the defining a function portion of Python.


texts: Convert string to fishy and fishy to string

texts:
Inspired by this question.

Here's the code:

class FishyError(Exception):
    __module__ = Exception.__module__

def string_to_fishy(string: str) -> str:
    """
    Converts a string to fishy code

    Examples:
        Hello World!
        ><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>

        007 James bond
        ><48> ><48> ><55> ><32> ><74> ><97> ><109> ><101> ><115> ><32> ><98> ><111> ><110> ><100>

    """

    l = []

    for char in string:
        l.append(f'><{ord(char)}>')

    return ' '.join(l)

def fishy_to_string(fishy: str) -> str:
    """
    Converts a fishy code to string

    Examples:
        ><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>
        Hello World!

        ><48> ><48> ><55> ><32> ><74> ><97> ><109> ><101> ><115> ><32> ><98> ><111> ><110> ><100>
        007 James bond

    """

    if not fishy:
        return ''

    fishy_chars = fishy.split(' ')

    string = ''

    for char in fishy_chars:
        if not char:
            raise FishyError('Invalid syntax: Extra whitespace')

        if not (char.startswith('><') and char.endswith('>')):
            raise FishyError('Invalid syntax: ' + char)

        try:
            value = int(char[2:-1])
            string += chr(value)

        except ValueError:
            raise FishyError('Invalid syntax: ' + char)

    return string

while True:
    print(fishy_to_string(input()))

This works well, but doesn't look that great. Any ideas?


texts: Handling Circular References Without Recursion

texts:
Despite the many decent answers to this question, one was unable to find an iterative solution. Here's what I came up with:
Code:
type CircularReferenceHandler = (parentKey: IndexKey, parentValue: Dictionary<IndexKey, any>, childKey: IndexKey, childValue: Dictionary<IndexKey, any>) => void;
type Dictionary<TKey extends IndexKey, TValue> = Record<TKey, TValue>;
type IndexKey = (number | string);

const processCircularReferences = <T extends object>(input: T, handler: CircularReferenceHandler, initialPathValue = "o"): T => {
    const objectStack = [{ k: initialPathValue, v: input, },];
    const objectTracker = new WeakSet<Dictionary<IndexKey, any>>();

    objectTracker.add(input);

    while (objectStack.length) {
        const { k: parentKey, v: parentValue } = objectStack.shift()!;

        for (const [childKey, childValue] of Object.entries(parentValue)) {
            if ((childValue && ("object" === typeof childValue))) {
                if (objectTracker.has(childValue)) {
                    handler(parentKey, parentValue, childKey, childValue);
                }
                else {
                    objectStack.push({ k: `${parentKey}.${childKey}`, v: childValue, });
                    objectTracker.add(childValue);
                }
            }
        }
    }

    return input;
}

Usage:
let o: any = { x: 0, y: 1, };

o.me = {};
o.me.self = o;
o.self = o;

processCircularReferences(o, (pK, pV, cK, _cV) => {
    console.log(`${pK}.${cK}`);

    pV[cK] = undefined;
});

console.log(o);

/*
    [log]: o.me.self
    [log]: o.self
    [log]: {
               me: {
                   self: undefined
               },
               self: undefined,
               x: 0,
               y: 1
           }
 */


texts: Correct, DRY, and efficient use of Django Managers?

texts:
I'm writing a custom Manager for my django app that lets you group django-enumfields:

class NWODCharacter(models.Model):

    class Meta:
        abstract = True

    attributes = GenericRelation('CharacterAttributeLink')

    @property
    def physical_attributes(self):
        return [self.attributes.filter(attribute=attribute) for attribute
                in AttributeAbility.objects.physical()]
    # And 8 others

To get to the attributes we need these two:

class CrossCharacterMixin(models.Model):
    cross_character_types = models.Q(app_label='mage', model='mage')
    content_type = models.ForeignKey(ContentType, limit_choices_to=cross_character_types,
                                     null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        abstract = True

class CharacterAttributeLink(Trait, CrossCharacterMixin):
    attribute = models.ForeignKey('AttributeAbility')

And now AttributeAbility and the CategoryManager:

class AttributeAbility(models.Model):

    class Attributes(AutoNumber):
        INTELLIGENCE = ()  # Mental, Power
        WITS = ()  # Mental', 'Finesse
        RESOLVE = ()  # Mental', 'Resistance
        STRENGTH = ()  # Physical', 'Power
        DEXTERITY = ()  # Physical', 'Finesse
        STAMINA = ()  # Physical', 'Resistance
        PRESENCE = ()  # Social', 'Power
        MANIPULATION = ()  # Social', 'Finesse
        COMPOSURE = ()  # Social', 'Resistance

    attribute = EnumField(Attributes)
    objects = CategoryManager()

    @property
    def category(self):
        attribute_group = lambda attribute: (
            int((attribute.value - 1) / 3)) + 1 % 3

        return Category(attribute_group(self.attribute))

    class Meta:
        verbose_name_plural = "Attribute Abilities"

    def __str__(self):
        return self.attribute.label

class Category(AutoNumber):
    MENTAL = ()
    PHYSICAL = ()
    SOCIAL = ()

class CategoryManager(models.Manager):

    '''
    Class to manage instances that rely on the category enum
    '''

    def physical(self):
        return [categorised_item for categorised_item in super(CategoryManager, self).get_queryset().all()
                if categorised_item.category == Category['PHYSICAL']]

    def mental(self):
        return [categorised_item for categorised_item in super(CategoryManager, self).get_queryset().all()
                if categorised_item.category == Category['MENTAL']]

    def social(self):
        return [categorised_item for categorised_item in super(CategoryManager, self).get_queryset().all()
                if categorised_item.category == Category['SOCIAL']]

My concern is over the number of queries, and the use of List Comprehension. I'm also wondering if this is a common pattern, or if there is a 'better' practice to achieving this.

1 AutoNumber.


texts: Is there a simpler way to make an English-readable list from strings in a tuple?

texts:
I looking over some old code, I had written the function below with a C-style for-loop iterating over a count variable. I then fixed it up with new knowledge, but still am suspicious that there is even a better way to do this.

The function should behave like so:

>>> join_list(['a'])
'a'
>>> join_list(['a', 'b'])
'a or b'
>>> join_list(['a', 'b', 'c'])
'a, b, or c'

The function I have currently:

def join_list(my_list):
    length = len(my_list)
    if length == 1:
        return my_list[0]
    elif length == 2:
        return ' or '.join(my_list)
    else:
        head = ', '.join(my_list[:-1])
        return head + ', or ' + my_list[-1]


texts: Backward elimination of fixed effects using lme4

texts:
I am trying to write a function that used drop1.merMod from the lme4 package to automatically
remove fixed effect terms until the removal of a term will result in a higher AIC.

This is complicated by trying to account for times when the models do not converge.

Generally, the scheme I'm using is

The function takes a fitted lmer or glmer model that is known to converge.
drop1 is applied:
--  if drop1 includes models that don't converge then update the iterations in the original model
--  try drop1 again
repeat
   --  If drop1 converges then
      --update model by removing term
 until no term to be removed

If the scheme cant proceed without convergence warnings then NA should be retuned.

And the code I've written that tries to do this

stepdown <- function(x, iter=1e5, n=3) {

  options(warn=2)
  mod = x
  drop =  try(lme4:::drop1.merMod(mod), silent=TRUE)
  ret = NA # default return in case of non-convergence

  # function to rerun model with updated starting parameters
  update_mod <- function(mod, iter){
      if (isLMM(mod)) {
        pars = getME(mod,"theta")
        control=lmerControl(optCtrl=list(maxfun=iter))
      }else{
        pars = getME(mod, c("theta","fixef"))
        control=glmerControl(optCtrl=list(maxfun=iter))
      }
      mod = update(mod, start=pars, control=control)
  }

  # If drop throws an error try increasing the number
  # of iterations within mod
  if(inherits(drop, "try-error")){
    mod = update_mod(mod, iter)
    drop = try(lme4:::drop1.merMod(mod))
  }
      # if no error try removing terms as required
      if(!inherits(drop, "try-error")){
          nms  =  row.names(drop)[order(drop$AIC)][1]
          if(nms == "<none>") {
            ret = paste(attr(terms(mod), "term.labels"), collapse=",")
            }else{
              # remove terms until "<none>" can be removed
              repeat{
                mod  = try(update(mod, as.formula( paste(". ~ . -", nms, collapse="") )))
                i = 1
                # try refitting model (with term removed) with new starting positions n times
                repeat{
                        if(inherits(mod, "try-error")){
                              mod = try(update_mod(mod, iter))
                          }
                  i = i + 1
                  if( i > n) break
                }

                drop = try(drop1(mod))

                if(inherits(drop, "try-error")){
                    mod = update_mod(mod, iter)
                    drop = try(lme4:::drop1.merMod(mod))
                  }

            if(!inherits(drop, "try-error")){
                nms  =  row.names(drop)[order(drop$AIC)][1]
                ret  = paste(attr(terms(mod), "term.labels"), collapse=", ")
                if(nms == "<none>") break
              }
              }
            }
      }
  return(ret)
}

This is a worked example

# devtools::install_github("dmbates/RePsychLing")
library(RePsychLing)
library(lme4)

options(warn=0)

mod <- lmer(dif ~ 1+S+F+SF + (1+S+F+SF|subj) + (1+S+F+SF|item), bs10, REML=FALSE, start=thcvg$bs10$m0,
           control=lmerControl(optimizer="Nelder_Mead",optCtrl=list(maxfun=1L),
                               check.conv.grad="ignore",check.conv.hess="ignore"))

stepdown(mod)

Can any suggestions be offered in regards to tidying up the code, and if I have caught the convergence / error handling okay.
(I am aware of the dubious statistics being used)


texts: I made a guess the number game in Python

texts:
I just started programming a week ago. Online tutorials aren't my thing, so I decided to just start projects and learn what I need for the project.

My first project is a guess the number game. The user is asked to guess a number between 0 and 20. If the user's guess is too high, they will be told it's high and likewise if it's too low. This will go on until the user guesses correctly.

print("Enter a random number between 0 and 20")
userInput = int(input())
random_number= random.randint(0,20)

def random_num_checker(num,guess):
    if num== guess:
        print('CORRECT')
    else:
        while guess != num:
            if guess > 20:
                print('I said between 0 and 20')
            if guess < num:
                print('too small')
            elif guess > num:
                print('too big')
            guess=int(input())
        print('CORRECT')
random_num_checker(random_number,userInput)


texts: C++ code to find distance between line and point

texts:
So I made this simple program that allows users to construct points and lines and then return the smallest distance between a given point and a line. In doing so I have used some OOP concepts and operator overloading (both of which are fairly new territory for me). As such, I would really appreciate feedback. Furthermore, the code assumes that the user specifies a line by providing two distinct points and that this line is infinite.

#include <vector>
#include <algorithm>
#include <iostream>

class Point {
    public:
    int x;
    int y;
    Point (int x, int y) : x(x), y(y) {};
    Point() : x(0), y(0) {};
};

class Vector {
    public:
        int x;
        int y;
        Vector () : x(0), y(0) {};
        Vector (Point p1, Point p2) : x(p2.x - p1.x), y(p2.y - p1.y) {};
};

class Line {
    public:
    Point start;
    Point finish;
    Vector direction_vector;
    Line(Point st, Point fin) {
        direction_vector = Vector(st, fin);
        start = st;
        finish = fin;
    };
};

int operator^(const Vector& v1, const Vector& v2) {
    int ret = ((v1.x) * (v2.y)) - ((v1.y) * (v2.x));
    //cross product should return 3d vector but for convenience
    //return an int (for example by dotting result with unit z vector)
    return ret;
}

int operator*(const Vector& v1, const Vector& v2) {
    int ret = ((v1.x) * (v2.x)) + ((v1.y) * (v2.y));
    return ret;
}

double distance_line_point(Line l, Point p) {
    Vector AB = l.direction_vector;
    Vector AC(l.start, p);
    int abs = ((AB)*(AB));
    double norm = (double) std::sqrt(abs);
    //return distance by using area of triangle is base*height / 2
    //and then calculate area using cross product
    double dist = ((double) (AB^AC)) / ((double) norm);
    return std::abs(dist);
}

int main() {
    Point p1(1, 1);
    Point p2(2, 6);
    //construct two points to form line
    Point p3(3,3);
    //construct point to find distance to line
    Line l1(p1, p2);
    //make line from two points
    double res = distance_line_point(l1, p3);
    std::cout << res << std::endl;
    return 0;
}


texts: Refactoring legacy code for unit testing

texts:
I'm trying to refactor some code for unit testing and was hoping you could critique it.

This is the original method:

public class MyNonRefactoredClass
{
   public List<MyClass> DoSomething()
  {
      List<MyClass> data = GetData();

      if (data.Count == 0)
        return new List<MyClass>();

      data = GetFormattedData(data);

      if (data.Count == 0)
        return new List<MyClass>();

      //Do some more stuff

      return data;
   }

  public List<MyClass> GetData()
  {
      //Do db query and return data
  }

  public List<MyClass> GetFormattedData(List<MyClass> Data)
  {
      //Do some logic on Data variable. Might return empty if data is not what I like
  }

}

Here is my new approach. I have done it like this as I believe I need an entry point to try and access methods that I want to test.

public class MyRefactoredClass
{
  public List<MyClass> DoSomething()
  {
    //Dependency Injection needs to work somehow here
    MySeparateClass newClass = new MySeperateClass(new DataProvider());
    List<MyClass> dbData = newClass.GetData();
    if (db.Data.Count == 0)
      return new List<MyClass>();
    dbData = newClass.GetFormattedData();
    if (db.Data.Count == 0)
      return new List<MyClass>();
    //Continue method doing other things...
    }
}

public class MySeparateClass
{
  private IDataProvider dbProvider;

  public MySeparateClass(IDataProvider DataProvider)
  {
    dbProvider = DataProvider;
  }

  public List<MyClass> GetData()
  {
    //Do DB stuff
    return dbProvider.GetData();
  }

  public List<MyClass> GetFormattedData(List<MyClass> Data)
  {
    //Format
  }
}

[Test]
public DoSomething_DBReturnsNoData_ReturnEmptyList()
{
  //Setup mock of IDataProvider
  //Tell mock to not return data from GetData
  //Assert that result.count == 0
}

[Test]
public DoSomething_FormattedReturnsNoData_ReturnsEmptyList()
{
  //Setup mock of IDataProvider
  //Tell mock to return some data from GetData
  //Setup mock of MySeparateClass
  //Tell mock to return no data from GetFormattedData
  //Assert that result.Count == 0
}


texts: In my Hangman game, one of my functions is correct but messy

texts:
I got a ton of helpful tips last time I posted some code, so I thought I would come back to the well.

My function is deciding whether or not the secretWord has been guessed in my hangman game.  I am trying to accomplish this by taking a list, lettersGuessed, and comparing it to the char in each index of the string secretWord. My code works, but I feel as though it is not optimal nor formatted well.

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    chars = len(secretWord)
    place = 0
    while place < chars:
        if secretWord[0] in lettersGuessed:
            place += 1
            return isWordGuessed(secretWord[1:], lettersGuessed)
        else:
            return False
    return True

I tried to use a for loop (for i in secretWord:) originally, but I could not get my code to return both True and False.  It would only do one or the other, which is how I ended up with the while loop. It seems that while loops are discouraged/looked at as not very useful.  Is this correct?

Also, I am wondering if the recursive call is a good way of accomplishing the task.


texts:
I'm reading Head First Design Patterns and I'm currently reading about the observer pattern. Is what I produced correct?

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class ObserverInterface
{
public:
    virtual void update(std::string message) = 0;
};

class concreteObserver : ObserverInterface
{
    std::string name;
    std::string message;
public:
    concreteObserver(std::string name)
        :name(name)
    {}
    void update(std::string message)
    {
        this->message = message;

        std::cout << "Dear " << name << ", " << message << " from eBay" << std::endl;
    }
};

class SubjectInterface
{
public:
    void subscribe(concreteObserver *subscriber)
    {
        subscribers.push_back(subscriber);
    }
    void unsubscribe(concreteObserver *subscriber)
    {
        subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), subscriber), subscribers.end());
    }
    void notify(std::string message)
    {
        std::vector<concreteObserver*>::const_iterator itr = subscribers.begin();
        while (itr != subscribers.end())
        {
            (*itr)->update(message);
            ++itr;
        }
    }
private:
    std::vector<concreteObserver*> subscribers;
};

class concreteSubject : public SubjectInterface
{
public:
    void newMessage(std::string msg)
    {
        notify(msg);
    }
};

int main(int argc, char* argv[])
{
    // EBAY
    concreteSubject ebay;

    // USERS
    concreteObserver user1("Steven");
    concreteObserver user2("John");

    // SUBSCRIBERS TO EBAY
    ebay.subscribe(&user1);
    ebay.subscribe(&user2);

    // EBAY SENDS NEW PROMOTIONS TO SUBSCRIBERS
    ebay.newMessage("enjoy free weekend listings");

    // UNSUBSCRIBE FROM EBAY
    ebay.unsubscribe(&user2);

    // EBAY SENDS NEW PROMOTION TO SUBSCRIBERS
    ebay.newMessage("free listings extended until 1st August");

    std::cout << std::endl << std::endl;
    system("pause");
    return 0;
}


texts: Sending data to a database in size-limited chunks

texts:
I have a method which takes a parameter which is Partition enum. This method will be called by multiple background threads around same time period by passing different value of partition. Here dataHoldersByPartition is a map of Partition and ConcurrentLinkedQueue<DataHolder>.

  private void validateAndSend(final Partition partition) {
    ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(partition);
    Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder = new HashMap<>();
    int totalSize = 0;
    DataHolder dataHolder;
    while ((dataHolder = dataHolders.poll())  != null) {
      byte[] clientKeyBytes = dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8);
      if (clientKeyBytes.length > 255)
        continue;
      byte[] processBytes = dataHolder.getProcessBytes();

      int clientKeyLength = clientKeyBytes.length;
      int processBytesLength = processBytes.length;

      int additionalLength = clientKeyLength + processBytesLength;
      if (totalSize + additionalLength > 50000) {
        Message message = new Message(partition, clientKeyBytesAndProcessBytesHolder);
        sendToDatabase(message.getAddress(), message.getLocation());
        clientKeyBytesAndProcessBytesHolder.clear(); // watch out for gc
        totalSize = 0;
      }
      clientKeyBytesAndProcessBytesHolder.put(clientKeyBytes, processBytes);
      totalSize += additionalLength;
    }
    // calling again with remaining values only if clientKeyBytesAndProcessBytesHolder is not empty
    if(!clientKeyBytesAndProcessBytesHolder.isEmpty()) {
        Message message = new Message(partition, clientKeyBytesAndProcessBytesHolder);
        sendToDatabase(message.getAddress(), message.getLocation());
    }
  }

In the method, I will iterate dataHolders CLQ and I will extract clientKeyBytes and processBytes from it. Here is the validation that I am supposed to do:

If the clientKeyBytes length is greater than 255 then I will skip it and continue iterating.
I will keep incrementing the totalSize variable which will be the sum of clientKeyLength and processBytesLength, and this totalSize length should always be less than 50000 bytes.
As soon as it reaches the 50000 limit, I will send the clientKeyBytesAndProcessBytesHolder map to the sendToDatabase method and clear out the map, reset totalSize to 0 and start populating again.
If it doesn't reaches that limit and dataHolders got empty, then it will send whatever it has.

Basically, what I have to make sure is whenever the sendToDatabase method is called, the clientKeyBytesAndProcessBytesHolder map should have size less than 50000 (sum of all keys and values length). It should never be called with the size greater than 50000 (50k).

Question:

My code works fine, but as you can see, I am calling the sendToDatabase method at two places: one is as soon as it is reaching the 50k limit, and the other is it didn't reach because we ran out of elements.

Is there any way by which I can call the sendToDatabase method just once and still fulfill both my conditions by rewriting it in a better way? I am working with Java 7.


texts: Get value from dictionary given a list of nested keys

texts:
I would like to get a deeply-nested value, for example {"a":{"b":{"c":"myValue"}} by providing the keys to traverse. I tried chaining together .get() but that didn't work for cases where some of the keys were missing—in those cases, I want to get None instead.

Could this solution be improved?

#!/usr/bin/env python
# encoding: utf-8

def nestedGet(d,p):
    if len(p) > 1:
        try:
            return nestedGet(d.get(p[0]),p[1:])
        except AttributeError:
            return None
    if len(p) == 1:
        try:
            return d.get(p[0])
        except AttributeError:
            return None

print nestedGet({"a":{"b":{"c":1}}},["a","b","c"]) #1
print nestedGet({"a":{"bar":{"c":1}}},["a","b","c"]) #None


texts:
Topic 1: Switching to another form from the project startup form

I use the following code that calls an instance of my form for payment (frmPayment) from my startup form (frmMainMenu) using a click event:

Private Sub btnPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPayment.Click, PaymentToolStripMenuItem.Click
        Dim frmPaymentX As New frmPayment() 'declare payment form
        Me.Visible = False
        frmPaymentX.ShowDialog()
End Sub

Should I use something other than Me.Visible = False in handling my startup form (frmMainMenu) during my form switch?

Topic 2: Switching back to the startup form

Likewise, I use the following code to return to my startup form (frmMainMenu) from my form for payment (frmPayment):

Private Sub btnMainMenu_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMainMenu.Click
        frmMainMenu.Show()
        Me.Close()
End Sub

Should I directly call my startup form (frmMainMenu) as I am doing in my example or should I be calling an instance of my starup form (frmMainMenu)?
I believe that I should use show() and not showdialog() for this.  Is this correct?
Should I use something other than Me.Close()?


texts: AJAX request authentication to PHP script

texts:
Recently I started looking at my AJAX call security and found some code that uses tokens, request and referer in an attempt to authenticate the call and stop XSS and CSRF.

The AJAX calls are for the article list / article table in the admin section.

Note: The PHP will not run unless you are logged in — it uses a cookie and sessions to authenticate user.

EDIT: Implemented schisms function name suggestion.

The following code works as it should but is it a good method?

Create our Token:

$token = md5(rand(1000,9999));
$_SESSION['token'] = $token;

The button to deactivate / activate an article:

if($article_active === 1){
echo '<input type="button" class="active_button" title="Deactivate" value="YES" name="'.$article_id.'"/>';
}
else {
echo '<input type="button" class="active_button" title="Activate" value="NO" name="'.$article_id.'" />';
}
echo '

The AJAX call:

// ACTIVATE / DEACTIVATE WITH LINK
$(document).on("click",".active_button",function() {

    var form_data = {
        articleID: $(this).attr("name"),
        active: $(this).val(),
        selector: $("#selector").attr("name"),
        data: $("#data").val(),
        token:'<?php echo $token; ?>',
        is_ajax: 1
    };

    $.ajax({
    type: "POST",
    url: "controllers/articlecontrol.php",
    data: form_data,
    success: function(data){
        document.location.reload(true);
    }
    });
});

The PHP that validates the AJAX request and sends the data to a PHP function:

// ACTIVATE / DEACTIVATE w/BUTTON
if(isset($_POST['active']) && $selector === 'article') {

    if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token']) && $_POST['token'] === $_SESSION['token']){

                $articleid = $_POST['articleID'];
                $active = ($_POST['active'] === 'YES') ? 0 : 1;
                $backend->setArticleStatus($articleid, $active);
            }
            else {
                $_SESSION['status'] = '
There was a Problem Activating / Deactivating that Article
';
            }
}

The PHP activate / deactivate function (part of a class):

/**
 * Activate / Deactivate Article w/Button
 */

 public function setArticleStatus($articleid, $active) {
    $query = 'UPDATE wcx_articles SET article_active = :active WHERE article_id = :articleid';
    $stmt = $this->queryIt($query);
    $stmt = $this->bind(':active', $active);
    $stmt = $this->bind(':articleid', $articleid);
    if($this->execute()) {
        if ($active === 0) {
            $_SESSION['status'] = '
Article Deactivated Successfully
';
        }
        else {
            $_SESSION['status'] = '
Article Activated Successfully
';
        }
    }
    else {
        $_SESSION['status'] = '
There was a Problem Activating / Deactivating that Article
';
    }
 }


texts: Functional Re-Write in Scala: Rows of Strings with a Max Width

texts:
I came across an issue the other day where I really just could not think of a functional solution. So I fell back on my imperative programming skills. Since a functional solution still eludes me, I figured I'd shout out for some help here.

Use Case

I have a List of Strings with arbitrary lengths. These Strings need to be combined into rows that have the same max length.

When a single String's length is greater than max length, that String just gets it's own row as each row eventually get's handled by a function that ensures all Strings are truncated to an appropriate length.

Example Usage

scala> val rows = combineStrings(List("Short", "This is a particularly long String...", "More", "Small", "Strings"), 35)

Current Output

scala> rows.foreach(println)
Short
This is a particularly long String...
More, Small, Strings

Desired Output

scala> rows.foreach(println)
Short, More, Small, Strings
This is a particularly long String...

Current Solution

def combineStrings(strs: List[String], maxLen: Int)
: List[String] = {
  import scala.collection.mutable.ListBuffer

  var scratch = strs.mkString("|")
  val rows = ListBuffer[String]()

  while (scratch.length > 1) {
    scratch.indexOf("|") match {
      case idx if (idx == -1 || scratch.length < maxLen) =>
        rows += scratch
        scratch = ""

      case idx if idx > maxLen =>
        rows += scratch.substring(0, idx)
        scratch = scratch.substring(idx+1)

      case idx =>
        val lIdx = scratch.lastIndexOf("|", maxLen)
        rows += scratch.substring(0, lIdx)
        scratch = scratch.substring(lIdx+1)
    }
  }

  rows.toList.map(_.replaceAll("\\|", ", "))
}

Notes

Pipes are used because the original Strings are more likely to have their own commas than their own pipes. Maybe other solutions won't need this hackery.
Strings are kept in the same order, but in the end I'd prefer to have the most "compact" rows possible.

Summary

Any ideas on how to make this more functional would be greatly appreciated. I found several functions in Scala's "String" that looked promising, but I'm not really sure how to integrate them with the length requirements.


texts: Rspec test reuse code for before_filter and method

texts:
Consider following example (controller):

MyController < ApplicationController
    def index
      @objects = Object.fancy_way_of_retrieval
      @properties = Property.fancy_way_of_retrieval_two

      @something_else = @objects.do_something
    end

    def another_method
      @something_other = SomethingOther.get_values
      @objects = Object.fancy_way_of_retrieval
      @properties = Property.fancy_way_of_retrieval_two
    end
  end

First thing I did is to move the duplicate code in the before_filter

MyController < ApplicationController
before_filter :set_variables

  def index
    @something_else = @objects.do_something
  end

  def another_method
    @something_other = SomethingOther.get_values
  end

private
  def set_variables
    @objects = Object.fancy_way_of_retrieval
    @properties = Property.fancy_way_of_retrieval_two
  end
end

Which looks better, right? Now on to the test :

describe 'before filters' do
  let(:objects) { [FactoryGirl.build_stubbed(:object)] }
  let(:properties) { [FactoryGirl.build_stubbed(:property)] }

  before do
    allow(Object).to receive(:fancy_way_of_retrieval).and_return { objects }
    allow(Property).to receive(:fancy_way_of_retrieval_two).and_return { properties }
  end

  it 'assigns objects' do
    get :index
    expect(assigns(:objects)).to eq(objects)
  end

  it 'assigns properties' do
    get :index
    expect(assigns(:properties)).to eq(properties)
  end
end

Now onto the controller action method test :

describe '#index' do
  let(:objects) { [FactoryGirl.build_stubbed(:object)] }
  let(:properties) { [FactoryGirl.build_stubbed(:property)] }

  before do
    allow(Object).to receive(:fancy_way_of_retrieval).and_return { objects }
    allow(Property).to receive(:fancy_way_of_retrieval_two).and_return { properties }
  end

  it 'asssigns something else' do
  ....
  end
end

See I had to write the let and before blocks for objects and properties stubs for both before filter method and the controller action method, in order for test to pass. Because the @something_else uses the @objects instance variable.

How do I do this without repeating this bit of code?


texts:
I'm learning Clojure and solved Project Euler #1, I'd like to have my code reviewed on all aspects. I'm marking this as follow-up of Project Euler #1 because I answered my own question and implemented it.

Task: Multiples of 3 and 5

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

My solution

 (ns euler)

 (defn divisible-by?
   [x divisor]
   (zero? (mod x divisor)))

(->> (range 1000)
     (filter #(some (partial divisible-by? %) '(3 5)))
     (reduce +)
     println)


texts: Dynamic array of integers: another attempt

texts:
This is follow up to this one. In the previous some minor errors slipped, so I couldn't update the code. Also took some advice.
So final version is below.

header:

#define DEFAULT_CAPACITY 1000

// Define a vector type
typedef struct
{
  int nrOfElements; // This just denotes current number of elements.
  int capacity;     // This denotes the capacity of the array.
  int *data;        // Actual pointer to array elements.
} CVectorInt;

typedef enum {VECTOR_SUCCESS, VECTOR_OUTOFBOUNDS, VECTOR_MEMORYERROR, VECTOR_LIMITEXCEEDED} vector_status;

vector_status CVectorInit(CVectorInt *vector);
vector_status CVectorAppend(CVectorInt *vector, int value);
vector_status CVectorGet(CVectorInt *vector, int index, int * value);
vector_status CVectorSet(CVectorInt *vector, int index, int value);
void CVectorFree(CVectorInt *vector);

source:

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

///
// Initialize vector.
//  Set capacity to default value. Current number of elements to 0.
//  Allocate memory dynamically for the default number of elements.
//
//
// Return
//  If there is some problem, error code is returned.
//
vector_status CVectorInit(CVectorInt *vector)
{
    int i = 0;

    vector->capacity = DEFAULT_CAPACITY;
    vector->nrOfElements = 0;

    // Allocate array
    vector->data = malloc(sizeof(int) * vector->capacity);
    if(vector->data == NULL)
        return VECTOR_MEMORYERROR;

    // Initialization the array to default values.
    for(i = 0; i < DEFAULT_CAPACITY; i++)
        vector->data[i] = 0;

    return VECTOR_SUCCESS;
}

vector_status CVectorAppend(CVectorInt *vector, int value)
{
    int * ptr = NULL;
    int i = 0;

    if(vector->capacity == 32000)
        return VECTOR_LIMITEXCEEDED;

    // Do we have room to append elements?
    if(vector->capacity <= vector->nrOfElements)
    {
        // No, increase capacity
        vector->capacity *= 2;

        // Resize array
        ptr = realloc(vector->data, vector->capacity * sizeof(int));
        if(ptr == NULL)
        {
            // We had an error
            return VECTOR_MEMORYERROR;
        }
        else
        {
            vector->data = ptr;

            // Initialize only new elements to 0.
            for(i = vector->nrOfElements; i < vector->capacity; i++)
                vector->data[i] = 0;
        }
    }

    // Now, after possible resize, add the element.
    vector->data[vector->nrOfElements++] = value;

    return VECTOR_SUCCESS;

}

vector_status CVectorGet(CVectorInt *vector, int index, int * value)
{
    // Is the index within bounds?
    if(index < vector->nrOfElements && index >= 0)
    {
        *value = vector->data[index];
        return VECTOR_SUCCESS;
    }else
    {
        return VECTOR_OUTOFBOUNDS;
    }
}

vector_status CVectorSet(CVectorInt *vector, int index, int value)
{
    // We can't set outside capacity
    if(index >= vector->capacity || index < 0)
        return VECTOR_OUTOFBOUNDS;

    // zero fill the vector up to the desired index
    while(vector->nrOfElements <= index)
        CVectorAppend(vector, 0);

    vector->data[index]=value;
}

void CVectorFree(CVectorInt *vector)
{
  // Free underlying array
  free(vector->data);
}


texts:
I want to review the URL routing for my appengine webapp:

routes = [
        (r'/', CyberFazeHandler),
        (r'/vi/(eyes|mouth|nose)', CyberFazeHandler),
        (r'/realtime', RealtimeHandler),
        (r'/task/refresh-user/(.*)', RefreshUserHandler),
        ('/ai', FileUploadFormHandler),
        ('/serve/([^/]+)?', ServeHandler),
        ('/upload', FileUploadHandler),
        ('/generate_upload_url', GenerateUploadUrlHandler),
        ('/file/([0-9]+)', FileInfoHandler),
        ('/file/set/([0-9]+)', SetCategoryHandler),
        ('/file/([0-9]+)/download', FileDownloadHandler),
        ('/file/([0-9]+)/success', AjaxSuccessHandler),
        ]

app = webapp2.WSGIApplication(routes,
            debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'
            ))

Does it look alright to you? Can you recommend an improvement? Should I use the 'r prefix to my regexes?


texts: Largest Prime Factor of Number in PHP or QBasic

texts:
I was solving the 3rd problem at Project Euler which requires me to calculate the largest prime factor of 600851475143  which I think is a really large number (more than 6 billion).

QB64

At first, I tried solving this problem using QB64.

CLS
n = 600851475143
FOR x = 1 TO n
    IF n MOD x = 0 THEN
        FOR y = 1 TO (x / 2) - 1
            IF x MOD y = 0 THEN
                factor = y
            END IF
        NEXT y
        IF factor = 1 THEN
            ans = x
        END IF
    END IF
NEXT x
PRINT ans

However, on running the program, QB64 would appear busy executing the program, but no result would appear even after waiting for a long time.

QuickBasic 4.5

On getting no help from a compiler, I switched to QuickBasic 4.5 which is an interpreter. I executed the same code, but on trying to run the program, QuickBasic would trigger the following error on the line where I define the number.

Overflow

And, the program wouldn't execute at all.

Repl.it / QBasic

Getting no success, I tried using an online interpreter. View the live code at repl.it

On executing the same code on repl.it, the results were similar to what I got for QB64

PHP

I termed this as a limitation for the QBasic language and hence re-wrote the same logic in PHP.

$n = 600851475143;
for($x = 1; $x <= $n; $x++){
    if($n % $x == 0){
        for($y = 1; $y < $x/2; $y++){
            if($x % $y == 0){
                $factor = $y;
            }
        }
        if($factor == 1){
            $ans = $x;
        }
    }
}
echo $ans;

Localhost

On executing this code in my local server (http://localhost:8000) I got no result, instead, the following error:

Maximum execution time of 30 seconds exceeded -- at line 5

I increased the max_execution_time from the php.ini to a few hours. However, I got now result from the code as it never executed completely. I waited for more than 6 hours, but the code continued to execute indefinitely without giving any result.

Online PHP compilers

I then tried a number of online compilers like:

repl.it

Live code here.

WritePHPOnline
PHPFiddle

However, none of them could give me the result as they would either never stop executing or would show the maximum execution time error.

So, my question is, How can I SUCCESSFULLY execute this code to solve my problem? Do I need to:

Use a different, more efficient Compiler / Interpreter
Switch to a different language altogether
Make my logic even more concise to reduce execution time

Note: When I used the above codes with a smaller number like 13195, the result was exactly correct, i.e., 29.


texts:
I have recently learnt about RAII and exceptions and I have been trying to implement them into my code, but I have met an impasse.

With this code here what I am trying to do is manage everything that is being created so that there is nothing left over for when the program ends. I have deliberately set it so that media throws an exception. But before I continue on with more code, I am wondering if this general way of doing things is correct and if are there any other/better approaches to what I am doing.

The two classes that confuse me most are Media and Game. In their destructor, they have it stated that when they go out of scope. They should inform the console that they have gone out of scope, but it isn't currently doing that.

main.cpp

#include "Enemy.h"
#include "Media.h"
#include "Window.h"
#include "Game.h"

#include <SDL.h>
#include <iostream>

int main(int argc, char *args[])
{
    try
    {
        Window window;
        Media media;
        Game game;
    }
    catch (const std::exception &e)
    {
        std::cout << e.what();
        std::cout << "\nProgram failed.";
    }

    char c;
    std::cin >> c;
    return 0;
}

Window.h

#pragma once
#include <SDL.h>
#include <memory>
#include <string>
class Window
{
public:
    Window();
    ~Window();

    SDL_Window* getWindow() const { return m_window; }
    SDL_Surface* getWindowSurface() const { return m_windowSurface; }

    static constexpr int SCREEN_WIDTH = 800;
    static constexpr int SCREEN_HEIGHT = 800;

private:

    void createWindow();
    void CreateWindowSurface();
    SDL_Window* m_window = nullptr;
    SDL_Surface* m_windowSurface = nullptr;
};

Window.cpp

#include "Window.h"
#include <iostream>
Window::Window()
{
    createWindow();
    CreateWindowSurface();
}

Window::~Window()
{
    SDL_DestroyWindow(m_window);
    std::cout << "Window destroyed.\n";
}

void Window::createWindow()
{
    m_window = SDL_CreateWindow("Snake", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    std::cout << "Window created.\n";
    if (m_window == nullptr) {
        throw(std::exception("Failed to initialize Window.\n"));
    }
}

void Window::CreateWindowSurface()
{
    m_windowSurface = SDL_GetWindowSurface(m_window);
    if (m_windowSurface == nullptr) {
        SDL_DestroyWindow(m_window);
        throw(std::exception("Failed to get window surface.\n!"));
    }
}

Media.h

#pragma once
#include <SDL.h>
class Media
{
public:
    Media();
    ~Media();

private:
    void loadSurface();

    SDL_Surface* m_playerSurface = nullptr;
};

Media.cpp

#include "Media.h"
#include <iostream>

Media::Media()
{
    loadSurface();
    //Load all other textures that are associated with the game
}

Media::~Media()
{
    std::cerr << "Media destroyed.\n";
}

void Media::loadSurface()
{
    m_playerSurface = SDL_LoadBMP("Origrimmar.bmp");
    if (m_playerSurface == nullptr) {
        throw(std::exception("Cannot load player texture"));
    }
}

Game.h

#pragma once
#include <SDL.h>
class Game
{
public:
    Game();
    ~Game();

};

Game.cpp

#include "Game.h"
#include <iostream>

Game::Game()
{
    std::cerr << "Game created.\n";
}

Game::~Game()
{
    std::cerr << "Game destroyed.\n";
}


texts: Check if an element is present within a linked list - follow up

texts:
This is a follow up question from here. I have revised my code as
  per the suggestions of peer reviewers. I still feel there is lot of
  scope for improvement in this code.

class Node(object):
    def __init__(self,data, next=None):
        self.data = data
        self.next = next

class LinkedList(object):

    def __init__(self):
        self.head = None
        self.size =0

    def extend(self, seq = None):
        """extends list with the given sequence"""

        for i in range(0, len(seq)):
            node = Node(seq[i])
            self.size +=1
            node.next = self.head
            self.head = node

    def append(self, item):
        """append item to the end of list"""
        node = Node(item)
        node.next = self.head
        self.head = node
        self.size += 1

    def printdata(self):
        """print elements of linked list"""
        node = self.head
        while node:
            print node.data
            node = node.next

    def __iter__(self):
        node = self.head
        while node:
            yield node.data
            node = node.next

    def __contains__(self, item):
        """checks whether given item in list"""
        node = self.head
        while node:
            if node.data == item:
                return True
            node = node.next

    def len(self):
        """returns the length of list"""
        return self.size

    def remove(self, item):
        """removes item from list"""
        node = self.head
        current = self.head.next
        if node.data == item:
            self.size -= 1
            self.head = current
            current = current.next
        while current:
            if current.data == item:
                current = current.next
                node.next = current
                self.size -= 1
            node = current
            current = current.next

    def __str__(self):
        return  str(self.data) + str(self.size)

test cases :

if __name__ == "__main__":

    llist = LinkedList()

    llist.extend([98,52,45,19,37,22,1,66,943,415,21,785,12,698,26,36,18,
    97,0,63,25,85,24])

    print "Length of linked list is ", llist.len()

    llist.append(222)

    print "Length of linked list is ", llist.len()

    llist.remove(22)

    print "Elements of linked list  \n", llist.printdata()
    print "Length of linked list is ", llist.len()

   ## Search for an element in list
    while True:
        item = int(raw_input("Enter a number to search for: "))
        if item in llist:
            print "It's in there!"
        else:
            print "Sorry, don't have that one"