texts: Avoid using C Strings on C++ code to trim leading whitespace

texts:
I'm learning C++ and wrote a function to remove all the spaces and tabs at the beginning of the input string. It removes them until it find a character different of space and tabs.

In the first version I have mixed C and C++ code and someone has told me that this is a bad coding style, but in the second version I have tried to use only C++ code.

Did I do well?

#include <fstream>
#include <ios>
#include <iostream>
#include <string>

std::string trimLeft(const std::string& input) {

    if ((input.empty()) ||
        ((input.at(0) != ' ') && (input.at(0) != '\t')))
        return input;
    else {
        char * tab2 = new char[input.length() + 1];
        char *trimmed = new char[input.length() + 1];

        strcpy(tab2, input.c_str());

        bool skip = true;
        size_t pos = 0;

        for (size_t i = 0; i < (input.length() + 1); i++) {
            if (skip) {
                if ((tab2[i] == ' ') || (tab2[i] == '\t'))
                    continue;
                else {
                    skip = false;

                    trimmed[pos] = tab2[i];
                    pos++;
                }
            }
            else {
                trimmed[pos] = tab2[i];

                if (tab2[i] == '\0')
                    break;
                else
                    pos++;
            }
        }

        std::string stringTrimmed(trimmed);

        return stringTrimmed;
}

So, I have tried to implement it using only C++ strings:

#include <fstream>
#include <ios>
#include <iostream>
#include <string>

std::string trimLeft(const std::string& input) {

    if ((input.empty()) ||
        ((input.at(0) != ' ') && (input.at(0) != '\t'))) {
        return input;
    }
    else {
        size_t pos = 0;

        for (size_t i = 0; i < input.length(); i++) {
            if ((input.at(i) == ' ') || (input.at(i) == '\t'))
                continue;
            else {
                pos = i;
                break;
            }
        }

        return input.substr(pos, (input.length() - pos));
    }
}


texts: Sorting a list of numbers, each with a character label

texts:
I am working on a project that requires me to modify an input list as follows:

INPUT: List of numbers, each tagged with a label i.e. [[2, 'a'], [3, 'b'], [1, 'c'], ...]

DESIRED OUTPUT: Sort the list and grab the elements with the highest numerical component, store them in another list, and maybe rerun the function on the new list. This is an order determination scheme based on players rolling dice.

I have created the following code in Python 3.7 and it works just fine for me. I am curious to see if there are more clever ways to arrive at the same output. For some reason this took me about two hours to come up with (I am learning from scratch).

list = [[1,'a'],[3,'b'],[7,'c'],[6,'d'],[4,'e'],[1,'f'],[7,'g'],[4,'h'],[6,'i']]

def comp(list):

    new_list = []
    list.sort(reverse = True)
    for y in range(1, len(list)):
        if list[0][0] > list[y][0]:
            new_list.append(list[y])
    top_rolls = [x for x in list if x not in new_list]
    return(top_rolls)


texts: Grab first successful pair from a list of maps

texts:
I have a function that parses geographic coordinates through a list of different providers. In this case I want to look up two addresses. The main problem of this question is - given a List of of Geocode Service -> Resolved Address mappings, find the first successful pair that has a valid resolved address.

So each address results in a map(provider -> result). I'm given a list of them, and need to find the a successful pair from the list e.g provider1 from the first address and provider1 from the second address. I can't compare the resolved addresses if the providers do not match.

For example, the best scenario is that the addresses are perfect. I can use the head map entry of the first address and query the map entry for the second address. Then compare their values. However, it's rarely that simple.

I started out with a foldLeft, but I feel that can be inefficient if it matches successfully immediately.

val result: List[Map[GeoProviders.GeoProvider, Either[GeoCodeErrors.GeocodeError, PostalAddress]]]
                  result match {
                    case firstAddressOption :: secondAddressOption :: Nil => {
                      firstAddressOption.foldLeft[Option[Double]](None)((result, address1: (GeoProvider, Either[GeocodeError, PostalAddress])) => {
                        result match {
                          case Some(_) => result
                          case None =>
                            val address2 = secondAddressOption.get(address1._1)
                            (address1._2, address2) match {
                              case  (Right(successAddr1), Some(Right(successAddr2))) => {
                                (successAddr1.coordinates, successAddr2.coordinates) match {
                                  case (Some(firstCoord), Some(secondCoord)) => {
                                    Some(haversineDistance((firstCoord.latitude, firstCoord.longitude), (secondCoord.latitude, secondCoord.longitude)))
                                  }
                                  case _ => None
                                }
                              }
                            }
                        }
                      })


texts: Count numbers with atleast one common factor, excluding one (updated)

texts:
Below is an updated version of  the question I asked prior:

Count numbers with atleast one common factor, excluding one

I have been trying to teach myself some python 3 by working through 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.

As for my update, I have tried:

(1) Utilizing list comprehension in python. While cleaner, I don't think this made any dramatic improvements for me.
(2) I only populate the list of possibilities once now as per the suggestion of Gareth Rees. I originally knew this was inefficient, but I thought this was bad form since it makes my code less flexible for the most general case. I realize now that the constraints should be used in a way to make the code faster for these types of time-limited problems.
(3) I have traded a while loop for a for loop since I read this was faster.

That said, I am still no where near the time limits they are imposing in the problem. Some thoughts I had:

(1) My guess is the main culprit is the nested for loop inside a for loop which is likely very time consuming, but I don't know how to get around using nested for loops in this.

(2) Also, I am wondering if Python is even suitable for severely time limited challenges of this sort? I have read that Python is generally slower than C++ and from what I can tell very few people use Python on time-limited sites like this.

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 (updated) code:

def myfun(num_in):

    int_list = []
    some_list = []
    final_list = []

    if num_in == 1:
        print(0)
    elif num_in > 1:

        # check remainder from division
        test = [num_in % pos[j] for j in range(0, (num_in + 1) // 2)]  # only need .5 the number or smaller

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

        # multiply factor by integers until it exceeds input
        # this seems like the best candidate to make more efficient
        for i in range(0, len(int_list)):
            temp = int_list[i]
            # for j in range(1, int(num_in / temp)):
            #     final_list.append(temp * j)

            ttempp = [j for j in range(1, int(num_in / temp))]
            some_list = list(map(lambda x: x * temp, ttempp))
            final_list = final_list + some_list

        #print(final_list)
        #print(set(final_list))
        # add 1 for the number itself since we don't check that (only checked up to .5 * num)
        print(len(set(final_list)) + 1)

# list all possibilities once
pos = [i for i in range(2, 1000000)]

# input code
# how many to run
tot_num = int(input())

# get full list of inputs
master_list = [int(input()) for i in range(tot_num)]

# run code on list of inputs
[myfun(master_list[q]) for q in range(tot_num)]


texts: Java Stream - Collections - remove duplicates based on string and presence/absence of local date value

texts:
I have a list of objects with a string (name) and a local date (date of deletion).

I wish to implement uniqueness on these objects based on:

If two objects have the same name, then I wish the one with no date
of deletion to have priority.
If two objects have the same name, and a date of deletion, then I wish the one with the most recent date of deletion to have priority.

Based on the above criteria, I have implemented, what I think is the right solution.

Do you have any pointers as to the correctness of my approach? Do you have any suggestions for improvements?

The class:

public class Unique implements Comparable<Unique>
{
    private String name;
    private LocalDate dateOfDeletion;

    public Unique(String name, LocalDate dateOfDeletion) {
        this.name = name;
        this.dateOfDeletion = dateOfDeletion;
    }

    public String getName() {
        return name;
    }

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

    public LocalDate getDateOfDeletion() {
        return dateOfDeletion;
    }

    public void setDateOfDeletion(LocalDate dateOfDeletion) {
        this.dateOfDeletion = dateOfDeletion;
    }

    @Override
    public String toString() {
        return "Unique [name=" +name + ", dateOfDeletion="+dateOfDeletion+"],";
    }

    /**
     * order based on name ascending, and date descending
     */
    @Override
    public int compareTo(Unique rhs) {
        Comparator<Unique> reverseDateComparator = (a, b) -> {
            LocalDate thisDodel = a.getDateOfDeletion() == null ? LocalDate.now().plusDays(1) : a.getDateOfDeletion();
            LocalDate thatDodel = b.getDateOfDeletion() == null ? LocalDate.now().plusDays(1) : b.getDateOfDeletion();
            return thatDodel.compareTo(thisDodel);
        };
        return Comparator.comparing(Unique::getName).thenComparing(reverseDateComparator).compare(this, rhs);
    }
}

The Test:

public static void main(String[] args) {
    List<Unique> uniqueList = Arrays.asList(
                new Unique("a", null)
                ,new Unique("b", null)
                ,new Unique("b", LocalDate.of(2016, Month.SEPTEMBER, 20))
                ,new Unique("c", LocalDate.of(2016, Month.SEPTEMBER, 19))
                ,new Unique("c", LocalDate.of(2016, Month.SEPTEMBER, 20))
                );

    System.out.println("list ordered, with duplicates: ");
    uniqueList.stream().sorted().forEach(System.out::println);

    System.out.println("=================");
    System.out.println("list ordered, duplicates removed: ");
    Comparator<Unique> uniqueComp = (a, b) -> a.getName().compareTo( b.getName() );
    //SOLUTION HERE: since list is already ordered by date desc, it will ignore the records with same name already added to the list
    TreeSet<Unique> sortedFilterd = uniqueList.stream().sorted().collect(Collectors.toCollection(() -> new TreeSet<Unique>(uniqueComp)));
    sortedFilterd.forEach(System.out::println);
}

What I expect to see is the following:

list ordered, with duplicates:
Unique [name=a, dateOfDeletion=null],
Unique [name=b, dateOfDeletion=null],
Unique [name=b, dateOfDeletion=2016-09-20],
Unique [name=c, dateOfDeletion=2016-09-20],
Unique [name=c, dateOfDeletion=2016-09-19],
=================
list ordered, duplicates removed:
Unique [name=a, dateOfDeletion=null],
Unique [name=b, dateOfDeletion=null],
Unique [name=c, dateOfDeletion=2016-09-20],

Here is a link to the working sample: Link to working sample to the above code


texts:
Currently I'm developing my business entities. I feel that the structure is a tad cumbersome.

What I mean is that a store on a particular day can have different open and closing times. So it's not as simple as a store opens and closes at 09:00 and 17:00 respectively every day at the week. A store may open at 09:00 and 19:00 on only Thursdays etc.

Entities

public class Store
{
    public int StoreID { get; set;}
    public string StoreName { get; set; }
    public ICollection<DayOfWeek> DaysOpen { get; set; }
    public List<KeyValuePair<DayOfWeek, StoreTimes>> DaysAndTimes { get; set; }

}

public class StoreTimes
{
    public string StartTime { get; set;}
    public string EndTime { get; set; }
}

The initialisation is a but cumbersome, see below.

Initialisation

 Store store = new Store()
            {
                StoreID = 1,
                StoreName = "Some Store",
                DaysOpen = new List<DayOfWeek>() { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday },
                DaysAndTimes = new List<KeyValuePair<DayOfWeek, StoreTimes>>()
                {
                    new KeyValuePair<DayOfWeek, StoreTimes>(DayOfWeek.Monday, new StoreTimes()
                    {
                        StartTime = "0900", EndTime = "1700"
                    }),
                    new KeyValuePair<DayOfWeek, StoreTimes>(DayOfWeek.Tuesday, new StoreTimes()
                    {
                        StartTime = "1000", EndTime = "1900"
                    })
                }

            };

Yes the initialisation needn't be a problem since the BLL will deal with it but how can this be refactored?


texts: Calculate the intersections of opening hours

texts:
I have a solution but it feels bloated and unclean. How can I clean it up? The second for loop especially does not feel right.

I'm trying to calculate the opening hours but where we only use the highest opening time and the lowest closing time in a time-block. I will show you an example to clarify it.

If we have two time-blocks with

10:00-12:00 and 10:30-12:30

The result for the opening hour is going to be

10:30-12:00

Now imagine we have an array for a specific day:

[
    {
        "opens": "10:00",
        "closes": "12:00",
        "weekday": 5
    },
    {
        "opens": "16:00",
        "closes": "19:30",
        "weekday": 5
    },
    {
        "opens": "11:00",
        "closes": "12:30",
        "weekday": 5
    },
    {
        "opens": "17:00",
        "closes": "18:30",
        "weekday": 5
    }
]

Our opening hour should be for this day:

[
    {
        "opens": "11:00",
        "closes": "12:00"
    },
    {
        "opens": "17:00",
        "closes": "18:30"
    }
]

Now to my approach:

First I'm going to through the whole opening hour array for a specific day:

this.filteredTimes.forEach((time, index, array) => {...});

Inside the for loop, I'm saving the opens and closes time in MomentJS:

let opens = this.momentTime(time.opens); //saving it to moment
let closes = this.momentTime(time.closes); //moment(time, 'HH:mm')

After that, I'm again going through the whole array in another for loop:

for(let i = 0; i < array.length; i++){...} //array === this.filteredTimes

Inside the loop, I'm saving the opens and closes times for each time block again, but now I'm comparing it to the opens and closes time from the first for loop.

let arrayOpens = this.momentTime(array[i].opens);
let arrayCloses = this.momentTime(array[i].closes);

if(arrayOpens.isBetween(opens, closes)){
   opens = arrayOpens.isAfter(opens) ? arrayOpens : opens;
}

If the arrayOpens is between the saved time block, we can save a new opens time if our condition is true.

After that, we are going to save the new opens and closes time and we try to avoid duplication:

let hour = {
    opens: opens.format('HH:mm'),
    closes: closes.format('HH:mm')
};

if(! openingHour.find(element => element.opens == hour.opens && element.closes == hour.closes)){
    openingHour.push(hour);
}

The whole code is here to test (or on JsFiddle):

moment().format();

let filteredTimes = [
 {
    "opens": "10:00",
    "closes": "12:00",
    "weekday": 5
  },
  {
    "opens": "16:00",
    "closes": "19:30",
    "weekday": 5
  },
  {
    "opens": "11:00",
    "closes": "12:30",
    "weekday": 5
  },
  {
    "opens": "17:00",
    "closes": "18:30",
    "weekday": 5
  }
];

let openingHour = [];

calculate();

function calculate(){

  filteredTimes.forEach((time, index, array) => {
    let opens = momentTime(time.opens);
    let closes = momentTime(time.closes);

    for(let i = 0; i < array.length; i++){
      let arrayOpens = momentTime(array[i].opens);
      let arrayCloses = momentTime(array[i].closes);

      if(arrayOpens.isBetween(opens, closes)){
        opens  = arrayOpens.isAfter(opens) ? arrayOpens : opens;
      }
      if(arrayCloses.isBetween(opens, closes)){
        closes  = arrayCloses.isBefore(closes) ? arrayCloses : closes;
      }
    }

    let hour = {
      opens: opens.format('HH:mm'),
      closes: closes.format('HH:mm')
    };

    if(! openingHour.find(element => element.opens == hour.opens && element.closes == hour.closes)){

      openingHour.push(hour);
    }

  });

  console.log(openingHour);
  return openingHour;
}

function momentTime(time){
 return moment(time, 'HH:mm');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>


texts: Counting length-2 substrings that are common to two strings at the same offset -- Python

texts:
I solved the CodingBat task:

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz"
yields 3, since the "xx", "aa", and "az" substrings appear in the same
place in both strings.
stringMatch("xxcaazz", "xxbaaz") → 3
stringMatch("abc", "abc") → 2
stringMatch("abc", "axc") → 0

import doctest

def all_two_chars_occurencies(string):
    """
    >>> list(all_two_chars_occurencies('abcd'))
    ['ab', 'bc', 'cd']
    >>> list(all_two_chars_occurencies('xxcaazz'))
    ['xx', 'xc', 'ca', 'aa', 'az', 'zz']
    """
    for index, char in enumerate(string[:-1]):
        yield char + string[index + 1]

def common_two_chars_occurences(a, b):
    """
    Given 2 strings, a and b, return the number of the positions where
    they contain the same length 2 substring.

    >>> common_two_chars_occurences('xxcaazz', 'xxbaaz')
    3
    >>> common_two_chars_occurences('abc', 'abc')
    2
    >>> common_two_chars_occurences('abc', 'axc')
    0
    """
    equal_duets = 0
    for a_duet, b_duet in zip(all_two_chars_occurencies(a),
                              all_two_chars_occurencies(b)):
        if a_duet == b_duet:
            equal_duets += 1
    return equal_duets

if __name__ == "__main__":
    doctest.testmod()


texts:
I'm very new to Python, and so I'm trying to learn it by doing simple programs, like a calculator. But I don't know if this is the "Pythonic" way to do it, or if I am making beginner errors.

So could someone please tell if something is wrong with it, and how to improve it?

Here is some sample input and output:

Enter the first number: 2
Enter the second number: 10
Enter an operator (valid operators are +, -, *, / and pow): pow
1024.0

Here is the code

#A basic calculator which supports +, -, *, / and pow

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    return a / b

def pow(a, b):
    return a ** b

if __name__ == "__main__":
    while True:
        try:
            number1 = float(input("Enter the first number: "))
            number2 = float(input("Enter the second number: "))
        except:
            print("That is not a number!")
            continue

        operator = input("Enter an operator (valid operators are +, -, *, / and pow): ")

        #Check if user operator is a valid one
        if operator == "+":
            func = add
        elif operator == "-":
            func = sub
        elif operator == "*":
            func = mul
        elif operator == "/":
            func = div
        elif operator == "pow":
            func = pow
        else:
            print("Invalid operator!")
            continue

        #Print result
        print(func(number1, number2))


texts:
I recently got rejected at a job interview for submitting this:

https://bitbucket.org/gnerr/password-validator

The interviewer asked for a password validation library that was configurable via Spring, with the following default validations:

  Must consist of a mixture of lowercase letters and numerical digits only, with at least one of each.
  Must be between 5 and 12 characters in length.
  Must not contain any sequence of characters immediately followed by the same sequence.

Unfortunately they never told me why my implementation is bad, so would someone be kind enough to tell me what I did wrong here?

Here's the main validation class for the library:

package dm.passwordvalidator;

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

/**
 * @author dm
 *
 */
public class PasswordValidator {

    private List<ValidationRule> rules;

    /**
     * Runs all your validation rules and returns true if it's valid, false otherwise
     * @param inPassword
     * @return boolean true if valid, false if otherwise
     */
    public boolean validate(String inPassword) {
        for (ValidationRule rule : this.getRules()) {
            if (!rule.validate(inPassword)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Runs all your validation rules and returns a {@link ValidationResult} with messages if
     * the password was invalid
     * @param inPassword
     * @return {@link ValidationResult} The validation result
     */
    public ValidationResult validateWithMessages(String inPassword) {
        ValidationResult returnValue = new ValidationResult();
        List<String> messages = new ArrayList<String>();
        for (ValidationRule rule : this.getRules()) {
            if (!rule.validate(inPassword)) {
                messages.add(rule.getMessage());
            }
        }
        if (messages.size() > 0) {
            returnValue.setValid(false);
        }
        returnValue.setMessages(messages);
        return returnValue;
    }

    public List<ValidationRule> getRules() {
        return this.rules == null ? this.getDefaultRules() : this.rules;
    }

    public void setRules(List<ValidationRule> inRules) {
        this.rules = inRules;
    }

    private List<ValidationRule> getDefaultRules() {
        List<ValidationRule> returnValue = new ArrayList<ValidationRule>();
        returnValue.add(new RegexValidationRule("(?!(.+?)\\1).*", DefaultValidatorMessages.NO_CYCLES));
        returnValue.add(new RegexValidationRule("[a-z0-9]+", DefaultValidatorMessages.LOWERCASE_AND_NUMBERS));
        returnValue.add(new RegexValidationRule(".*[a-z].*", DefaultValidatorMessages.LOWERCASE_AND_NUMBERS));
        returnValue.add(new RegexValidationRule(".*[0-9].*", DefaultValidatorMessages.LOWERCASE_AND_NUMBERS));
        returnValue.add(new RegexValidationRule(".{5,15}", DefaultValidatorMessages.FIVE_AND_TWELVE));
        return returnValue;
    }

}

The library is configurable as beans like this:

<bean id="lengthRule" class="dm.passwordvalidator.RegexValidationRule">
    <property name="regex" value=".{5,15}"/>
    <property name="message" value="Your password needs to be between 5 to 15 characters"/>
</bean>

<bean id="passwordValidator" class="dm.passwordvalidator.PasswordValidator">
    <property name="rules">
        <list>
            <ref bean="lengthRule" />
        </list>
    </property>
</bean>


texts: Saves Individual Worksheets as Workbooks in destination folder

texts:
This code takes, on average, 6 minutes to fully run with the workbook I am using. The workbook currently has 148 worksheets and will grow consistently with time.

I am curious if there is a way to edit the code from doing the task one worksheet at a time; and, instead complete the task all in one moment. In my mind, the code would run for a much shorter time and then populate all the worksheets as separate workbooks in the file destination at the same time. The worksheets would also not "pop-up" before saving themselves in the destination folder. Much like stopping screen updating and automatic calculations making a world of difference - except that did not work with this code.

Sub SaveFilesInFolder()
'
'Macro for saving each worksheet as a workbook in a destination folder
'

'
Dim sh As Worksheet
Dim wb As Workbook

For Each sh In Worksheets
    SheetName = sh.Name
    sh.Copy

        With ActiveWorkbook
            .SaveAs FileName:="FolderDestination" & SheetName
            .Close SaveChanges:=True
        End With

    Next sh

End Sub

Any suggestions are appreciated.


texts:
This is a calculator that only sums numbers:

module Data.Calculator where

data Expr = Plus Expr Expr | Value Int

evaluate :: Expr -> Int
evaluate (Value a) = a
evaluate (Plus (Value a) (Value b)) = a + b
evaluate (Plus (Plus left right) (Value b)) = (evaluate left) + (evaluate right) + b
evaluate (Plus (Value a) (Plus left right)) = a + (evaluate left) + (evaluate right)
evaluate (Plus a@(Plus left right) b@(Plus left' right')) = (evaluate a) + (evaluate b)

The evaluate function seems way to verbose. How do I make this better?


texts: Finding the indices of multiple words in a string

texts:
In response to a recent SO question, I answered with the following code, and was wondering if anyone had any input on it. I'm always looking for an opprotunity to learn!

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class WordFinder {

    public static void main(String[] args) {
        String phrase = "0123hello9012hello8901hello7890";
        String[] words = { "hello", "90" };

        Map<String, Stack<Integer>> dest = findWordsInString(words, phrase);

        System.out.println(dest.toString());
    }

    public static Map<String, Stack<Integer>> findWordsInString(String[] words, String phrase) {
        Map<String, Stack<Integer>> dest = new HashMap<>();

        for (String word : words) {
            Stack<Integer> locations = new Stack<>();

            for (int loc = -1; (loc = phrase.indexOf(word, loc + 1)) != -1;) {
                locations.add(loc);
            }

            dest.put(word, locations);
        }

        return dest;
    }
}

Program Output:

{90=[9, 19, 29], hello=[4, 13, 22]}


texts: A (possibly) great Polymer autocomplete widget

texts:
I have just finished writing this:

https://github.com/mercmobily/hot-autocomplete

This is the source at the time of me writing this post:

https://github.com/mercmobily/hot-autocomplete/blob/2380ed02ee1dd849c78575e69c00b40c18882c93/hot-autocomplete.html

This is one of my first complex-ish Polymer widgets. I was wondering if you could have a look for me.

Questions:

1)
I coded the keyboard navigation as best as I could. Focus is tricky. I found it really, really difficult to make sure that when the input field loses the focus, the suggestion bar should disappear. I think there must be better ways of doing it. Do you have any hints on that?

At the moment, I have this in the template:

And then:

  _a11ySubmitInputDown: function( e ){
    this.selectingSuggestion = true;
    if( this._suggestions.length > 1 ){
      this._suggestionsList.focus();
    } else {
      this._hideSuggestions();
    }
  },
  _a11ySubmitEscape: function(){
    this.selectingSuggestion = false;
    this._hideSuggestions();
    this.validateField();
    this._field.inputElement.focus();
  }

Basically, I use this.selectingSuggestions to check whether the box should be displayed or not. Note that this.selectingSuggestions is changed in other parts of the code (for example, when an item gets selected  this.selectingSuggestion becomes false.
Is this a good way to make things work? Or did I overlook a much easier way to do this?

2)
The wrapped element must be the first direct child of hot-autocomplete.

<hot-autocomplete url="/suggest?name={{fieldName1}}" method="get">
  <paper-input value="{{fieldName1}}" required id="name" name="name" label="Your name"></paper-input>
</hot-autocomplete>

The code is basic:

// Sets the form
  this._field = this.getEffectiveChildren()[0];
  this._suggestionsList = this.$.suggestionsList;
},

The template (only a portion)

<!-- The actual content distributed, from the light DOM -->
<content id="contentNode"></content>
<paper-listbox on-iron-select="_selected" id="suggestionsList" hidden>
  <template is="dom-repeat" items="{{_suggestions}}">
    <paper-item>{{item}}</paper-item>
  </template>
</paper-listbox>

The more I think about it, the more I think that a much better Polymer-ish way of doing it would be to require the input field to have a specific ID, and and use that ID to distribute the right content. So MAYBE the template should be:

<content select="#autocomplete" id="contentNode"></content>
<paper-listbox on-iron-select="_selected" id="suggestionsList" hidden>
  <template is="dom-repeat" items="{{_suggestions}}">
    <paper-item>{{item}}</paper-item>
  </template>
</paper-listbox>
<content></content>

Would this be better?

3) Any terrible crime in the code that you can see?


texts:
I just created a sample project using Spring 3.x, Jetty 9.x, GWT 2.5.1 and Gradle here. It's a slightly modified version of the 'Greeting' GWT application from Google, the only change being that RPC calls are handled by a spring controller.

It would be really great if someone can review it, I am particularly apprehensive of injecting the GwtRpcController into the GreetingServiceImpl. Should I be worried about any thread safety issues?

Main Controller

@Controller
public class GwtRpcController extends RemoteServiceServlet {

@Autowired
private ServletContext servletContext;

@Autowired
private RemoteService remoteService;

private Class<?> remoteServiceClass;

private HttpServletRequest request;

@RequestMapping(value = "/jettygwtspringsampleapp/*.rpc")
public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response ) throws Exception {
    super.doPost( request, response );
    return null;
}

@Override
public String processCall( String payload ) throws SerializationException {
    try {

        RPCRequest rpcRequest = RPC.decodeRequest( payload, this.remoteServiceClass );

        // delegate work to the spring injected service
        return RPC.invokeAndEncodeResponse( this.remoteService, rpcRequest.getMethod(), rpcRequest.getParameters() );
    } catch ( IncompatibleRemoteServiceException ex ) {
        getServletContext().log( "An IncompatibleRemoteServiceException was thrown while processing this call.", ex );
        return RPC.encodeResponseForFailure( null, ex );
    }
}

@Override
public ServletContext getServletContext() {
    return servletContext;
}

public void setServletContext( ServletContext servletContext ) {
    this.servletContext = servletContext;
}

public void setRemoteService( RemoteService remoteService ) {
    this.remoteService = remoteService;
    this.remoteServiceClass = this.remoteService.getClass();
}

public HttpServletRequest getThreadLocalHttpRequest() {
    return getThreadLocalRequest();
}

}

Service implementation

@Configuration
public class GreetingServiceImpl implements GreetingService {

@Autowired
GwtRpcController rpcController;

public String greetServer( String input ) throws IllegalArgumentException {
    // Verify that the input is valid.
    if ( !FieldVerifier.isValidName( input ) ) {
        // If the input is not valid, throw an IllegalArgumentException back to
        // the client.
        throw new IllegalArgumentException( "Name must be at least 4 characters long" );
    }

    String serverInfo = rpcController.getServletContext().getServerInfo();
    String userAgent = rpcController.getThreadLocalHttpRequest().getHeader( "User-Agent" );

    // Escape data from the client to avoid cross-site script vulnerabilities.
    input = escapeHtml( input );
    userAgent = escapeHtml( userAgent );

    return "Hello, " + input + "!

I am running " + serverInfo + ".

It looks like you are using:
" + userAgent;
}
.....
.....


texts: Check if two strings are one 'edit' apart using Python

texts:
The code below is my solution in python 3 to exercise 1.5 in Cracking the Coding Interview.  I would appreciate feedback on both the algorithm (improvements to space and time complexity) and/or coding style.  I think the time and space complexity of the code below is \$O(n^{2})\$ and \$O(n)\$ respectively.

The exercise statement is as follows:

  Given 2 Strings write a function to check if they are 1 edit away.  There are three type of edits

  1) Insert a character

  2) Remove a character

  3) Replace a character

I wrote the code in Python 3.5 and confirmed that it passed a small unit test.  For this problem I am particularly interested in feedback on where in my code (if at all) I should include more comments.

import unittest

def is_one_away(first: str, other: str) -> bool:
    """Given two strings, check if they are one edit away. An edit can be any one of the following.
    1) Inserting a character
    2) Removing a character
    3) Replacing a character"""
    if len(first) < len(other):
        first, other = other, first

    if len(first) - len(other) > 1:
        return False

    elif len(first) - len(other) == 1:
        for pos in range(len(first)):
            if first[:pos] + first[pos+1:] == other:
                return True
        return False

    else:
        num_different_chars = sum(1 for pos in range(len(first)) if first[pos] != other[pos])
        return num_different_chars < 2

class MyTest(unittest.TestCase):
    def test_is_one_away(self):
        self.assertEqual(is_one_away('pale', 'ale'), True)
        self.assertEqual(is_one_away('pales', 'pale'), True)
        self.assertEqual(is_one_away('pale', 'bale'), True)
        self.assertEqual(is_one_away('pale', 'bake'), False)
        self.assertEqual(is_one_away('ale', 'pale'), True)
        self.assertEqual(is_one_away('aale', 'ale'), True)
        self.assertEqual(is_one_away('aael', 'ale'), False)
        self.assertEqual(is_one_away('motherinlaw', 'womanhitler'), False)
        self.assertEqual(is_one_away('motherinlaw','motherinlow'), True)


texts:
This is a continuation of the last thread.

I wanted to add a thread-safety and I was considering AwaitableCriticalSection and Task+Mutex.  I ended up with mutex; it can be a bit slower but it would allow different files to be stored independently.

public static async Task<T> ReadJson<T>(String fileName)
{
    if (String.IsNullOrEmpty(fileName)) return default(T);

    return await TaskEx.Run(() =>
    {
        using (var myMutex = new Mutex(false, String.Format("{0}@{1}", AppUid, fileName)))
        {
            try
            {
                myMutex.WaitOne();
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Open, store))
                using (var sr = new StreamReader(stream))
                using (var jr = new JsonTextReader(sr))
                    return IsoStorageEx.jsonSerializer.Deserialize<T>(jr);
            }
            finally
            {
                myMutex.ReleaseMutex();
            }
        }
    });
}

public static async Task<bool> WriteJson<T>(String fileName, T content)
{
    if (String.IsNullOrEmpty(fileName))
        return false;

    return await TaskEx.Run(() =>
        {
            using (var myMutex = new Mutex(false, String.Format("{0}@{1}", AppUid, fileName)))
            {
                try
                {
                    myMutex.WaitOne();
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        store.CreateFolderIfNecessary(fileName);
                        using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, store))
                        using (var sw = new StreamWriter(stream))
                        using (var jw = new JsonTextWriter(sw))
                            IsoStorageEx.jsonSerializer.Serialize(jw, content);
                    }
                }
                finally
                {
                    myMutex.ReleaseMutex();
                }

                return true;
            }
        });
}

Where AppUid is just a random string, so mutexes of different apps would not collide.

Sample can be downloaded here.

Any suggestions?


texts:
The rules are unsurprisingly:

  Write a program that prints the numbers from 0 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”."

#include <stdio.h>

int main(void) {
    int i, j;
    i = j = 0;

    for (; i < 100 ; ++i, j = 0, putchar('\n')) {
        j += printf("%s", i % 3 ? "" : "Fizz");
        j += printf("%s", i % 5 ? "" : "Buzz");
        if (!j) printf("%d", i);
    }

    return 0;
}

If you were a job interviewer, would you be ok with an answer like this? Or would you ask for another solution that is not (ab)using the semantics of for and the return value of printf in order to do fewer operations?


texts: Converting embedded JSON into flat table

texts:
I am new Python user, who decided to use Python to create simple application that allows for converting json files into flat table and saving the output in cvs format. I was wondering if you could give me some advice how I could improve my code to make it work in more efficient way. I am asking since if I convert relatively small files everything works just fine but when I try to convert ~200 MB file it starts to take a while. I am afraid that when I begin to work with bigger files it might take quite some time to convert my datasets.

Here is my code, which I created with help of this great blog post about flattening json objects :

import sys, os, json, tkFileDialog, tkMessageBox
from Tkinter import *
from pandas.io.json import json_normalize

def openFile():
    currdir = os.getcwd()
    filename = tkFileDialog.askopenfilename(
        initialdir = currdir,
        title='Please select a file',
        filetypes=[('JSON file','.json')])

    return filename

def loading_file(path):
    #File path
    file_path = path

    #Loading json file
    json_data = open(file_path)
    data = json.load(json_data)
    return data

#Function that recursively extracts values out of the object into a flattened dictionary
def flatten_json(data):
    flat = [] #list of flat dictionaries
    def flatten(y):
        out = {}

        def flatten2(x, name=''):
            if type(x) is dict:
                for a in x:
                    if a == "name":
                            flatten2(x["value"], name + x[a] + '_')
                    else:
                        flatten2(x[a], name + a + '_')
            elif type(x) is list:
                for a in x:
                    flatten2(a, name + '_')
            else:
                out[name[:-1]] = x

        flatten2(y)
        return out

#Loop needed to flatten multiple objects
    for i in range(len(data)):
        flat.append(flatten(data[i]).copy())

    return json_normalize(flat)

#Outputing normalized data into csv
def csv_out(data, path):
    #creating csv file name
    name = '~/Desktop/' + os.path.basename(os.path.splitext(path)[0]) + '.csv'
    #converting to the csv
    data.to_csv(name, encoding='utf-8') #'~/Desktop/out.csv'

def done():
   tkMessageBox.showinfo('json2csv',"DONE!")

def main():
    filepath = openFile()
    data_file = loading_file(filepath)
    table = flatten_json(data_file)
    csv_out(table, filepath)
    done()

### Application Interface ###
tk = Tk()

#Creating window:
tk.geometry('250x150+600+300')
tk.title('JSON2CSV')

#Creating convert button
convertbutton = Button(tk, text = 'Convert to .csv', command = main)
convertbutton.place(x = 25, y = 50)

tk.mainloop()

Here you will find short example of the json structure I work with:

[{
 "_id": {
   "id": "123"
 },
 "device": {
   "browser": "Safari",
   "category": "d",
   "os": "Mac"
 },
 "exID": {
   "$oid": "123"
 },
 "extreme": false,
 "geo": {
   "city": "London",
   "country": "United Kingdom",
   "countryCode": "UK",
   "ip": "00.000.000.0"
 },
 "viewed": {
   "$date": "2011-02-12"
 },
 "attributes": [{
   "name": "gender",
   "numeric": 0,
   "value": 0
 }, {
   "name": "email",
   "value": false
 }],
 "change": [{
   "id": {
     "$id": "1231"
   },
   "seen": [{
     "$date": "2011-02-12"
   }]
 }]
}, {
 "_id": {
   "id": "456"
 },
 "device": {
   "browser": "Chrome 47",
   "category": "d",
   "os": "Windows"
 },
 "exID": {
   "$oid": "345"
 },
 "extreme": false,
 "geo": {
   "city": "Berlin",
   "country": "Germany",
   "countryCode": "DE",
   "ip": "00.000.000.0"
 },
 "viewed": {
   "$date": "2011-05-12"
 },
 "attributes": [{
   "name": "gender",
   "numeric": 1,
   "value": 1
 }, {
   "name": "email",
   "value": true
 }],
 "change": [{
   "id": {
     "$id": "1231"
   },
   "seen": [{
     "$date": "2011-02-12"
   }]
 }]
}]


texts: Login script that checks two users and their corresponding passwords

texts:
Please let me know what you think. Is the code well written?  Am I using best practices (like when I chose === over ==)?  Is my script too verbose?

Note: I'm only asking because the tutorial I'm using is a little old.

/* A login script to that checks two users and their
corresponding passwords and then greets one of them
*/
var input = '',
  guess = '',
  montyPswrd = 'Cheese',
  montyUser = 'Monty',
  chipUser = 'Chip',
  chipPswrd = 'Gadget';

var isMonty = function (name) {
    if (name === montyUser) {
        document.write('
Welcome to the site ' + montyUser + '
');
    } else {
        alert('Your not monty');
    }
};

var isChip = function (name) {
    if (name === chipUser) {
        document.write('
Welcome to the site ' + chipUser + '
');
    } else {
        alert('Your not chip');
    }
};

input = prompt('Enter Username:', 'username');

switch (input) {
    case montyUser:
        guess = prompt('Enter Password','password');
        break;
    case chipUser:
        guess = prompt('Enter Password','password');
    case null:
        break;
    default:
        alert('wrong useranme!');
        break;
}

paswrdCheck:
if (guess === '') {
    // then the user hit ESC or cancel
    // no point in asking for password
    break paswrdCheck;
} else {
    switch (guess) {
    case montyPswrd:
        isMonty(input); // makes sure monty is matched with right password
        break;
    case chipPswrd:
        isChip(input); // makes sure chip is matched with right password
        break;
    case null:
        break;
    default:
        alert('wrong password!');
        break;
    }
}


texts: Python implementation of stack to return minimum in O(1) time

texts:
I have written a stack in Python that is required to push, pop and return the minimum of the stack in \$O(1)\$ time.

#!python3
class Stack():
    def __init__(self):
        self.items = []
        self.min = None

    def push(self, item):
        self.items.append(item)
        self.minimum()

    def pop(self):
        if self.isEmpty():
            raise ValueError('Empty stack')
        else:
            return self.items.pop()

    def minimum(self):
        if self.min is None:
            self.min = self.peek()
        else:
            if self.peek() < self.min:
                self.min = self.peek()

    def getMinimum(self):
        return self.min

    def peek(self):
        try:
            return self.items[-1]
        except IndexError as e:
            print(e)

    def size(self):
        return len(self.items)

    def isEmpty(self):
        return self.size() == 0

stack = Stack()

nums = [6,4,8,9,1,5,2,3]
for i in nums:
    stack.push(i)

print(stack.getMinimum())

What I have tried to do is, compare the current minimum with each new addition to the stack so that the

self.min

attribute constantly updates.

Eventually, to get the minimum, I simply call the

self.getMinimum()

function to return the minimum. My question is, does this actually occur in \$O(1)\$ time?


texts:
I am a JavaScript programmer beginning with Go.  I tried to replicate filter and map functions like JavaScript's, as an exercise.
Here is what I came up with.
The filter function:
func Filter(slice interface{}, cb func(i interface{}) bool) []interface{}{
sliceValues := reflect.ValueOf(slice)
newSlice := []interface{}{}
for i := 0; i < sliceValues.Len(); i++{
    v := sliceValues.Index(i).Interface()
    passed := cb(v)
    if passed{
        newSlice = append(newSlice, v)
    }
}
return newSlice
}

Usage:
a := []int {1,2,3}

result := Filter(a,func(i interface{}) bool{
    v,_:= i.(int)
    return v > 1
})

fmt.Println(result) // [2 3]

The map function:
func Map(slice interface{}, cb func(i interface{}) interface{}) []interface{}{
sliceValues := reflect.ValueOf(slice)
newSlice := []interface{}{}
for i := 0; i < sliceValues.Len(); i++{
    v := sliceValues.Index(i).Interface()
    modifiedValue := cb(v)
    newSlice = append(newSlice, modifiedValue)
}
return newSlice

}
Usage:
a := []int {1,2,3}

result := Map(a,func(i interface{}) interface{}{
    v,_:= i.(int)
    return v + 1
})

fmt.Println(result) // [2 3 4]


texts:
I've got an object $contest which is a Symfony entity that has some other entities assigned. I can get them by $content->getEntries();. That will return an object with the lazyloaded db objects. I need to display them in a random order.

$tempEntries = $contest->getEntries();
$entries = array();
if (count($tempEntries)) {
    foreach ($tempEntries as $temp) {
        $entries[] = $temp;
    }
    shuffle($entries);
}

This is the code I use currently. I loop through all elements (if there are any) and then shuffle them. I feel like the looping through them is a wast of resources.

Any advice on how to improve this?


texts: Removing duplicate audio files with different UTC timestamps in filenames, using PowerShell 5

texts:
I have a drive with many thousands of sound effects.  The files have been stored on different operating systems and NAS devices over time and there are now duplicates of many files, but the filenames contain different UTC timestamps.  For example:

1-14 Crowded Bowling Alley (2016_06_28 02_14_41 UTC).aif

1-14 Crowded Bowling Alley (2016_02_18 05_56_59 UTC).aif

I would like to remove the duplicate files.  There are also junk files left over from audio software and operating system indexing that I would like to remove. Using a copied subset of the data I have tested the following PowerShell script under PS version 5.1, it appears to give me what I'm after:

# Remove files left over from audio editors
Get-ChildItem -Name -Recurse -Filter "*.clip*" | Remove-Item
Get-ChildItem -Name -Recurse -Filter "*.ptf" | Remove-Item
Get-ChildItem -Name -Recurse -Filter "*.wfm" | Remove-Item
Get-ChildItem -Name -Recurse -Filter "*.repeaks" | Remove-Item

# Remove old indexing files
Get-ChildItem -Name -Recurse -Filter "*.DS_STORE" | Remove-Item
Get-ChildItem -Name -Recurse -Filter "._.*" | Remove-Item
Get-ChildItem -Name -Recurse -Filter "Thumbs*.db" | Remove-Item
Get-ChildItem -Name -Recurse -Filter "*.ini" | Remove-Item

# Remove UTC stamp from all files (will fail on duplicates)
Get-ChildItem -Recurse -Filter "*(?????????? ???????? UTC).*" | Rename-Item -newname { $_.basename.substring(0,$_.basename.length-26) + $_.Extension }

# Remove files that still have the UTC stamp (they were the duplicates)
Get-ChildItem -Name -Recurse -Filter "*(?????????? ???????? UTC).*" | Remove-Item

However, I would love to get a critique of the script and learn a few things.  In particular it seems a little hacky to use an expected failed command as part of the workflow.  It also seemed wise to get notes before I run it on the entire set of files.


texts: Populate a list with combinations of one- and two- object functions

texts:
I have a nested set of for loops which achieves the desired outcome, but I don't know if it is the most efficient / pythonic way of populating this list.

I would like all combinations of the one object functions, combined with 0 to n combinations of the two object function.

Here, I have abstracted parts of the code away so we are only dealing with the loops:

import itertools as it

# Define arbitrary functions that act on two objects and single objects
def two_obj_fn(a, b):
    return 'two_obj_fn({}, {})'.format(a , b)

def A(a):
    return 'A({})'.format(a)

def B(b):
    return 'B({})'.format(b)

def C(c):
    return 'C({})'.format(c)

a = 'a'
b = 'b'

objects = [a, b]

n = len(objects)

two_obj_fns_coupled = set(two_obj_fn(first, second) for first, second in
                          it.zip_longest(objects, objects[1:], fillvalue=objects[0]))

single_obj_fns = {A, B, C}
single_fns_combinations = it.combinations_with_replacement(single_obj_fns, n)

double_fns_combinations = set()
for i in range(len(two_obj_fns_coupled) + 1):
    double_fns_combinations.update(it.combinations(two_obj_fns_coupled, i))

out = []
for combo in single_fns_combinations:
    if not combo.count(A) % 2 == 0:
         if not combo.count(C) == n:
             for permutation in it.permutations(combo):
                 for double_fns in double_fns_combinations :
                     single_fns_string = [fn(objects[i])for i, fn in
                                          enumerate(permutation)]

                     single_fns_string.extend(double_fns)
                     out.append(tuple(single_fns_string))

out = tuple(out)

I know that this blows up with the addition of more objects, but for the two objects a and b this gives the desired result of (linebreaks added for clarity):

(
('A(a)', 'B(b)', 'two_obj_fn(b, a)'),
('A(a)', 'B(b)'),
('A(a)', 'B(b)', 'two_obj_fn(a, b)'),
('A(a)', 'B(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)'),
('B(a)', 'A(b)', 'two_obj_fn(b, a)'),
('B(a)', 'A(b)'),
('B(a)', 'A(b)', 'two_obj_fn(a, b)'),
('B(a)', 'A(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)'),
('A(a)', 'C(b)', 'two_obj_fn(b, a)'),
('A(a)', 'C(b)'),
('A(a)', 'C(b)', 'two_obj_fn(a, b)'),
('A(a)', 'C(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)'),
('C(a)', 'A(b)', 'two_obj_fn(b, a)'),
('C(a)', 'A(b)'),
('C(a)', 'A(b)', 'two_obj_fn(a, b)'),
('C(a)', 'A(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)')
)

I would really appreciate some guidance on this, as I know it could get slow very quickly. Everything above and including n = len(objects) is just setting up the abstract implementation.


texts:
There are two aspects to this question that are inter-related.

Change I've made to the trie module in python (PyPI, GitHub) to make it serialisable (and deserialisable).

The change I made is visible on GitHub. I added two functions to the Node class used in serialisation.

def __getstate__(self):
    return (self.parent, self.key, self.nodes, self.value)

def __setstate__(self, state):
    (self.parent, self.key, self.nodes, self.value) = state
    if type(self.value) == object:
        self.value = Node.no_value

The Node class uses an instance of object to signify that there is no value for that Node. If you serialise and deserialise a Trie of Nodes then the values are set to different instances of object, this is why I added a check for the type being object and replacing it with Node.no_value.

Is this a reasonable way of doing things? Is anyone likely to want to store an actual instance of object?

Is there a better way of signifying that a Node has no value, that is more robust to serialisation?


texts: Any better way to solve Project Euler Problem #5?

texts:
Here's my attempt at Project Euler Problem #5, which is looking quite clumsy when seen the first time. Is there any better way to solve this? Or any built-in library that already does some part of the problem?

'''
    Problem 5:
    2520 is the smallest number that can be divided by each of the numbers from 1 to 10

    What is the smallest number, that is evenly divisible by each of the numbers from
    1 to 20?
'''

from collections import defaultdict

def smallest_number_divisible(start, end):
    '''
        Function that calculates LCM of all the numbers from start to end
        It breaks each number into it's prime factorization,
        simultaneously keeping track of highest power of each prime number
    '''
    # Dictionary to store highest power of each prime number.
    prime_power = defaultdict(int)

    for num in xrange(start, end + 1):
        # Prime number generator to generate all primes till num
        prime_gen = (each_num for each_num in range(2, num + 1) if is_prime(each_num))

        # Iterate over all the prime numbers
        for prime in prime_gen:
            # initially quotient should be 0 for this prime numbers
            # Will be increased, if the num is divisible by the current prime
            quotient = 0

            # Iterate until num is still divisible by current prime
            while num % prime == 0:
                num = num / prime
                quotient += 1

            # If quotient of this priime in dictionary is less than new quotient,
            # update dictionary with new quotient
            if prime_power[prime] < quotient:
                prime_power[prime] = quotient

    # Time to get product of each prime raised to corresponding power
    product = 1

    # Get each prime number with power
    for prime, power in prime_power.iteritems():
        product *= prime ** power

    return product

def is_prime(num):
    '''
        Function that takes a `number` and checks whether it's prime or not
        Returns False if not prime
        Returns True if prime
    '''
    for i in xrange(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

if __name__ == '__main__':
    print smallest_number_divisible(1, 20)

    import timeit
    t = timeit.timeit

    print t('smallest_number_divisible(1, 20)',
             setup = 'from __main__ import smallest_number_divisible',
             number = 100)

While I timed the code, and it came out with a somewhat ok result. The output came out to be:

0.0295362259729  # average 0.03

Any inputs?


texts: Allocating matrices for in-place modification

texts:
This code seems to be working. I am allocating matrices on the stack and passing them to functions to modify in place. Is this a standard practice, or am I doing it wrong?

Header:

#ifndef _MATRIX_H
#define _MATRIX_H

typedef enum {MT_OK, MT_INVAL} MT_RESULT;

typedef float mat4[4][4];
typedef float vec4[4];

MT_RESULT mat4multvec4(vec4 target, mat4 m, vec4 v);
MT_RESULT zero4(mat4 target);
MT_RESULT id4(mat4 target);
MT_RESULT translate(mat4 target, float x, float y, float z);
MT_RESULT scale(mat4 target, float x, float y, float z);
MT_RESULT perspective(mat4 target, float fov, float aspectratio, float nearclip, float farclip);

#endif

Implementation:

#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* memcpy */
#include <math.h>

#include "matrix.h"

#undef PI
#define PI 3.14159265

/*
Multiply 4x4 matrix with 1x4 vector
returns MT_OK
*/
MT_RESULT mat4multvec4(vec4 target, mat4 m, vec4 v)
{
    int i, j, sum;

    for(i = 0; i < 4; i++) {
        sum = 0;
        for(j=0; j<4; j++) {
            sum = sum + m[i][j] * v[j];
        }
        target[i] = sum;
    }

    return MT_OK;
}

/*
make a 4x4 zeros matrix
returns MT_OK
*/
MT_RESULT zero4(mat4 target)
{
    memset(target, 0, sizeof(float) * 16);
    return MT_OK;
}

/*
make a 4x4 identity matrix
returns MT_OK
*/
MT_RESULT id4(mat4 target)
{
    int i;
    zero4(target);

    for(i = 0; i < 4; i++)
                target[i][i] = 1;

    return MT_OK;
}

/*
Create 4x4 translation matrix for opengl
return MT_OK
*/
MT_RESULT translate(mat4 target, float x, float y, float z)
{
    id4(target);

    target[0][3] = x;
    target[1][3] = y;
    target[2][3] = z;

    return MT_OK;
}

/*
Create 4x4 scale matrix for opengl
return MT_OK
*/
MT_RESULT scale(mat4 target, float x, float y, float z)
{
    zero4(target);

    target[0][0] = x;
    target[1][1] = y;
    target[2][2] = z;
    target[3][3] = 1;

    return MT_OK;
}

/*
mat4 perspective(float fov, float aspectratio, float nearclip, float farclip)
{
    mat4 m = new_mat4();
    float frustumdepth = farclip - nearclip;
    float inversefrustumdepth = 1 / frustumdepth;

    m[]
}*/

void main(void)
{
    int i;
    mat4 myMatrix;
    vec4 myVector = {10.0f, 10.0f, 10.0f, 1.0f};
    vec4 myTVector;

    translate(myMatrix, 10.0f, 0.0f, 0.0f);

    mat4multvec4(myTVector, myMatrix, myVector);

    printf("Original Vector\n");
    for(i=0;i<4;i++) {
        printf(" %f", myVector[i]);
    }

    printf("\nTransformed Vector\n");
    for(i=0;i<4;i++) {
        printf(" %f", myTVector[i]);
    }
}


texts: Hands of Straights (LeetCode) Arrange the card

texts:
Tried this leetcode question Hands of Straights. https://leetcode.com/problems/hand-of-straights/
Description is
Alice has a hand of cards, given as an array of integers.

Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.

Return true if and only if she can.

Example 1.
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].

Example 2
Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.

My attempt to solve it using Haskell is here. Can someone review it. The code returns the correct values for most of the test cases that I have tried.

import Data.List

{-
solve 3 [1,1,2,2,2,3,3,3,4]
True

solve 3 [1,1,2,2,2,3,3,3]
False

solve 4 [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]
True
-}

solve::Int -> [Int] -> Bool
solve v xss = helper v $ group $ sort xss

helper::Int ->[[Int]] -> Bool
helper v [] = True
helper v xss = let (a, b) = splitAt v xss
    in case verify a  && ((length a) `mod` v == 0)  of
        True -> helper v $ (removeHead a []) ++ b
        False -> False

verify::[[Int]] -> Bool
verify [] = True
verify (x:[]) = True
verify (x:y:zx)
    | head y == succ (head x) = verify $ y:zx
    | otherwise = False

removeHead::[[Int]] -> [[Int]]-> [[Int]]
removeHead [] acc = acc
removeHead (x:xss) acc = case null (tail x) of
    True -> removeHead xss acc
    False -> removeHead xss (acc ++ [tail x])


texts:
Is this the optimal method to check for collisions in a 2d-based game?  I put together a working demo of 2D collisions here (WSAD to move, orange blocks collide).

I currently use the following code to check for collisions:

function checkmove(x, y) {
  if(level[Math.floor(x/20)][Math.floor(y/20)] == 1 || level[Math.ceil(x/20)][Math.floor(y/20)] == 1 || level[Math.floor(x/20)][Math.ceil(y/20)] == 1 || level[Math.ceil(x/20)][Math.ceil(y/20)] == 1) {
    return false;
  } else {
    return true;
  }
}

Update function:

function update(key) {
  switch(key) {
    case "W":
      if(checkmove(pos.x, pos.y-2)) {
        pos.y -= 2;
        break;
      } else {
        break;
      }
    case "S":
      if(checkmove(pos.x, pos.y+2)) {
      pos.y += 2;
        break;
      } else {
        break;
      }
    case "A":
      if(checkmove(pos.x-2, pos.y)) {
      pos.x -= 2;
      break;
      } else {
        break;
      }
    case "D":
      if(checkmove(pos.x+2, pos.y)) {
      pos.x += 2;
       break;
      } else {
        break;
      }
    default:
      break;
  }
}

This is called before movement is applied the the 'player'.  The game is laid out as a 2D array of 1's and 0's for testing purposes.

Can I use fewer mathematical operations (less expensive for each tick) to check for a collision between the player and a '1' on my game grid?


texts:
It's been a while since I last wrote some lolcode, so I felt like tackling Project Euler #1.

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

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

This is the code/script I wrote to solve this:

HAI 1.2
    VISIBLE "HAI, PROJEK LOLLER ONE!!"

    I HAS A LIMIT ITZ 1000
    I HAS A TOTAL ITZ 0
    I HAS A CHEEZ ITZ 3
    I HAS A BURGER ITZ 5
    I HAS A CHEEZBURGER ITZ PRODUKT OF CHEEZ AN BURGER

    HOW IZ I ADDTOTAL YR VALUE
        I HAS A RESULT ITZ SUM OF VALUE AN TOTAL
        FOUND YR RESULT
    IF U SAY SO

    IM IN YR MIND UPPIN YR NUMBER TIL BOTH SAEM NUMBER AN LIMIT

        I HAS A PICKLE ITZ FAIL

        BOTH SAEM 0 AN MOD OF NUMBER AN CHEEZBURGER
        O RLY?, YA RLY
            PICKLE R WIN
        NO WAI
            BOTH SAEM 0 AN MOD OF NUMBER AN CHEEZ
            O RLY?, YA RLY
                PICKLE R WIN
            NO WAI
                BOTH SAEM 0 AN MOD OF NUMBER AN BURGER
                O RLY?, YA RLY
                    PICKLE R WIN
                OIC
            OIC
        OIC

        BOTH SAEM PICKLE AN WIN
        O RLY?, YA RLY
            TOTAL R I IZ ADDTOTAL YR NUMBER MKAY
        OIC

    IM OUTTA YR MIND

    VISIBLE SMOOSH "TEH ANSWER IZ " AN TOTAL MKAY
    VISIBLE "DOWN WITH PROJEK LOLLER ONE!"

KTHXBYE

This code can be executed on CodingGround, and produces this output:

  HAI, PROJEK LOLLER ONE!!

(spoiler)

      TEH ANSWER IZ 233168

  DOWN WITH PROJEK LOLLER!

Is the fizzbuzz-like logic appropriate, or I fell in the "easy" trap? Would there be a way to collapse all the conditions into one and make a shorter script? Or is this algorithm a bad/inefficient one?


texts:
I am generating a random numerical 6-10 digit password. I need some important reviews of yours.  Is it OK or are there some needed modifications?

val AB = "0123456789669900"
val rnd = new Random()

def randomNumericalString(): String = {
    val len = rnd.nextInt(5) + 5
    val sb = new StringBuilder(len)
    for (i <- 0 to len)
      sb.append(AB.charAt(rnd.nextInt(AB.length())))
    return sb.toString
  }


texts: Fast nth prime in Python using trial division

texts:
I'm trying to speed this code up for larger values of N. Any suggestions?
I'd like to stick to this implementation and not move on to something more complex like numpy or sieves.
Is there any low hanging performance I'm missing?

import time

start = time.clock()
def prime(num, divs):
    prev = 1
    if divs:
        for x in divs:
            if num % x == 0:
                return False
            if num/x < prev:
                break
            prev = x
    return True

i = 0
j = 2
k = []

while i  != 50000:
    if prime(j, k) == True:
        k.append(j)
        i += 1
        #if i % 50000 == 0:
        #   print (i)
    j += 1

print ("Done", j)
print ("Time", time.clock()-start)

time.sleep(50)


texts: Pseudoportable C script pattern - follow-up

texts:
See the initial/previous iteration.

I have rewritten the script following the answer of @200_success.

Now it looks like this:

#! /bin/bash

# Create a temporary file name for the executable file:
TMP_PROGRAM_FILE="$(mktemp programXXXXXX)"

# Compile the embedded C program:
gcc -o "$TMP_PROGRAM_FILE" -x c - <<- END_OF_SOURCE
#include <stdio.h>

int main(int argc, char* argv[])
{
    int i;

    puts("Hello, world! I am a pseudoportable C program.");
    for (i = 1; i < argc; ++i)
    {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return argc - 1;
}
END_OF_SOURCE

# Run the program delegating all the arguments:
./$TMP_PROGRAM_FILE $@

# Save the exit status of the C program:
EXIT_STATUS=$(echo $?)

# Remove the executable file:
trap "rm $TMP_PROGRAM_FILE" EXIT

# Exit returning the exit status of the C program:
exit $EXIT_STATUS

Any critique much appreciated.


texts: Joining url path components intelligently

texts:
I'm a little frustrated with the state of url parsing in python, although I sympathize with the challenges. Today I just needed a tool to join path parts and normalize slashes without accidentally losing other parts of the URL, so I wrote this:

from urlparse import urlsplit, urlunsplit

def url_path_join(*parts):
    """Join and normalize url path parts with a slash."""
    schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))
    # Use the first value for everything but path. Join the path on '/'
    scheme   = next((x for x in schemes if x), '')
    netloc   = next((x for x in netlocs if x), '')
    path     = '/'.join(x.strip('/') for x in paths if x)
    query    = next((x for x in queries if x), '')
    fragment = next((x for x in fragments if x), '')
    return urlunsplit((scheme, netloc, path, query, fragment))

As you can see, it's not very DRY, but it does do what I need, which is this:

>>> url_path_join('https://example.org/fizz', 'buzz')
'https://example.org/fizz/buzz'

Another example:

>>> parts=['https://', 'http://www.example.org', '?fuzz=buzz']
>>> '/'.join([x.strip('/') for x in parts]) # Not sufficient
'https:/http://www.example.org/?fuzz=buzz'
>>> url_path_join(*parts)
'https://www.example.org?fuzz=buzz'

Can you recommend an approach that is readable without being even more repetitive and verbose?


texts: Dplyr friendly function for computing moving average

texts:
Background
The function computes moving arrange and offers some other minor widgets like possibility to return data frame in original order or automatically derive variable name for the moving average. In majority of actual use cases similar results could be easily achieved using combinations of usual suspects like across, mutate and so on. However, I was interested in an implementation that:

Is fairly generic and easily applicable to multiple data sets
Makes use of fairy standard dplyr verbs for easier usage in sparklyr, especially when working on old Spark backends that do not support apply. The function proved convoluted so I feel that I've failed in that goal, but that's a side point.

Sought feedback

Better approach to generating multiple lag calls. Through string manipulation I arrive at lag(var, n)... and then do:
dplyr::mutate(data_sorted,"{{val}}_mavg" := !!rlang::parse_expr(lag_call))

This feels naff and I would be grateful for suggestions on improvement.

Is there an elegant way of forcing evaluation on the left hand side of :=. Currently I'm doing:
if (res_val != "{{val}}_mavg") {
     data_avg <- dplyr::rename(res_val = "{{val}}_mavg")
}

This works but one-liner like evaluating res_val and then doing potentially necessary magic with curly-curly would be nice.

Any other observations

Function
#' Add Moving Average for an Arbitrary Number of Intervals
#'
#' The functions adds moving average for an arbitrary number of intervals. The
#'   data can be returned sorted or according to the original order.
#'
#' @details The function can be used independently or within dplyr pipeline.
#'
#' @param .data A tibble or data frame.
#' @param sort_cols Columns used for sorting passed in a manner consistent with
#'   \code{\link[dplyr]{arrange}}
#' @param val Column used to calculate moving average passed as bare column
#'   name or a character string.
#' @param res_val Resulting moving average, defaults to name of \code{val}
#'   suffixed with \code{_mavg}.
#' @param restore_order A logical, defaults to \code{FALSE} if \code{TRUE} it
#'   will restore original data order.
#'
#' @return A tibble with appended moving average.
#' @export
#'
#' @examples
#' add_moving_average(mtcars, sort_cols = c("mpg", "cyl"), val = hp, intervals = 2)
add_moving_average <-
    function(.data,
             sort_cols,
             val,
             intervals = 2,
             res_val = "{{val}}_mavg",
             restore_order = FALSE) {

        unique_id_name <- tail(make.unique(c(colnames(.data), "ID")), 1)
        data_w_index <- dplyr::mutate(.data, {{unique_id_name}} := dplyr::row_number())

        index_col_name <- tail(names(data_w_index), 1)

        # Create desired number of calls to get moving average calculation
        lag_calls <- paste0("lag(",  rlang::as_string(rlang::ensym(val)), ", ", 1:intervals, ")")
        lag_call <- paste(lag_calls, collapse = " + ")
        lag_call <- paste0("(", lag_call, ") / ", intervals)

        data_sorted <- dplyr::arrange(data_w_index, dplyr::across(sort_cols))

        data_avg <- dplyr::mutate(data_sorted,"{{val}}_mavg" := !!rlang::parse_expr(lag_call))

        if (res_val != "{{val}}_mavg") {
            data_avg <- dplyr::rename(data_avg, res_val = "{{val}}_mavg")
        }

        if (restore_order) {
            data_avg <- dplyr::arrange(data_avg, !!rlang::sym(index_col_name))
        }

        data_avg <- dplyr::select(data_avg, -dplyr::last_col(1))
        data_avg
    }

Tests
add_moving_average(.data = mtcars, sort_cols = c("am", "gear"), val = disp, intervals = 3)
add_moving_average(.data = mtcars, sort_cols = c("am", "gear"), val = disp, intervals = 3)
add_moving_average(.data = mtcars, sort_cols = c("am", "gear"), val = disp, intervals = 3,
                   restore_order = TRUE)


texts: Generate a nested structure based on a list of file paths

texts:
I'm currently working on a small application, as a learning exercise for a Javascript novice. I need to generate an object based on a folder structure. Here is an example of the folder structure:

  RootFolder/FolderA/FolderB/FileA

  RootFolder/FolderA/FolderB/FileB

  RootFolder/FolderA/FolderB/FolderC/FileA

  RootFolder/FolderA/FolderB/FolderC/FileB

The desired resulting object should have the following structure:

{
    RootFolder: {
        FolderA: {
            FolderB: {
                FileA: {},
                FileB: {},
                FolderC: {
                    FileA: {},
                    FileB: {}
                }
            }
        }
    }
};

So far I came up with the following code and it seems to be doing the job, but I'm concerned with 'eval' use and generally believe there is a more elegant way of doing it.

module.exports = {
  structure: function(structureArray) {
    var generatedObject = {};
    for (var i = 0; i < structureArray.length; i++) {
      var objectElements = '';
      var path = (structureArray[i].split('/')).filter(Boolean);
      for (var l = 0; l < path.length; l++) {
        if (objectElements.indexOf(path[l]) == -1 || path[l].length == 1) {
          objectElements += '["' + path[l] + '"]';
        }
        if (!(eval('generatedObject' + objectElements))) {
          eval('generatedObject' + objectElements + '= {}')
        }
      }
    }
    return generatedObject;
  }
};

structureArray contains full path strings as in the folder structure example above (e.g. 'RootFolder/FolderA/FolderB/FileA')


texts:
I am new at programming and I'm really confused about how should I do this, because at first I thought I should ask user which path to export. However I have been told that I should check if it exists the directory and if doesn't I should create it. How can I even create a directory path or ask user if it can be created? Sorry if my question is too odd but I'm very confused about this, I was convinced that simply asking was enough to export data.

static void exportData(string[,] matrix)
{

    var dir = "";
    do
    {
        Console.Clear();
        Console.Write("Insert path to export txt: ");
        dir = Console.ReadLine();
    } while (String.IsNullOrEmpty(dir));

    var path = Path.Combine(dir, "export.txt");

    using (StreamWriter sw = File.CreateText(path))
    {

        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1) - 1; j++)
            {

                {
                    sw.Write($"\t{matrix[i, j]}\t");
                }

            }
            Console.WriteLine("\n");
        }

    }


texts: Regular Expression for parsing PHP annotations containing multiple lines and markup

texts:
I am writing a regular expression for parsing PHP annotations in a flexible way.
I'd like to accomplish all the goals listed above with one single expression. So I would appreciate any suggestions about the quality of it (in terms of corner cases, performance, best practices and correctness).

PCRE expression:

/[\*\s]*@(?P<name>\w+[\\\w]*?)(?:\s|\()
(?P<value>
  (?:[\/\w\s\"\<\>\_\#\=\-\.\'\{\}:;,\*\(\)\[\]]*[^\R\*\s\/\)])
)?
(?:\s | $|\))/gsxmu

Goals of the regular expression:

List all annotations with their values
Values can be multi-lined and have markup (html, json or markdown)
The initial space + * of each line should be removed from the value
Many annotations can be in the same line
Annotation names can be namespaced

Sample PHPDoc string:

/**
 * Description
 *
 * @Tag name name @annotation beee @aaf dsfsd fgdg
 * @Tag name name {"json":"dfsf"}
 * @Tag asdasd <html> #markdown ==markdown== __markdown__
 * - markdown
 * > mark 1
.mark
"string"
'string'
 * @Annotation()
 * @Tag name name @annotation beee @aaf dsfsd fgdg <markdown> #markdown ==markdown==
 * @a() @b("name") @c()
 * @Annotation\Name("var1()", "var2") @n("name()_name")
 * @Annotation(["var1", "var2"], "var3")
 * @Annotation\Filter\Name(["var1", "var2"], "var3", {"var4": "var5"})
 * @Annotation(
 *    ["GET", "POST"]
   ) @Name({"name": "Tomas"})
 * @Tag name name
 */

Expected result:

<?php

array(
  [
      'name' => 'Tag',
      'value' => 'name name'
  ],
  [
      'name' => 'annotation',
      'value' => 'bee'
  ],
  [
      'name' => 'aaf',
      'value' => 'dsfsd fgdg'
  ]
  // ... and so on... (see live example)
);

A live demo can be found here.


texts: Filtering lines in a log file using multiple regexes

texts:
In python2.7:
2 for loops are always a little inefficient, especially in python. Is there a better way to write the following filter function?
It tags a line from a log file, if it is useful. Otherwise the line will be ignored. Because there are different possible interesting lines, it tries different compiled regexes for each line, until it finds one. Note that no more regexes are checked for a line, after the first one successfully matched.

def filter_lines(instream, filters):
    """ignore lines that aren't needed

    :param instream: an input stream like sys.stdin
    :param filters: a list of compiled regexes
    :yield: a tupel (line, regex)
    """
    for line in instream:
        for regex in filters:
            if regex.match(line):
                yield (line,regex)
                break

(The "tagging" is done with the regex object itself, because it can be used later on for retrieving substrings of a line, like filename and row number in an occuring error)


texts: processing webhook request coming from a 3rd party application

texts:
I need some help to evaluate whether I am doing it right. The scenario is, a 3rd party application is sending a webhook request after a successful payment but the problem is that sometimes this application may send the same notification more than once. So it is recommended to ensure that implementation of the webhook is idempotent. So steps that I am implementing for this are if signature is correct (assume it is correct), find orders record in the database using orderId in the request params. Please note: orderId in request params is payment_gateway_order_identifier in orders table. If txStatus is 'SUCCESS' AND haven't already processed COLLECTION payment for this same order, create payments record. 201 response with nothing in the response body. Otherwise, 201 response with nothing in the response body. Otherwise, 422 response with {message: "Signature is incorrect"} in response body.
views.py
        @api_view(['POST'])
        def cashfree_request(request):
            if request.method == 'POST':
                data=request.POST.dict()
                payment_gateway_order_identifier= data['orderId']
                amount = data['orderAmount']
                transaction_status = data['txStatus']
                signature = data['signature']
                if(computedsignature==signature): #assume it to be true
                    order=Orders.objects.get(
                             payment_gateway_order_identifier=payment_gateway_order_identifier)
                    if transaction_status=='SUCCESS':
                        try:
                            payment= Payments.objects.get(orders=order)
                            return Response({"Payment":"Done"},status=status.HTTP_200_OK)
                        except (Payments.DoesNotExist):
                            payment = Payments(orders=order,amount=amount,datetime=datetime)
                            payment.save()
                            return Response(status=status.HTTP_200_OK)
                else:
                    return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)

models.py
    class Orders(models.Model):
        id= models.AutoField(primary_key=True)
        amount = models.DecimalField(max_digits=19, decimal_places=4)
        payment_gateway_order_identifier = models.UUIDField(
                                         primary_key=False,default=uuid.uuid4,editable=False,unique=True)

    class Payments(models.Model):
        id = models.AutoField(primary_key=True)
        orders = models.ForeignKey(Orders, on_delete=models.CASCADE)
        amount = models.DecimalField(max_digits=19, decimal_places=4, verbose_name='Price in INR')
        datetime = models.DateTimeField(auto_now=False,auto_now_add=False)


texts: Fill a collection from a database with all values filled

texts:
I have some data in a database, organized like (time, category, value), and basically, I want to show it in a histogram. But the library I use to draw historgrams only works properly if every value is filled.

For instance, this does not work:

bin category value
1   A        5
2   B        3

But this is ok:

bin category value
1   A        5
2   A        0
1   B        0
2   B        3

So I have to insert zeros for every time/category combination that are not in the database. I came up with the following code:

List<Info> allCategories = GetAllCategories(cnn); //select distinct ...
var data = new List<Info>();
using (var cmd = cnn.CreateCommand())
{
    cmd.CommandText = sqlSelect;
    while (blah blah)
    {
        [setting command parameters]

        //prepare a copy of reference values
        var valuesToAdd = new List<Info>(allCategories.Count);
        foreach (var x in allCategories)
            valuesToAdd.Add(x.Clone());
        int bin = [get bin]
        foreach (var info in valuesToAdd)
            info.Bin = bin;

        using (var reader = cmd.ExecuteReader())
        while (reader.Read())
        {
            int category = reader.GetInt32(1);
            Info info = valuesToAdd.Find(i => i.category == category); //get the the object to modify
            info.value = reader.GetInt64(2);
        }
        data.AddRange(valuesToAdd);
    }
}
return data;

So, basically I make a copy of the list of possible combination for each bin of the graph, and then I update the values found in the database.

I'm not really fond of this solution, partly because it involves a .Clone, and I'm looking for a more elegant solution...


texts:
I have written a script that allows a user to walk around a dungeon pick up gold and once they have picked it all up they can exit the game through an exit.

What I am doing now is writing a bot to do the same. So far I have come up with a 'stupid' bot that is based mainly on randomness. The bot has has actions to the following functions;

look() - Can see around the ASCII map in a radius of 2. The function prints it out so the bot cant actually store it in memory(I am allowed to store it memory).

move <direction>() - move in the direction these include N E S W.

pickUp() - If the bot is standing on gold this picks it up.

exitGame() - If the bot is standing on an exit, has all the gold and this command is ran he will exit the game.

Here is my bot code so far.

import java.io.IOException;
import java.util.Random;

public class Bot{
    public GameLogic bot;

    public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
        GameLogic bot = new GameLogic("map2.txt");
        bot.startGame();
        int gold = bot.gold();
        System.out.println(gold);
        int turn = 0;
        char[][] myWorld = bot.getMap();
        while(true){
            int posX = bot.getPosX();
            int posY = bot.getPosY();
            Random rn = new Random();
            int min = 0;
            int max = 3;
            int n = max - min + 1;
            int i = rn.nextInt(n);
            if(myWorld[posX][posY] == 'G'){
                bot.pickUp();
            }
            if(myWorld[posX][posY] == 'E'){
                boolean y = bot.exitGame();
                if(y){break;}
            }
            turn++;
            if(i == 0){
                bot.moveN();
            }else if(i == 1){
                bot.moveE();
            }else if(i == 2){
                bot.moveS();
            }else if(i == 3){
                bot.moveW();

            }else{
                System.out.println("SOMETHING WENT WRONG!!!");
            }

        }
        System.out.println(turn);

    }
}

What I am asking is what would be a better way to do this. How can I improve my bot so it takes less turns to complete? How can I make my bot 'smarter'?


texts:
I've just started learning assembly yesterday, and the first useful thing I've written is a clearmem function.

I'm looking for general feedback regarding my coding of this function, whether there any flaws with it other than the obvious one of a user passing a value <= 0 to the size argument, or an invalid pointer to the ptr argument (should I really even check for that in practical use)?

I also observed an odd behavior that I still don't quite understand, so if you can explain that, then that would be much appreciated as well.

Intel x64 Assembly - on Linux

clearmem:                         ; void clearmem( void* ptr, long size )
    mov rcx, rsi                  ; copy rsi/size to rcx (aka the counter register)
    next:                         ; for( long i = size; i > 0; i-- )
        mov byte [rdi+rcx-1], 0   ;    *(reinterpret_cast<char*>(ptr+i-1)) = 0;
    loop next                     ; dec rcx; cmp rcx, 0; jg next
    ret                           ; return

Intel x64 Assembly - on Windows

clearmem proc
    xchg rcx, rdx                 ; swap arg1 and arg2... windows uses rcx for arg1, and rdx for arg2
    next:
        mov byte ptr[rdx+rcx-1], 0
    loop next
    ret
clearmem endp

Example usage in C++

#include <iostream>
// ...
extern "C" void clearmem( void* ptr, long size );
// ...
int main( int argc, char* argv[] )
{

    int z[] = {1,2,3,4,5,6,7,8,9,10};
    int zlen = sizeof(z) / sizeof(int);

    std::cout << "z[] before clearmem() = ";
    print_array<int>(z, zlen);

    clearmem(&z, sizeof(z));
    std::cout << "z[] after clearmem() = ";
    print_array<int>(z, zlen);

    return 0;
}

Output of C++ program

z[] before clearmem() = 1,2,3,4,5,6,7,8,9,10
z[] after clearmem() = 0,0,0,0,0,0,0,0,0,0

Odd Behavior

If I change all of the registers and variables to their 4 byte equivalent (e.g. rcx -> ecx, long -> int) then it still works fine in Windows, but on Linux it will segfault. I used GDB to set a break point on mov byte[rdi+rcx-1], 0 and used info registers to see the values in the registers and they were extrmely high. For instance rdi was 0x00007FFFFFFFE6E0 at the time, and considering I only have 16 GB of RAM, I would have expected a value less than 0x0000000400000000.

What's going on here? Why does this work on Windows, but not on Linux? Note: Obviously, I know I shouldn't do this, but I like breaking things...


texts:
This is not very memory-efficient. Can you please suggest a better way or improvement?

public class Test{

    public static void main(String[] args) {
        System.out.println(replaceSpace("All men must die"));
    }

    public static String replaceSpace(String s) {
        String[] stringArray = s.split(" ");
        StringBuffer sb = new StringBuffer();
        for(String s3 : stringArray) {
            sb.append(s3);
            sb.append("%20");
        }
        // if the last character is not space then, don't append %20.
        if(s.charAt(s.length()-1) != ' ') {
            return sb.substring(0, sb.length()-3).toString();
        }

        return sb.toString();
    }
}


texts: cache with least accessed items eviction

texts:
I wrote this code, in order to implement a cache decorator which handles least accessed eviction.
The role of this decorator is to memoize decorated functions calls with args and kwargs and return the previously computed value if still in cache.
Warning, this handles only serializable args and kwargs, for the sake of simplicity.
Please review it and tell me if this makes sense.
The code:
import json
import hashlib
from collections import OrderedDict

class EvictionCache(OrderedDict):

    def __init__(self, *args, **kwargs):
        max_size = kwargs.pop('max_size', None)
        super(EvictionCache, self).__init__(*args, **kwargs)
        self._max_size = max_size

    @property
    def full(self):
        return len(self) >= self._max_size

    def set(self, hash, value):
        if self.full:
            self.evict()
        super(EvictionCache, self).__setitem__(hash, value)

    def get(self, hash):
        value = super(EvictionCache, self).pop(hash, None)
        if value:
            super(EvictionCache, self).__setitem__(hash, value)
        return value

    def evict(self):
        print 'evicting oldest cached item'
        super(EvictionCache, self).popitem(last=False)

def cache(max_size=None):

    def make_md5(args, kwargs):
        data = dict(args=args, kwargs=kwargs)
        md5 = hashlib.md5(json.dumps(data, sort_keys=True)).hexdigest()
        return md5

    def wrapper(f):
        # make this cache belong to the decorated function to prevent the cache
        # to be shared between different decorated functions
        f._cache = EvictionCache(max_size=max_size)

        def inner(*args, **kwargs):
            md5 = make_md5(args, kwargs)
            res = f._cache.get(md5)
            if res:
                print 'from cache'
                return res

            res = f(*args, **kwargs)
            print 'to cache'
            f._cache.set(md5, res)

            return res

        return inner
    return wrapper

@cache(max_size=2)
def func(x):
    return x * 2

if __name__ == '__main__':

    print func(1)
    print func(2)
    print func(2)
    print func(1)
    print func(2)
    print func(3)
    print func(4)
    print func(5)

output
to cache
2
to cache
4
from cache
4
from cache
2
from cache
4
to cache
evicting oldest cached item
6
to cache
evicting oldest cached item
8
to cache
evicting oldest cached item
10


texts: Create JSON file from WordPress ACF options

texts:
I am using a WordPress multisite network and want to pull information from options pages in Advanced Custom Fields to create a json file. I currently have this code running whenever an options field is updated on a subsite. The json file lives on the main site.

The code works and runs successfully, however, it takes forever and often results in 502 errors due to running out of time. This is solved by refreshing the page and attempting to update the options value again.

How can I optimize my code and make it run faster or more efficiently?

functions.php

require_once( 'httpful.phar' );

function create_locations_json( $post_id ) {
    // check if acf field updated is on options page
    if ($post_id == 'options' || $post_id == 0) {
        $stageurl = array();
        $posts = array();
        $args = array(
            'public'     => true,
            'limit'      => 500
        );

        // get all public sites in multisite network
        $sites = wp_get_sites($args);
        foreach ($sites as $site) {
            // loop through sites and pull stage variable from options
            switch_to_blog($site['blog_id']);
            $stage = get_field('stage', 'option');
            if (isset($stage)) {
                $stageurl[] = $site['domain'];
            }
            restore_current_blog();
        }

        // loop through sites to generate json content
        foreach ($stageurl as $i => $stages) {
            $mainurl = parse_url(network_site_url());

            // check if http (local) or https (production)
            if($mainurl['scheme'] == 'https'){
                $url = "https://" . $stageurl[$i] . "/wp-json/acf/v2/options";
            } else {
                $url = $stageurl[$i] . "/wp-json/acf/v2/options";
            }

            // send api url to Httpful to get acf json
            $response = \Httpful\Request::get($url)->send();

            // get fields from acf json
            $name = "{$response->body->acf->small_location_name}";
            $sitestatus = "{$response->body->acf->stage}";
            $city = "{$response->body->acf->city}";
            $state = "{$response->body->acf->state}";
            $email = "{$response->body->acf->email}";

            // get lat and lng from google maps api
            $mapsurl = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($city) . ",+" . $state . "&key=KEYHERE";
            $mapsresponse = \Httpful\Request::get($mapsurl)->send();
            $lat = "{$mapsresponse->body->results[0]->geometry->location->lat}";
            $lng = "{$mapsresponse->body->results[0]->geometry->location->lng}";

            // create different json responses based on stage
            if ($sitestatus > 1) {
                $address = "{$response->body->acf->address_1}";
                $address2 = "{$response->body->acf->address_2}";
                $postal = "{$response->body->acf->zip}";

                $posts[] = array('id' => $i, 'name' => $name, 'site_status' => $sitestatus, 'address' => $address, 'address_2' => $address2, 'city' => $city, 'state' => $state, 'postal' => $postal, 'lat' => $lat, 'lng' => $lng, 'email' => $email, 'web' => $stageurl[$i]);
            }
            else {
                $posts[] = array('id' => $i, 'name' => $name, 'site_status' => $sitestatus, 'city' => $city, 'state' => $state, 'lat' => $lat, 'lng' => $lng, 'email' => $email, 'web' => $stageurl[$i]);
            }
        }

        // overwrite whole json file with new array
        file_put_contents(plugin_dir_path( __FILE__ ) . '../library/json/locations.json', json_encode($posts));
    }
    else {
        return $post_id;
    }

    return $post_id;
}

// run when acf field is updated
add_action('acf/save_post', 'create_locations_json', 20);


texts:
Interview Q:  Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example: Given the array [-2,1,-3,4,-1,2,1,-5,4],  the contiguous subarray [4,-1,2,1] has the largest sum = 6.

For this problem, return the maximum sum.

My solution (pseudocode and code) is below.  Works, but can someone tell me

Is there a faster algo?
Is the code structure done for an interview?

Pseudocode

//maxTillNow=A[0]
//maxStart=0
//maxLength=1
//Set currIndex =0
//Loop till currIndex == arrayLength
//  Set offset,sum=0
//      If A(currIndex] is -ve, then the only thing you need to do is check if it is > maxTillNow (in case all elements are -ve). If yes, set maxTillNow to A[currIndex] and move on

//      if +ve
//          Look at sums of elements starting at A[currIndex] ... A[currIndex+offset] for offsets in range 0 to currIndex+offset<length
//            if any sum > maxTillNow, store
//            Also find index of first -ve element you encounter as you look at elements A[currIndex+1]... -->firstNegIndex
//            nextElement to look at it firstNegIndex+1

Full code

int maxSubArray(const int* A, int n1) {
    int currIndex=0;
    int maxSumTillNow=A[0] ;
    int maxSumStart=0 ;
    int maxSumLength=1 ;
    int currLength;
    int sum ;
    int firstNeg ;

    while(currIndex<=n1-1)
    {
        if(A[currIndex]<0)
        {
            if(A[currIndex]>maxSumTillNow)
                maxSumTillNow=A[currIndex] ;
            currIndex++ ;
            continue ;
        }
        sum=0 ;
        firstNeg=-1 ;
        for(currLength=0;currLength+currIndex<=n1-1;currLength++)
        {
            sum+=A[currIndex+currLength] ;
            if(sum>maxSumTillNow)
            {
                maxSumTillNow=sum ;
                maxSumStart=currIndex ;
                maxSumLength=currLength+1 ;
            }
            if(firstNeg==-1 && A[currIndex+currLength]<0)
            {
                firstNeg=currIndex+currLength ;
            }
        }
        if(firstNeg==-1)
        {
            break ;
        }
        currIndex=firstNeg+1 ;
    }
    return maxSumTillNow ;

   }

I can also get additional info on exact sequence leading to max sum as below

    //    printf("Max sum is = %d, starting at index %d and length =%d\n",maxSumTillNow,maxSumStart,maxSumLength) ;
    //    printf("Max sub Array is [") ;
    //    for(currIndex=maxSumStart;currIndex<=maxSumStart+maxSumLength-1;currIndex++)
    //    {
    //        printf("%d,",A[currIndex]) ;
    //    }
    //    printf("]\n") ;

      }


texts: Writing a class to hold Arduino Properties for an Arduino I2C Debugger

texts:
I have this class which mostly holds a bunch of properties and their setters. I also have wrappers for some functions of another module. Here is the class:

class ARCArduino(object):
    """
    Class to manage Arduino functionality
    """

    def __init__(self, tree_item, port, identifier):
        self.__i2c = ArduinoI2C()
        self.__i2c.setPort(port)
        self.__i2c.connectPort()
        self.__id = None
        self.__i2c_version = None
        self.__switch_version = None
        self.__tree_item = tree_item
        self.__address_list = []
        self.__port = port
        self.__identifier = identifier

    @property
    def id(self):
        if self.__id is None:
            try:
                self.__id = self.__i2c.getID()
            except IOError:
                self.__id = "NO CONNECTION"
        return self.__id

    @property
    def i2c_version(self):
        if self.__i2c_version is None:
            try:
                self.__i2c_version = self.__i2c.i2cVersion()
            except IOError:
                self.__i2c_version = "NO CONNECTION"
        return self.__i2c_version

    @property
    def switch_version(self):
        if self.__switch_version is None:
            try:
                self.__switch_version = self.__i2c.switchVersion()
            except IOError:
                self.__switch_version = "NO CONNECTION"
        return self.__switch_version

    @property
    def tree_item(self):
        return self.__tree_item

    @tree_item.setter
    def tree_item(self, item):
        if type(item) is not wx.TreeItemId:
            return
        self.__tree_item = item

    @property
    def address_list(self):
        return self.__address_list

    @address_list.setter
    def address_list(self, addr_list):
        if type(addr_list) is not list:
            return
        self.__address_list = addr_list

    @property
    def port(self):
        return self.__port

    @port.setter
    def port(self, port):
        if port[:3] != "COM":
            return
        self.__port = port

    @property
    def identifier(self):
        return self.__identifier

    @identifier.setter
    def identifier(self, letter):
        if type(letter) is not str:
            return
        if letter[-1] != ':':
            letter += ':'
        self.__identifier = letter

    def serialCommand(self, command):
        """
        Wrapper for ArduinoI2C serialCommand function
        """
        return self.__i2c.serialCommand(command)

    def close(self):
        self.__i2c.close()

    def connectPort(self):
        self.__i2c.connectPort()

This implementation feels a little dumb to me. Is there a more elegant way to implement something like this?

Here is some further clarification on the functionality of the class:

self.__i2c is an instance of an Arduino I2C communication module that was internally developed at my company. It allows users to send commands to I2C devices over the Arduino's I2C bus. setPort and connectPort are setting and connect a COM port for the specific Arduino.

self.__id is a serial number generated for the Arduino from a company-MySQL database. It is set elsewhere in the program.

self.__switch_version and self.__i2c_version are two floats stored on the Arduino that are the version number of some software running on the Arduino.

self.__tree_item is a wx.TreeItemId (I believe it's stored as just an int) that is the id of the wx.TreeItem stored in a wx.TreeCtrl elsewhere in the program.

self.__address_list is a list of ints which are the I2C addresses of devices discovered on the Arduino's I2C bus.

self.__port is a string which holds the COM port the Arduino is inserted in.

self.__identifier is a letter which identifies the Arduino elsewhere in the program. The program expects the user has multiple Arduinos concurrently being used, so a letter is a quick shorthand to easily identify them.


texts: Find all pairs in an array whose absolute difference equals x

texts:
I have an array A of integers with n values and an integer x. I need to find all the pairs in that array whose absolute difference is equal to x.

For example, take A = {13, 1,-8, 21, 0, 9,-54, 17, 31, 81,-46} and x = 8, my algorithm should print this:

0 & 3 with values 13 & 21
1 & 5 with values 1 & 9
2 & 4 with values -8 & 0
5 & 7 with values 9 & 17
6 & 10 with values -54 & -46

I worked out a solution, however, it is \$O(n^2)\$:

for (int i = 0 ; i < A.length; i ++)
    {
        for (int j = i; j < A.length; j++)
        {
          if (abs(A[i]-A[j]) == x)
             System.out.println("Indices " + i + " & " + j + " with values " + A[i] + " & "+ A[j]);
        }
    }

Without sorting first, is there any way to optimize this code to be faster? I know \$O(n^2)\$ isn't great but I can't think of a better way of doing it (without sorting first).
For my algorithm, the best case Omega is also \$Ω(n^2)\$, correct? I need to compare every value in any case.