texts: Simple Python script to sort and make json data unique

texts:
I'm retrieving e-mails from a collection of a few hundred *.json files using the following:

Python Script

import os, json

ordersDirectory = "C:\dev\orderArchive"
eMails = []
numUniqueEmails = 0
numEmails = 0

# json objects stored in multiple files, itterate over all of them
for filename in os.listdir(ordersDirectory):
    with open(ordersDirectory + '\\' + filename) as data_file:
        data = json.load(data_file)
        eMails.append(data["details"]["email"])
        numEmails +=1

# create and sort unique list of e-mails
uniqueEmails = sorted(list(set(eMails)))

print("Comma dilimited e-mails: \n")
for email in uniqueEmails:
    # print e-mails to console (comma delimited)
    numUniqueEmails += 1
    print(email + ",", end= " ")

print("\n\nNumber of unique e-mails is: " + str(numUniqueEmails) + " (originally " + str(numEmails) + ")")

Example JSON:

{
   "details":{
      "firstName":"Tester",
      "surname":"Testerman",
      "email":"test@test.com"
      },
   "orders":[
      {
         "name":"A test order",
         "quantity":20
      },
      {
         "name":"Testable data",
         "quantity":20
      }]
}

Example output

Assuming that 30 files were processed and there were 3 unique e-mail addresses among them.

  Comma dilimited e-mails:

  test@test.com, test2@test.com, emailhereagain@test.com,

  Number of unique e-mails is: 3 (originally 30)

I know it's not very functional however I'm a C# developer primarily - I can get the job done in Python (and had to quickly for this task) but I'd love to know how to think more "pythonic". Any feedback or suggestions about style or performance are also appreciated.


texts: Python: Function to Find 2 Closest Points Among [x,y] Coordinates

texts:
I'm writing some code in Python that takes a set of [x,y] coordinates (in a list of tuples) and also an x-value. I need to find the two closest x coordinates to my x-value.

To find the closest x, I created a list of all the x-coordinates, used that list to create a lambda function that found the closest x to my x-value, and then found the index of that x.

Finding the 2nd closest value was a bit trickier. I created a new list that excluded the closest x and followed the same process.

Code is below. Any suggestions on how to improve this or make it more efficient?

def closest_2_points(list_of_tuples, x_value):

    x_points = []

    for i in list_of_tuples:
        x_points.append(i[0])

    # find closest point
    closest_xpoint_1 = min(x_points, key=lambda z:abs(z-x_value))
    closest_xpoint_1_idx = x_points.index(closest_xpoint_1)

    # find 2nd closest point
    x_points_2 = [x for x in x_points if x != closest_xpoint_1]
    closest_xpoint_2 = min(x_points_2, key=lambda z:abs(z-x_value))
    closest_xpoint_2_idx = x_points.index(closest_xpoint_2)

    closest_points = [(list_of_tuples[closest_xpoint_1_idx][0], list_of_tuples[closest_xpoint_1_idx][1]), (list_of_tuples[closest_xpoint_2_idx][0], list_of_tuples[closest_xpoint_2_idx][1]) ]

    return closest_points

When running the function, it should look something like this:

closest_2_points([(4,6),(2,5),(0,4),(-2,3)], 6)

And return something like this:

[(4, 6), (2, 5)]


texts: Revealing module implicity calling an internal function - is this a “smell”

texts:
I'm trying to improve my javascript and have been using the revealing module pattern to good effect but I noticed that code in the module not in a function or the return is executed on creation have utilised this, such as:

var MyModule = function ($) {

    setUp();

    function setUp() {
        // execute code to be run when module created
    }

    function doStuff() {
    }

    return {
        doStuff: doStuff
    }
}

I can see this is creating a form of constructor for the function which relies on it being called by var myModule = new MyModule(jQuery).

Any feedback on the rights or wrongs of this appreciated.


texts: Fibonacci in linear time by using an extra pointer

texts:
I have a function to find the nth number in a Fibonacci sequence, in which I am recursively calling the function. The sum is stored in a class variable and I have an extra pointer I increment every time the function gets called.

This extra pointer is the gate keeper which dictates the base case of when to exit from the loop. The performance I get, using this algorithm is, \$O(n)\$ linear time and with \$O(1)\$space.

I get the expected answer but I am confused if this an acceptable solution from a coding interview stand point.

var x = 0
var sum = 0
func myFibonacci(of n: Int, a: Int, b:Int) -> Int {
  x+=1
  if (x == n) {
    return sum
  } else {
    sum = a+b
    return myFibonacci(of: n, a: b, b: sum)
  }
}

let finalAns = myFibonacci(of: 9, a: 0, b: 1)
print("The nth number in Fibonacci sequence is \(finalAns)")

Output: 34

Time complexity: \$O(n)\$ linear time

Space complexity \$O(1)\$

Is this an acceptable solution for a coding interview?


texts:
I'm looking for a good and easy to use solution for creating MultiSelectLists in MVC for many-to-many relationships.

I have this following example code and it works fine, but it just takes a lot of code.  It would be cool if it were shorter, smarter, or even made generic somehow, so that it's easy to create MultiSelectLists in future projects.

My Database using Entity Framework Code First:

Books, and authors, where one book, can have multiple authors.

public class DataContext : DbContext
{
    public DbSet<Book> Books { get; set; }
    public DbSet<Author> Authors { get; set; }
}
public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }

    //Allows multiple authors for one book.
    public virtual ICollection<Author> Authors { get; set; }
}
public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }

    [NotMapped]
    public int[] SelectedBooks { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

Controller

    public ActionResult Edit(int id = 0)
    {
        Author author = db.Authors.Find(id);
        if (author == null)
        {
            return HttpNotFound();
        }
        ViewData["BooksList"] = new MultiSelectList(db.Books, "Id", "Name", author.Books.Select(x => x.Id).ToArray());

        return View(author);
    }

    [HttpPost]
    public ActionResult Edit(Author author)
    {
        ViewData["BooksList"] = new MultiSelectList(db.Books, "Id", "Name", author.SelectedBooks);

        if (ModelState.IsValid)
        {
            //Update all the other values.
            Author edit = db.Authors.Find(author.Id);
            edit.Name = auther.Name;

        //------------
            //Make adding items possible
            if (edit.Books == null) edit.Books = new List<Book>();

            //Remove the old, add the new, instead of finding out what to remove, and what to add, and what to leave be.
            foreach (var item in edit.Books.ToList())
            {
                edit.Books.Remove(item);
            }
            foreach (var item in author.SelectedBooks)
            {
                edit.Books.Add(db.Books.Find(item));
            }
        //-------------
        // This is the code i want to simplify
        // Would be cool with a generic extention method like this:
        // db.ParseNewEntities(edit.Books, author.SelectedBooks);
        // I just don't know how to code it.

            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(author);
    }

View

    @Html.ListBox("SelectedBooks",(MultiSelectList)ViewData["BooksList"])


texts:
How can I improve upon this code to apply logic based on the user's response to a SaveAs Dialog Box 'do you want to overwrite existing file' question:

Sub SaveFile(fName As String)

cancelSave = False
Retry:
saveAsFileName = Application.GetSaveAsFilename(InitialFileName:=fName, FileFilter:="Excel Files (*.xlsx), *.xlsx")
If saveAsFileName <> False Then
    If Not Dir(saveAsFileName) <> vbNullString Then
        ActiveWorkbook.SaveAs fileName:=saveAsFileName
    Else
        On Error Resume Next
        ActiveWorkbook.SaveAs fileName:=saveAsFileName, FileFormat:=xlWorkbook, ConflictResolution:=xlLocalSessionChanges
        If Err.Number = 1004 Then
            On Error GoTo 0
            GoTo Retry
        Else
            On Error GoTo 0
        End If
    End If
Else
    cancelSave = True
End If

End Sub


texts:
I wanted to work on HttpSessions and JSP.

This is the view I have:

<!DOCTYPE html>

    <meta charset="utf-8">

    <c:out value="All available products:"/>

    <c:forEach items="${applicationScope.allProducts}" var="product">
        <c:out value="${product}"/>
        &nbsp;
        <a href="${pageContext.servletContext.contextPath}/shop?addProductbyName=<c:out  value="${product}"/>">Add to basket

    </c:forEach>

    Currently your cart contains these items dude:

    <c:forEach items="${sessionScope.cart}" var="product">
        <c:out value="${product.key}"/>
        &nbsp;
        <c:out value="${product.value}"/>

    </c:forEach>

And the Servlet:

package com.tugay;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * User: koraytugay
 * Date: 20/07/14
 * Time: 18:07
 */

@WebServlet(urlPatterns = "/shop", name = "shoppingServlet")
public class ShopServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        if (getServletContext().getAttribute("allProducts") == null) {
            getServletContext().setAttribute("allProducts", Database.getAllProducts());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {
        Map<String, Integer> cart = doSessionStuff(httpServletRequest, httpServletResponse);
        String addProductbyName = httpServletRequest.getParameter("addProductbyName");
        if (addProductbyName != null) {
            if (cart.get(addProductbyName) == null) {
                cart.put(addProductbyName, 0);
            }
            cart.put(addProductbyName, cart.get(addProductbyName) + 1);
        }

        httpServletResponse.sendRedirect(getServletContext().getContextPath()+"/shopping.jsp");
    }

    @SuppressWarnings("unchecked")
    private Map<String, Integer> doSessionStuff(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        HttpSession session = httpServletRequest.getSession();
        Map<String, Integer> cartMap = null;
        if (session.getAttribute("cart") == null) {
            cartMap = new HashMap<String, Integer>();
            session.setAttribute("cart", cartMap);
        }
        cartMap = (Map<String, Integer>) session.getAttribute("cart");
        return cartMap;
    }
}

And the "Mock" Db:

package com.tugay;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * User: koraytugay
 * Date: 20/07/14
 * Time: 17:58
 */
public class Database {

    private static HashMap<Integer,String> products = new HashMap<Integer, String>();

    static {

        products.put(1,"Table");
        products.put(2,"Sofa");
        products.put(3,"Chair");
        products.put(4,"Window");

    }

    public static List<String> getAllProducts() {
        return new ArrayList<String>(products.values());
    }

}

This is what my page looks like:

If anyone wants to review this, they are welcome.


texts: Customer segmentation using RFM analysis

texts:
Currently, my code works perfectly well but i would like to make it cleaner for other users by removing the duplicate and similar lines of code into functions or for loops. Because I am still new learning Python, I still did not get a hang of functions and for loops. My data frame rfm includes 5 columns:

Max Date (latest transaction)
Id (unique identifier)
Recency (today's date minus Latest Transaction Date)
Frequency (total # of transactions per Id since its subscription)
Monetary (total amount of $ spent by Id since its subscription)

Separating the main data frame into 3 different df because the sort differs for each cumulative sum column. Frequency and Monetary dfs have identical calculations:

rfm_recency = rfm[['Max_Date', 'Id', 'Member_id', 'Recency']].copy()
rfm_recency = rfm_recency.sort_values(['Recency'], ascending=True)

rfm_frequency = rfm[['Id', 'Member_id', 'Frequency']].copy()
rfm_frequency = rfm_frequency.sort_values(['Frequency'], ascending=False)
rfm_frequency['cum_sum'] = rfm_frequency['Frequency'].cumsum()
rfm_frequency['cum_sum_perc'] = rfm_frequency['cum_sum'] / rfm_frequency['Frequency'].sum()

rfm_monetary = rfm[['Id', 'Member_id', 'Monetary']].copy()
rfm_monetary = rfm_monetary.sort_values(['Monetary'], ascending=False)
rfm_monetary['cum_sum'] = rfm_monetary['Monetary'].cumsum()
rfm_monetary['cum_sum_perc'] = rfm_monetary['cum_sum'] / rfm_monetary['Monetary'].sum()

def scorefm(x):
    """Function for separating data into 5 bins for Frequency & Monetary df """
    if x <= 0.20:
        return 5
    elif x <= 0.40:
        return 4
    elif x <= 0.60:
        return 3
    elif x <= 0.80:
        return 2
    else:
        return 1

# Divide the Recency df into equal quantiles
rfm_recency['r_score'] = 5 - pd.qcut(rfm_recency['Recency'], q=5, labels=False)

# Create scores from cum_sum_perc for Frequency and Monetary
rfm_frequency['f_score'] = rfm_frequency['cum_sum_perc'].apply(scorefm)
rfm_monetary['m_score'] = rfm_monetary['cum_sum_perc'].apply(scorefm)

# Resorting data frames by ID to merge
rfm_recency = rfm_recency.sort_values('Id')
rfm_frequency = rfm_frequency.sort_values('Id')
rfm_monetary = rfm_monetary.sort_values('Id')

# Merging data frames together
result = rfm_recency.copy(['Recency', 'r_score'])
result = result.join(rfm_frequency[['Frequency', 'f_score']])
result = result.join(rfm_monetary[['Monetary', 'm_score']])

# Create an FM and RFM score based on the individual R, F, M scores.
result['FM'] = (result['f_score'] + result['m_score']) / 2
result['RFM_Score'] = result['r_score'] * 10 + result['FM']

Fiddle Data:

import pandas as pd

col_names = ['Max_Date', 'Id', 'Member_id', 'Recency', 'Frequency', 'Monetary'] # 6 columns
data =[['2019-01-21',456,'dwfv84',23,261,4221],
['2019-02-10',123,'qwbe78',3,83,9251],
['2019-01-25',789,'adqw87',19,478,19195],
['2018-01-04',988,'afdi25',40,321,3753],
['2018-03-19',784,'asdf48',331,413,8551],
['2018-04-15',445,'asfv41',304,246,10215],
['2018-04-10',589,'sdqw88',309,80,19569],
['2018-05-20',741,'dsdg46',269,282,3108],
['2018-06-30',852,'cvgo87',228,261,5975],
['2019-01-19',963,'ewgs45',25,357,4405],
['2019-01-12',369,'fbbr54',32,197,1019],
['2019-01-18',258,'fwgs77',26,132,18100],
['2019-02-10',147,'jkyu87',3,32,8678],
['2019-02-05',753,'yukh20',8,132,19871]]

rfm = pd.DataFrame(data=data, columns=col_names,)
rfm ['Max_Date'] = pd.to_datetime(rfm ['Max_Date'])


texts:
I've been learning Java for a very short period of time but with a couple of pointers, I've been able to put this simple VAT calculator together.  If anyone could offer any ideas for improvement that'd be great!

import java.text.DecimalFormat;
import java.util.Scanner;

public class TaxCalc {

    public static void main(String[] args) {

        System.out.println("Welcome to the simple VAT Calculator.");
        System.out.println("To Calculate VAT Payable and the ex-VAT Cost type the total cost below:");
        System.out.println("----------");
        Scanner cost = new Scanner (System.in);
        double totalCost = cost.nextDouble();

        cost.close();

        System.out.println("----------");
        double exVat;
        exVat = (totalCost * 0.8);
            DecimalFormat df = new DecimalFormat("0.00");
            String exVatStr = df.format(exVat);
            exVat = Double.valueOf(exVatStr);

        double vat;
        vat = totalCost - exVat;
            DecimalFormat df2 = new DecimalFormat("0.00");
            String vatStr = df2.format(vat);
            vat = Double.valueOf(vatStr);

        System.out.println("The VAT payable is £" + vatStr);
        System.out.println("The ex-VAT Cost is £" + exVatStr);

    }
}


texts:
I've started building extension methods for my EF classes like below because it makes building queries so easy, and the intellisense provided helps keep people from writing a new Where() clause in code every time they do to do something.

Example Extensions to an EF User Class

public static class UserIQX
{
    public static IQueryable<User> WhereInSearch(this IQueryable<User> value, string search)
    {
        search = search.ToLower();
        return value.Where(user => user.FirstName.ToLower().Contains(search) || user.LastName.ToLower().Contains(search) || user.EmailAddress.ToLower().Contains(search));
    }

    public static IQueryable<User> WhereInRole(this IQueryable<User> value, RoleEnum role)
    {
        return value.Where(user => user.RoleID == (int)role);
    }
}

Examples - "Get all admins named Bob"

protected void Page_Load(object sender, EventArgs e)
{
    var search = "Bob";

    //With Extensions
    var activeAdmins = db.Users
    .WhereInRole(RoleEnum.Admin)
    .WhereInSearch(search)
    .Select(u => new { EmailAddress = u.EmailAddress })
    .ToList();

    //Without extensions
    search = search.ToLower();
    var pq = db.Users
        .Where(u => (
            u.FirstName.ToLower().Contains(search)
            || u.LastName.ToLower().Contains(search)
            || u.EmailAddress.ToLower().Contains(search))

            && u.RoleID == (int)RoleEnum.Admin)
        .Select(u => new { EmailAddress = u.EmailAddress })
        .ToList();
}

Results

The results are comparable with the inline one edging out ahead in speed. It's interesting that the extension-based one used a parameter for the roleID and the inline one did not.  That's the only real difference I can see.

I really like the fluent-like style the Extension method provides, and how it encapsulates logic to prevent erroneous queries from being written (like forgetting to ToLower() the string fields or something).  Is there a good reason why this would be a Really Bad Idea?  If not, I prefer the easy maintainability of the Extension methods over inline.


texts: jQuery code to detect whether form fields have the default value when a checkbox is unchecked

texts:
How could I rewrite this jquery code to compact it in a more elegant form:

$(document).ready(function(){
     $('input[name="table_exist"]').click(function(){
      if($('input[name="table_name"]').val()=='users' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="table_name"]').val('');
   }
   else if($('input[name="table_name"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="table_name"]').val('users');
   }

   if($('input[name="user_id"]').val()=='user_id' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_id"]').val('');
   }
   else if($('input[name="user_id"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_id"]').val('user_id');
   }

   if($('input[name="user_name"]').val()=='user_name' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_name"]').val('');
   }
   else if($('input[name="user_name"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_name"]').val('user_name');
   }

   if($('input[name="user_email"]').val()=='user_email' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_email"]').val('');
   }
   else if($('input[name="user_email"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_email"]').val('user_email');
   }

   if($('input[name="user_pass"]').val()=='user_pass' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_pass"]').val('');
   }
   else if($('input[name="user_pass"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="user_pass"]').val('user_pass');
   }

   if($('input[name="joining_date"]').val()=='joining_date' && $('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="joining_date"]').val('');
   }
   else if($('input[name="joining_date"]').val()=='' && !$('input[name="table_exist"]').is(':checked'))
   {
    $('input[name="joining_date"]').val('joining_date');
   }
     });
 });

<form method="POST">

DB Table

     Activate the slider if you already have your own database table created!

     <input type="checkbox" name="table_exist" />

     Edit here only if you have your own predifined table header names!

     <input type="text" name="table_name" value="users" required />
     Table Name

     <input type="text" name="user_id" value="user_id" required />
     User ID

     <input type="text" name="user_name" value="user_name" required />
     User Name

     <input type="text" name="user_email" value="user_email" required />
     User E-mail

     <input type="text" name="user_pass" value="user_pass" required />
     User Password

     <input type="text" name="joining_date" value="joining_date" required />
     User Added Date

    <button type="submit" name="btn-install">
     Install
    </button>

   </form>

The whole process is to identify if the fields have the default values when a checkbox is unchecked. If the state is changed to checked then empty all fields to input custom information/values. If unchecked again it returns the initial values.


texts:
I'm creating a Web Api in .NET Framework that is connected to an ASMX service. No own logic, just pass through data.

Everything works as expected. But not sure if it's good. Have to repeat the same try/catch block in all controller actions.

SecurityController - send username and password and retrieve a session Id to use in subsequent calls:

public class SecurityController : ApiController
{
    public SecurityController(ILogger logger)
    {
        Logger = logger;
    }

    ILogger Logger { get; }

    [HttpPost]
    public IHttpActionResult StartSession([FromBody] StartSessionRequestModel requestModel)
    {
        var client = new SecurityFacade(); // from proxy class
        var requestMessage = new StartSessionRequest
        {
            Username = requestModel.Username,
            Password = requestModel.Password
        };

        try
        {
            var startSessionResponse = client.StartSession(requestMessage);

            return Ok(new
            {
                startSessionResponse.SessionId
            });
        }
        catch (SoapException ex)
        {
            return BadRequest(ex.Code.Name);
        }
        catch (Exception ex)
        {
            Logger.Error(ex);
            return InternalServerError(ex);
        }
    }
}

Output when entered wrong user/password

{
    "Message": "InvalidUsernameAndPasswordPair"
}

On the client (Xamarin), using RestSharp.

var request = new RestRequest("security/startsession");
request.AddParameter("Username", Username);
request.AddParameter("Password", Password);
restClient.PostAsync<StartSessionResponse>(request, (response, handle) =>
{
    if (response.IsSuccessful)
    {
        var sessionId = response.Data.SessionId;

        // todo
    }
    else
    {
        var responseMessage = JsonConvert.DeserializeAnonymousType(response.Content, new { Message = "" });

        if (responseMessage.Message == "InvalidUsernameAndPasswordPair")
        {
            // todo: show "invalid user/password" error
        }
        else
        {
            // todo: show other nicely worded error
        }
    }
});


texts:
For eligibility to events I need to know the age of a competitor at a specific date.

Now the thing is the date calculations are checked in two places, an online PHP app where the entries are registered, and an offline Java app that runs the events.

So I have 2 versions of the same code, the PHP one was written originally and the Java is a conversion of that. (So that I am using the same calculations in both places).

My Java skills are very rusty.

I am happy to take any improvements onboard, but it is essential that both calculations return the same result.

PHP

public function ageAt($age_reference_date) {
    $ts_ref = strtotime($age_reference_date);
    list($dob_year, $dob_month, $dob_day) = explode('-', $this->date_of_birth);

    $age = date('Y', $ts_ref) - $dob_year;

    if (date('md', $ts_ref) < $dob_month.$dob_day) {
        $age--;
    }

    return $age;
}

Java

public int ageAt(Date ageReferenceDate) {
    Calendar calAgeReferenceDate = Calendar.getInstance();
    Calendar calDateOfBirth = Calendar.getInstance();
    int refDateMonth;
    int dobDateMonth;
    int age;

    calAgeReferenceDate.setTime(ageReferenceDate);

    calDateOfBirth.setTime(this.dateOfBirth);
    age = calAgeReferenceDate.get(Calendar.YEAR) - calDateOfBirth.get(Calendar.YEAR);

    refDateMonth = Integer.parseInt(String.format("%02d", calAgeReferenceDate.get(Calendar.MONTH)) + String.format("%02d", calAgeReferenceDate.get(Calendar.DAY_OF_MONTH)));
    dobDateMonth = Integer.parseInt(String.format("%02d", calDateOfBirth.get(Calendar.MONTH)) + String.format("%02d", calDateOfBirth.get(Calendar.DAY_OF_MONTH)));

    if (refDateMonth < dobDateMonth) {
        age--;
    }

    return age;
}


texts: AngularJS image size validation directive

texts:
I've written a directive to validate the width and height of an image in AngularJS. I'm not a JS genius but I get along with it. So I would appreciate some feedback on this directives code if this can be done better in the context of Angular and the JS language itself.

angular.module('app').directive('imageFileValidator', ['fileReader', function (fileReader) {
return {
    restrict: 'A',
    require: '^ngModel',
    link: function ($scope, el, attr, ctrl) {
        // Binds the change callback for the element
        el.bind('change', function (e) {
            var file = ((e.srcElement || e.target).files[0]);

            fileReader.getImageSize(file, $scope).then(function(result) {
                var imageSize = result;

                if (attr.validateHeight != undefined) {
                    var heightRule = attr.validateHeight.split(' ');
                    var validHeight = validateImageSize(imageSize.height, heightRule[0], heightRule[1]);
                    ctrl.$setValidity('imageSizeY', validHeight);
                }

                if (attr.validateWidth != undefined) {
                    var widthRule = attr.validateWidth.split(' ');
                    var validWidth = validateImageSize(imageSize.width, widthRule[0], widthRule[1]);
                    ctrl.$setValidity('imageSizeX', validWidth);
                }
            });

            var validateImageSize = function(value1, operator, value2) {
                if (operator == '==') {
                    return (value1 == value2);
                }
                if (operator == '>=') {
                    return (value1 >= value2);
                }
                if (operator == '>') {
                    return (value1 > value2);
                }
                if (operator == '<=') {
                    return (value1 <= value2);
                }
                if (operator == '<') {
                    return (value1 < value2);
                }
                throw 'Invalid operator ' + operator + ' !';
            };
        });
    }
}
}]);


texts: Return the shortest substring containing all the characters in the set

texts:
The task:

  Given a string and a set of characters, return the shortest substring
  containing all the characters in the set.

  For example, given the string "figehaeci" and the set of characters
  {a, e, i}, you should return "aeci".

  If there is no substring containing all the characters in the set,
  return null.

My solution:

// init
const originalStr = 'figehaeci';
const set = Object.freeze(['a', 'e', 'i']);

// helpers
const isEmpty = s => s.length === 0;
const copy = s => s.slice(0);
const getNextResult = (currRes, endRes) => {
    if (!endRes || isEmpty(endRes)) {
      return currRes;
    }
    return currRes.length < endRes.length ?
           currRes : endRes;
};

// main
const contains = (str, endResult) => {
  const currStr = str;
  const currSet = copy(set);
  let pushIt;
  const currResult = currStr
    .split('')
    .reduce((acc, item) => {
      if (pushIt === false) {
        return acc;
      }
      if (currSet.includes(item)) {
        currSet.splice(currSet.indexOf(item), 1);
        pushIt = true;
      }
      if (pushIt) {
        acc.push(item);
      }
      if (isEmpty(currSet)) {
        pushIt = false;
      }
      return acc;
    }, []);

  const nextStr = str
    .split('')
    .slice(1)
    .join('');

  // exit case
  if (isEmpty(nextStr)) {
    return endResult ? endResult.join('') : null;
  }

  // recursive case
  const nextResult = isEmpty(currSet) ?
        getNextResult(currResult, endResult) :
        endResult;

  return contains(nextStr, nextResult);
}

// result
console.log(contains(originalStr, null));

I don't like the many ifs and the flag (pushIt). Do you know how to get rid of them without sacrificing readability and maintainability?

Doesn't have to be in functional programming style. Just looking for an elegant solution.


texts: Reddit bot to gather listening suggestions

texts:
import praw
import time
import database

# Create a user agent and log into Reddit
UA = 'OZBOZZ v0.1'
r = praw.Reddit(UA)
# Log UA into reddit with my personal user name and password
r.login('', '', disable_warning='True')
subreddit = r.get_subreddit('listentothis')
current_time = int(time.time())
user = ''
submission_list = []
results = []
count = 0
genres = ["Big Band Funk", "progressive Rock", "rock", "progressive metal"]

def botstuff():
# while condition is true...
while True:
    # Print Working so That I know the Next iteration has begun
    print("Working...")

    # For submission in subreddit /r/listen to this get up to 20 new posts
    for submission in subreddit.get_new(limit=20):
        # Create a variable called Sub_age that is current time minus the submission creation time divided by 60
        # divided by 60  divided by 12
        sub_age = (current_time - submission.created_utc) / 60 / 60 / 24
        # If the submission age is less than one (posted in last 24 hours)...
        if sub_age < 1:
            # Add that submission to the submission list. Each entry contains the title and Link to post
            submission_list.append([submission.title, submission.permalink])

    # Print the submission list, so I know I got something. Debugging
    print(submission_list)

    # For each list entry in submission_list
    for x in submission_list:
        # any of element in the list genre are found in the 1st... element property(?)
        if any(a in x[1] for a in genres):
            # Append the element with matching genre tags in to the results list.
            results.append(x)

    # Print the submission list, so I know I got something. Debugging
    print(results)

    # if the results list is empty
    if not results:
        # Send the user a message  letting them know I havent found something
        r.send_message(user, 'Nothing Yet', 'Hey, I didn\'t find anything')
    # Otherwise...
    else:
        # Create a message variable from the bot with the list of results.
        msg = 'Hey, Check these out.  -oz \n' + "\n" +'[%s]'.strip('[]') % ''.join(map(str, results)).strip('[]')
        # Sent the message to the user.
        r.send_message(user, 'Suggestions', msg)
        print("Message Sent")

    count = count + 1
    print("Sleep cycle " + str(count))
    #wait 60 minutes
    time.sleep(3600)

So this is the code completely working code so far. What this bot accomplishes is scanning new posts on /r/listentothis that are less than 24 hours old and parsing the text of the submission post that matches my list of genres called genres. If a match is found, it appends it to a results list. If the results list is empty it sends me a message stating that it didn't find anything, otherwise, it sends me a message with a suggestsion to check out some results and then prints out the results list.

I'm looking for ways to multithread this bot.
Make this a modular function because the goal is to make it so that a reddit user can send this bot account a message with genres and it will put the uname and genres into a database and do a search for them every hour.
Clean up results output so each result is printed on a new line.
Improve the string search efficiency if possible.
Search Specifically for only the strings providied. So for example, "rock" will not return "Glam rock"


texts: React onDrop function for a task manager

texts:
This a working function as part of a drag and drop task manager im playing around with. The function is working fine, but it just looks messy and long to me. I haven't added all the code as I'm looking just to tidy up the function itself. I have added the state though as guidance.

function

onDrop = () => {

  let people = [...this.state.people]
  let newPeopleArray = []
  let newChoresArray = []
  let personToUpdate = {}

  people.forEach( person => {
    if ( person.name !== this.state.targetPerson ) {
      newPeopleArray.push(person)
     } else {
      personToUpdate = person
      personToUpdate.chores.forEach( chore => {
          if ( chore !== this.state.targetChore ) {
          newChoresArray.push(chore)
        }})
      personToUpdate.chores = newChoresArray
    }})
 newPeopleArray.push(personToUpdate)
 this.setState ({ people: newPeopleArray})
}

state

class App extends Component {
  state = {

    targetChore: '',
    targetPerson: '',

    people: [
    { name: 'Grace', chores: ['clean kitchen', 'wash dog', 'laundry']  },
    { name: 'Sam', chores: ['walk dog', 'wash car', 'go shopping']  },
    { name: 'Rose', chores: ['wash windows', 'vaccum', 'clean bathroom'] }
    ]
}


texts:
I got the inspiration to write this algorithm from this question. The OP cited the Sieve of Atkin as one of the fastest ways to generate primes. So I figured I would give it a try:

def sieve_primes(limit=100):
    sieve = [False]*limit
    loop_range = range(1, int(limit**(1/2)))

    for x, y in [(x,y) for x in loop_range for y in loop_range]:
        for x_coef, y_coef, mods in [(4, 1, [1, 5]), (3, 1, [7]), (3, -1, [11])]:
            if y_coef == -1 and x <= y:
                continue

            value = x_coef * x**2 + y_coef * y**2
            if value > limit:
                continue

            if value % 12 in mods:
                sieve[value] = not sieve[value]

    for value in loop_range[4:]:
        if sieve[value]:
            for square in [i * value**2 for i in range(limit//value**2+1)
                           if i * value**2 < limit]:
                sieve[square] = False

    return sieve

The algorithm is based off of pseudocode given by the reference to the Sieve of Atkins above. The reference does say:

  This pseudocode is written for clarity. Repeated and wasteful calculations mean that it would run slower than the sieve of Eratosthenes. To improve its efficiency, faster methods must be used to find solutions to the three quadratics.

I wanted to make the pseudocode feel as Pythonic as possible. I also tried to optimize it as much as I could without delving too much into the mathematics.

Do you guys see any improvements, performance or style-wise?

Here's some profiling:

import timeit

for x in [100, 1000, 10000]:
    time = timeit.timeit('sieve_primes({})'.format(x),
                         setup='from __main__ import sieve_primes', number=10000)
    print('Number of primes found: {}'.format(x))
    print('\tTotal time: {}\n\tTime per iteration: {}'.format(time, float(time)/10000))

# Results
Number of primes found: 100
    Total Time: 2.3724100288364544
    Time per Iteration: 0.00023724100288364545
Number of primes found: 1000
    Total Time: 26.933066114727716
    Time per Iteration: 0.0026933066114727716
Number of primes found: 10000
    Total Time: 297.5023943142171
    Time per Iteration: 0.0297502394314171


texts: Setters dependent on other instance variables in Java

texts:
I am relatively new to java and I am trying to set up a class with non-trivial setters, but I wonder if setting an instance variable via another one is allowed/good practice?
public class Pdf {

    private byte[] bytearray;
    private String name;
    private PDDocument pddocument;
    private int lastPage;

    public Pdf() {
        super();
    }

    public Pdf(String name, byte[] bytearray) {
        super();
        this.name = name;
        this.bytearray = bytearray;
    }

    public String getName(String name) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getBytearray() {
        return bytearray;
    }

    public void setBytearray(byte[] bytearray) {
        this.bytearray = bytearray;
    }

    public PDDocument getPddocument() {
        return pddocument;
    }

    public void setPddocument() {

        PDDocument pddocument = null;
        try {
            pddocument = org.apache.pdfbox.pdmodel.PDDocument.load(this.bytearray);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.pddocument = pddocument;
    }

    public int getLastPage() {
        return lastPage;
    }

    public void setLastPage() {

        this.lastPage = this.pddocument.getNumberOfPages()-1;
    }
}


texts:
I wondering what people think of this game of life. I don't think it is working properly, but I am interesting in what people think of the general design.

module GameOfLife where
import Data.List

--Our types
type Coord = (Int, Int)
origin = (0, 0)

--Think of an image more like an infinite manifold
type DiscreteImage a = (Coord -> a)

--Cat is our "out of bounds"
data GamePiece = Alive | Dead | Cat
    deriving(Show, Eq)

type GameBoard = DiscreteImage GamePiece

type TransitionRule = (GameBoard -> GamePiece)

under_population = make_population_transition Alive Dead (<2)
overcrowding     = make_population_transition Alive Dead (>3)
birth            = make_population_transition Dead Alive (==3)

--Order is not important. Only one transition applies per peice,
--the others operate like id
transition_rule :: TransitionRule
transition_rule image = foldl (\image f -> f image) image
    [
        under_population,
        overcrowding,
        birth
    ] origin

--return a new gameboard that applies the transition rule to every
--spot on the gameboard
step :: TransitionRule -> GameBoard -> GameBoard
step trans gb = trans . offset gb

--apply the tranisition rule n number of times
simulate :: Int -> TransitionRule -> GameBoard -> GameBoard
simulate count trans gb = foldl apply_step gb steps where
  steps = replicate count (step trans)
  apply_step gb s = s gb

--translate the image
offset :: DiscreteImage a -> Coord -> Coord -> a
offset image (offsetX, offsetY) (x, y) = image (offsetX + x, offsetY + y)

--make a square of coords
square_coords :: Int -> [Coord]
square_coords radius = [(x, y) | x <- diameter_list, y <- diameter_list] where
        diameter_list = [(negate radius) .. radius]

--return a neighborhood with the center missing
punctured_neighborhood :: Int -> DiscreteImage a -> [a]
punctured_neighborhood size image = map image $ filter (not . (==origin)) $ square_coords size

--a little test
main = do
    let (width, height) = get_bounds test_list
    let board1 = simulate 1 transition_rule test_board
    putStr $ unlines [ unwords [ ppr_peice $ board1 (x, y) | x <- [0..(width -1)]] |
                y <- [0..(height - 1)]]

test_list =
    [
        [Alive, Dead, Alive, Dead],
        [Alive, Dead, Dead, Alive],
        [Dead, Alive, Dead, Alive],
        [Dead, Alive, Alive, Alive]
    ]

test_board = image_from_lists test_list Cat

--helpers
population_count = length . filter is_Alive . punctured_neighborhood 1

--does nothing if the origin peice /= from, otherwise test for replacement
make_population_transition from to condition image | image origin == from =
    if (condition . population_count) image
            then replace image origin to
            else image
make_population_transition from to test image | otherwise = image

replace image coord_to_replace value coord = if coord_to_replace == coord
                                                 then value
                                                 else image coord

bi f g h x = f x `h` g x

is_Alive Alive = True
is_Alive _ = False

from_Bool True = Alive
from_Bool False = Dead

image_from_lists xs default_value coord@(x, y) = if is_in_bounds1 coord
    then (xs !! x) !! y
    else default_value where
      bounds = get_bounds xs
      is_in_bounds1   = is_in_bounds bounds

get_bounds xs = if null xs
    then (0, 0)
    else (length xs, length $ head xs)

is_in_bounds (xb, yb) (x, y) = (y < yb && y > -1) && (x < xb && x > -1)

ppr_peice Dead = "O"
ppr_peice Alive = "X"
ppr_peice Cat = "C"


texts: (Codewars) Linked Lists-Sorted Insert (2)

texts:
Original Question.
So I rewrote the code for the problem described in the original question, but someone had already answered that question, and my rewrite would have invalidated their answer, so I just posted a new question.
Updated Solution
def sorted_insert(head, data):
    tmp = Node(None)
    tmp.next = head
    node = Node(data)
    while tmp.next:
        if tmp.next.data > data:
            break
        tmp = tmp.next
    node.next = tmp.next
    tmp.next = node
    return head if tmp.data else node


texts:
I'm attempting to improve my OOP design skills through solving sample problems. Below is an implementation of a flight booking system where the passenger can only request a seat class, but no number. Also, flight statistics must be printed.

In your review, please focus on design: How can I design the classes better (or design better classes) to lower coupling, increase cohesion and maintainability?

One source of 'developer anxiety' I get is when I send arguments to an instance method that mutate both the instance and the argument. For example, Passenger.book() mutates both the Passenger and Flight instances at the same time. Is this bad design?

In case you are wondering, this is not homework.

#!/usr/bin/env python3
import random

letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

class BookingClass:
    ECONOMY = 'Economy'
    BUSINESS = 'Business'

class Seat:
    def __init__(self, row_number: int, letter: str):
        self.row_number = row_number
        self.letter = letter

    def __str__(self):
        return '{}{}'.format(self.row_number, self.letter)

class SeatingArea:
    def __init__(self, booking_class: str, start_row: int, row_count: int, seats_per_row: int):
        self.booking_class = booking_class
        self.seat_count = row_count * seats_per_row
        self.seats_remaining = []

        for row_number in range(start_row, row_count + start_row):
            for seat_number in range(seats_per_row):
                new_seat = Seat(row_number, letters[seat_number])
                self.seats_remaining.append(new_seat)

class Flight:
    def __init__(self, economy_seats: SeatingArea, business_seats: SeatingArea):
        # should I use the SeatingArea.booking_class attribute as the key?
        self.seating_areas = {
            BookingClass.ECONOMY: economy_seats,
            BookingClass.BUSINESS: business_seats}

    def print_statistics(self):
        for booking_class, seating_area in self.seating_areas.items():
            print('{}: {}% available'.format(
                booking_class,
                len(seating_area.seats_remaining) / seating_area.seat_count * 100))

    def remaining_seat_count(self, booking_class: str):
        return len(self.seating_areas[booking_class].seats_remaining)

    def get_seat(self, booking_class: str):
        return self.seating_areas[booking_class].seats_remaining.pop()

class Passenger:
    def __init__(self, name: str):
        self.name = name
        self.booking_id = None
        self.seat = None

    def has_booked(self):
        return self.booking_id is not None

    def book(self, flight: Flight, booking_class: str):
        if flight.remaining_seat_count(booking_class) != 0:
            self.seat = flight.get_seat(booking_class)
            self.booking_id = random.Random().randrange(1000, 10000)
            return True

        return False

# Example usage
def main():
    business = SeatingArea(BookingClass.BUSINESS, start_row=1, row_count=5, seats_per_row=4)
    economy = SeatingArea(BookingClass.ECONOMY, start_row=6, row_count=20, seats_per_row=6)

    flight = Flight(economy, business)

    john = Passenger('John')
    john.book(flight, BookingClass.ECONOMY)
    print(john.seat)
    print(john.booking_id)

    flight.print_statistics()

if __name__ == '__main__':
    main()


texts: Selecting coins with alert count by using a subquery

texts:
I have a table called alerts and is related to a table called coin (coin can have many alerts). I would like to return a list of alerts but also return a subquery count of how many alerts that coin has.

Here is my query. I would love some feedback on how it can be improved.

 context.Alerts
            .Include(x => x.Coin)
            .Where(x => !x.IsComplete)
            .OrderByDescending(x => x.CreatedDateUtc)
            .Take(topCount)
            .Select(x => new AlertDto(x, context.Alerts.Where(y => y.CoinId == x.CoinId && !y.IsComplete).Count()))
            .ToList();

Here is the SQL generated code. It does one for the main alerts.

exec sp_executesql N'SELECT TOP(@__p_0) [x].[AlertId], [x].[CoinId], [x].[CreatedDateUtc], [x].[EmailAddress], [x].[IsComplete], [x].[IsFake], [x].[IsUp], [x].[Threshold], [x].[ThresholdPercent], [x.Coin].[CoinId], [x.Coin].[Icon], [x.Coin].[LastPriceBtc], [x.Coin].[LastPriceUsd], [x.Coin].[LastUpdated], [x.Coin].[Name], [x.Coin].[Rank], [x.Coin].[Symbol]
FROM [Alerts] AS [x]
INNER JOIN [Coins] AS [x.Coin] ON [x].[CoinId] = [x.Coin].[CoinId]
WHERE [x].[IsComplete] = 0
ORDER BY [x].[CreatedDateUtc] DESC',N'@__p_0 int',@__p_0=100

A 100(topcount) more query db of these:

exec sp_executesql N'SELECT COUNT(*)
FROM [Alerts] AS [y0]
WHERE ([y0].[CoinId] = @_outer_CoinId) AND ([y0].[IsComplete] = 0)',N'@_outer_CoinId int',@_outer_CoinId=864


texts: Lockless Queue Multiple-Reader Singler-Writer in C++

texts:
I wrote a lockless queue for sending small objects from a single thread to a random worker thread.

Assumptions:

x86/x86_64 compiled with GCC
one thread may Write(), multiple threads may Read()
notifying a thread that data is available is done elsewhere
T is copy assignable and sizeof(T) is small
N is a power of two

Any suggestions welcome.

//RnW1FifoFixed.h
#pragma once
#include <memory>

//multiple reader single writer first in first out fixed length ring buffer queue
//compatible with x86/x86_64 GCC
template<typename T,uint32_t N> class RnW1FifoFixed
{
private:
  const uint32_t MASK = 2*N-1;
public:
  RnW1FifoFixed()
    :m_array(new T[N]),m_read(0),m_write(0)
  {
    static_assert(std::is_default_constructible<T>::value,"T does not have a default constructor.");
    static_assert(std::is_copy_assignable<T>::value,"T does not support copy assignment.");
    static_assert(N!=0,"N is too small.");
    static_assert(N!=0x80000000,"N is too large.");
    static_assert((N&(N-1))==0,"N is not a power of two.");
  }
  //one thread
  bool Write(T t)
  {
    //full
    if(m_write-m_read==N)
      return false;
    m_array[m_write&MASK] = t;
    //CPU does not reorder writes
    //prevent compiler from reordering writes
    asm volatile("":::"memory");
    m_write++;
    return true;
  }
  //multiple threads
  bool Read(T& t)
  {
    while(true)
    {
      //use a constant m_read each loop
      uint32_t read = m_read;
      //empty
      if(read==m_write)
        return false;
      t = m_array[read&MASK];
      if(__sync_bool_compare_and_swap(&m_read,read,read+1))
        return true;
    }
  }
private:
  std::unique_ptr<T[]> m_array;
  uint32_t m_read;
  uint32_t m_write;
};


texts:
I'd like some feedback.

from random import randint

turns = 1
computer_guess = randint(1, 10)
while True:
    user_guess = raw_input("Guess Number: ")
    print 4-turns, "Turns left"
    if turns == 4:
        print "You lost!, LOOSER!"
        exit()
    else:
        if int(user_guess) == int(computer_guess):
            print "Congratulations, You won!\n"
            play_again = raw_input("Do You Want To Play Again? (Y / N): ")
            if play_again.upper() == 'Y':
                continue
            else:
                exit()
        else:
            turns += 1
            print "Try again - N was ", computer_guess


texts: Computing integer square roots in Java - follow-up

texts:
(See the previous iteration.)

My two previous methods for computing the integer square root of a number \$N\$ ran in the \$\mathcal{O}(\sqrt{N})\$ worst case time. Now I have added a method (intSqrt3) that runs in \$\mathcal{O}(\log \sqrt{N})\$ time:

Main.java:

import java.util.Random;
import java.util.function.Function;

public class Main {

    public static long intSqrt1(long number) {
        long sqrt = 0L;

        while ((sqrt + 1) * (sqrt + 1) <= number) {
            sqrt++;
        }

        return sqrt;
    }

    public static long intSqrt2(long number) {
        if (number <= 0L) {
            return 0L;
        }

        long sqrt = 1L;

        while (4 * sqrt * sqrt <= number) {
            sqrt *= 2;
        }

        while ((sqrt + 1) * (sqrt + 1) <= number) {
            sqrt++;
        }

        return sqrt;
    }

    public static long intSqrt3(long number) {
        if (number <= 0L) {
            return 0L;
        }

        long sqrt = 1L;

        // Do the exponential search.
        while (4 * sqrt * sqrt <= number) {
            sqrt *= 2;
        }

        long left = sqrt;
        long right = 2 * sqrt;
        long middle = 0;

        // Do the binary search over the range that is guaranteed to contain
        // the integer square root.
        while (left < right) {
            middle = left + (right - left) / 2;

            if (middle * middle < number) {
                left = middle + 1;
            } else if (middle * middle > number) {
                right = middle - 1;
            } else {
                return middle;
            }
        }

        // Correct the binary search "noise". This iterates no more than 3
        // times.
        long ret = middle + 1;

        while (ret * ret > number) {
            --ret;
        }

        return ret;
    }

    public static long intSqrt4(long number) {
        return (long) Math.sqrt(number);
    }

    private static void profile(Function<Long, Long> function, Long number) {
        long result = 0L;
        long startTime = System.nanoTime();

        for (int i = 0; i < ITERATIONS; ++i) {
            result = function.apply(number);
        }

        long endTime = System.nanoTime();

        System.out.printf("Time: %.2f, result: %d.\n",
                          (endTime - startTime) / 1e6,
                          result);
    }

    private static final int ITERATIONS = 1_000;
    private static final long UPPER_BOUND = 1_000_000_000_000L;

    public static void main(String[] args) {
        long seed = System.nanoTime();
        Random random = new Random(seed);
        long number = Math.abs(random.nextLong()) % UPPER_BOUND;

        System.out.println("Seed = " + seed);
        System.out.println("Number: " + number);

        profile(Main::intSqrt1, number);
        profile(Main::intSqrt2, number);
        profile(Main::intSqrt3, number);
        profile(Main::intSqrt4, number);
    }
}

The performance figures I get looks like this:

Seed = 19608492647714
Number: 54383384696
Time: 531.18, result: 233202.
Time: 218.41, result: 233202.
Time: 1.81, result: 233202.
Time: 0.43, result: 233202.

Above, intSqrt3 took 1.81 milliseconds.

Critique request

Is there something I could improve? Naming/coding conventions? Performance? API design?


texts:
I am fairly rusty with assembler, let alone the AT&T syntax. I would appreciate it if someone with more experience could please review the following memcpy implementation. Note that this will only ever be called with aligned data.

inline static void alignedMemcpySSE(void *dst, const void * src, size_t length)
{
#if defined(__x86_64__) || defined(__i386__)
  size_t rem = (7 - ((length & 0x7F) >> 4)) * 10;
  void * end = dst + (length & ~0x7F);

  __asm__ __volatile__ (
   // save the registers we intend to alter, failure to do so causes problems
   // when gcc -O3 is used
   "push        %[dst]\n\t"
   "push        %[src]\n\t"
   "push        %[end]\n\t"

   "cmp         %[dst],%[end] \n\t"
   "je          remain_%= \n\t"

   // perform 128 byte SIMD block copy
   "loop_%=: \n\t"
   "vmovaps     0x00(%[src]),%%xmm0 \n\t"
   "vmovaps     0x10(%[src]),%%xmm1 \n\t"
   "vmovaps     0x20(%[src]),%%xmm2 \n\t"
   "vmovaps     0x30(%[src]),%%xmm3 \n\t"
   "vmovaps     0x40(%[src]),%%xmm4 \n\t"
   "vmovaps     0x50(%[src]),%%xmm5 \n\t"
   "vmovaps     0x60(%[src]),%%xmm6 \n\t"
   "vmovaps     0x70(%[src]),%%xmm7 \n\t"
   "vmovntdq    %%xmm0,0x00(%[dst]) \n\t"
   "vmovntdq    %%xmm1,0x10(%[dst]) \n\t"
   "vmovntdq    %%xmm2,0x20(%[dst]) \n\t"
   "vmovntdq    %%xmm3,0x30(%[dst]) \n\t"
   "vmovntdq    %%xmm4,0x40(%[dst]) \n\t"
   "vmovntdq    %%xmm5,0x50(%[dst]) \n\t"
   "vmovntdq    %%xmm6,0x60(%[dst]) \n\t"
   "vmovntdq    %%xmm7,0x70(%[dst]) \n\t"
   "add         $0x80,%[dst] \n\t"
   "add         $0x80,%[src] \n\t"
   "cmp         %[dst],%[end] \n\t"
   "jne         loop_%= \n\t"

   "remain_%=: \n\t"

   // copy any remaining 16 byte blocks
#ifdef __x86_64__
   "leaq        (%%rip), %[end]\n\t"
   "add         $10,%[end] \n\t"
#else
   "call        .+5 \n\t"
   "pop         %[end] \n\t"
   "add         $8,%[end] \n\t"
#endif
   "add         %[rem],%[end] \n\t"
   "jmp         *%[end] \n\t"

   // jump table
   "vmovaps     0x60(%[src]),%%xmm0 \n\t"
   "vmovntdq    %%xmm0,0x60(%[dst]) \n\t"
   "vmovaps     0x50(%[src]),%%xmm1 \n\t"
   "vmovntdq    %%xmm1,0x50(%[dst]) \n\t"
   "vmovaps     0x40(%[src]),%%xmm2 \n\t"
   "vmovntdq    %%xmm2,0x40(%[dst]) \n\t"
   "vmovaps     0x30(%[src]),%%xmm3 \n\t"
   "vmovntdq    %%xmm3,0x30(%[dst]) \n\t"
   "vmovaps     0x20(%[src]),%%xmm4 \n\t"
   "vmovntdq    %%xmm4,0x20(%[dst]) \n\t"
   "vmovaps     0x10(%[src]),%%xmm5 \n\t"
   "vmovntdq    %%xmm5,0x10(%[dst]) \n\t"
   "vmovaps     0x00(%[src]),%%xmm6 \n\t"
   "vmovntdq    %%xmm6,0x00(%[dst]) \n\t"

   // alignment as the previous two instructions are only 4 bytes
   "nop\n\t"
   "nop\n\t"

   // restore the registers
   "pop         %[end]\n\t"
   "pop         %[src]\n\t"
   "pop         %[dst]\n\t"
   :
   : [dst]"r" (dst),
     [src]"r" (src),
     [end]"c" (end),
     [rem]"d" (rem)
   : "xmm0",
     "xmm1",
     "xmm2",
     "xmm3",
     "xmm4",
     "xmm5",
     "xmm6",
     "xmm7",
     "memory"
  );

  //copy any remaining bytes
  for(size_t i = (length & 0xF); i; --i)
    ((uint8_t *)dst)[length - i] =
      ((uint8_t *)src)[length - i];
#else
  memcpy(dst, src, length);
#endif
}


texts:
Would this be secure enough to hash passwords?

/**
 * Creates a SHA-256 hash
 * @param  string $salt Salt for hashing algorithm
 * @param  string $string What is getting hashed
 * @return string Returns a hashed string
 */
public function hash ($string, $salt) {
    $crypt = crypt($string, '$5$rounds=5000$' . $salt . '$');
    $hash = str_replace('$5$rounds=5000$' . $salt . '$', '', $crypt);

    return $hash;
}


texts: Count numbers with atleast one common factor, excluding one

texts:
I have been trying to teach myself some python 3 lately by working through some problems at geeksforgeeks.org. A common issue I am having is that my code runs on my machine, and in their test environment, but my code ultimately exceeds their time limits upon submission. I was wondering if anyone had any general advice on making my code more efficient so I could continue to make use of the practice problems. Also, if there are any concerns about using geeksforgeeks.org and folks could recommend other practice problem sites that would be appreciated. The problem I have been working on is:

http://practice.geeksforgeeks.org/problems/mathematical-manipulation/0

  Given a number \$N\$, find the total numbers, less than or equal to \$N\$ which have at-least one common factor with \$N\$ other than \$1\$.

  Input:
  The first line of input contains an integer \$T\$ denoting the no of test cases. Then \$T\$ test cases follow. Each test case consist of an integer \$N\$.

  Output:
  For each test case output an integer denoting the count of numbers, less than or equal to \$N\$ having at-least one common factor between the number and \$N\$ except \$1\$.

  Constraints:
  \$1 \le T \le 100000\$
  \$1 \le N \le 1000000\$

  Example:
  Input:

3
1
6
15

  Output:

0
4
7

And my code:

def myfun(num_in):

    new = num_in

    pos = []
    test = []
    int_list = []
    temp_list = []
    final_list = []

    if num_in == 1:
        print(0)
    elif num_in > 1:
        # list all possibilities
        for i in range(2, num_in):
            pos.append(i)

        # check remainder from division
        for i in range(0, len(pos)):
            test.append(num_in % pos[i])

        # record if remainder is 0, if it is, keep that because it will be lowest common denominator
        for i in range(0, len(test)):
            if test[i] == 0:
                int_list.append(pos[i])

        # multiply factor my integers until it exceeds input
        for i in range(0, len(int_list)):
            temp_val = int_list[i]
            j = 1
            while temp_val * j < num_in:
                final_list.append(temp_val * j)
                j += 1

        # add 1 for the number itself since we don't need to check that
        print(len(set(final_list)) + 1)

master_list = []

tot_num = int(input())

for p in range(tot_num):
    temp_val = int(input())
    master_list.append(temp_val)

for q in range(tot_num):
    myfun(master_list[q])


texts: Removing extra spaces without using a regular expression

texts:
I want to remove the extra spaces without using a regular expression. I'm using two while loops.

How can this become better / more elegant?

String str = "Hola  caracola  ";

char[] src = str.toCharArray(), dest = new char[src.length];
int i = 0, j = 0;
while (i < src.length - 1) {
    while (i < src.length - 1 && src[i] == ' ' && src[i + 1] == ' ') {
        i++;
    }
    dest[j++] = src[i++];
}

System.out.println(new String(dest, 0, j));


texts: Solving jumbled letters using a given dictionary

texts:
Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters.
Example:

Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};
       boggle[][]   = {{'G','I','Z'},
                       {'U','E','K'},
                       {'Q','S','E'}};

Output:  Following words of dictionary are present
         GEEKS, QUIZ

Below is my code:

dictSize=int(raw_input())
dictionary=raw_input().split(' ')
m,n=map(int,raw_input().split(' '))
boggle=[[0 for x in range(n)] for y in range(m)]
#print dictionary

bString=raw_input().split()
for i in range(0,m):
    for j in range(0,n):
        boggle[i][j]=bString[(i*n)+j]
#print boggle

lookUp={}
for i in range(0,m):
    for j in range(0,n):
        lookUp[boggle[i][j]]=lookUp.get(boggle[i][j],0)+1

possibility=[]
flag=0
for i in range(0,len(dictionary)):
    for s in dictionary[i]:
        if(lookUp.has_key(s)):
            flag=0
        else:
            flag=1
    if(flag==0):
        possibility.append(dictionary[i])
#print possibility

for i in range(0,len(possibility)):
    print possibility[i],


texts: SQL Negation: Find X when X does not do Y

texts:
I'm learning The essence of SQL by Rozenshtein indirectly from the SQL Cookbook which has a section on it with modern SQL operators introduced after the book was released.

The exercise:

Given:

create table student
( sno integer,
  sname varchar(10),
  age integer
);
--
/* table of courses */
create table courses
( cno varchar(5),
  title varchar(10),
  credits integer
);
/* table of students and the courses they take */
create table take
( sno integer,
  cno varchar(5)
);

The question is: Find students who do not take CS112

I came up with:

with s1 as (
    select sno from student except select s.sno from student s inner join take t on s.sno = t.sno where t.cno = 'CS112'
)
select s.* from student s inner join s1 on s.sno = s1.sno

Rozenshtein:

select *
from student
where sno not in (select sno
                  from take
                  where cno = 'CS112')

SQL Cookbook style 1:  Group by

select s.sno, s.sname, s.age
from student s left join take t on (s.sno = t.sno)
group by s.sno, s.sname, s.age
having max(case when t.cno = 'CS112' then 1 else 0 end) = 0;

SQL Cookbook style 2: Window function

select distinct sno, sname, age
from (
    select s.sno,
           s.sname,
           s.age,
           max(case when t.cno = 'CS112' then 1 else 0 end) over (partition by s.sno, s.sname, s.age) as takes_CS112
    from student s left join take t on (s.sno = t.sno)
) as x
where takes_CS112 = 0;

I just wanted your opinion on how my query would perform compared to the other queries and if they are in the same ballpark, especially the SQL Cookbook queries. I'm targeting PostgreSQL.


texts: Javascript to compute max width and height for a nested HTML element

texts:
I wrote the following code to give an HTML element max width/height in its parent container.
I think I address the box model issues but I am wondering if anyone can see issues and or shortcomings.

Are there other solutions out there that accomplish this? I want to make sure I didn't re-invent the wheel.

function heightBuffer(control) {
    return parseInt((control.outerHeight(true)) - control.height());
}

function widthBuffer(control) {
    return parseInt((control.outerWidth(true)) - parseInt(control.width()));
}

function MaxHeightInParent(control, minHeight, controlHeightsToSubtract) {
    var h = parseInt(control.parent().height()) - heightBuffer(control);
    if (controlHeightsToSubtract != null)
        $.each(controlHeightsToSubtract, function(index, value) {
            h = h - parseInt(value.outerHeight(true));
        });

    if (minHeight != null && h < minHeight) h = minHeight;
    control.height(0);
    control.css('min-height', h);
}

function MaxWidthInParent(control, minWidth, controlWidthsToSubtract) {
    var w = parseInt(control.parent().width()) - widthBuffer(control);
    if (controlWidthsToSubtract != null)
        $.each(controlWidthsToSubtract, function(index, value) {
            w = w - parseInt(value.outerWidth(true));
        });
    if (minWidth != null && w < minWidth) w = minWidth;
    control.width(0);
    control.css('min-width', w);
}

Note controlHeightsToSubtract / controlWidthsToSubtract are if you wish to pass an array of controls that share the containing element with the element you are attempting to maximize in Height/Width.


texts: Python Calculator Test Driven Development

texts:
I am a beginner in TDD and I just coded a Calculator in Python with TDD approach. I would be more than happy to hear your opinions out. And since I am a beginner in TDD, I would love to hear some tips.

Tests :

import Calculator
import unittest

class CalculatorTests(unittest.TestCase):

    def setUp(self):
        self.calculator = Calculator.Calculator()

    def test_add_method(self):
        result = self.calculator.add(4, 2)
        self.assertEqual(6, result)

    def test_add_method_invalid_value(self):
        self.assertRaises(ValueError, self.calculator.add, "four", "five")

    def test_multiply_method(self):
        result = self.calculator.multiply(5, 3)
        self.assertEqual(15, result)

    def test_multiply_method_invalid_value(self):
        self.assertRaises(ValueError, self.calculator.multiply, "four", "five")

    def test_sub_method(self):
        result = self.calculator.sub(6, 4)
        self.assertEqual(2, result)

    def test_sub_method_invalid_value(self):
        self.assertRaises(ValueError, self.calculator.sub, "four", "five")

    def test_div_method(self):
        result = self.calculator.div(5, 1)
        self.assertEqual(5, result)

    def test_div_method_invalid_value(self):
        self.assertRaises(ValueError, self.calculator.div, "five", "four")

    def test_div_method_zero(self):
        self.assertRaises(ZeroDivisionError, self.calculator.div, 5, 0)

if __name__ == '__main__':
    unittest.main()

Calculator.py :

number_types = (int, float, complex)

class Calculator:

    @staticmethod
    def validate_args(x, y):
        if not isinstance(x, number_types) and not isinstance(y, number_types):
            raise ValueError

    def add(self, x, y):
        self.validate_args(x, y)
        return x + y

    def multiply(self, x, y):
        self.validate_args(x, y)
        return x*y

    def sub(self, x, y):
        self.validate_args(x, y)
        return x-y

    def div(self, x, y):
        self.validate_args(x, y)
        return x/y


texts: Polymorphic event notification model in Rails

texts:
I have a polymorphic notification model. When user gets a notification he can get on the page of the notifiable to check  out what happened exactly. For instance invited you to join product or commented on a post. On the top of this I also have a polymorphic comment model. So user can get a notification not only for commented on a post but also for commented on a product customeror commented on a product, which of course just makes the whole situation more complex.

So the flow is the  following:

If the user clicks on the notification, the link redirects to the custom checking_decreasing action to check the notification and decrease the notification number if necessary, and then it redirects to the desired page with anchor.

As you see my notification_redirection_path action looks terrible and I'm not even sure if it should be in application controller. Any ideas how I could refactor this code?

notifications index page (there is also a json version for dropdown notifications)

<%= link_to checking_decreasing_user_notifications_path(
      current_user,
      notifiable_type: notification.notifiable_type,
      notifiable_id: notification.notifiable_id,
      notification_action: notification.action
     ) do %>

notifications_controller

def checking_decreasing
  current_user.decreasing_comment_notification_number(
    params[:notifiable_type],
    params[:notifiable_id]
  )
  redirect_to notification_redirection_path(
    params[:notifiable_type],
    params[:notifiable_id],
    params[:notification_action]
  )
end

application controller

def notification_redirection_path(notifiable_type, notifiable_id, action)
  if action == "commented"
    if notifiable_type == "ProductCustomer"
      product_customer = ProductCustomer.find(notifiable_id)
      product_id = product_customer.product_id
    elsif notifiable_type == "ProductLead"
      product_lead = ProductLead.find(notifiable_id)
      product_id = product_lead.product_id
    end
    route = case notifiable_type
            when "Post"
              posts_path(anchor: "post_#{notifiable_id}")#{}"/posts#post_#{notifiable_id}"
            when "Product"
              product_path(notifiable_id, anchor: "comment-panel")#/products/#{notifiable_id}#comment-panel"
            when "ProductLead"
              product_product_lead_path(product_id, notifiable_id, anchor: "comment-panel")#{}"/products/#{product_id}/#{notifiable_type}/#{notifiable_id}#comment-panel"
            when "ProductCustomer"
              product_product_customer_path(product_id, notifiable_id, anchor: "comment-panel") #/products/#{product_id}/#{notifiable_type}/#{notifiable_id}#comment-panel"
            end
  elsif action == "invited"
    product_path(notifiable_id, anchor: "product-invitation-well")
  elsif action == "accepted"
    product_product_users_path(notifiable_id)
  end
end


texts: Write a recursive function that takes a positive integer n and plots an N-by-N Hadamard pattern where N = 2^n

texts:
This is web exercise 2.3.20. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

Write a recursive program  that takes a command-line argument n and
plots an N-by-N Hadamard pattern where N = 2^n. Do not use an array. A
1-by-1 Hadamard pattern is a single black square. In general a
2N-by-2N Hadamard pattern is obtained by aligning 4 copies of the
N-by-N pattern in the form of a 2-by-2 grid, and then inverting the
colors of all the squares in the lower right N-by-N copy. The N-by-N
Hadamard H(N) matrix is a boolean matrix with the remarkable property
that any two rows differ in exactly N/2 bits. Here are the first few
Hadamard matrices.

Here is my program:
public class wexercise2_3_20
{
    public static void hadamard(int n, double x, double y, double size,
                                boolean color)
    {
        double x1 = x - size/2, x2 = x + size/2;
        double y1 = y - size/2, y2 = y + size/2;
        if (n == 0) return;
        if (color)
        {
            StdDraw.setPenColor(StdDraw.BLACK);
            StdDraw.filledSquare(x,y,size);
        }
        else
        {
            StdDraw.setPenColor(StdDraw.WHITE);
            StdDraw.filledSquare(x,y,size);
        }
        hadamard(n-1, x1, y1, size/2, color);
        hadamard(n-1, x1, y2, size/2, color);
        hadamard(n-1, x2, y2, size/2, color);
        hadamard(n-1, x2, y1, size/2, !color);

    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        hadamard(n, 0.5, 0.5, 0.5, true);
    }
}

StdDraw is a simple API written by the authors of the book.
Is there any way that I can improve my program?
Thanks for your attention.


texts:
I'm using a simple octree in my program and wanted to know if my implementation could be faster. It is part of this program.

Octree.H:

#ifndef OCTREE_H
#define OCTREE_H

#include "Rendera.H"

class Octree
{
public:
  struct node_t
  {
    float value;
    struct node_t *child[8];
  };

  Octree();
  virtual ~Octree();

  void clear(struct node_t *);
  void write(const int &, const int &, const int &, const float &);
  void writePath(const int &, const int &, const int &, const float &);
  float read(const int &, const int &, const int &);

  struct node_t *root;
};

#endif

Octree.cxx:

#include "Octree.H"

Octree::Octree()
{
  root = new node_t;
  root->value = 0;

  for(int i = 0; i < 8; i++)
    root->child[i] = 0;
}

Octree::~Octree()
{
  clear(root);
}

void Octree::clear(struct node_t *node)
{
  for(int i = 0; i < 8; i++)
    if(node->child[i])
      clear(node->child[i]);

  delete node;
}

void Octree::write(const int &r, const int &g, const int &b,
                   const float &value)
{
  struct node_t *node = root;

  for(int i = 7; i >= 0; i--)
  {
    const int index = ((r >> i) & 1) << 0 |
                      ((g >> i) & 1) << 1 |
                      ((b >> i) & 1) << 2;

    if(!node->child[index])
    {
      node->child[index] = new node_t;
      node = node->child[index];
      node->value = 0;

      for(int j = 0; j < 8; j++)
        node->child[j] = 0;
    }
    else
    {
      node = node->child[index];
    }
  }

  node->value = value;
}

// Sets entire path to value.
// This allows the octree to be used in a different way.
// (Needed for palette lookup.)
void Octree::writePath(const int &r, const int &g, const int &b,
                       const float &value)
{
  struct node_t *node = root;

  for(int i = 7; i >= 0; i--)
  {
    const int index = ((r >> i) & 1) << 0 |
                      ((g >> i) & 1) << 1 |
                      ((b >> i) & 1) << 2;

    if(!node->child[index])
    {
      node->child[index] = new node_t;
      node = node->child[index];
      node->value = value;

      for(int j = 0; j < 8; j++)
        node->child[j] = 0;
    }
    else
    {
      node = node->child[index];
    }
  }
}

float Octree::read(const int &r, const int &g, const int &b)
{
  struct node_t *node = root;

  for(int i = 7; i >= 0; i--)
  {
    const int index = ((r >> i) & 1) << 0 |
                      ((g >> i) & 1) << 1 |
                      ((b >> i) & 1) << 2;

    if(node->child[index])
      node = node->child[index];
    else
      break;
  }

  return node->value;
}


texts:
So, I'm diving into C and decided to create cons cells. I'd like some thoughts on style and correctness. There are no warnings with -Wall -g and Valgrind doesn't complain about anything.

I'm really not sure what to do when the list is NULL in the first function.

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

struct Cell {
    int val;
    struct Cell *next;
};

struct Cell *cons(int val, struct Cell *rest)
{
    struct Cell *cell = malloc(sizeof(struct Cell));
    cell->val = val;
    cell->next = rest;
    return cell;
}

int first(struct Cell *list)
{
    if (list) {
        return list->val;
    }
    return 0;
}

struct Cell *rest(struct Cell *list)
{
    return list->next;
}

int length(struct Cell *list)
{
    if (list) {
        return 1 + length(rest(list));
    }
    return 0;
}

void destroy(struct Cell *list)
{
    if (list) {
        destroy(rest(list));
        free(list);
    }
}

void print(struct Cell *list)
{
    if (list) {
        printf("%d\n", first(list));
        print(rest(list));
    }
}

The main function.

int main(int argc, char *argv[])
{
    struct Cell *list = NULL;
    int i;
    for (i = 1; i < argc; ++i) {
        list = cons(atoi(argv[i]), list);
    }
    puts("Entire list:");
    print(list);
    puts("First:");
    printf("%d\n", first(list));
    puts("Rest:");
    print(rest(list));
    puts("Length:");
    printf("%d\n", length(list));
    destroy(list);
    return 0;
}

Running it.

./cons 1 2 3 4


texts: Deflating a Stream using System.IO.Compression

texts:
I receive messages from a MessageWebSocket connection frequently, which are compressed with zlib. The following code decompresses them to a stream which can be read with JSON.Net's JsonReader.

I'm pretty sure there are some improvements to be done, but can't quite put my finger on what:

private MemoryStream _compressed;
private DeflateStream _decompressor;
private void HandleMessage(object sender, MessageWebSocketMessageReceivedEventArgs e)
{
    using (var datastr = e.GetDataStream()?.AsStreamForRead())
        using (var ms = new MemoryStream())
            {
                datastr.CopyTo(ms);
                ms.Position = 0;
                byte[] input = new byte[ms.Length];
                ms.Read(input, 0, (int)ms.Length);
                int index = 0;
                int length = input.Length;
                using (var output = new MemoryStream())
                {
                    if (input[0] == 0x78)
                    {
                        //Remove the zlib header
                        _compressed.Write(input, index + 2, length - 2);
                        _compressed.SetLength(length - 2);
                    }
                    else
                    {
                        _compressed.Write(input, index, length);
                        _compressed.SetLength(length);
                    }

                    _compressed.Position = 0;
                    _decompressor.CopyTo(output);
                    _compressed.Position = 0;
                    output.Position = 0;

                    using (var reader = new StreamReader(output))
                    using (JsonReader jsreader = new JsonTextReader(reader))
                    {
                        //Deserialize JSON from the jsreader stream
                    }
                }
            }
}


texts:
The code below takes a directory of XML files and parses them into a CSV file.
Right now parsing around 60 XML files is fast and the output is a CSV file that is around 250MB.

That is a really big file and the reason is because columns are being repeated. I'm repeating the columns for the reason that every element should have all the information. In red is one of the cases where the ID Z048 had multiple lines of setdata so that is why the other columns in red had to be repeated.

I'm planning to increase the number of XML files to 5k, meaning that the CSV file will be relatively large.

Asking this question to maybe get any answer if the size of my CSV file can be lowered somehow. Even though I tried to code with the mindset that I want my code to be fast and produce not too big CSV files.

from xml.etree import ElementTree as ET
from collections import defaultdict
import csv
from pathlib import Path

directory = 'path to a folder with xml files'

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)

    headers = ['id', 'service_code', 'rational', 'qualify', 'description_num', 'description_txt', 'set_data_xin', 'set_data_xax', 'set_data_value', 'set_data_x']
    writer.writerow(headers)

    xml_files_list = list(map(str, Path(directory).glob('**/*.xml')))
    print(xml_files_list)
    for xml_file in xml_files_list:
        tree = ET.parse(xml_file)
        root = tree.getroot()

        start_nodes = root.findall('.//START')
        for sn in start_nodes:
            row = defaultdict(str)

            repeated_values = dict()
            for k,v in sn.attrib.items():
                repeated_values[k] = v

            for rn in sn.findall('.//Rational'):
                repeated_values['rational'] = rn.text

            for qu in sn.findall('.//Qualify'):
                repeated_values['qualify'] = qu.text

            for ds in sn.findall('.//Description'):
                repeated_values['description_txt'] = ds.text
                repeated_values['description_num'] = ds.attrib['num']

            for st in sn.findall('.//SetData'):
                for k,v in st.attrib.items():
                    row['set_data_'+ str(k)] = v
                for key in repeated_values.keys():
                    row[key] = repeated_values[key]
                row_data = [row[i] for i in headers]
                writer.writerow(row_data)
                row = defaultdict(str)


texts:
I would appreciate some feedback on the below code I wrote for a Project Euler problem. The answer comes out correct but I'd like feedback on the design of the function and implementation of docstrings. It seems to me that it may be overly complicated but I'm not sure how to simplify.

"""
Number letter counts

Problem 17
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are
3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many
letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains
23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing
out numbers is in compliance with British usage.
Answer = 21124
"""

num_word_map = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
                6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
                11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
                15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
                19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty',
                50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty',
                90: 'ninety', 100: 'hundred', 1000: 'thousand'}

def convert_to_word(x, spacing=''):
    """
    Recursive function that converts number to it's equivalent word up to a limit of 9999.
    Function is called recursively until x < 20.

    Parameters
    ----------
    x : number to convert to word
    spacing : keeps track appropriate value to enter between words. This will be 'and' or an empty string

    Returns
    -------
    Equivalent word for the number x

    """
    if x / 1000 == 1:
        return convert_to_word(x // 1000) + num_word_map[1000]
    if 0 < x//100 < 10:
        if x % 100:
            return convert_to_word(x//100) + num_word_map[100] + convert_to_word(x % 100, 'and')
        else:
            return convert_to_word(x//100) + num_word_map[100]
    elif 2 <= x//10 < 10:
        return spacing + num_word_map[x - (x % 10)] + convert_to_word(x % 10)
    # 0 included to prevent TypeError on a value like 80
    elif 0 <= x < 20:
        return spacing + num_word_map[x]
    else:
        "Value out of bounds"

def count_letters(limit=1000):
    """
    Counts the number of letters in a word corresponding to a number from one to limit

    Parameters
    ----------
    limit : upper limit of numbers to convert and count to

    Returns
    -------
    None

    """
    count = 0
    for val in range(1, limit + 1):
        s = convert_to_word(val)
        print(s)
        count += len(s)
    print(count)

if __name__ == '__main__':
    count_letters()


texts: Find the maximum number of consecutive zeros in an array

texts:
Question: To find the maximum number of consecutive zeros in a given
  array.

  Example:

  Input: \${1, 2, 0, 0, 2, 4, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 7, 0}\$

  Output: "Maximum number of consecutive zeros : 6"

Here is what I've come up with:

public class ZeroSeriesLength {

    public static void main(String[] args) {

        int[] values = {1, 2, 0, 0, 2, 4, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 7, 0};

        int maxLength = 0;
        int tempLength = 0;

        for (int i = 0; i < values.length; i++) {

            if (values[i] == 0) {
                tempLength++;
            } else {
                tempLength = 0;
            }

            if (tempLength > maxLength) {
                maxLength = tempLength;
            }
        }

        System.out.println("Maximum number of consecutive zeros : " + maxLength);
    }
}

Is the logic correct? Or can it be done via a simple approach?


texts:
I've written a Controller for the keyboard so that I can map certain keys to callbacks within a game. A key can only call one callback, but a callback can be called by many keys.

Currently, a Controller has two std::maps - one for when the key(s) is pressed/held, and one for when the key(s) are released. These maps are SDL_Scancode to std::string (Which I may change later to an enum rather than a string? But strings are easier to read so maybe not.) The Controller also has a ControllerContext object, which is just a wrapper around two std::maps of std::string to std::function<void(void)>: one map for callbacks to happen when a key is pressed, another for callbacks to happen when a key is released.

I feel like some kind of change could be made to make the code more readable, and I am unsure of if I should have the context stored in a shared_ptr, or if I should just keep a raw pointer within the Controller.

This is how it would work:

//An event union provided by SDL
//https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlevent.html
SDL_Event e;
//A controller
Controller controller_;
ControllerContext context_;

//Build the context
controller_.SetContext(&context);

//Poll all events in the event queue, feeding them to the structure e
while(SDL_PollEvent(&e))
{
   switch(e.type)
       case SDL_KEYDOWN:
           controller_.OnKeyPress(e.key);
           break;
       case SDL_KEYUP:
           controller_.OnKeyRelease(e.key);
           break;
       default:
           break;
}

keyboardcontroller.h

#ifndef SHMUPPY_HEADER_KEYBOARDCONTROLLER_H_
#define SHMUPPY_HEADER_KEYBOARDCONTROLLER_H_

#include <map>
#include <SDL.h>
#include <iostream>
#include <exception>
#include <string>
#include <memory>

struct ControllerContext;

class Controller
{
public:
    Controller();

    int OnKeyPress(const SDL_Event &e);

    int OnKeyRelease(const SDL_Event &e);

    void SetContext(std::shared_ptr<ControllerContext> context_);

protected:
    std::map<SDL_Scancode, std::string> keypress_action_map_;
    std::map<SDL_Scancode, std::string> keyrelease_action_map_;
    std::shared_ptr<ControllerContext> controller_context_;
};

#endif

keyboardcontroller.cpp

#include "KeyboardController.h"
#include "ControllerContext.h"

Controller::Controller()
{
    //Some test initializations
    keypress_action_map_[SDL_SCANCODE_LEFT] = "Left";
    keypress_action_map_[SDL_SCANCODE_DOWN] = "Down";
    keypress_action_map_[SDL_SCANCODE_RIGHT] = "Right";
    keypress_action_map_[SDL_SCANCODE_UP] = "Up";

    keyrelease_action_map_[SDL_SCANCODE_LEFT] = "Left";
    keyrelease_action_map_[SDL_SCANCODE_DOWN] = "Down";
    keyrelease_action_map_[SDL_SCANCODE_RIGHT] = "Right";
    keyrelease_action_map_[SDL_SCANCODE_UP] = "Up";
}

int Controller::OnKeyPress(const SDL_Event& e)
{
    try
    {
        //std::cout << keypress_action_map_.at(e.key.keysym.scancode) << std::endl;
        controller_context_->keypress_events_.at(keypress_action_map_.at(e.key.keysym.scancode))();
        return 1;
    }
    catch (std::exception ex)
    {
        return 0;
    }
}

int Controller::OnKeyRelease(const SDL_Event& e)
{
    try
    {
        std::cout << keyrelease_action_map_.at(e.key.keysym.scancode) << std::endl;
        return 1;
    }
    catch (std::exception ex)
    {
        return 0;
    }
}

void Controller::SetContext(std::shared_ptr<ControllerContext> context_)
{
    controller_context_ = context_;
}

ControllerContext.h

#ifndef SHMUPPY_HEADER_CONTROLLER_CONTEXT_H
#define SHMUPPY_HEADER_CONTROLLER_CONTEXT_H

#include <map>
#include <functional>

struct ControllerContext
{
    std::map<std::string, std::function<void(void)>> keypress_events_;
    std::map<std::string, std::function<void(void)>> keyrelease_events_;
};

#endif


texts:
In Rails 3, I have two models: Nutrient and Recommendation:

Nutrient has_many Recommendation
Recommendation belongs_to Nutrient

I am trying to implement the create method of the recommendation in the controller. Is this the proper way to do it?

def create
  nutrient_id = params[:recommendation][:nutrient_id]
  if nutrient_id.blank?
    #nutrient_id was blank in the submit, get other recommendation params and re-render 'new'
    params[:recommendation].delete(:nutrient_id)
    @recommendation=Recommendation.new(params[:recommendation])
    render 'new'
  else
    @nutrient = Nutrient.find(nutrient_id)
    if @nutrient
      #nutrient was found by id, create recommendation
      @recommendation = @nutrient.recommendations.build(params[:recommendation])
      if @recommendation.save
        redirect_to @recommendation
      else
        render 'new'
      end
    else
      #nutrient was not found by id, get other recommendation params and re-render 'new'
      params[:recommendation].delete(:nutrient_id)
      @recommendation = Recommendation.new(params[:recommendation])
      render 'new'
    end
  end
end


texts:
I have written a change calculator using Ada. when the user inputs an amount of money it returns a list of the coins and bills needed to create that total. It starts off by trying to use the largest money types then tries smaller ones.

I am still learning how to use Ada and would like to know how i can make better use of the language features. Am i using the right data types, is there a way to make the change calculation loop more readable?

with Ada.Text_IO;
with Ada.Float_Text_IO;
with Ada.IO_Exceptions;
with Ada.Integer_Text_IO;
use Ada;

procedure Change_Calculator is
   type Money is delta 0.01 digits 10;
   Input_Amount : Money := 0.0;
   package Money_IO is new Text_IO.Decimal_IO(Money);

   type Currency_Denomination is record
      Name : String(1..10);
      Value : Money;
   end record;

   Currency_Names  : array (1..10) of Currency_Denomination;
   Currency_Counts : array (1..10) of Integer := (others=>0);
   Currency_Index  : Integer range 1..10;

   procedure Get_Money_Prompt(Amount: out Money) is
      Response : String(1..20);
      Last     : Natural;
   begin
      loop
         declare
         begin
            Text_IO.Put("amount: ");
            Text_IO.Flush;
            Text_IO.Get_Line(Response, Last);
            -- try to convert string input to money type
            Amount := Money'Value(Response(1 .. Last));
            -- quit the loop if the money converted -- '
            exit;
         exception
            when Constraint_Error =>
               Text_IO.Put_Line("ERROR: bad money format");
         end;
      end loop;
   end Get_Money_Prompt;

begin
   Currency_Names := (("Penny     ", 0.01),
                      ("Nickle    ", 0.05),
                      ("Dime      ", 0.10),
                      ("Quarter   ", 0.25),
                      ("Dollar    ", 1.00),
                      ("5 Dollar  ", 5.00),
                      ("10 Dollar ", 10.00),
                      ("20 Dollar ", 20.00),
                      ("50 Dollar ", 50.00),
                      ("100 Dollar", 100.00));

   -- read money amount from the user
   Get_Money_Prompt(Input_Amount);

   -- calculate needed currency
   for I in Currency_Names'Range loop
      -- calculate inverse of index to count backwords
      Currency_Index := (Currency_Names'Length-I)+1;
      while Input_Amount >= Currency_Names(Currency_Index).Value loop
         Input_Amount := Input_Amount - Currency_Names(Currency_Index).Value;
         -- increment currency useage in array
         Currency_Counts(I) := Currency_Counts(I) + 1;
      end loop;
   end loop;

   -- display needed currency
   for I in Currency_Counts'Range loop
      Currency_Index := (Currency_Names'Length-I)+1;
      -- do not display unused currency
      if Currency_Counts(Currency_Index) /= 0 then
        Text_IO.Put(Currency_Names(I).Name & " ");
        Integer_Text_IO.Put(Currency_Counts(Currency_Index));
        Text_IO.New_Line;
      end if;
   end loop;

end Change_Calculator;


texts:
My program needs to parse an e-mail string. There are two possibilities to enter an e-mail-address. Either with the alias or without one, plain the e-mail-address.

1st possibity:

string addressWithAlias = "test my address <bla@blub.com>";

2nd possibility:

string addressWithoutAlias = "bla@blub.com";

So, I wrote two functions:

private static string[] getAddressPartsRegex(string address)
{
    string plainaddress = address.Trim();

    Regex reg = new Regex(@"(.+?(?=<))<(.*@.*?)>");
    var gr = reg.Match(plainaddress).Groups;

    return gr.Count == 1
        ? new[] { plainaddress }
        : new[] { gr[1].Value.Trim(), gr[2].Value.Trim() };
}

private static string[] getAddressParts(string address)
{
    var splittedAdress = address.Split(' ');
    return splittedAdress.Last().Trim().StartsWith("<")
        ? new[] { string.Join(" ", splittedAdress.Take(splittedAdress.Length - 1)), splittedAdress.Last().Trim(' ', '<', '>') }
        : splittedAdress;
}

They both work fine and the results are the same. One uses regex, the other uses Split and Join.
What would you suggest to use, and why? What is the more beautiful function?
Are there any bugs I didn't see?


texts:
According to the local cop (rubocop), my method has too many lines.

lib/awesomelibrary/tunnelable.rb:4:5: C: Method has too many lines. [17/10]
    def tunnel_run(cmd) ...
    ^^^^^^^^^^^^^^^^^^^

Below is the method. How do I refactor it?

module AwesomeLibrary
  # Gives object the ability to execute bash commands on itself via ssh
  module Tunnelable
    def tunnel_run(cmd)
      retries = 0
      code = nil
      Net::SSH.start(@tunnel_ip, @tunnel_username, keys: @tunnel_key_name, verify_host_key: false) do |ssh|
        the_channel = ssh.open_channel do |channel|
          channel.exec cmd do |ch, success|
            raise "could not execute command" unless success
            ch.on_data { |_c, data| print data }
            ch.on_extended_data { |_c, _type, data| print data }
            ch.on_request("exit-status") { |_ch, data| code = data.read_long }
          end
        end
        the_channel.wait
      end
      abort "#{cmd} returned #{code} !!" if code != 0
    rescue Net::SSH::ConnectionTimeout
      puts "Net::SSH::ConnectionTimeout"
      retry if (retries += 1) < 3
    end
  end
end

I'm using this is the library: Net::SSH 4.x.


texts: Django ListView with MySQL query for the queryset

texts:
(Note: Even if you don't know Django, it's probably the query that needs work anyway, so you probably don't need to know Django/Python)

I have a ListView that displays all the entries in a mapping table between the pizza table and the topping table. Unfortunately, I can't just use Django's helpfulness and just give it the model to use (I'm skipping why for the sake of brevity), and have to use get_queryset instead. Unfortunately again, the load time is slow - there are almost 700 pizzas in the table and I need to use it in my sql query to order by pizza name. Here's what I'm currently doing:

class MapPizzaToppingListView(ListView):
    model = MapPizzaTopping
    paginate_by = 20
    template_name = 'onboardingWebApp/mappizzatopping_list.html'

    def get_queryset(self):
        cursor = connections["default"].cursor()
        cursor.execute("""SELECT map.*
                          FROM map_pizza_topping as map
                          INNER JOIN pizza
                              ON (map.pizza_id = pizza.id)
                          ORDER BY pizza.name""")
        queryset = dictfetchall(cursor)
        for row in queryset:
            pizza = Pizza.objects.get(id=row['pizza_id'])
            topping = Topping.objects.get(id=row['topping_id'])
            row['pizza_name'] = "%s (%s)" % (pizza.name, pizza.merchant.name)
            row['topping_name'] = topping.name
        return queryset

It takes a few seconds to load now, but we're going to be adding tons more pizzas eventually, so this really needs to be sped up. Unfortunately, my MySQL knowledge, though decent, isn't really to a point where I know how to make it better. What can I do to improve it?

Some more information that could be useful - the map_pizza_topping table just has a pizza_id column, a topping_id column, and a quantity column. The pizza table just has name, price, customer_id, and merchant_id columns, and the topping table just has name and is_dairy columns.


texts:
The original idea behind the problem is that the API I'm working with returns one type of a response for GET, and requires another type to do POST / PUT. The object I'm receiving from the GET has a format like this:

 const rawObject = {
  data1: {
    id: 1,
    value: 444
  },
  data2: null
 }

In order to be able to update it, or do a POST request to create a new one, I had to convert it into this format (This is the final output of my solution as well):

const convertedObject = {
  data1: 444,
  data2: null
};

The object I'm converting consists of another objects within it (One level max - as in the first example) or null. If the object is not null, I only care about the value of a nested object, therefore I flatten it as - data1: 444.

The solution I came up with is this (It works perfectly):

const rawObject = {
  data1: {
    id: 1,
    value: 444
  },
  data2: null
}

let convertedObject: any = {};

Object.entries(rawObject).map((item: any) => {
  const rawObjectKey = item[0];
  const rawObjectValue = item[1];
  if (rawObjectValue) {
    convertedObject = {...convertedObject, ...{[rawObjectKey]: rawObjectValue.value}};
    return;
  }
  convertedObject = {...convertedObject, ...{[rawObjectKey]: null}};
  return;
});
console.log(convertedObject); // Check the Output in example above

Stackblitz

I decided to use Object.entries() as I need both key:value pairs available. The if check I'm doing is there because object could have null value, therefore rawObjectValue would be null.


texts: Implementing an open/close function in Prolog

texts:
I'm going through the Adventure in Prolog tutorial and I'm trying to implement an open/close rule for each of the doors I have.

  Add an open/closed status for each of the doors. Write open and close predicates that do the obvious

:- dynamic here/1, location/2, have/1, turned_on/1, turned_off/1.
room(kitchen).
room(office).
room(hall).
room('dining room').
room(cellar).

location(desk, office).
location(apple, kitchen).
location(flashlight, desk).
location('washing machine', cellar).
location( nani,'washing machine' ).
location(broccoli, kitchen).
location(crackers, kitchen).
location(computer, office).

door(office, hall).
door(kitchen, office).
door(kitchen, cellar).
door(hall, 'dining room').
door('dining room', kitchen).

edible(apple).
edible(crackers).

tastes_yucky(broccoli).

turned_off(flashlight).

here(kitchen).

connect(X, Y) :- door(X, Y).
connect(X, Y) :- door(Y, X).

list_things(Place) :-
  location(X, Place),
  tab(2),
  write(X), nl,
  fail.
list_things(AnyPlace).

list_connections(Conn) :-
  connect(Conn, X),
  tab(2),
  write(X),
  nl,
  fail.
list_connections(_).

look :-
  here(X),
  write('you are in the '), write(X), nl,
  write('you can see:'), nl,
  list_things(X),
  write('you can go to:'), nl,
  list_connections(X).

goto(Place) :-
  can_go(Place),
  move(Place),
  look.

can_go(Room) :-
  here(X),
  connect(X, Room).
can_go(Room) :-
  write('You can\'t go there from here'),nl,
  fail.
move(Place):-
  retract(here(X)),
  asserta(here(Place)).

take_object(X) :-
  retract(location(X, _)),
  asserta(have(X)).
  write('taken'), nl.

put(X) :-
  retract(have(X)),
  asserta(location(X,_)).
inventory:-
  have(X),
  write('you have the following items:'), nl,
  write(X).
turn_on(X):-
  turned_off(X),
  retract(turned_off(X)),
  asserta(turned_on(X)),
  write('flash light turned on').
turn_on(X):-
  write('you can\'t turn that on').

turn_off(X):-
  turned_on(X),
  retract(turned_on(X)),
  asserta(turned_off(X)),
  write('flash light is now off').
turn_off(X):-
  write('you can\'t turn that off').

Now to actually add the rules:

door(office, hall).
door(kitchen, office).
door(kitchen, cellar).
door(hall, 'dining room').
door('dining room', kitchen).

opened(office, hall).
closed(kitchen, office).
opened(kitchen, cellar).
closed(hall, 'dining room').
opened('dining room', kitchen).

open(X, Y) :-
  closed(X, Y),
  retract(closed(X, Y)),
  asserta(opened(X, Y)),
  writeln('door opened').
open(X, Y) :-
  closed(Y, X),
  retract(closed(Y, X)),
  asserta(opened(Y, X)),
  writeln('door opened').
close(X, Y) :-
  opened(X, Y),
  retract(opened(X, Y)),
  asserta(closed(X, Y)),
  writeln('door closed').
close(X, Y) :-
  opened(Y, X),
  retract(opened(Y, X)),
  asserta(closed(Y, X)),
  writeln('door closed').

I'm only concerned  that I'm using the open(X,Y) twice (also the close).  Is there a better way?