texts: Constructing a simple tree with ASCII in F#

texts:
This is just a basic HackerRank challenge I was working on to better understand F#. Its purpose is just to print a tree that has a straight 'trunk' of \$n\$, splits into 2 branches which diverge to \$n\$, then branches grow a straight trunk to \$\frac{n}{2}\$ which split and diverge to \$\frac{n}{2}\$, etc.

(Note: I was told to avoid using variables if possible, so the only one I used was to store the iterations which are meant to be \$n \le 5\$.)

[<EntryPoint>]
let main argv =

    let iterations = System.Convert.ToInt32(System.Console.ReadLine())

    //63 rows
    //100 cols
    //16 length

    let splitRoots = fun x -> Array.collect (fun elem -> [|elem-1;elem+1|]) x

    let isEven = fun i -> if i % 2 = 0 then true else false

    let advanceBranch = fun x -> Array.mapi (fun i elem -> if isEven i then elem-1 else elem+1) x

    let treeLine = fun oneLocs w ->
        String.concat "" (Seq.map (fun x -> if Array.exists (fun elem -> elem = x) oneLocs then "1" else "_") w)

    //if trunk and counter > 0  -->  write more trunk
    //if trunk and counter = 0 --> split and transition to branch
    //if branch and counter > 0 --> write more branch
    //if branch and counter = 0 --> transition to trunk and deecrement max
    let rec tree = fun l w h max original counter branch roots acc ->
        match branch with
        | _ when max = 0 ->
            acc
        | false when counter > 0 ->
            tree l w h max original (counter-1) false roots (acc @ [ treeLine roots (seq { 1 .. w }) ])
        | false when counter = 0 ->
            tree l w h max original (original-1) true (splitRoots roots) acc
        | true when counter > 0 ->
            tree l w h max original (counter-1) true (advanceBranch roots) (acc @ [ treeLine roots (seq { 1 .. w })])
        | true when counter = 0 ->
            tree l w h (max-1) (original/2) (original/2) false roots (acc @ [ treeLine roots (seq { 1 .. w }) ])

    let emptyRow = String.concat "" (Seq.map (fun x -> "_") (seq{ 1..100}))

    let makeEmptyRowList n = [1..n] |> List.map (fun x -> emptyRow)

    let fillList notFilled = (fun x -> x @ (makeEmptyRowList (63-x.Length))) notFilled

    (tree 16 100 64 iterations 16 16 false [| 50 |] (List.empty))
        |> fillList
        |> List.rev
        |> List.iter (fun (x:string) -> System.Console.WriteLine(x))

    0 // return an integer exit code


texts:
I have implemented a simple strcmp() in asm64. I'm very new to assembly so it must be awful ! I would like to know what errors were made.

    global  mstrc
mstrc:
        mov     r15b, [rsi]
        cmp     [rdi], r15b;compare two characters
        jne stop;if they are different, return
        cmp     byte [rdi], 0
        je      stop;else if end of string 1, return
        cmp     byte [rsi], 0
        je      stop;else if end of string 2, return
        ;increment both string adresses then loop
        add     rdi, 1;
        add     rsi, 1;
        jmp     mstrc;
stop:
;setup return value (s1[i] - s2[i]) then return
            mov     rax, [rdi]
            sub     rax, [rsi]
            ret


texts: A simple C WinAPI program for terminating processes via process image names - follow-up

texts:
(See the previous (i.e. first) version of this tool.)
(See the next follow-up.)
After taking into consideration all the advice by Martin R, I ended up with the following tool for terminating all the processes with given process image names:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <TlHelp32.h>

int main(int argc, char* argv[]) {
    if (argc != 2) {
        fprintf(stderr, "processkiller.exe PROCESS_NAME");
        return EXIT_FAILURE;
    }

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (snapshot == INVALID_HANDLE_VALUE) {
        fputs("Error: could not get the process snapshot.", stderr);
        return EXIT_FAILURE;
    }

    size_t totalProcessesMatched = 0;
    size_t totalProcessesTerminated = 0;

    if (Process32First(snapshot, &entry)) {
        do {
            if (strcmp(entry.szExeFile, argv[1]) == 0) {
                totalProcessesMatched++;

                HANDLE hProcess = OpenProcess(PROCESS_TERMINATE,
                                              FALSE,
                                              entry.th32ProcessID);

                if (hProcess == NULL) {
                    fprintf(stderr,
                            "Error: could not open the process with ID = %d, "
                            "called \"%s\".\n",
                            entry.th32ProcessID,
                            entry.szExeFile);
                } else {
                    BOOL terminated = TerminateProcess(hProcess, 0);

                    if (terminated) {
                        totalProcessesTerminated++;

                        BOOL closed = CloseHandle(hProcess);

                        if (!closed) {
                            fprintf(stderr,
                                    "Warning: could not close a handle "
                                    "for process ID = %d, called \"%s\".\n",
                                    entry.th32ProcessID,
                                    entry.szExeFile);
                        }

                        printf("Terminated process ID %d\n", entry.th32ProcessID);
                    }
                }
            }
        } while (Process32Next(snapshot, &entry));
    }

    BOOL snapshotHandleClosed = CloseHandle(snapshot);

    if (!snapshotHandleClosed) {
        fputs("Warning: could not close the process snapshot.", stderr);
    }

    printf("Info: total matching processes: %d, total terminated: %d.\n",
           totalProcessesMatched,
           totalProcessesTerminated);

    return EXIT_SUCCESS;
}

Critique request
Am I going anywhere? Is this tool coded properly? Am I sufficiently verbose about statistics/error information?


texts: Avoid duplicate conditional checks in multiple boolean conditions

texts:
I have a method that returns either true or false based on a value contained by a java.util.List.

List<Long>list=new ArrayList<Long>(){{
    add(1L);
    add(2L);
    add(3L);
}};

public boolean checkId(Long id)
{
    return list.contains(id);
}

Based on the return value of this method and several other conditions a test is required to be performed.

boolean isIdChanged=true;
boolean isAjaxRequest=true;

Long id=1L;
Test test = new Test();

if(id!=null && id>0 && test.checkId(id) && isIdChanged || id!=null && id>0 && test.checkId(id) && !isAjaxRequest)
{
    //... do something
}

Assuming isIdChanged, isAjaxRequest and id have dynamic values.

In the if test, it can be noticed that the conditional expression id!=null && id>0 && test.checkId(id) is combined (repeated) on both side of the short-circuit || operator.

Is there a precise way to avoid this duplicate check?

One way to assign the result of this test to a boolean variable first like so,

boolean check=id!=null && id>0 && test.checkId(id);

and then the conditional test in the if statement can be trimmed like,

if(check && isIdChanged || check && !isAjaxRequest)
{
    //... do something
}

But I doubt it is still not sufficient. There should be a more precise way to achieve this.

Based on the comment below, the actual code is as follows (it is related to the JSF component library, Primefaces).

@Override
public List<StateTable> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters)
{
    int rowCount = stateService.rowCount().intValue();

    if(rowCount<=currentPage(first, pageSize)*pageSize-pageSize)
    {
        first-=pageSize;
    }

    if(id!=null&&id>0&&stateService.checkId(id)&&(isIdChanged||!FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()))
    {
        int currentRow=(int) (stateService.getCurrentRow(id)-1);  // Returns the current row number from the database.
        final DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form:dataTable");
        first=currentRow-(currentRow%pageSize);
        dataTable.setFirst(first); //Sets the starting index of the page holding the row based on the id supplied as a query-string.
        isIdChanged=false;
    }

    setRowCount(rowCount);
    return stateService.getList(first, pageSize, sortOrder, sortField);
}

In this method test has been replaced by stateService. The method is intended to fetch data from a database in a page-wise manner.

The first two parameters as their names imply, indicate the starting index where the rows are to be retrieved and the number of rows in a page - the page size respectively. The rest may be unrelated to the question.

The first line inside the method returns the number of rows in a given table.

The immediate conditional check evaluates to true only during the deletion of rows held by a table structure (Primefaces DataTable) on the client-side. When a user deletes rows on the last page, the previous page is opened automatically as soon as he/she deletes all of the rows in the last page.

Afterwards the statements inside an if block are meant to highlight a row. When an id is supplied as a GET request parameter, the page containing that row should be opened automatically and the row corresponding to the id (supplied as a query-string) is highlighted by a different background colour of that row on the client-end.

Something similar happens, when you click this link pointing to a question on StackOverflow which automatically opens up the fifth page containing the answer this link is pointing to.

And finally, the number of rows are set by calling a super class method setRowCount() and the List is returned from the database.


texts: K&R Exercise 1-6 & 1-7: working with EOF

texts:
I'm working through K&R at the moment and I've found my first exercise that seems to be a good use for my first CodeReview post.

Exercise 1-6 - Verify that the expression getchar() != EOF is 0 or 1.

Exercise 1-7 - Write a program to print the value of EOF.

I've completed both of these together in the same file.

I think I've understood the question here, but let me know if I haven't. I wanted to post here before looking up any sort of "official" answer so that I could learn some stuff instead of just "going to the back of the book".

#include <stdio.h>

void main()
{
        int c;

        c = getchar();
        while ((c = getchar()) != EOF == (0 | 1)) {
                putchar(c);
        }
        printf("%d\n", EOF);
}

Compiled with:

gcc putchar.c -o putchar

Sending EOF using:

<ctrl-d>

Runs through fine, and when I ctrl-d I get a -1 return code.


texts: Pull out text within specific divs on a webpage

texts:
I am looking for some guidance and feedback on my first golang program. The language is very new to me and its been a long while since I have written anything close to C.

Below is a simple program that takes a url and looks for divs within the page containing a specific class. Once found I read the text within the div outputting it to the terminal.

I am looking for general feedback especially on my use of pointers and slices, the way I am getting the text out of the div (in a loop with a bool variable) which seems a bit hacky to me

package main

import (
    "fmt"
    "net/http"
    "sort"

    "golang.org/x/net/html"
)

// Helper function to identify if the token is an image div
func isImageDiv(token html.Token) (ok bool) {
    // Iterate over all of the Token's attributes until we find "class"
    for _, a := range token.Attr {
        if a.Key == "class" {
            // The image labels are surrounded by div with the class "project-title"
            if a.Val == "project-title" {
                ok = true
                return
            }
        }
    }

    // "bare" return will return the variables (ok) as defined in
    // the function definition
    return
}

func getLabel(z *html.Tokenizer) (label string) {
    return string(z.Text())
}

func crawl(url string, foundLabels *[]string) {
    resp, err := http.Get(url)

    if err != nil {
        fmt.Println("ERROR: Failed to crawl \"" + url + "\"")
        return
    }

    b := resp.Body
    defer b.Close() // close Body when the function returns

    z := html.NewTokenizer(b)

    readText := false
    for {
        tt := z.Next()

        switch {
        case tt == html.ErrorToken:
            // End of the document, we're done
            return
        case tt == html.StartTagToken:
            t := z.Token()

            // Check if the token is an <div> tag
            isDiv := t.Data == "div"
            if !isDiv {
                continue
            }

            // Verify that is has the class we are looking for, if there is one
            ok := isImageDiv(t)
            if !ok {
                continue
            }
            readText = true
        case tt == html.TextToken && readText == true:
            *foundLabels = append(*foundLabels, getLabel(z))
            readText = false
        }
    }
}

func main() {

    url := ""

    foundLabels := make([]string, 0)

    crawl(url, &foundLabels)

    sort.Strings(foundLabels)

    for _, element := range foundLabels {
        // element is the element from someSlice for where we are
        fmt.Println(element)
    }
}


texts: Get index of value in ObservableCollection

texts:
I have an ObservableCollection<MyType> ItemList, and I need to know the index of a specific MyType in the collection.  However, when I hard-code the values like this:

ItemList.IndexOf(new MyType(val1, val2, val3));

it can't find the value because it is a different instance of MyType, even if all the values are the same.

So, I wrote this simple method:

private int IndexOfValInItemList(MenuItem val)
{
    for (int i = 0; i < ItemList.Count; i++)
    {
        if (ItemList[i].Title == val.Title && ItemList[i].Page == val.Page && ItemList[i].Menu == val.Menu) { return i; }
    }

    return -1;
}

This is in the same class as the value and directly accesses the value.  I know that I could expand it to take any ObservableCollection<MyType>, but I haven't because ItemList cannot be passed by reference:

private ObservableCollection<MenuItem> _itemList = new ObservableCollection<MenuItem>();
public ObservableCollection<MenuItem> ItemList
{
    get { return _itemList; }
    set
    {
        if (_itemList == value) return;
        _itemList = value;
        OnPropertyChanged();
    }
}

Is this a good way to implement this, or is there are different way?  Is there a way I could call ItemList.IndexOf(MyType(...)) and override the equality operator used to check it?  I already tried overriding the == operator, and that did not work.

I will have a second ObservableCollection<MyType> soon as I finish implementing my ViewModel, so I would like to know a generic solution, but if I have to write a second method to get the value from that collection, that is OK too.


texts: Sanitizing and validating a user signup form before submission

texts:
The first part of the code (above the in-code comment in the middle) looks messy.

I know I could use variables to make it cleaner, I just don't exactly know yet how can I effectively apply those when dealing with jQuery objects. So I'd appreciate a review on that.

As for the if-statements, I think they're okay but if they could be improved I'm all open for it.

Any other suggestions are always welcome.

$(function() {
    // magic number
    var MAX_FIRST_NAME_LENGTH = 35;

    // Hide additional input messages by default except errors.
    $("#signup .addition:not(.error)").css("display", "inline-block").parent().hide();

    // Select (focus) first input and show it's additional (erroneous) message.
    if ($("#signup .error").length === 0) {
        $("#signup input[name=firstName]").select();
        $("#signup input[name=firstName]").siblings("#signup div").show();
    } else if ($("#signup .error").first().parent("#signup div").siblings($("#signup input[name=firstName]")).val().length >= 1) {
        if ($("#signup input[name=firstName]").val().length > MAX_FIRST_NAME_LENGTH) {
            $("#signup input[name=firstName]").select();
        } else {
            $("#signup input[name=lastName]").select();
        }
    } else {
        $("#signup .error").first().parent("#signup div").siblings($("#signup input")).select();
    }

    // Toggle slide on the additional message focus / blur of corresponding input.
    $("#signup input").on("focus blur", function(e) {
        if (!$(this).siblings("#signup div").children("#signup .addition").hasClass("error")) {
            $(this).siblings("#signup div").stop()[e.type === "focus" ? "slideDown" : "slideUp"]("fast");
        }
    });

/// I think the code below is good as is.

    var $form = $("#signup");

    $form.on("submit", function() {
        var emptyInputs = 0;

        $form.find("input").each(function() {
            var $this = $(this),
                val   = $this.val();

            if ($this.prop("type") !== "password") {
                val = $.trim(val);
            }

            // Focus (select) first empty field if any.
            if (val === "" && !emptyInputs++) {
                $this.select();
            }
        });

        if (emptyInputs === 0) {
            var $button = $("#signup button");

            $button.prop("disabled", true);

            return true;
        }

       return false;
    });
});


texts: C++ regex_replace with arbitrary function

texts:
This is a version of C++17 regex_replace that handles arbitrary functions to do the replacement, instead of using regex_replace's weird minigame language ($&, $', and $`). Also, I made it take string_view instead of const string&; that's more to see if people have opinions on string_view than for any practical reason. :) (The standard C++17 regex library is not aware of the existence of string_view.)

template<class F>
std::string regex_replace(std::string_view haystack,
                          const std::regex& rx, const F& f)
{
    std::string result;
    const char *begin = haystack.data();
    const char *end = begin + haystack.size();
    std::cmatch m, lastm;
    if (!std::regex_search(begin, end, m, rx)) {
        return std::string(haystack);
    }
    do {
        lastm = m;
        result.append(m.prefix());
        result.append(f(m));
        begin = m[0].second;
        begin += (begin != end && m[0].length() == 0);
        if (begin == end) break;
    } while (std::regex_search(begin, end, m, rx,
        std::regex_constants::match_prev_avail));
    result.append(lastm.suffix());
    return result;
}

void test()
{
    auto s = "std::sort(std::begin(v), std::end(v))";
    auto t = regex_replace(s, std::regex("\\bstd::(\\w+)"),
        [](auto&& m) { return m[1]; });
    assert(t == "sort(begin(v), end(v))");

    auto u = regex_replace(s, std::regex("\\bstd::(\\w+)"),
        [](auto&& m) { return "my::" + m.str(1); });
    assert(u == "my::sort(my::begin(v), my::end(v))");

    auto v = regex_replace(s, std::regex("\\bstd::(\\w+)"),
        [](auto&& m) {
            std::string result;
            std::transform(m[1].first, m[1].second, back_inserter(result), ::toupper);
            return result;
        });
    assert(v == "SORT(BEGIN(v), END(v))");
}

Any bugs in regex_replace? Any way to shorten it up? Any way to reuse the standard regex_iterator or regex_token_iterator would be greatly appreciated.


texts: Using one function to go from one element to another

texts:
After I made a change to the html structure for a project, I found myself having to change many jquery selectors in many places.  To avoid this problem in the future I decided to make a simple function where I pass an element indicating where I am and a string indicating where I want to go.  This function should apply whatever logic is necessary to access the given endpoint.  I showed this code to someone and he didn't like it, he said I should use multiple functions or an object.  I thought that would make the code too much longer for little to no benefit, but I'm not really sure.  The code below is for this tool, which is a tree-based time-tracking app, so for example, "node" refers to a node in the tree.  The logic is not exhaustive as I only add code to the function on an as-needed basis.

// Access one particular element from another.
function from(start, end) {
  start = $(start)
  if(start.parent().hasClass('headline')) {
    var node = start.parent().parent()
    if(end == 'node')  return node
    else if(end == 'model')  return get_model(node.attr('model_id'))
  }
  if(end == 'headline')  return start.children('.headline')
  if(end == 'child_list')  return start.children('ol')
  if(end == 'each_child')  return start.find('> ol > .model')
  if(end == 'parent')  return start.parents('.model')
  if(end.indexOf('.') != 0)  end = '.' + end
  if(start.hasClass('headline'))  return $(start.children(end))
  return start.find('> .headline > ' + end)
}


texts:
I have two classes responsible for attributes validation:

class NameValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    message = options.fetch(:message, I18n.t('errors.attributes.name.invalid'))
    record.errors[attribute] << message unless NameValidator.valid_name?(value)
  end

  def self.valid_name?(name)
    name =~ /\A[a-z][\w\p{Blank}]+\z/i
  end
end

and the second one:

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    message = options.fetch(:message, I18n.t('errors.attributes.email.invalid'))
    record.errors[attribute] << message unless EmailValidator.valid_email?(value)
  end

  def self.valid_email?(email)
    email =~ /\A.+@.+\..+\z/i
  end
end

They're basically the same. Should I inherit them from one class with protected utility methods or what?


texts: Drawing a line in any direction with pixels

texts:
I am doing an image drawing and rendering library, and would like some feedback on this code, it simply draws a line in any direction.

The equation for that is:

m = (y2 - y1) / (x2 - x1)

b = y1 - m * x1

y = mx + b

It works but all these if statements are bothering me, and I am not sure if it's the best solution.

proc line*(img: var Image, x1, y1, x2, y2: int) =
  # Necessary pass the values to variables so we can manipulate them
  var
    a1 = x1
    a2 = x2
    b1 = y1
    b2 = y2

  # To draw correctly we need to iterate over the longest axis
  if abs(a1 - a2) > abs(b1 - b2):
    swap(a1, b1)
    swap(a2, b2)

  # ¹ To make sure we are iterating from the lower to the higher
  if b1 > b2:
    swap(a1, a2)
    swap(b1, b2)

  let m = (a2 - a1) / (b2 - b1)
  let s = float(a1) - m * float(b1)

  # ¹ Since we swiped the axis we need to swap x and y
  if abs(x1 - x2) > abs(y1 - y2):
    for b in b1..b2:
      let a = float(b) * m + s
      img.pixel(b, toInt(a), img.strokeColor)
  else:
    for b in b1..b2:
      let a = float(b) * m + s
      img.pixel(toInt(a), b, img.strokeColor)


texts: "Find the Min" challenge on Facebook Hacker Cup

texts:
I was solving the "Find the Min" problem on Facebook Hacker Cup.

The code below works fine for the sample inputs given there, but for input size as big as 109, this takes hours to return the solution.

  Problem statement:

  After sending smileys, John decided to play with arrays. Did you know
  that hackers enjoy playing with arrays? John has a zero-based index
  array, m, which contains n non-negative integers. However, only
  the first k values of the array are known to him, and he wants to
  figure out the rest.

  John knows the following: for each index i, where k <= i < n,
  m[i] is the minimum non-negative integer which is not contained in
  the previous *k* values of m.

  For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1.

  John is very busy making the world more open and connected, as such,
  he doesn't have time to figure out the rest of the array. It is your
  task to help him.

  Given the first k values of m, calculate the nth value of this
  array. (i.e. m[n - 1]).

  Because the values of n and k can be very large, we use a
  pseudo-random number generator to calculate the first k values of
  m. Given positive integers a, b, c and r, the known values
  of m can be calculated as follows:

m[0] = a
m[i] = (b * m[i - 1] + c) % r, 0 < i < k

  Input

  The first line contains an integer T (T <= 20), the number of test cases.
  This is followed by T test cases, consisting of 2 lines each.
  The first line of each test case contains 2 space separated integers,
    n, k (\$1 <= k \le 10^5, k < n \le 10^9\$).
  The second line of each test case contains 4 space separated integers
  a, b, c, r (\$0 \le a, b, c \le 10^9, 1 \le r <= 10^9\$).

My solution:

import sys
cases=sys.stdin.readlines()
def func(line1,line2):
    n,k=map(int,line1.split())
    a,b,c,r =map(int,line2.split())
    m=[None]*n
    m[0]=a
    for i in xrange(1,k):
        m[i]= (b * m[i - 1] + c) % r
    #print m
    for j in range(0,n-k):

        temp=set(m[j:k+j])
        i=-1
        while True:
            i+=1
            if i not in temp:
                m[k+j]=i
                break

    return m[-1]

for ind,case in enumerate(xrange(1,len(cases),2)):
    ans=func(cases[case],cases[case+1])
    print "Case #{0}: {1}".format(ind+1,ans)

Sample input:

5
97 39
34 37 656 97
186 75
68 16 539 186
137 49
48 17 461 137
98 59
6 30 524 98
46 18
7 11 9 46


texts: Using inheritance and polymorphism in Java

texts:
I'm trying to use inheritance and polymorphism to make it easy for the program to be enhance to many more rules. ClassificationRule is the base class and RuleFirstOccrnc and RuleOccrncCount and derived classes and by using the same non-static apply() method ClassificationRule should invoke all other non-static apply() method. I'm just starting on Java and I'm not sure if I'm doing it right. Can anyone tell me if I'm using inheritance or just calling the apply() method?

//PrioritRule Class
public class PrioritRuls {
     final static ArrayList<ClassificationRule> rulesA
            = new ArrayList<ClassificationRule>();

     static{
            rulesA.add( new RuleFirstOccrnc() );
            rulesA.add( new RuleOccrncCount() );
     }
     public static void prioritize( final String aUserInput ){
            for (ClassificationRule rule:rulesA)
                    rule.apply(aUserInput);
    }
}

// ClassificationRule Class - Based Class
public class ClassificationRule {

     public void apply (final String aUserInput) {
           apply( aUserInput );
     }
}

//RuleFirstOccrnc - Derived Class
public class RuleFirstOccrnc extends ClassificationRule {
     public void apply ( final String aUserInput ) {
          for( TweetCat t: TwtClassif.tCat )
               applyFirstOccurrenceRuleTo( t, aUserInput );
}
   * * *

//RuleOccrncCount - Derived Class
public class RuleOccrncCount extends ClassificationRule {
     public void apply ( final String aUserInput ) {
          for( TweetCat t: TwtClassif.tCat )
               applyOccurrenceCountRuleTo( t, aUserInput );
}
  * * *


texts:
I have a WCF service which should authenticate user against any bruteforce attack.
Below is the code to avoid any bruteforce attack. I have used MemoryCache to keep track of invalid attempts by a user.

Could you please review the code and let me know if there are any issues?

Following defined in config file:

<InvalidLoginAttemptsThreshold value = "5"/>
<InvalidLoginLockoutInMinutes value = "20"/>

Code to add invalid login to cache and lock the account if invalid logins reaches threshold set in config.

private readonly CacheItemPolicy cacheInvalidLoginPolicy = new CacheItemPolicy();
private readonly ObjectCache cacheInvalidLogins = MemoryCache.Default; //Cache to hold Invalid Login Attempts: {UserId, obj UserLogin}

public class UserLogin
{
    public string UserName { get; set; }
    public List<DateTime> InvalidLoginTimestamp { get; set; }
    public bool IsLocked { get; set; }
}
private bool AuthenticateUser(string userName, string password)
{
    bool validCredentials = false;
    string userNameUpperCase = userName.ToUpper(); //MemoryCache treats 'a' and 'A' as different names
    if (cacheInvalidLogins.Contains(userNameUpperCase) && ((UserLogin)cacheInvalidLogins[userNameUpperCase]).IsLocked)
    {
        log.ErrorFormat("UserId: {0} tried to access locked account at {1}", userName, DateTime.Now);
        throw new FaultException("Your account is locked out. Please try after some time.", new FaultCode("AccountLocked"));
    }

    try
    {
        validCredentials = securityService.Authenticate(userName, password);

        if (!validCredentials)
        {
            AddInvalidLoginToCache(userNameUpperCase);
        }
        else if (validCredentials && cacheInvalidLogins.Contains(userNameUpperCase))
        {
            //For valid credentials - remove from cache
            cacheInvalidLogins.Remove(userNameUpperCase);
        }
    }
    catch (Exception exception)
    {
        log.Error(exception);
    }

    return validCredentials;
}

private void AddInvalidLoginToCache(string userName)
{
    if (cacheInvalidLogins.Contains(userName))
    {
        string clientId = userName.Split('\\')[0];
        //Increment InvalidLoginCount for this user
        UserLogin invalidLogin = (UserLogin)cacheInvalidLogins[userName];
        invalidLogin.InvalidLoginTimestamp.Add(DateTime.Now);
        cacheInvalidLogins[userName] = invalidLogin; //todo: update cache policy here

        //Lock user account if InvalidLoginCount reach threshold set in config
        if (invalidLogin.InvalidLoginTimestamp.Count == invalidLoginThresholdFromConfig))
        {
            invalidLogin.IsLocked = true;
            cacheInvalidLogins.Set(userName.ToUpper(), invalidLogin, LockOutCachePolicyFromConfig());
            log.ErrorFormat("Invalid Login attempted by UserId: {0} at these timestamps: {1}", userName, String.Join(",", invalidLogin.InvalidLoginTimestamp));
            log.ErrorFormat("Account is locked out for UserId: {0}", userName);
            throw new FaultException("Your account is locked out. Please try after some time.", new FaultCode("AccountLocked"));
        }
    }
    else
    {
        //todo: check if extra config setting is required for this cache policy
        cacheInvalidLoginPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5);
        cacheInvalidLogins.Add(userName.ToUpper(),
                               new UserLogin {UserName = userName, InvalidLoginTimestamp = new List<DateTime> {DateTime.Now}},
                               cacheInvalidLoginPolicy);
    }
}


texts:
This is my Python 3 code to generate text using a Markov chain.
The chain first randomly selects a word from a text file. Out of all the occurrences of that word in the text file, the program finds the most populer next word for the first randomly selected word. It continues the process to form a very understandable text.

The best thing about this code is that it copies the style of writing in the text file. At the first trial of the code, I put 3 of the most famous Shakespeare's plays, the Macbeth, Julius Caesar and The Comedy of Errors. And when I generated text from it the outcome was very much like a Shakespeare poem.

My knowledge in Python coding is between intermediate and expert. Please review my code and make changes as you like. I want suggestions from both experts and beginners.

# Markov Chain Poetry

import random
import sys

poems = open("text.txt", "r").read()
poems = ''.join([i for i in poems if not i.isdigit()]).replace("\n\n", "
").split(' ')
# This process the list of poems. Double line breaks separate poems, so they are removed.
# Splitting along spaces creates a list of all words.

index = 1
chain = {}
count = 1000 # Desired word count of output

# This loop creates a dicitonary called "chain". Each key is a word, and the value of each key
# is an array of the words that immediately followed it.
for word in poems[index:]:
    key = poems[index - 1]
    if key in chain:
        chain[key].append(word)
    else:
        chain[key] = [word]
    index += 1

word1 = random.choice(list(chain.keys())) #random first word
message = word1.capitalize()

# Picks the next word over and over until word count achieved
while len(message.split(' ')) < count:
    word2 = random.choice(chain[word1])
    word1 = word2
    message += ' ' + word2

# creates new file with output and prints it to the terminal
with open("output.txt", "w") as file:
    file.write(message)
output = open("output.txt","r")
print(output.read())

Thanks!!!


texts:
The textbook problem:

  (strictly identical arrays) Two arrays list1[] and list2[] are
  strictly identical if they have the same length and list1[] is equal
  to list2[] for each[i].

  Write a function that returns true if list1 and list2 are strictly
  identical using the following header:

bool strictlyEqual(const int list1[], const int list2[], int size)

  Write a test program that prompts the user to enter two lists of
  integers and displays whether the two are strictly identical. The
  sample runs follow. Note that the first number in the input indicates
  the number of the elements in the list. This number is not part of the
  list. Assume the list size is maximum.

Any general tips to clean up this code? It just seems that I can accomplish the task w/o doing all the checks.

   #include <iostream>
   using namespace std;

   bool strictlyEqual(int const list1[], int const list2[], int size);

   bool strictlyEqual (int x1[], int x2[], int n)
   {
     int f=0; int i;
     for (i =1; i<=n; i++)
     {
               if (x1[i] != x2[i])
               {
                  // breaks loop
                    f=1;
                    break;
                }
     }

 if (f==0)
 return (true);
 else
 return(false);
 }

int main () {
cout << "enter list1: " << endl;
int list1[20], i;
cin >> list1[0];
for (i=1; i<= list1[0]; i++)
cin>> list1[i];

cout <<"enter the list2" << endl;
int list2[20];
cin >> list2[0];
for (i=1; i<= list2[0]; i++)
cin >> list2[i];

if (list1[0] == list2[0])
{
     int size = list2[0];
     bool v=strictlyEqual(list1, list2, size);
     if (v== true)
     cout << "identical" << endl;
     else
     cout << "not identical " << endl;
 }

  return 0;
 }


texts:
Implementation:

static void ReverseMatrix<T>(T[,] matrix)
{
    int width = matrix.GetLength(1);
    int height = matrix.GetLength(0);
    int startRow = 0;
    int startCol = 0;
    int endRow = height-1;
    int endCol = width-1;

    while (true)
    {
        if (startRow == height-1 || endRow == 0) return;

        // swap
        var temp = matrix[startRow, startCol];
        matrix[startRow, startCol] = matrix[endRow, endCol];
        matrix[endRow, endCol] = temp;

        startCol++;
        endCol--;
        if (startCol == width)
        {
            startRow++;
            startCol = width - 1;
        }
        if (endCol == -1)
        {
            endRow--;
            endCol = 0;
        }
    }
}

Test program:

static void Main()
{
    var matrix = new[,]
    {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    ReverseMatrix(matrix);

    PrintMatrix(matrix);
}

static void PrintMatrix(int[,] matrix)
{
    for (int row = 0; row < matrix.GetLength(0); row++)
    {
        for (int col = 0; col < matrix.GetLength(1); col++)
        {
            Console.Write("{0}\t",matrix[row,col]);
        }
        Console.WriteLine();
    }
}

Input:

1 2 3
4 5 6
7 8 9

Output:

9 8 7
6 5 4
3 2 1

How can I improve this implementation?


texts: Printing factors and prime factors of a number


texts: Using mutable keyword to implement an owner-pointer class (C++03)

texts:
For a couple of days, I have been trying to implement an own templated class called owner_ptr (for my little project) whose instances has ownership over a dynamically allocated object (or array). I want this template to support the deletion of dynamically allocated arrays too and also make it possible to pass ownership between owner_ptr objects. I've tried out many things and ideas (the last one was this) but each of them had some drawbacks.

The necessity of passing ownership between owner_ptr objects causes that you must modify the pointer of the passed owner_ptr object during copy-constructing or assignment (you have to set the pointer to NULL). Copy-constructor and assignment operator with const-reference is necessary to make this class work with std::vector.

template <typename T>
class owner_ptr
{
    /* Private members */

public:
    owner_ptr(const owner_ptr<T>&);
    owner_ptr& operator=(const owner_ptr<T>&);

   /* Other public member functions */
}

But how can I modify the objects if I have const-reference to them? The problem can be solved if I store the encapsulated pointer as a mutable member variable.

Here is my implementation:

template <typename T>
class owner_ptr
{
    mutable T* p;

    T* get_ownership() const
    {
        T* tmp = p;
        p = NULL;
        return tmp;
    }

public:
    explicit owner_ptr(T* ptr = NULL) : p(ptr) {}
    owner_ptr(const owner_ptr<T>& orig) : p(orig.get_ownership()) { }

    owner_ptr& operator=(const owner_ptr<T>& rhs)
    {
        if (this != &rhs)
        {
            this->pass(rhs.get_ownership());
        }
        return *this;
    }

    void pass(T* ptr = NULL)
    {
        if (p != ptr)
        {
            delete p;
            p = ptr;
        }
    }

    T* get() const { return p; }
    T* operator->() const { return p; }
    T& operator*() const { return *p; }

    ~owner_ptr()
    {
        this->pass();
    }
};

And a specialization for arrays (almost the same):

template <typename T>
class owner_ptr<T[]>
{
    mutable T* p;

    T* get_ownership() const
    {
        T* tmp = p;
        p = NULL;
        return tmp;
    }

public:
    explicit owner_ptr(T* ptr = NULL) : p(ptr) {}
    owner_ptr(const owner_ptr<T[]>& orig) : p(orig.get_ownership()) { }

    owner_ptr& operator=(const owner_ptr<T[]>& rhs)
    {
        if (this != &rhs)
        {
            this->pass(rhs.get_ownership());
        }
        return *this;
    }

    void pass(T* ptr = NULL)
    {
        if (p != ptr)
        {
            delete[] p;
            p = ptr;
        }
    }

    T* get() const { return p; }
    T* operator->() const { return p; }
    T& operator*() const { return *p; }
    T& operator[](int i) const { return p[i]; }

    ~owner_ptr()
    {
        this->pass();
    }
};

I tested the code and it seems to be working. std::vector also accepts this template, so I can use it for creating heterogeneous containers.

My questions:

Is it a bad idea to use mutable to solve the ownership-passing
problem? Are there any scenarios where it can cause undefined behaviour?
Is there anything that I implemented incorrectly in the template?
Any affect on performance?
Before C++11, why did we have only the silly std::auto_ptr which couldn't be used with std::vector?

NOTE: I'm doing this for learning purposes. This question is totally independent from the features and smart-pointers of C++11.


texts:
I found this question on leetcode and that was my answer ... But someone told me it's too bad that it takes \$O(n^3)\$ I am not sure that it takes all that time ... and trying to find better understandable Javascript solution.

  Given a string containing just the characters '(', ')', '{', '}', '['
  and ']', determine if the input string is valid. The brackets must
  close in the correct order, "()" and "()[]{}" are all valid but "(]"
  and "([)]" are not.

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    while (s.length != 0 && s.includes("[]") || s.includes("()") || s.includes("{}")) {
        s = s.replace("[]", "");
        s = s.replace("()", "");
        s = s.replace("{}", "");
    }
    return s.length < 1
};

console.log(isValid("({(())})")); // True
console.log(isValid("({((}))})")); // False


texts:
Previous question:

Counting words in files - follow-up 2

For simplifying the code, I have implemented std::regex rather than templates.

How can I improve this code further?

//
//program name: WordCounter
//
//usage: C:\>WordCounter.exe test.txt test1.txt
//
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <regex>

using Words = std::unordered_map<std::string, std::size_t>;

template<typename T>
std::string getToken(T begin, T end, std::regex e = std::regex{ R"([^.,\n\r]+)" })
{
    std::smatch match{};

    std::string result{};

    if (std::regex_search(begin, end, match, e))
    {
        result.append(match.str());
    }

    return result;
}

bool loadFromFile(const std::string& fileName, Words& words)
{
    std::ifstream file(fileName);

    if (!file)
    {
        return false;
    }

    for (std::string word; file >> word;)
    {
        ++words[getToken(word.cbegin(), word.cend())];
    }

    return true;
}

template<typename T>
void showResult(const T& begin, const T& end)
{
    std::vector<T> words;

    words.reserve(std::distance(begin, end));

    for (auto i = begin; i != end; ++i)
    {
        words.push_back(i);
    }

    std::sort(words.begin(), words.end(),
        [&](const T& it1, const T& it2)
    {
        return it1->second > it2->second;
    });

    int x = 0;

    for (const auto& i : words)
    {
        if (x++ == 0)
        {
            std::cout << "\nThe most repeated element is: " << i->first << "\n\n";

            std::cout << " Word\tRepeated Times";

            std::cout << '\n' << std::setfill('-') << std::setw(23) << '\n';
        }

        std::cout << ' ' << std::setfill(' ')
            << std::setw(10) << std::left << i->first
            << std::setw(6) << std::internal << i->second << '\n';
    }
}

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

    for (int i = 1; i < argc; ++i)
    {
        if (!loadFromFile(argv[i], words))
        {
            std::cerr << "Can't open the file " << argv[i] << '\n';
        }
    }

    showResult(words.begin(), words.end());
}


texts: Script that makes an API call to and parses the response to get a URL from where to download another file

texts:
This is my first script and I am having a hard time writing the shortest possible code.

exportsData=$(curl -X GET \
 -H 'Accept: application/vnd.xxxxx+json; version=3.0' \
 -H 'Authorization: Bearer RCexxxxxxxxxxxxxxxxxxxxxxxxxcVefI5mWy' \
 -H 'Content-Type: application/json' \
https://api.xxxx.com/apps/9xxxxxxxxx15f96fe/exports)
status=$(echo $exportsData | jq '.[0].status')
downloadURL=$(echo $exportsData | jq '.[0].download_url')
 export ENCRYPTED_AES_KEY=$(echo $exportsData | jq '.[0].encrypted_aes_key')
export AES_IV=$(echo $exportsData | jq '.[0].aes_iv')

export ENCRYPTED_TARBALL=encryptedChatDump.tar.gz.enc
 $(curl -X GET -o ENCRYPTED_TARBALL \
 -H 'Accept: application/vnd.xxxxx+json; version=3.0' \
 -H 'Authorization: Bearer RCexxxxxxxxxxxxxxxxxxxxxxxxxcVefI5mWy' \
 -H 'Content-Type: application/json' \
https://storage.googleapis.com/someUrlWhereTheFileIsBeingDownloadedFrom)

export OUTPUT_TAR=finalChatDumpUnencrypted.tar.gz
export PRIVATE_KEY_PATH=~/.ssh/id_rsa


texts: TDD svino Problem #4 - largest value from concatenated integers?

texts:
From this blog post:

  Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.

I did this in with two tests and using a TDD style.

I am pretty unfamiliar with Java, so looking for overall feedback.  And/or inputs this fails on...

import static org.junit.Assert.*;

import java.util.Arrays;
import junit.framework.TestCase;
import org.junit.Test;

public class ProblemFourTest extends TestCase{
    ProblemFour p;
    public void setUp(){
         p = new ProblemFour();
    }

    @Test
    public void testExample() {
        assertEquals("95021",p.largestNumberFromList(Arrays.asList(50,2,1,9)));

    }
    @Test
    public void test50556() {
        assertEquals("56550",p.largestNumberFromList(Arrays.asList(50,5,56)));

    }
    @Test
    public void testComplicatedExamples() {
        assertEquals("9999129220201",p.largestNumberFromList(Arrays.asList(99,2,20,20,29,91,1,9)));
    }

}

The associated code is:

import java.util.List;

public class ProblemFour {

    public String largestNumberFromList(List<Integer> input){

        return getStringFromList(sortIntegerList(input));
    };

    private String getStringFromList(List<Integer> input){
        String s = "";
        for (int i = 0; i < input.size(); i++){
            s += input.get(i);
        }

        return s;

    }
    private List<Integer> sortIntegerList(List<Integer> input){

        for (int i = 0; i < input.size(); i++){

            for (int j = i + 1; j < input.size(); j++) {

                int a = input.get(i);
                int b = input.get(j);

                if (b == getLargestLexiographcal(a,b)){
                    input.set(i, b);
                    input.set(j, a);
                }
            }

        };

        return input;

    }

    int getLargestLexiographcal(int a, int b){

        String first = "" + a;
        String second = "" + b;

        for (int i = 0; i < Math.max(first.length(), second.length()); i++){

            int firstVal = Integer.valueOf(first.charAt(Math.min(i,first.length() - 1)));
            int secondVal = Integer.valueOf(second.charAt(Math.min(i,second.length() - 1)));

            if (firstVal != secondVal ){
                if (firstVal > secondVal){
                    return Integer.valueOf(first);
                }
                else
                {
                    return Integer.valueOf(second);
                }
            }
        }

        return 0;

    }

}

I found that the refactor stage was quite easy to do having the test cases. I dropped a bunch of duplication from getLargestLexiographcal after my second test case. It was very, very painful to write working code and not refactor once I realized I was duplicating code. I had previous treated the equal length case as different than the unequal length. However, once the test passed refactoring was very simple and straightforward - a compelling reason for me to not refactor when trying to pass a test, and only afterwards. It lets you incremental refactor, rerun tests, repeat very quickly.


texts: Prime sieve: improve efficiency while keeping it reasonably simple?

texts:
public static void listPrimesThree(int maxNum){
long startTime = System.currentTimeMillis();

boolean[] booleanArray = new boolean[maxNum+1];
int root = (int)Math.sqrt(maxNum);

for (int m = 2; m <= root; m++){
  for (int k = m*m; k <= maxNum; k+=m){
    booleanArray[k] = true;
  }
}
for (int m = 3; m <= maxNum; m+=2){
  if(!booleanArray[m]){
    System.out.println(m);
  }
}
long endTime = System.currentTimeMillis();
System.err.println(endTime - startTime+"ms");
}


texts:
I wrote code in python that works slow. Because I am new to python, I am not sure that I am doing everything right. My question is what I can do optimally?
About the problem: I have 25 *.json files, each is about 80 MB. Each file just contain json strings. I need make some histogram based on data.

In this part I want create list of all dictionaries ( one dictionary represent json object):

d = [] # filename is list of name of files
for x in filename:
d.extend(map(json.loads, open(x)))

then I want to create list u :

u = []
for x in d:
  s = x['key_1'] # s is sting which I use to get useful value
  t1 = 60*int(s[11:13]) + int(s[14:16])# t1 is useful value
  u.append(t1)

Now I am creating histogram:

plt.hist(u, bins = (max(u) - min(u)))
plt.show()

Any thought and suggestions are appreciated.
Thank you!


texts: Reporting progress to main form's controls from within a threaded heavy task

texts:
I'm trying to figure out how to nicely write a Winforms app that reports the progress of completing a long task onto the main form's controls without causing Cross-thread op exceptions and such. So far I've come up with this scheme which at least works, but doesn't look very nice:

Progress<MyProgress> progress = new Progress<MyProgress>();
private void Form1_Load(object sender, EventArgs e)
{
    progress.ProgressChanged += (x, y) =>
        Invoke(new Action(() => { toolStripStatusLabel1.Text = y.text;
                                  toolStripProgressBar1.Value = y.percentage; }));
}

bool DoVeryHeavyStuff(IProgress<MyProgress> progress)
{
    progress.Report(new MyProgress() { percentage = 0, text = "Doing heavy stuff…" });
}

async void button_doHeavyStuff_Click(object sender, EventArgs e)
{
    bool success = await Task.Run(() => DoVeryHeavyStuff(progress));
}

As you can see, the right part of the progress.ProgressChanged += looks overly complex. Isn't there a way it can be written more simply?

One thing I could think of is creating a separate method, but that wouldn't help much, as it would still have to be referred to in that line.

progress.ProgressChanged += (x, y) =>
    Invoke(new Action(() => progress_ProgressChanged(x, y)));

void progress_ProgressChanged(object sender, MyProgress e)
    {
        toolStripStatusLabel1.Text = e.text;
        toolStripProgressBar1.Value = e.percentage;
    }

I managed to break it apart like this, but it looks even worse:

progress.ProgressChanged += (x, y) => ReportProgressA(x, y);
void ReportProgressA(object sender, MyProgress e)
{
    Invoke(ReportProgressB(sender, e));
}
Action ReportProgressB(object sender, MyProgress e)
{
    return () => progress_ProgressChanged(sender, e);
}

Invoke seems to be essential to avoiding cross-thread exceptions, but it requires a delegate as a parameter. I don't have much experience with delegates, so I don't know how to simplify the Action initialization code.

It looks like I can't just drop the explicit cast to Action for some reason:


texts:
I tried to solve a  symmetric tree problem

  Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

  For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

  But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

  Note:
  Bonus points if you could solve it both recursively and iteratively.

My solution with recursion

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        if not root: return True #None is symmetic
        return self.isMirror(root.left, root.right)

    def isMirror(self, l, r):
        if not l and not r: return True #base case 1
        if not l or not r: return False #base case 2
        if l.val != r.val: return False #base case 3
        #recur case
        left = self.isMirror(l.left, r.right)
        right = self.isMirror(l.right, r.left)
        return left and right

I assumed it as a decent solution to this problem but get a low score

  Runtime: 32 ms, faster than 24.42% of Python online submissions for Symmetric Tree.
  Memory Usage: 12.2 MB, less than 5.08% of Python online submissions for Symmetric Tree.

How could improve the my solution?


texts: Project Euler #2 - Sum of even Fibonacci numbers to 4,000,000

texts:
This particular problem has already been posted here before, but the community is ok with me to post it again, so I can have feedback on my own implementation.

I tried to keep things simple, with each function having its own responsibility so they can be reused in other contexts. Here it is:

(ns marcofiset.euler.problem2)

(defn fib [n]
  (if (< n 0)
    (throw (Exception. "Can't compute fib of n < 0"))
    (loop [i n cur 1 next 1]
      (if (zero? i)
        next
        (recur (dec i) next (+ cur next))))))

(defn fibs []
  (map fib (iterate inc 0)))

(defn fibs-until [max]
  (take-while #(< % max) (fibs)))

(defn solution []
  (apply + (filter even? (fibs-until 4000000))))

(println (solution))

I'm beginning to learn Clojure and this is one of my first exercices. I'd like to have some feedback from more experienced Clojure programmers.


texts:
When my program begins, I want to allow the user to hit a key to enter debug mode for one of the modules. Many of the solutions (involving alarm(), in particular) seemed complicated and involved multiple functions. Instead, I adapted this answer:

// Check to see if we should enter GSM de-bug mode
fd_set          s;
struct timeval  timeout;

timeout.tv_sec = 0;
timeout.tv_usec = 100000;
int i = 100000;

do {
    printf("Press [ENTER] for GSM debug mode... %i  \r",i/10000);
    fflush(stdout);
    FD_ZERO(&s);
    FD_SET(STDIN_FILENO, &s);
    select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);
    i--;
} while (FD_ISSET(STDIN_FILENO, &s) == 0 && i > 0);

if ( i <= 0 ) { printf("\nSkipping debug mode...\n"); }
else
{
    printf("\nEntering debug mode...\n");

    // fill in the debug code here

}

This code works, based on a few quick tests, and exhibits the behavior I want. But, have I created any problems for myself?


texts:
As more fully detailed in my question here, I'm in the process of starting a small, local business and wanted to avoid showing sequential invoice IDs to clients, and instead generate completely random ones. Thanks to the advice in the comments to that question, I decided to eliminate the risk of any collisions by incorporating logic that checks against a database (a flat text file) of all IDs that have previously been generated.
This is my attempt at doing so, which to my amazement is functional, but probably not as robust as it could be. Since then I have also decided on using 5-digit numbers, as these look better to me and a limit of 99,000 transactions (without 00000, and I might even exclude the first 10,000 digits through to 09999) will be more than enough for me, and the logic of the script means that collisions should no longer be an issue.
#!/usr/bin/env bash

generate_num() {
num=$(head /dev/urandom | tr -dc '[:digit:]' | cut -c 1-5)
}

read -p "Are you sure you want to generate a new invoice ID? [Y/n] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
    generate_num && echo Generating a random invoice ID and checking against database...
    sleep 2

    while grep -xq "$num" "ID_database"
        do
            echo Invoice ID \#$num already exists in database...
            sleep 2
            generate_num && echo Generating new random invoice ID and checking against database...
            sleep 2
        done

    echo Generated random invoice ID \#$num
    sleep 1
    echo Invoice ID \#$num does not exist in database...
    sleep 2
    echo $num >> "ID_database" && echo Successfully added Invoice ID \#$num to database...
fi

I have two main questions I'd like answered about it.

Can the code itself be improved on? This is one of the few Bash scripts I've ever written the core logic for, and perhaps the most involved, so if there's anything I shouldn't be doing or anything I could do better, I'd appreciate this.

Would it be conceivable to move the "database" into the script file itself, thus avoiding the need to maintain two separate files? If not, what are the reasons for this?

Thank you in advance, I'd appreciate some help from those more experienced with Bash than I am.


texts:
I'm wanting to calculate exponential moving averages of a variable, distance. Is the logic (and math) correct in the below code?

time and lastTime are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.

lastA etc are the exponential moving averages from the last calculations.

a etc will be left with the calculated exponential moving averages.

var distance = ...;
var a = Math.pow(1.16, -(time-lastTime)),
    b = Math.pow(1.19, -(time-lastTime)),
    c = Math.pow(1.22, -(time-lastTime)),
    d = Math.pow(1.26, -(time-lastTime)),
    e = Math.pow(1.30, -(time-lastTime)),
    f = Math.pow(1.35, -(time-lastTime)),
    g = Math.pow(1.40, -(time-lastTime));
a = a*lastA + (1-a)*distance;
b = b*lastB + (1-b)*distance;
c = c*lastC + (1-c)*distance;
d = d*lastD + (1-d)*distance;
e = e*lastE + (1-e)*distance;
f = f*lastF + (1-f)*distance;
g = g*lastG + (1-g)*distance;


texts: Instantiating objects with many attributes

texts:
I have a class with quite a few attributes, most of which are known when I create an instance of the object.  So I pass all the values in the constructor:

$op = new OpenIdProvider($imgPath . $name . $ext, 'openid_highlight',
                         0, 0, 108, 68, 6, $info[0], $info[1], $name);

I'm finding that having this many parameters makes it confusing both when writing and reading the code, as it's not easy to determine which attribute each value corresponds to.  Also, this has a bit of a code smell to it - seems like there should be a better way.  Any suggestions?


texts: Bank account balance, withdraw, deposit: compartmentalize without losing functionality

texts:
Is there a better way to write this while maintaining its current functionality? (checking balances, updating, subtracting, etc...) If so, where would I begin? I saw a code briefly in class that was for a similar questions and it looked more streamlined.

class Account:

    # constructor
    def __init__(self, name, account_number, balance):
        self.name = name
        self.account_number = account_number
        self.balance = balance

    # returns string representation of object
    def __str__(self):
        return"Account Name: {0}\nAccount Number: {1} \nAccount Balance:\
    ${2:.2f}".format(self.name, self.account_number, self.balance)

    # add given amount to balance
    def deposit(self, amount):
        self.balance += amount

    # subtract amount and fee from balance
    def withdraw(self, amount, fee):
        self.balance = self.balance - amount - fee

if __name__ == '__main__':
    # make 3 objects
    acct1 = Account('Guy Mann', 90453889, 100)
    acct2 = Account('Donald Duck', 83504837, 100)
    acct3 = Account('Joe Smith', 74773321, 100)

    # print
    print(acct1)
    print(acct2)
    print(acct3)

    # deposit and print
    acct1.deposit(25.85)
    acct2.deposit(75.50)
    acct3.deposit(50)
    print(acct1)
    print(acct2)
    print(acct3)

    # withdraw and print
    acct1.withdraw(25.85, 2.50)
    acct2.withdraw(75.50, 1.50)
    acct3.withdraw(50, 2)
    print(acct1)
    print(acct2)
    print(acct3)


texts: Naive Bayes Classifier for sentiment labelled documents

texts:
In order to continue improving my Python knowledge, I have implemented a naïve Bayes classifier as described in "An introduction to Information Retrieval". I would be very interested which parts could be improved, be it e.g. coding style or use of data structures.
"""Implementation of a naive Bayes classifier based on sentiment labelled sentences.
See https://nlp.stanford.edu/IR-book/pdf/irbookonlinereading.pdf for the algorithm.
The dataset was obtained from
https://archive.ics.uci.edu/ml/datasets/Sentiment+Labelled+Sentences"""
import sys
import re
import math
from collections import Counter
from stop_words import get_stop_words

# PARAMETERS
DATAFILE = "data\\imdb_labelled.txt"

# FUNCTIONS
def load_data(filepath):
    """Load the sentiment labelled data."""
    # A library is a list of categories, which label a list of documents
    library = [[],[]]

    # The textfile is formatted as document (string), TAB, category (int), NL
    with open(filepath, 'r') as file:
        for line in file:
            document, category = line.split('\t')
            library[int(category)].append(document)

    return library

def clean_library(library):
    """Clean documents in the library array."""
    for i, category in enumerate(library):
        for j, document in enumerate(category):
            cleaned_doc = clean_document(document)
            library[i][j] = cleaned_doc

def clean_document(document):
    """Clean a document from stop words, numbers and various other
       characters and return a list of all words."""
    stop_words = get_stop_words('en')

    new_doc = document.strip().lower()
    new_doc = re.sub("[-0-9.,!;:\\/()\"&]", "", new_doc)
    new_doc = new_doc.split()
    new_doc = [word for word in new_doc if word not in stop_words]

    return new_doc

def train_categories(library):
    """Calculate probabilities for the naive Bayes classifier and
       return the vocabulary with conditional probabilities and the priors."""
    total_docs = sum((len(category) for category in library))
    vocabulary = [word for category in library
                       for document in category
                       for word in document]

    cond_prob = []
    prior = []

    for category in library:
        # Prior probability
        total_cat_docs = len(category)
        prior.append(total_cat_docs / total_docs)

        # Conditional probabilities
        text = [word for document in category for word in document]

        word_count = Counter(text)
        total_word_count = sum(word_count.values())

        cat_cond_prob = {}

        for word in vocabulary:
            cat_cond_prob[word] = (word_count[word] + 1) / (total_word_count + 1)

        cond_prob.append(cat_cond_prob)

    return (vocabulary, prior, cond_prob)

def apply_nb(vocabulary, priors, cond_prob, document):
    """Apply the naive Bayes classification to a document in order
       to retrieve its category."""
    prepared_doc = clean_document(document)
    prepared_doc = [word for word in prepared_doc if word in vocabulary]

    score = [math.log(prior) for prior in priors]

    for cat, cat_cond_prob in enumerate(cond_prob):
        score[cat] = sum((math.log(cat_cond_prob[word]) for word in prepared_doc))

    return score.index(max(score))

def main(argv):
    """Train a naive Bayes classifier and apply it to a user-supplied string."""
    if len(argv) == 0:
        print("Please supply a document string.")
        return

    user_doc = argv[0]

    library = load_data(DATAFILE)
    clean_library(library)
    vocabulary, priors, cond_prob = train_categories(library)

    doc_cat = apply_nb(vocabulary, priors, cond_prob, user_doc)
    print(f'"{user_doc}": Category {doc_cat}')

if __name__ == "__main__":
    main(sys.argv[1:])


texts:
Given a linked list, remove the nth node from the end of list and return its head.

For example,

  Given linked list: 1->2->3->4->5, and n = 2.

  After removing the second node from the end, the linked list
  becomes 1->2->3->5.

ListNode *removeNthFromEnd(ListNode *head, int n) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (head == NULL) {
      return NULL;
    }

    ListNode *pre, *cur;
    pre = cur = head;
    for (int i = 0; i < n; ++i) {
      pre = pre->next;
    }

    while (pre != NULL && pre->next != NULL) {
      cur = cur->next;
      pre = pre->next;
    }

  //mistake
  //if (cur == head) {
  // I use the above line to check if it's the first node to be deleted,
  // there is a problem for this case: list: 1->2, n : 1
    if (pre == NULL) {
      ListNode *newHead = head->next;
      delete head;
      return newHead;
    }
    else {
      ListNode *tmp = cur->next;
      cur->next = tmp->next;
      delete tmp;
      return head;
    }
}


texts: Get item from database by ID and get all items from database

texts:
I have 2 methods for getting data from the database (the data I get are both List of tuples with doubles and datetimes in it). I would like to know if it is possible to use one method for both queries.

How can I make this code DRY? In my opinion I'm defining 2 methods which clearly does nearly the same. How can I improve this? I've read some about predicates and delegates but I'm not sure how to apply them here.

 private IEnumerable<Tuple<double, DateTime>> GetCarHdopById(int id)
        {
            var tp = new List<Tuple<double, DateTime>>();
            db.OpenConnection();
            var result = db.QueryDatabaseById("SELECT avg(hdop),to_char(datetime, 'YYYY-MM-DD') as average_hdop FROM positions where unitid = :id group by to_char(datetime, 'YYYY-MM-DD');",id);
            while (result.Read())
            {

                var avgHdopPerCar = Convert.ToDouble(result[0]);
                var date = Convert.ToDateTime(result[1]);
                tp.Add(new Tuple<double, DateTime>(avgHdopPerCar, date));
            };
            db.CloseConnection();
            return tp;

        }

        private List<Tuple<double, DateTime>> GetCarHdopTotalCarsPerDay()
        {
            var tp = new List<Tuple<double, DateTime>>();
            db.OpenConnection();
            var result = db.QueryDatabase("SELECT avg(hdop),to_char(datetime, 'YYYY-MM-DD') as average_hdop FROM positions group by to_char(datetime, 'YYYY-MM-DD');");
            while (result.Read())
            {

                var avgHdopPerCar = Convert.ToDouble(result[0]);
                var date = Convert.ToDateTime(result[1]);
                tp.Add(new Tuple<double, DateTime>(avgHdopPerCar, date));
            };
            db.CloseConnection();
            return tp;
        }

Query database method (I can probably overload this one):

   public NpgsqlDataReader QueryDatabase(string query)
    {
        var command = new NpgsqlCommand(query, conn);
        command.Connection = conn;
        return command.ExecuteReader();
    }

     public NpgsqlDataReader QueryDatabaseById(string query, int parameters)
    {
        var command = new NpgsqlCommand(query, conn);
        command.Parameters.Add("id",NpgsqlDbType.Integer);
        command.Prepare();
        command.Parameters[0].Value = parameters;
        command.Connection = conn;
        return command.ExecuteReader();
    }


texts:
I wanted to try multithreading out in C, so I did Dining Philosophers using C11 threads with the approach of having one of the philosophers left-handed. Any suggestions?

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

#define NUM_THREADS 5

struct timespec time1;
mtx_t forks[NUM_THREADS];

typedef struct {
    char *name;
    int left;
    int right;
} Philosopher;

Philosopher *create(char *nam, int lef, int righ) {
    Philosopher *x = malloc(sizeof(Philosopher));
    x->name = nam;
    x->left = lef;
    x->right = righ;
    return x;
}

int eat(void *data) {
    time1.tv_sec = 1;
    Philosopher *foo = (Philosopher *) data;
    mtx_lock(&forks[foo->left]);
    mtx_lock(&forks[foo->right]);
    printf("%s is eating\n",  foo->name);
    thrd_sleep(&time1, NULL);
    printf("%s is done eating\n",  foo->name);
    mtx_unlock(&forks[foo->left]);
    mtx_unlock(&forks[foo->right]);
    return 0;
}

int main(void) {
    thrd_t threadId[NUM_THREADS];
    Philosopher *all[NUM_THREADS] = {create("Teral", 0 ,1),
                    create("Billy", 1, 2),
                    create("Daniel", 2,3),
                    create("Philip", 3, 4),
                    create("Bennet", 0, 4)};
    for (int i = 0; i < NUM_THREADS; i++){
        if (mtx_init(&forks[i], mtx_plain) != thrd_success){
            puts("FAILED IN MUTEX INIT!");
            return 0;
        }
    }
    for (int i=0; i < NUM_THREADS; ++i) {
        if (thrd_create(threadId+i, eat, all[i]) != thrd_success) {
            printf("%d-th thread create error\n", i);
            return 0;
        }
    }

    for (int i=0; i < NUM_THREADS; ++i)
        thrd_join(threadId[i], NULL);
    return 0;
}


texts: Good interface for reverting effect of function

texts:
In my job, we often write functions that do some calculation and write the result to a database. Sometimes mistakes are made and wrong stuff ends up being saved, therefore we also want to supply an interface to clean up after the function. This is an attempt of solving that problem.
from functools import wraps

def revert(func):
    if not hasattr(func,'_revert'):
        raise NotImplementedError(func.__name__ + " does not have a revert registered")

    @wraps(func._revert)
    def wrapper(*args,**kwargs):
        return func._revert(*args,**kwargs)
    return wrapper

def register_revert(revert):
    def revert_added(func):
        func._revert = revert

        @wraps(func)
        def wrapper(*args,**kwargs):
            return func(*args,**kwargs)
        return wrapper
    return revert_added

def _is_it_a_str(maybe_str):
    if not isinstance(maybe_str,str):
         raise ValueError("I need a string")

def _revert_stuff(a_str):
    _is_it_a_str(a_str)
    print('revert stuff with ' + a_str)

@register_revert(_revert_stuff)
def do_stuff(a_str):
    _is_it_a_str(a_str)
    print('doing stuff with ' + a_str)

do_stuff('something')
# Oops:
revert(do_stuff)('something')

The idea is to write your function doing your job - do_something in this case. And then when you are ready to take it to the next level, you write its revert, register it and you are done.
I like that

the solution does not require changing anything in the main functionality.
you can use the same identical interface for many functions
the syntax reads relatively intuitively

I think it is inconvenient that

I need to maintain two identical interfaces - the one on do_stuff and _revert_stuff needs to be identical (or at least _revert_stuff needs to work getting the one from do_stuff).
sometimes I want to type-check the arguments which I then also have to repeat (exemplified here with _is_it_a_str). I thought about moving that to another decorator, but I'm afraid it gets too confusing.

Edit: We use the newest stable version of Python
p.s. My first question tried my best. Critique welcome!


texts: Using Angular directives for connect HTML clicks in buttons and controller actions

texts:
I'm trying to improve my Angular directive. I'm pretty new to CoffeeScript, so I think there may be inconsistent code.

'use strict'
class Main extends Directive
  constructor: (VerifyService) ->
    return {
      restrict : 'M'
      link : (scope) ->
        scope.watch 'events', ->
          ACTION =
            booking = () ->
              scope.ctrl.create()

          filter = (control) ->
            if ACTION[control]
              ACTION[control]()
            return

          door = () ->
            control = $(this).data('controller-control')
            filter(control)
            return

          init = () ->
            PROP.element.bind('click', door)
            return
          return

          test = () ->
            if VerifyService.each(PROP)
              init()
            return

          test()
          return
    }

I'm using directives not only to manipulate the HTML, but to use as a bridge between HTML and CONTROLLERS. Please do not question why I'm doing like this; there is a very big reason.

I'm using the GULP-NG-CLASSIFY, which makes available the use of CoffeeScript class syntax.

Inside of the link function (which all directive have) I'm starting my code from the bottom to the top.

First I test if all my HTML properties are available (in this code I only have one):

      test = () ->
        if VerifyService.each(PROP)
          init()
        return

      test()
      return

If all the PROP exists in the HTML, I want initialize the script, which will bind a click in the PROP.element:

      init = () ->
        PROP.element.bind('click', door)
        return
      return

So, in the door, I want get the data from data-controller-control:

      door = () ->
        control = $(this).data('controller-control')
        filter(control)
        return

I need filter and I want get the controller action requested. I need to be sure that the action in my controller exists:

      filter = (control) ->
        if ACTION[control]
          ACTION[control]()
        return

Finally I call the ACTION requested by the user:

      ACTION =
        booking = () ->
          scope.ctrl.create()

In this case I only have one.


texts: Getting a Future from a Vector and a function

texts:
I'm pretty new to Rust and to it's async/await model, and I'm trying to do something that looks like a specialized Haskell's traverse function. Given a Vec<T> and a function T -> Future<Output = R> I want to get a Future<Output = Vec<R>>.

At the moment, I have the following:

use futures::{FutureExt, StreamExt};

pub async fn traverse<I, T, R, F, FN>(xs: I, f: FN) -> Vec<R>
where
    I: IntoIterator<Item = T>,
    F: FutureExt<Output = R>,
    FN: Fn(T) -> F,
{
    futures::stream::iter(xs)
        .fold(vec![], |acc, item| {
            f(item).map(move |app| {
                let mut a = acc;
                a.push(app);

                a
            })
        })
        .await
}

It works as expected, but doesn't feel very idiomatic. Does anybody has suggestion how to improve this function?


texts:
I have two functions that replace letters. In one function, I'm replacing a regular Hebrew letter with its final form, and the other function undoes this operation. (Consider it like lowercase/uppercase, except only a few letters have both forms.)

I created an object where the keys are the regular forms and the values are the final forms. In each function, I iterate over the object and run a regex - in one function it's map[i] -> i; the other is i -> map[i].

Would it be worth it / even possible to abstract this for loop into a function?

var map = {
    כ: 'ך',
    מ: 'ם',
    נ: 'ן',
    פ: 'ף',
    צ: 'ץ'
};

exports.toFinal = function(text) {
    for (var i in map) {
        text = text.replace(new RegExp(i,'g'), map[i]);
    }
    return text;
}

exports.toRegular = function(text) {
    for (var i in map) {
        text = text.replace(new RegExp(map[i],'g'), i);
    }
    return text;
}

(exports is Node.js's exports object, and the code is implicitly running in a closure.)


texts: Get metadata from an Icecast radio stream

texts:
I am new to Python and not very familiar with advanced Python data structures.

I have written a function to receive data from a socket in Python and perform string manipulations on it. The basic purpose of the code is to get the metadata from an Icecast radio stream based on suggestions I found elsewhere.

The function seems to work but it would be great it someone can help me optimize the string operation.

def radioPoller():
    msg1="GET / HTTP/1.1"+'\r'+'\n'+"Host: sc.buddharadio.com"+'\r'+'\n'+"User-Agent: VLC/2.0.5 LibVLC/2.0.5"+'\r'+'\n'+"Range: bytes=0-"+'\r'+'\n'+"Connection: close"+'\r'+'\n'+"Icy-MetaData: 1"+'\r'+'\n'+'\r'+'\n'

    if os.path.exists("/media/hdd1/data.txt"):
        os.unlink("/media/hdd1/data.txt")

    HOST = 'sc.buddharadio.com'                      # The remote host
    PORT = 80                                # The same port as used by the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))

    f=open("/media/hdd1/data.txt","w")

    s.send(msg1)                                 #sending http request
    data=""
    while len(data)<1024:
        data=s.recv(1024)               #recieving a few characters

    t=data.find("metaint")                       #finding the metaint response header which contains interval after which metadata will be visible in data stream eg:-icy-metaint:32768
    data=data[t+8:]                      #jumping 8 characters to the end of the string

    splitter="\r\n"                         # to split the contents and find when header ends and
    data1=data.split(splitter)                      #data1 stores the splitted data. First list has length and last has data

    metaInt=int(data1[0])                      #find the metadata interval byte length
    #print metaInt

    string12=data1[len(data1)-1]                #contains only the data part

    lengthTotal= len(string12)                  #length of data we have

    print "total data is", lengthTotal,"\n"

    print "TOtal bytes we should get is", (metaInt+4080),"\n"

    while lengthTotal<(metaInt+4080):
        data = s.recv(8192)
        lengthTotal=lengthTotal+len(data)
        print "Total length now is", lengthTotal
        string12=string12+data
        #The first character after MetaInterval number of characters define the length of actual metadata/16
    metaLen=ord(string12[metaInt])
    print "This is multiplier", metaLen, "No of characters to read ", (metaLen*16)

    metaString=string12[metaInt+1:metaInt+1+(metaLen*16)]+'\n'
    print "Extracted String is \n", metaString

    f.write(str(metaString))
    s.close
    f.close

The code sends a request header to the radio stream and then receives a response like this:

  ICY 200 OK
  icy-notice1:This stream requires Winamp
  icy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.8
  icy-name:Buddha
  icy-genre:
  icy-url:http://www.buddharadio.com
  content-type:audio/aac
  icy-pub:0
  icy-metaint:32768
  icy-br:32

The icy-metaint defines the data interval after the metadata appears in the data stream.

I use a while loop to read in the Meta Data Interval+Max Meta Data Length of data and then slice the metadata and save it in a file.


texts: Filtering a collection by an async result

texts:
I'm trying to do something like this:

var loudDogs = dogs.Where(async d => await d.IsYappyAsync);

The "IsYappyAsync" property would return a Task<bool>.

Obviously this isn't supported, so instead I've built an extension method called WhereAsync.

public static async Task<IEnumerable<T>> WhereAsync<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
    var results = new List<T>();
    var tasks = new List<Task<bool>>();

    foreach (var item in items)
    {
        var task = predicate.Invoke(item);
        tasks.Add(task);
    }

    var predicateResults = await Task.WhenAll<bool>(tasks);

    var counter = 0;
    foreach (var item in items)
    {
        var predicateResult = predicateResults.ElementAt(counter);

        if (predicateResult)
            results.Add(item);

        counter++;
    }

    return results.AsEnumerable();
}

This probably isn't the best approach, but I'm at a loss for something better. Any thoughts?


texts:
I'm trying to find out if it is possible to simplify my framework a little bit more. The current solution works, but it does cause some code duplication for me and some other issues that might come down the road.

public class Browsers {

  private String Browser;
  private String Windows;
  private String Ver;

  protected WebDriver driver;

  @BeforeTest
  public void BeforeMethod() {

    DriverFactory driverfactory = new DriverFactory();
    driver = driverfactory.createdriver(Browser);
  }

  @AfterTest
  public void AfterMethod() {}

  public Browsers(String Browser, String Windows, String Ver) {
    this.Browser = Browser;
    this.Windows = Windows;
    this.Ver = Ver;

  }

  @DataProvider
  public static Object[][] dataProviderMethod() {
    return new Object[][] {{"FF", "WIndows", "10"}, {"Chrome", "Windows", "10"}};
  }

}

public class DriverFactory {

  private WebDriver driver;

  public WebDriver createdriver(String Browser) {
    if (Browser.contains("FF")) {

      driver = new FirefoxDriver();
    }

    else {
      driver = new ChromeDriver();
    }
    return driver;
  }

}

public class LoginTests extends Browsers {

  @Factory(dataProvider = "dataProviderMethod")
  public LoginTests(String Browser, String Windows, String Ver) {
    super(Browser, Windows, Ver);
  }

  @Test
  public void LoginValid() {

  }

  @Test
  public void LoginInvalid() {

  }

}

Problem

Currently, I'm able to run tests when I create a factory on each of the test classes.

I have to write a constructor to all the test classes that I create. Which causes me some code duplication. When I have 100 tests then it will be quite a lot. Is it possible to avoid it.


texts: How can I avoid unchecked cast warning in my generic recursive Iterator?

texts:
It's somewhat odd that Java's collection framework has no iterator for recursive data structures.  Since I needed something like this, I wrote my own. First off, I need recursive elements:

public interface RecursiveElement<T>
{
    public Iterator<T> getChildrenIterator();
}

And then an Iterator:

public class RecursiveIterator<T> implements Iterator<T>
{
    private Deque<Iterator<T>> stack;
    private Iterator<T> currentStackItem;

    /**
     * Creates a new instance
     *
     * @param root
     *            all children of this node are iterated. The root node itself
     *            is not returned
     * @throws NullPointerException
     *             if root is null
     */
    public RecursiveIterator(final RecursiveElement<T> root)
    {
        if (root == null)
            throw new NullPointerException(
                    "root argument to this iterator must not be null");
        stack = new LinkedList<Iterator<T>>();
        currentStackItem = root.getChildrenIterator();
    }

    @Override
    public boolean hasNext()
    {
        return currentStackItem != null;
    }

    @Override
    public T next()
    {
        final T result = currentStackItem.next();
        if (result instanceof RecursiveElement)
        {
            stack.addLast(currentStackItem);
             // Here is the warning:
            currentStackItem = ((RecursiveElement<T>)result).getChildrenIterator();
        }
        while (currentStackItem != null && !currentStackItem.hasNext())
            currentStackItem = stack.pollLast();
        return result;
    }

    @Override
    public void remove()
    {
        currentStackItem.remove();
    }
}

That code works very well, but I do get a warning from the compiler in the next() method in the line I marked. It is clear to me why this warning occurs, but I have not come up with any solution on how to solve the problem without this warning (save suppressing the warning). Any ideas?


texts: A storage bin thingy for Repl.it projects

texts:
I have a Repl.it account that I use for my projects, and I don't really want to make a new api for storage every time, I've seen some like EasyDB and Jsonstore (I use Jsonstore in the background as storage here) but it doesn't have some of the features i want. It isn't done, but its working. I just wanted to see if there's any improvements I could make before I start working on the next few features.

from os import getenv as env
from flask import make_response
from flask import Flask, request
from flask_limiter import Limiter
from json_store_client import Client
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import check_password_hash
from werkzeug.security import generate_password_hash

app = Flask('app')
auth = HTTPBasicAuth()
db = Client(env("TOKEN"))

limiter = Limiter(
    app,
    key_func=lambda: auth.username(),
    default_limits=["100 per second"]
)

@auth.verify_password
def verify_password(username, password):
    user = db.retrieve(f"users/{username}")
    try:
        if check_password_hash(user["password"], password):
            return True
    except: return False
    return False

@app.route('/regester', methods = ['POST'])
def register():
    if request.is_json: user = request.get_json()['username']
    else: user = request.form['username']
    if db.retrieve(f"users/{user}"):
        return False
    if request.is_json: db.store(f"users/{user}", { "password": generate_password_hash(request.get_json()['password'])})
    else: db.store(f"users/{user}", { "password": generate_password_hash(request.form['password'])})
    return make_response(user, 201)

@app.route('/', methods = ['GET'], defaults={'fullurl': ''})
@app.route('/<path:fullurl>', methods = ['GET'])
@auth.login_required
def index_get(fullurl):
    data = db.retrieve(f"data/{auth.username()}/{fullurl}")
    if data: return make_response(data, 200)
    return make_response({}, 204)

@app.route('/', methods = ['POST'], defaults={'fullurl': ''})
@app.route('/<path:fullurl>', methods = ['POST'])
@auth.login_required
def index_post(fullurl):
    if request.id_json: db.store(f"data/{auth.username()/{fullurl}}", request.get_json())
    else: db.store(f"data/{auth.username()}", request.form)
    return make_response(db.retrieve(f"data/{auth.username()}"), 201)

app.run(host="0.0.0.0")


texts: Python program to translate sentences from "bird language"

texts:
Given a sentence in 'bird language', where there are two rules:

After each consonant there is a random vowel added. For example if the consonant is "l" it will end as "la" or "le"...
After each vowel there are two extra vowels which are the same as the first. For example if there is a "u" it will end as "uuu"

Vowels are "aeiouy"

Examples:

hieeelalaooo → hello
hoooowe yyyooouuu duoooiiine → how you doin
aaa bo cy da eee fe → a b c d e f
sooooso aaaaaaaaa → sos aaa

The code is:

VOWELS = "aeiouy"

def translate(phrase):

    result = ""
    num_of_letters_to_ignore = 0

    for i, letter in enumerate(phrase):
        if num_of_letters_to_ignore > 0:
            num_of_letters_to_ignore -= 1
            continue

        if letter in VOWELS:
            num_of_letters_to_ignore += 2
        elif letter.isalpha():
            num_of_letters_to_ignore += 1
        result += letter

    return result

How can it be improved?

EDIT: I have added the first sentence which was missing where it is correctly specified that y is in the vowels!


texts: Removing Asterisks and neighbors from a string

texts:
I am going through the CodingBat exercises for Java. I got to this problem:

  Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right (if any) are gone. So "ad", "ab*cd", "ab**cd", "*ead", and "ade*" all yield "ad".

I decided to solve this using regular expressions. Here is my code:

public String starOut(String str){

    String s = " " + str + " "; //Avoiding OOB exceptions.
    String n = ""; //Used for replacements of s.

    if (s.contains("***")) {
        n = s.replaceAll(".[*][*][*].", "");
        s = n;
    }

    if (s.contains("**")) {
        n = s.replaceAll(".[*][*].", "");
        s = n;
    }

    if (s.contains("*")) {
        n = s.replaceAll(".[*].", "");
    }

    String theOne = n.replaceAll("\\s", ""); //Remove whitespace created by s declaration.
    return theOne;
}

My code is inefficient and repetitious, and does not account for situations of a string containing more than three * adjacent to each other. I can't help feeling like I'm missing something obvious of regex that would be a beautifully logical solution.

What would be a good solution to ensure my code utilises regex in an efficient and sensical way? Would it be more appropriate to solve this by looping through characters in the original string?


texts: Project Euler problems 1 and 2 in python

texts:
What do you think about my code? I am a beginner and just started doing some algorithmic exercises to sharpen up my python skills.

Here is code for problem #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."""

x = 0

for i in range(1000):
    if i % 3 == 0 or i % 5 == 0:
        x += i

print(x)

Problem 2:

"""Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms."""

numbers = [1, 2]
total = 0

for i in range(4000000):
    if i == numbers[-1] + numbers[-2]:
        numbers.append(i)

for n in numbers:
    if n % 2 == 0:
        total += n

print(total)

I'm sure there are better ways to solve those problems but would like to see what you think about my quite simple idea.


texts: Refactoring from if-else-if to Dictionary

texts:
I have come across the following piece of code

 if (Region.Current == Region.EU)
    {
      return RegionalPriceLN;
    }
    else if (Region.Current == Region.NY)
    {
      return RegionalPriceNY;
    }
    else if (Region.Current == Region.HK)
    {
      return RegionalPriceHK;
    }
    else if (Region.Current == Region.TK)
    {
      return RegionalPriceTK;
    }

    return null;

And want to refactor it to use a Dictionary. Was thinking of something like below:

return Map.TryGetValue(Region.Current, out func) ? func() : null;

And the dictionary being initialized like this:

 Map = new Dictionary<Region, Func<double?>>
                             {
                               {Region.EU, () => RegionalPriceLN},
                               {Region.NY, () => RegionalPriceNY},
                               {Region.HK, () => RegionalPriceHK},
                               {Region.TK, () => RegionalPriceTK}
                             };

Another approach, to optimize memory usage would be to hold a static dictionary instead of an instance one:

private static readonly Dictionary<Region, Func<TickingBasket, double?>> Map = new Dictionary<Region, Func<TickingBasket,double?>>
                             {
                               {Region.EU, t_ => t_.RegionalPriceLN},
                               {Region.NY, t_ => t_.RegionalPriceNY},
                               {Region.HK, t_ => t_.RegionalPriceHK},
                               {Region.TK, t_ => t_.RegionalPriceTK}
                             };

This would require for us to pass "this" to the delegate:

return Map.TryGetValue(Region.Current, out func) ? func(this) : null;

Can you think of a more elegant way to do this?

Regards.

UPDATE: Region is a reference type.


texts: Python rewrite the code to become more elegantly

texts:
I am new to python from R. They are quite different. I wrote a python code to deal with Excel file. The code was running well, but I think it's kind of the style of R. I want somebody to show me writing the code in python way.

The data structure looks like:

      Name     Details
1     AAA      first(100%-8)
2     BBB      first(50%-8),second(50%-8)
3     CCC      sixth(30%-8),seventh(60%-7),first(10%-7.75)
4     DDD      third(100%-6)
5     EEE      fifth(70%-7.5),second(30%-7.5)
6     FFF      first(70%-8),ninth(30%-6.75)
...   ...      ..........

As you can see, Mr.first gave Mr.AAA 8 points with 100% weights. Otherwise, in the 2nd,3rd,6th row, Mr.first gave different peoples with different scores. So the average scores that Mr.first gave is (8+8+7.75+8)/4 = 7.94, which is the average score of his group.

What I am looking for is: for the Mr.AAA, his final score is not 8 * 100%，it's
8 * (7.5/7.94)*100%, where 7.5 is a constant and 7.94 is the average score of the group of Mr.first. Similarly, for the Mr.BBB, his final score is
 8 * (7.5/7.94)*50% + 8 * (7.5/7.75)*50%. Hope you get it.

So, question is pretty simple.

My code:

#-*- coding:utf-8 -*-
import xlrd
import re
data = xlrd.open_workbook(filename)   #read the data
table = data.sheets()[0]              #read the sheet
nrows = table.nrows                   #get the number of total rows
regr = r'[\u4e00-\u9fa5a-zA-Z]+' # regular expression for CHN and ENG names
regr1 = r'[0-9]+'                # for scores and percentage
score = {}                       # The dict: {AAA:{first:[1.0,8.0]},......}
group = {}                       # The dict: {first:[8,8,7.75,8],......}

for i in range(2,nrows):
   target = table.cell(i,10).value  # the details data [first(100%-8)]
   person = table.cell(i,2).value   # the Name data    [AAA]
   c = target.split(',')            # If in details data there are more than
                                    # one person, then split them
   score[person] = {}               # set an empty dict
   for j in c:
         d = re.findall(regr,j)     # get the name
         d = "".join(d)             # transfer the list to string
         value = re.findall(regr1,j)   #get the score and percentage
         value1 = int(value[0])/100 # get the percentage
         value2 = '.'.join([x for x in value[1:]])   # get the score
         value2 = float(value2)                      # change to float
         group.setdefault(d,[]).append(value2)
         score[person].setdefault(d,[value1,value2])

#This part is for calculating the group average
for key in group:
   total = 0
   length = len(group[key])
   group[key] = [x for x in group[key]]
   for x in group[key]:
      total = total + x
   group[key] = total/length

output = {}       #set an empty dict to store output: {AAA:7.56,......}

#this part is for calculating the final score
for key in score:
   average = 0
   for subkey in score[key]:
      average = score[key][subkey][0] * score[key][subkey][1]
                *7.5/group[subkey] + average
      output[key] = average

print(output)                                       #print the output

Finally here:   For the reason of secrecy, I can not provide the raw data. But if you need, I can create the raw data. I am here, because I feeling that my code is tedious. I hope someone can help me to write it more elegantly. it's for future work.

Thanks.


texts: Thread, handler and activity structure for a bouncing ball animation

texts:
This is a custom MyActivity class with two custom views (bar and a ball):

public class MyActivity extends Activity {

    // set class variables
    RelativeLayout content;
    public Ball view;
    Bar bar;
    Handler handler;
    BounceLoop thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        content = (RelativeLayout) findViewById(R.id.content);
    }

    @Override
    public void onWindowFocusChanged(boolean hasChanged) {
        view = new Ball(this);
        bar = new Bar(this);
        Random rand = new Random();
        int min = 50;
        int max = content.getWidth();
        int randNum = rand.nextInt(max-min+1) + min;
        view.setPosition(randNum, min);
        bar.setY(content.getHeight() - 220);
        bar.setMaxWidth(content.getWidth());
        content.addView(bar);
        content.addView(view);
        thread = new BounceLoop();
        thread.start();
        handler = new Handler() {
            public void handleMessage(Message msg) {
                view.setPosition(msg.arg1,msg.arg2);
                view.invalidate();
            }
        };
    }
    @Override
    protected  void onDestroy() {
        super.onDestroy();
        content.removeAllViews();
    }
    @Override
    protected  void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    class BounceLoop extends Thread {
        public boolean running;
        int speed = 1;
        boolean reachedWidth, reachedHeight;
        int x = view.x,y = view.y, maxWidth = content.getWidth(), maxHeight = content.getHeight();
        int radius = 40;

        public void onPause() {
            running = false;
        }
        public boolean isCollision(int x, int y) {
            if( x > bar.x && x < bar.x + bar.getBarWidth()) {
                if(y >= bar.getY() - 50) {
                    return true;
                }
            }
            return false;
        }
        public void run() {

            running = true;
            Log.d("prevPos", String.valueOf(x + " : " + y));

            while(running) {
                if(reachedWidth) {
                    x -= speed;
                } else {
                    x += speed;
                }

                if(reachedHeight) {
                    y -= speed;
                } else {
                    y += speed;
                }

                if( x > maxWidth - radius) {
                    reachedWidth = true;
                } else if ( x < 0 + radius) {
                    reachedWidth = false;
                }

                if( y > maxHeight - radius || isCollision(x,y)) {
                    reachedHeight = true;
                } else if ( y < 0 + radius) {
                    reachedHeight = false;
                }
                try {
                    Thread.sleep(1);
                    Message msg = new Message();
                    msg.arg1 = x;
                    msg.arg2 = y;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

How do I re-construct it better and how can I put thread class outside? I really don't like having the thread class inside the activity class. The code seems to be working for now, but I really want to make it better! What can I do about it?


texts:
I want to convert my list of optional strings to a list of strings by getting rid of the empty Optionals.

Is there a shorter version for achieving this than the following code (except statically importing the methods of Collectors)?

List<Optional<String>> stringsMaybe = Arrays.asList(Optional.of("Hi"),
                                      Optional.empty(), Optional.of(" there!"));

List<String> strings = stringsMaybe
            .stream()
            .filter(Optional::isPresent)
            .collect(Collectors.mapping(Optional::get, Collectors.toList()));