texts: bash wrapper around 'git commit' to automatically bump (Python) package CalVer and create matching CalVer tag on new commit

texts:
I'm doing a lot of Python development lately for various (small-)data analysis pipelines at work. I've been wrestling with how to robustly and ~automatically version the code at a fine-grained level, so as to provide strong guarantees of reproducibility of a result generated from any particular version of the code, at any particular point in my development process.

I've settled on a CalVer approach. Given that I often want to have multiple versions of the code tagged within a single day, I'm using a ~nonstandard $TIMESTAMP format of YYYY.MM.DD.hhmm. (hhmmss seemed like it would be overkill.)

In any event, I want two things to happen every time I commit code to one of these data analysis repos:

Wherever relevant in the package (usually just in the main __init__.py), __version__ should be updated to $TIMESTAMP.
Once the code is committed, a tag named $TIMESTAMP should be applied to the new commit

Ancillary goals are the usual: easy to configure, minimal likelihood of breaking all the things, and minimal additional cleanup effort in common non-happy-path scenarios.

The following is a bash script I've put together for the purpose:

#! /bin/bash

export TIMESTAMP="$( date '+%Y.%m.%d.%H%M' )"
export VERPATH='.verpath'

if [ -z $VERPATH ]
then
  # Complain and exit
  echo "ERROR: Path to files with versions to update must be provided in {repo root}/.verpath"
  echo " "
  exit 1
fi

# $VERPATH must contain the paths to the files to be updated with
# the timestamped version, one per line
while read VERFILE
do
  # Cosmetic
  echo ""

  if [ -e "$VERFILE" ]
  then
    # File to be updated with version exists; update and add to commit.
    # Tempfile with old file stored in case of commit cancellation.
    echo "Updating $VERFILE"
    cp "$VERFILE" "$VERFILE.tmp"
    sed -i "s/^__version__ = .*$/__version__ = '$TIMESTAMP'/" $VERFILE
    git add "$VERFILE"

  else
    echo "$VERFILE not found!"

  fi

done < $VERPATH

# Cosmetic
echo ""

# So user can see what was updated
sleep 2s

# Actually do the commit, passing through any parameters
git commit $@

# If the commit succeeded, tag HEAD with $TIMESTAMP and delete temp file(s).
# If the commit failed, restore the prior state of the $VERFILEs.
if [ "$?" -eq "0" ]
then
  git tag -f "$TIMESTAMP"

  while read VERFILE
  do
    rm -f "$VERFILE.tmp"
  done < $VERPATH

else
  while read VERFILE
  do
    if [ -e "$VERFILE.tmp" ]
    then
      git reset HEAD "$VERFILE" > /dev/null 2>&1
      rm "$VERFILE"
      mv "$VERFILE.tmp" "$VERFILE"
    fi
  done < $VERPATH

fi

The contents of .verpath in my test repo are:

pkg/__init__.py
pkg/__dupe__.py
pkg/nofile.py

Both pkg/__init__.py and pkg/__dupe__.py exist; pkg/nofile.py does not.

I have *.tmp in my .gitignore so that the $VERFILE.tmp don't show up as untracked files when drafting the commit message.

It works like I want it to... the happy path works great, and it handles aborted commits and nonexistent .verpath files gracefully.

I'm no bash expert, though, so I'm partly concerned about subtle misbehaviors I haven't thought of. Also, I'm not super thrilled about the use of in-folder temporary files, and per here and here the while read VERFILE ... done < $VERPATH has the potential to be fragile if I don't set it up correctly.


texts:
I am a newbie trying to insert elements after the n:th element in the list. Any shorter/smarter ways?

def InsertElements(listName, var1, var2, n):

    listName.insert(n, var1)
    listName.insert(n+1, var2)
    return listName

myList = ["banana", "orange", "apple", "cherry", "grape"]

result = InsertElements(myList, "mango", "papaya", 3)


texts: A* implementation is not running efficiently but gets correct result

texts:
I'm not entirely sure what code other people will need to see, if I miss something off that is important please leave me a comment and I will update it as soon as I possibly can.

I have coded an A* algorithm following the pseudo code from Wikipedia. The problem is, from a relatively short route I am getting about 180 loops through the while loop where as from other people I've heard that they only get about 30

@Override
public RouteInfoInterface GetRoute(String[] start, String[] end, int routetype) {
    int pos = vertex.GetItem(start[0], start[1]);
    if (pos == -1) {
        return null;
    }
    Vertex pStart = vertex.data[pos];
    pos = vertex.GetItem(end[0], end[1]);
    if (pos == -1) {
        return null;
    }
    Vertex pEnd = vertex.data[pos];
    Heap openSet = new Heap();   //known nodes
    openSet.Push(pStart);                 //only start initially
    openSet.heap[1].gScore = 0;
    openSet.heap[1].fScore = heuristicFormula(pStart, pEnd); //complete heuristic guess

    while (openSet.GetLastItem() != 0) {  //THIS IS THE LOOP GETTING EXCESSIVE INVOCATIONS
        Vertex current = openSet.Pop();   //get node in openSet with lowest fScore and remove it from the openSet
        if (current == pEnd) {
            eVector route = new eVector();
            while (current.whereFrom != null) {
                route.AddItem(current.whereFrom);
                current = current.whereFrom.from;
            }
            RouteInfoInterface rI = new RouteInfo(route);
            resetData();
            return rI;
        }

        current.closed = true; //add openSet item to closedSet

        for (int i = 0; i < current.edges.length; i++) { //for each neighbour
            double d = current.gScore + (current.edges[i].distance);    //calc tenative distance
            if (d >= current.edges[i].to.gScore) {
                continue;
            }
            if (current.edges[i].to.closed) { //if neighbour in closed set skip
                continue;
            }
            if (!checkOpenSet(openSet, current.edges[i].to)) { //discovered new node?
                openSet.Push(current.edges[i].to); //add it to openSet

            }
            current.edges[i].to.whereFrom = current.edges[i];
            current.edges[i].to.gScore = d;
            current.edges[i].to.fScore = current.edges[i].to.gScore + heuristicFormula(current.edges[i].to, pEnd);
        }
        openSet.BuildMinHeap();
    }
}

A note on the Heuristic, the distance data given is in meters, I divide by 1609.34 to put it into miles as I use miles for other sections of the program that are not shown here

private double heuristicFormula(Vertex from, Vertex to) {
    double result = (Math.sqrt(Math.abs((from.x - to.x) ^ 2 + (from.y - to.y) ^ 2)) / 1609.34);
    return result;
}

My algorithm does get the right route however I am trying to make the algorithm as fast as possible. Again if theres anything else people need then please let me know.


texts: JavaScript form validation: improve on 'good, but not good enough'

texts:
I recently received a 'good, but not good enough' rating on a coding exercise I was asked to perform. It was to validate that if "Product complaint" option was selected that Product name, Product size, Use-by date and Batch code fields all needed to have values. What can I do to improve the JS to go from 'good, but not good enough' to 'great'?

JS:

document.querySelector("form").addEventListener("submit", function(e) {

  var enquiryType = document.querySelector("#enquirytype");

  if (enquiryType.value === "pc") {

      validateProductDetails();
      e.preventDefault();

  }

  });

  function validateProductDetails() {

  var requiredFields = document.querySelectorAll('[id^="product-"]'),
      requiredLabel = document.querySelectorAll('[for^="product-"]'),
      formSubmit = document.forms[0],
      requiredIsEmpty = [],
      i;

  for (i = 0; i < requiredFields.length; i += 1) {

      if (requiredFields[i].value.length === 0) {

          alert('Please enter the ' + requiredLabel[i].innerHTML + ".");
          requiredFields[i].focus();
          requiredIsEmpty.push(requiredFields[i]);
          return false;

      }

  }

  if (requiredIsEmpty.length === 0) {

      formSubmit.submit();
      return true;
  }

}

HTML:

<form action="/" method="get">

  Enquiry type
  <select name="enquiry" id="enquirytype" required>
    <option value="">Choose</option>
    <option value="ge">General enquiry</option>
    <option value="pf">Product feedback or enquiry</option>
    <option value="pc">Product complaint</option>
  </select>

  Product name
  <input type="text" id="product-name">

  Product size
  <input type="text" id="product-size">

  Use-by date
  <input type="text" id="product-use-by">

  Batch code
  <input type="text" id="product-batch">

  <input type="submit" value="Submit" id="form-submit">

 </form>


texts: Iterate through a list of data and add it to nested models

texts:
I have to go through files with metadata and I am unhappy with the iteration and how I have build it due to the fact, that I have a modeltree with lists. So basically I iterate through filesOfFolder and pick each file and then I am adding the metadata. In the else I am checking, if the fileName has the same beginning then the fileNameBefore, because then it is a child of the last file, and it needs a different documentOrderNumber.
The modeltree is like and it cannot get changed:
Mainmodel
   Documents (public MainDocumentModel[] and AttDocumentModel[])
       MainDocumentModel
           FileContent
       AttDocumentModel
           FileContent

So as of this tree I did it so and I am totally unhappy with that:
string fileNameBefore = "";
model.Documentlist = new Documents
{
    Attdocument = new AttDocumentModel[filesOfFolder.Count() + 1]
};
int i = 0;
int j = 0;
int k = 0;

string mainPath = System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/" + model.DocId + "/");
string directoryAttPath = mainPath + "Att/";
Directory.CreateDirectory(directoryAttPath);

foreach (var file in filesOfFolder)
{
    if (file.f_name.Contains("Maindocument") || file.f_name.Contains("Wrapdocument"))
    {
        FileContent fContent = new FileContent();
        fContent.FileType = "PDF";
        fContent.FileName = "Maindocument.pdf";

        MainDocumentModel mainDoc = new MainDocumentModel();
        mainDoc.MainDoc = new List<FileContent>();
        mainDoc.Message = "";
        mainDoc.Status = true;
        mainDoc.MainDoc.Add(fContent);

        model.Documentlist.Maindocument = new MainDocumentModel[1];
        model.Documentlist.Maindocument[0] = mainDoc;
        string mainDocumentPath = mainPath + fContent.FileName;
        System.IO.File.WriteAllBytes(mainDocumentPath, file.f_file);
    }
    else
    {
        if (!(fileNameBefore.Split(' ')[0] == file.f_name.Split(' ')[0]))
        {
            j = 0;
            i++;
        }
        else
        {
            j++;
        }
        FileContent attachment = new FileContent();
        string documentOrderNumber = GenerateOrderNumberForRis(i, j, fileNameBefore);
        attachment.FileName = documentOrderNumber + ".pdf";
        attachment.FileType = "PDF";

        AttDocumentModel attDoc = new AttDocumentModel();
        attDoc.AttDoc = new List<FileContent>();
        attDoc.Message = "";
        attDoc.Status = true;
        attDoc.ShowName = file.f_subject;
        attDoc.AttDoc.Add(attachment);

        model.Documentlist.Attdocument[k] = attDoc;
        System.IO.File.WriteAllBytes(directoryAttPath + documentOrderNumber + ".pdf", file.f_file);
        k++;
        fileNameBefore = file.f_name;
    }
}

Here are the models:
public class MainModel
{
    ....
    [XmlIgnore]
    public MainDocumentModel Maindocument { get; set; }

    [XmlIgnore]
    public AttDocumentModel Attdocument { get; set; }

    [XmlElement(ElementName = "documentlist")]
    public Documents Documentlist  { get; set; }
}

[XmlRoot(elementName: "maindocument")]
public class MainDocumentModel
{
    [XmlIgnore]
    public String Message { get; set; }

    [XmlIgnore]
    public Boolean Status { get; set; }

    [XmlElement("content")]
    public List<FileContent> MainDoc { get; set; }
}

[XmlRoot(elementName: "attacheddocument")]
public class AttDocumentModel
{
    [XmlIgnore]
    public String Message { get; set; }

    [XmlIgnore]
    public Boolean Status { get; set; }

    [XmlElement("showname")]
    public string ShowName { get; set; }

    [XmlElement("content")]
    public List<FileContent> AttDoc { get; set; }
}

public class FileContent
{
    [XmlElement("dataformat")]
    public string FileType { get; set; }

    [XmlElement("uri")]
    public string FileName { get; set; }
}


texts:
I am more than willing to use both a Promise library and an AJAX calls one if the situation calls for it. This base class sits at the very bare bones of my system and it needs to be done right.

My goal here was to create a bass class in JS that can be extended to help with AJAX calls using Promises. And so I did. But it has one big issue:

It doesn't really handle errors. jQuery.AJAX's error function cannot handle 500 errors and such. In my implementation, when I hit the error spot, I just reject the promise. This doesn't work.

Here's what I cooked:

class Promise_Helped_AJAX_Call {

    constructor(ajax_url, data_package, callback_object, ajax_prerequisites = {'type': 'POST', 'dataType': 'json'}) {
        this.ajax_url = ajax_url;
        this.data_package = data_package;
        this.callback_object = callback_object || undefined;

        this.ajax_prerequisites = ajax_prerequisites;
    }

    call() {
        return new Promise((resolve, reject) => {
            jQuery.ajax({
                url: this.ajax_url,
                type: this.ajax_prerequisites.type,
                dataType: this.ajax_prerequisites.dataType,
                data: {
                    action: this.data_package.ajax_action,
                    security: this.data_package.ajax_nonce,
                    [this.data_package.backend.data_handle]: JSON.stringify(this.data_package.backend.data),
                },
                success: (response) => {
                    this.data_from_response = response;
                    resolve(response);
                },

                error: (response) => {
                    this.data_from_response = response;
                    reject(response);
                }
            });
        });
    }

    ajax_success(response) {
    }

    ajax_error(response) {
    }

    get response_data() {
        if (this.data_from_response.length == 0) {
            return undefined;
        }

        return this.data_from_response;
    }

    set ajax_data_package(new_data_package) {
        this.data_package.backend.data_handle = new_data_package.data_handle;
        this.data_package.backend.data = new_data_package.data;
    }
}

The ajax_success and ajax_error are to be extended by other classes, so maybe you could push the respones to a handler or other things but my base extensions as of now does nothing:

class Base_Ajax_Requester extends Promise_Helped_AJAX_Call {
    ajax_success(response) {
    }

    ajax_error(response) {
    }
}

And my request function:

/**
 * Retrieves all registered demos' data.
 */
const getDemosData = () => {
    return new Base_Ajax_Requester(
        localized_data.ajax_url,
        {
            'ajax_action': 'demos_data_endpoint',
            'ajax_nonce': localized_data.ajax_nonce,
            'backend': {
                'data_handle': 'demos_data_endpoint_request_data',
                'data':
                    {
                    }
            }
        },
        null,
        {
            'type': 'POST',
            'dataType': 'json'
        }
    );
}

Which I'd call like: getDemosData().call().then(response =>....

This doesn't handle errors properly nor is it in any way pretty and, to me, returning a promise that can resolve eventually just...smells -- not sure if it's a just concern, just feels that way.

How can I improve this for it to at least handle errors?


texts:
I'm looking for some feedback on my first program. It's a small game you play with matches.

It's a two-player game, where the players take turns picking matches (1, 2 or 3) and cannot pick the same number of matches as the other player: if player one picks 2 matches, player two will have to pick either 1 or 3 matches. The player who cannot pick anymore matches loses the game, which means there are two end scenarios : when there are no more matches, or there is 1 but the other player picked 1 during the previous round.

Is there a more efficient way to do something (performance-wise or with less code to write)? Can I improve the overall presentation/organization of the code? (am I unaware of a convention?) Any advice or criticism is very welcome.

import java.util.Scanner ;

public class JeuDeNim2 {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in) ;

    int totalMatches ;
    do {
        System.out.println("How many matches do you want to play with? "
        + "(from 6 to 60)") ;
        totalMatches = sc.nextInt() ;
    }
    while (totalMatches < 6 || totalMatches > 60) ;

    int matchesThisTurn ;
    int matchesPreviousTurn = 0 ;
    int round = 0 ;
    int player = 0 ;
    int previousPlayer ;

    while (true) {

        round++ ;
        previousPlayer = player ;
        player = round % 2 ;
        if (player == 0) {
            player = 2 ;
        }

        while (true) {

            if (totalMatches == 1) {
                System.out.println("There is only one match left on "
                + "the table") ;
            } else {
                System.out.println("There are " + totalMatches
                + " matches on the table") ;
            }

            if (round == 1 || round == 2) {
                System.out.println("Player " + player + ": How many "
                + "matches do you want to pick? (1, 2 or 3)") ;
            } else {
                System.out.println("Player " + player + ": How many "
                + "matches do you want to pick this turn?") ;
            }

            matchesThisTurn = sc.nextInt() ;

            if (matchesThisTurn < 1 || matchesThisTurn > 3) {
                System.out.println("Wrong entry: you have to pick 1, 2 "
                + "or 3 matches") ;
                continue ;
            }
            if (matchesThisTurn == matchesPreviousTurn) {
                System.out.println("You cannot pick the same number of "
                + "matches as Player " + previousPlayer) ;
                continue ;
            }
            if (totalMatches == 1 && matchesThisTurn > totalMatches) {
                System.out.println("You cannot pick " + matchesThisTurn
                + " matches: there is only one match left") ;
                continue ;
            }
            if (matchesThisTurn > totalMatches) {
                System.out.println("You cannot pick " + matchesThisTurn
                + " matches: there are only " + totalMatches
                + " matches left") ;
                continue ;
            }
            break ;
        }

        totalMatches -= matchesThisTurn ;
        matchesPreviousTurn = matchesThisTurn ;

        if (totalMatches == 0) {
            System.out.println("*** There are no more matches! ***") ;
            break ;
        }
        if (totalMatches == 1 && matchesThisTurn == 1) {
            System.out.println("*** There is only one match left, but "
            + "Player " + player + " already took one! ***") ;
            break ;
        }
    }

    System.out.println("*** The game is over! Player " + player
    + " Wins! ***") ;
}
}


texts:
I wrote this JavaScript function to change an element tag name to a div.

function divilize(elem) {
    var elemDiv = document.createElement("div");
    var elemAttrs = elem.attributes;
    for (var attr = 0; attr < elemAttrs.length; attr++)
        elemDiv.setAttribute(elemAttrs[attr].name, elemAttrs[attr].value);
    elemDiv.className += 'divilize-'+elem.tagName.toLowerCase();
    while (elem.firstChild)
        elemDiv.appendChild(elem.firstChild);
    elem.parentNode.replaceChild(elemDiv,elem)
}

divilize(document.getElementById('one'));

Basically, it receives an element, creates a div, copies the attributes, adds in a class with the original tag name for styling purposes (I can make a .divilize-span {display: inline;}), and copies over all of the child elements. I designed with fast reusable code in mind and to avoid losing any event handlers.

Let me know your thoughts...


texts: Class for exposing information with computer properties (getters)

texts:
I need some advice on my code structure. I have read that setters and getters break one of the OOP principals, encapsulation, and that we should avoid them if possible but I cannot think of any other way to expose info other than getters.

I have a class which calculates price, savings and taxes based three inputs from the user through the initializer (initialPrice, discount and taxRate).

I'm using three computer properties to exposed the results, is this considered a bad thing? If yes, why and how can I improve my code?

Besides what I described above the class also has the ability to add all of the items in an array, assuming the instances of the CalculatorBrain were placed in an array.

Again, I'm more concern about the structure of my code. Any advice will be appreciated.

class CalculatorBrain {

        private var taxRate:Double = 0
        private var discount:Double = 0
        private var initialPrice:Double = 0

        func setInitialValues(initialPrice:Double, discount:Double, taxRate:Double){
            self.taxRate = taxRate
            self.discount = discount
            self.initialPrice = initialPrice
        }

        private func salePrice()->Double{
            return initialPrice - savings
        }

        var price:Double{
            get{
                return salePrice() + taxes
            }
        }

        var savings:Double{
            get{
                return initialPrice * discount / 100
            }
        }

        var taxes:Double{
            get{
                return salePrice() * taxRate / 100
            }
        }

        internal func grandTotals(list:Array<Item>)->(grandPrice:Double, grandSavings:Double, grandTaxes:Double){
            var grandPrice:Double = 0
            var grandSavings:Double = 0
            var grandTaxes:Double = 0

            for i in 0..<list.count {
                grandPrice = grandPrice + Double(list[i].totalPrice)
                grandSavings =  grandSavings + Double(list[i].savings)
                grandTaxes = grandTaxes + Double(list[i].taxes)
            }
            return (grandPrice, grandSavings, grandTaxes)
        }
    }


texts: Trying to Find a Loop to use for a specific MySQL query

texts:
I'm trying to see if there is a loop I can use in order to pull off this code a little more elegantly. I was previously using a foreach($row as $cell) with $row = mysqli_fetch_row($result) but because of that I couldn't access the data from the 'user' column in order to check it against the session variables in the if statment. Here's the code:

$sql = "SELECT * FROM tbl_name ORDER BY subject, description LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);

if($num_rows>0){
$field_num = $mysqli->field_count;
echo "
HERE ARE SOME RESULTS:
";
echo "
";

while($row = mysqli_fetch_array($result))
{
    echo"
";
    echo"".$row['subject']."	";
    echo"".$row['description']."	";
    echo"".$row['user']."	";
    if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
    echo"You can delete this	";
    }
    else{
    echo"Code didn't work	";
    }
    echo "
\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no results!';
}
?>

Is there a loop I can run that can also allow me to access data from each row so I don't have to print out a new line of code for each column but keep the if statement in tact? Thanks!


texts: Applicative permutation to generate knight moves

texts:
I want to understand Haskell better by trying to stretch possibilities of Functor, Applicative, and Monad as much as possible and study how they behave. So in Learn You a Haskell there's an exercise to generate all possible moves for a knight from a given position on chessboard:

moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = filter onBoard
    [(c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1)
    ,(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)
    ]
    where onBoard (c,r) = c `elem` [1..8] && r `elem` [1..8]

Now I thought to myself, wait a second, I can actually generate that list [(c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1),(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)] instead of hardcoding it. So this is how I did it with list comprehensions:

invert x
  | x == 1 = 2
  | x == 2 = 1
  | otherwise = 0

moves = [(c `f` a, r `g` (invert a)) |
         c <- [6],
         r <- [2],
         f <- [(+), (-)],
         g <- [(+), (-)],
         a <- [1, 2]]

-- generates: [(7,4),(8,3),(7,0),(8,1),(5,4),(4,3),(5,0),(4,1)]

So the above works correctly, but the code looks ugly. Because every list comprehension is equivalent to a lift, the above code could be rewritten with liftA5:

liftA5 :: Applicative g => (a -> b -> c -> d -> e -> f) -> g a -> g b -> g c -> g d -> g e -> g f
liftA5 f a b c d e = f <$> a <*> b <*> c <*> d <*> e

liftA5 (\c r f g a -> (c `f` a, r `g` (invert a))) [6] [2] [(+), (-)] [(+), (-)] [1,2]

My questions are:

Are there any way to generate the above list in a more elegant way?
How to generalize it to arbitrary possible permutations? (So that my code could parametrized and not fixed to just numbers 1 and 2, or just + and -, etc)
What intuitions, insights and lessons can I get from this exercise?

I know that this is a massively contrived situation, but they serve me as an exercise to understand the language better.


texts: Gluing pieces of scrambled text (challenge on CodeEval)

texts:
I'm trying to solve this challenge on CodeEval. Quoting:

For example, you can put pieces together and get the original text:
evil pl
vil pla
il plan
The answer is ‘evil plan’.
Your task is to print out the original text. Due to repetitions in the text, you will sometimes get identical pieces.
Your program should accept a path to a file as its first argument. Each line in the file is one test case with the pieces of shredded text separated by a pipe. Each test case starts and finishes with symbol '|'.
For example:
|deEva|lan t|to ha|evil |ankin|il-ev|o hac| to h|vil p|an to|The e|CodeE| evil|plan |hack |Eval |ack C|l ran|king.|l-evi|evil-|-evil|l pla|il pl| hack|al ra|vil-e|odeEv|he ev|n to |ck Co|eEval|nking| rank| Code|e evi|ranki|k Cod| plan|val r|
Print to stdout the original text for each test case:
The evil-evil plan to hack CodeEval ranking.
CONSTRAINTS:
For the text with the length t shredded into pieces with the length n, there are t - (n - 1) pieces of text in the input file. Each piece of text is shifted by one character. For example, the word ‘secret’ and n = 4:
secr
ecre
cret
There is only one correct answer for each test case.
The minimum number of pieces is 125, the maximum number is 975.
The minimum length of a piece of text is 8, the maximum length is 28.
The number of test cases is 20.

My algorithm produces correct output but it takes longer than maximum 10 seconds for challenge input. Can't check the input though because it is hidden.
static bool SubstringEquals(StringBuilder s1, string s2, int start1, int start2, int l)
{
    for (var i = 0; i < l; i++)
        if (s1[start1 + i] != s2[start2 + i]) return false;

    return true;
}

static int CompareFragments(StringBuilder s1, string s2, int l)
{
    if (SubstringEquals(s1, s2, 0, s2.Length - l, l)) return -1;
    if (SubstringEquals(s1, s2, s1.Length - l, 0, l)) return 1;
    return 0;
}

static string GlueFragments(List<string> a)
{
    var l = a[0].Length - 1;
    var s = new StringBuilder(a[0], a.Count + l);
    a.RemoveAt(0);

    while (a.Any())
    for (var i = a.Count - 1; i >= 0; i--)
    {
        var j = CompareFragments(s, a[i], l);
        if (j == 1) s.Append(a[i][l]);
        if (j == -1) s.Insert(0, a[i][0]);
        if (j != 0) a.RemoveAt(i);
    }

    return s.ToString();
}

static IEnumerable<string> ParseInput(string s)
{
    int l = s.IndexOf('|', 1) - 1;

    for (var i = 1; i < s.Length; i += l + 1)
        yield return s.Substring(i, l);
}

static void Main(string[] args)
{
    using (var r = File.OpenText(args[0]))
    while (!r.EndOfStream)
    {
        var a = ParseInput(r.ReadLine()).ToList();
        Console.WriteLine(GlueFragments(a));
    }

}

Any tips? Is it possible to achieve less than O(n2) complexity? Maybe there's some data structure that fits this problem perfectly I'm unaware of.


texts: Dynamically generating Strings (or other variables)

texts:
I've got a Python script which is meant to launch several other shell scripts with the appropriate setup and parameters.  I construct the file paths from other variables so that it's easier to change one setting and have it apply everywhere, rather than hardcoding everything.

So, for example:

HOME_DIRECTORY = os.path.dirname(os.path.realpath(__file__))

ONHAND_ACC_NAME = 'onhand_accuracy'
SHRINK_NAME = 'shrink'
SHELL_SCRIPT_EXTENSION = '.ksh'
CONFIG_FILE_EXTENSION = '.conf'

ONHAND_ACC_SHELL_SCRIPT = HOME_DIRECTORY + '/' + ONHAND_ACC_NAME + SHELL_SCRIPT_EXTENSION
SHRINK_SHELL_SCRIPT = HOME_DIRECTORY + '/' + SHRINK_NAME + SHELL_SCRIPT_EXTENSION
ONHAND_ACC_CONFIG_FILE = HOME_DIRECTORY + '/' + ONHAND_ACC_NAME + CONFIG_FILE_EXTENSION
SHRINK_CONFIG_FILE = HOME_DIRECTORY + '/' + SHRINK_NAME + CONFIG_FILE_EXTENSION

These are all constants defined at the top of the script.  (Feel free to tell me a more Pythonic way to do this than constants, as well.  I've heard before that "Python should have no constants at all", though I'm not sure how accurate or purist that is.)

In Java, I would do something much cleaner, like use an enum to generate appropriate file paths as needed:

public enum FileType {

    SHELL_SCRIPT   (".ksh"),
    CONFIGURATION  (".conf");

    private static final String HOME_DIRECTORY = "/path/to/scripts";
    private static final String FILE_SEPARATOR = FileSystems.getDefault().getSeparator();

    private final String extension;

    private FileType(String extension) {
        this.extension = extension;
    }

    public String getFilePath(String name) {
        return HOME_DIRECTORY + FILE_SEPARATOR + name + extension;
    }
}

Then I could simply invoke this whenever I wanted to and get a file path, rather than hardcoding them as constants, like so:

FileType.SHELL_SCRIPT.getFilePath("onhand_accuracy");

Any similar tips on how I can improve this practice/technique in Python?  I know I could have a similar function in Python that uses a lot of if/elif on a string input, but that still seems much dirtier than an enum, since the calling code can pass in whatever it wants for that string.

(In the Java, I would probably also have an enum for the associated Script, but that would clutter up my example.)


texts: How could this Java CLABE control digit calculation be enhanced

texts:
I recently wrote the following Java 1.8 snippet to generate a CLABE control digit based on the following subheading on the CLABE page on Wikipedia and I was curious on how it could be improved.

private void generateCLABEControlDigit() {
    final int[] expectedResults = {0,1,2,3,6,0,0,0,0,3,7,8,9,5,9,1,7};
    final String incompleteClabe = "03218000011835971";
    final String completeClabe = "032180000118359719";

    char[] clabeChars = incompleteClabe.toCharArray();
    int[] weightFactors = {3, 7, 1};
    int[] results = new int[clabeChars.length];
    int count = 0;

    for (int i = 0; i < incompleteClabe.length(); i++) {
        int clabeInt = Integer.parseInt(String.valueOf(clabeChars[i]));
        int weightFactor = weightFactors[count];
        int result = clabeInt * weightFactor % 10;
        results[i] = result;
        if(count == 2) {
            count = 0;
        } else {
            count++;
        }
    }

    final int controlDigit =  (10 - Arrays.stream(results).sum() % 10) % 10;

    assert Boolean.TRUE.equals(Arrays.equals(expectedResults, results));
    assert completeClabe.equals(incompleteClabe + controlDigit);
}

I have included the incomplete CLABE and complete expected CLABE, these are also present within the Wiki article.

This snippet normally takes a String value and would return an integer, this being the generated control digit. However, for purposes of the review I've simply refactored it so it can be simply lifted into a class and run along with the expected outcome (See the assert).

The CLABE comes into the system as a String, which resulted in the not so elegant one liner.

int clabeInt = Integer.parseInt(String.valueOf(clabeChars[i]));


texts:
I'm trying Rxjs 5 to simplify some Node.js nested callbacks. I need to read a directory (fs.readdir), then read stats of each file (fs.stats) and parse them if they were modified since last sync.

The following code works but I find it a bit odd and not "the rxjs way" because of the first switchMap which is too big!

const fs = require('fs');
const path = require('path');
const { Observable } = require('rxjs');

const lastSync = new Date(2017, 01, 01);
const pathToFolder = '/any/path/';

Observable.bindNodeCallback(fs.readdir)(pathToFolder)
  .switchMap((files) => {
    const array = files.map((fileName) => {
      return Observable.zip(
        Observable.of(fileName),
        Observable.bindNodeCallback(fs.stat)(path.join(pathToFolder, fileName))
      );
    });
    return Observable.concat(...array);
  })
  .filter(([fileName, stats]) => stats.mtime.getTime() > lastSync.getTime())
  .subscribe(([fileName, stats]) => parseFile(fileName));

function parseFile(fileName) { /* ... */ }

How can I improve it?


texts: Sticking to a working proxy generated by a rotating proxy script

texts:
I've created a script in python to make proxied requests by picking working proxies from a list of proxies scraped from a free proxy site. The bot traverses few links to parse the urls of the different posts from a website. The script however uses a new working proxy every time it makes a new requests as there are multiple requests to make.

At this point I've rectified the logic within my script in such a way so that the script will first check whether the existing proxy is still working in making new requests. If it is still a working proxy then the script should stick to it otherwise It will pick a random one from the list to go on.

The logic to reuse the same working proxy in multiple requests (until it is invalid) is defined within this start_script() function.

The script eventually has got a weird look. I suppose there are rooms for improvement to make it more concise and less verbose.

This is what I've created so far (working one):

import random
import requests
from random import choice
from bs4 import BeautifulSoup
from urllib.parse import urljoin

test_url = 'https://stackoverflow.com/' #It is for testing proxied requests
base_url = 'https://stackoverflow.com'
main_urls = ['https://stackoverflow.com/questions/tagged/web-scraping?sort=newest&page={}&pagesize=50'.format(page) for page in range(2,5)]
cbool = False
usable_proxy = None

def get_proxies():
    response = requests.get("https://www.sslproxies.org/")
    soup = BeautifulSoup(response.text,"lxml")
    proxies = [':'.join([item.select_one("td").text,item.select_one("td:nth-of-type(2)").text]) for item in soup.select("table.table tr") if "yes" in item.text]
    return proxies

def get_random_proxy(proxy_vault):
    while proxy_vault:
        print("trying to get one----")
        random.shuffle(proxy_vault)
        proxy_url = proxy_vault.pop()
        proxy_dict = {
            'http': proxy_url,
            'https': proxy_url
        }
        try:
            res = requests.get(test_url, proxies=proxy_dict, timeout=10)
            res.raise_for_status()
            return proxy_url
        except:
            continue

def start_script(url):
    global cbool
    global usable_proxy
    if not cbool:
        proxy = get_proxies()
        random_proxy = get_random_proxy(proxy)
        if random_proxy:
            usable_proxy = {'https': f'http://{random_proxy}'}
            urls = make_requests(url,usable_proxy)
            cbool = True
            return urls
        else:
            return start_script(url)
    else:
        urls = make_requests(url,usable_proxy)
        if urls:
            return urls
        else:
            cbool = False

def make_requests(url,proxy):
    try:
        res = requests.get(url, proxies=proxy, timeout=10)
    except Exception:
        return start_script(url)
    print("proxy used in requests:",proxy)
    if res.status_code!=200:
        return start_script(url)
    soup = BeautifulSoup(res.text, "lxml")
    return [urljoin(base_url,item.get("href")) for item in soup.select(".summary .question-hyperlink")]

if __name__ == '__main__':
    for url in main_urls:
        print(start_script(url))


texts: Proper use of a generic value type wrapper class

texts:
I have a wrapper class:

[Serializable]
// (465 references)
public class Value<T>
{
    private T value;

    [NonSerialized]
    private List<IValueListener<T>> listeners = new List<IValueListener<T>>();

    // (232 references)
    public Value(T value)
    {
        this.value = value;
    }

    // (274 references)
    public T Get()
    {
        return value;
    }

    // (18 references)
    public void Set(T value)
    {
        if (!this.value.Equals(value))
        {
            this.value = value;

            foreach (IValueListener<T> listener in listeners)
            {
                listener.ValueUpdated(this);
            }
        }
    }

    public void AddListener(IValueListener<T> listener)
    {
        listeners.Add(listener);
    }

    public void RemoveListener(IValueListener<T> listener)
    {
        listeners.Remove(listener);
    }
}

The listener interface:

public interface IValueListener<T>
{
    void ValueUpdated(Value<T> source);
}

It's used in a program that alters save files of a game. An object is constructed using the save file data and any value types encountered are wrapped in the Value class. Object is then managed by the program and the save file is rewritten from the objects data upon saving.

The listener is here since altering some data in the save file influences other, so this gives me a way to manage that on a low level (instead of making TextBoxes notify each other).

When I save the file, I actually clone the object, process the clone for saving and save the clone. That's why the class is Serializable. I don't care about listeners when saving so the list of them isn't.

My question is whether what I have done here is a well written code or should it be substituted with something else.

I also copied some of the # of references that VS displays just to demonstrate how heavily this class is used.


texts:
This is my code for a server using EAP (Sockets).

Is AsyncOperation.Post the right way to raise thread safe events?

AsyncOperation.Post states:

  Invokes a delegate on the thread or context appropriate for the application model.

Is there any other mistake in the code (i.e something that can be improved or is a bad thing to do)?

public sealed class Server
{
    private Socket _server;
    private SocketAsyncEventArgs _acceptArg;
    private AsyncOperation _asyncOperation;

    public EndPoint LocalEndPoing { get; private set; }
    public bool Listening { get; private set; }

    public delegate void ErrorOccuredEventHandler(Server sender, Exception e);

    public delegate void ClientConnectedEventHandler(Server sender, EndPoint remoteEndpoint);

    public event ErrorOccuredEventHandler ErrorOcurred;

    public event ClientConnectedEventHandler ClientConnected;

    private void OnErrorOccured(Exception e)
    {
        if(ErrorOcurred!=null)
            ErrorOcurred.Invoke(this,e);
    }

    private void OnClientConnected(EndPoint remoteEndPoint)
    {
        if(ClientConnected!=null)
            ClientConnected.Invoke(this,remoteEndPoint);
    }

    public Server(EndPoint localEndPoint)
    {
        LocalEndPoing = localEndPoint;
        Listening = false;
        _asyncOperation = AsyncOperationManager.CreateOperation(null);
    }

    public void Start()
    {
        try
        {
            if (Listening)
                return;

            _server = _server ?? new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _server.Bind(LocalEndPoing);
            _server.Listen(10);

            Listening = true;

            _acceptArg = _acceptArg ?? new SocketAsyncEventArgs();
            _acceptArg.Completed += _acceptArg_Completed;

            if (!_server.AcceptAsync(_acceptArg))
                _acceptArg_Completed(null, _acceptArg);

        }
        catch (Exception exception)
        {
            _asyncOperation.Post(ex=>OnErrorOccured(ex as Exception),exception);
        }
    }

    public void Stop()
    {
        try
        {
            if(!Listening)
                return;

            _server.Close();
            _acceptArg.Dispose();

            _server = null;
            _acceptArg = null;

            Listening = false;

        }
        catch (Exception exception)
        {
            _asyncOperation.Post(ex => OnErrorOccured(ex as Exception), exception);
        }
    }

    private void _acceptArg_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            _asyncOperation.Post(remoteEndPoint=>OnClientConnected(remoteEndPoint as EndPoint),e.AcceptSocket.RemoteEndPoint);

            //Do nasty things with the accepted socket

            e.AcceptSocket = null;

            if(!_server.AcceptAsync(e))
                _acceptArg_Completed(null,e);
        }
        else
        {
            _asyncOperation.Post(ex => OnErrorOccured(ex as Exception), new SocketException((int)e.SocketError));
            Stop();
        }
    }
}


texts: DBSCAN in C++ for general and Android use

texts:
I've implemented a templated DBSCAN for general use. At the moment, it's going to be used on Android through the JNI. I used Wikipedia's pseudocode and a little bit of the DBSCAN paper for reference. It's pretty naive, so I'm wondering how I can speed it up, and what I can do to make it perform reasonably well on a phone. How can I improve my code?

template <typename T>
    struct node {
        T val;
        bool visited;
        bool clustered;
        node() : visited(false), clustered(false) {}
    };

    template <typename T>
    using cluster = std::vector<T>;

    template <typename T>
    using adj_list = std::list<node<T>*>;

    template <typename T>
    using graph = std::map<node<T>*, adj_list<T>>;

    template <typename T>
    std::vector<cluster<T>> DBSCAN(T* const& dataset, size_t const& dataset_size, double const& eps, size_t const& min_pts, double(*distance_function)(T const& lhs, T const& rhs)) {

        std::vector<node<T>> node_list(dataset_size);
        for (auto i = 0; i < dataset_size; ++i) {
            node_list[i].val = dataset[i];
        }

        graph<T> g;
        for (auto i = 0; i < node_list.size(); ++i) {
            for (auto j = 0; j < i; ++j) {
                if (distance_function(node_list[i].val, node_list[j].val) < eps) {
                    g[&node_list[i]].push_back(&node_list[j]);
                    g[&node_list[j]].push_back(&node_list[i]);
                }
            }
        }

        std::vector<cluster<T>> clusters;
        cluster<T> C;
        for (node<T>& n : node_list) {
            if (n.visited) continue;
            n.visited = true;
            adj_list<T> neighbour_pts = g[&n];
            if (neighbour_pts.size() >= min_pts) {
                expandCluster(n, neighbour_pts, C, g, min_pts);
                clusters.push_back(C);
                C = cluster<T>();
            }
        }

        return clusters;
    }

    template <typename T>
    void expandCluster(node<T>& point, adj_list<T>& neighbourhood, cluster<T>& C, graph<T>& g, unsigned const& min_pts) {
        C.push_back(point.val);
        point.clustered = true;
        for (node<T>*& n : neighbourhood) {
            if (!n->visited) {
                n->visited = true;
                adj_list<T> next_neighbourhood = g[n];
                if (next_neighbourhood.size() >= min_pts) neighbourhood.splice(neighbourhood.end(), next_neighbourhood);
            }
            if (!n->clustered) {
                C.push_back(n->val);
                n->clustered = true;
            }
        }
    }


texts:
I'm creating an app in C++ designed to run an experiment. The model I created is here:

#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include <filesystem>

namespace Experiment {
    enum Option { None = 0, Left = 1, Right = 2 };
    enum Mode { Stereo = 0, Mono_Left = 1, Mono_Right = 2 };

    struct Vector
    {
        int x = 0, y = 0;

        friend std::ostream& operator<<(std::ostream& os, const Vector& v);
    };

    struct Trial
    {
        std::string imageName = "";
        Option correctOption = Option::None;

        Vector position = {};
        Mode mode = Mode::Stereo;

        Option participantResponse = None;
        double duration = 0.0;

        friend std::ostream& operator<<(std::ostream& os, const Trial& t);
    };

    struct Run
    {
        std::string id = "";
        std::string folderPath = "";

        float flickerRate = 0.1f;
        int timeOut = 8;

        int distance = 500;
        Vector dimensions = {1200, 1000};

        std::vector<Trial> trials = {};

        static Run CreateRun(const std::filesystem::path& configPath);
        void Export(const std::filesystem::path& path) const;

        friend std::ostream& operator<<(std::ostream& os, const Run& r);
    };

    std::ostream& operator<<(std::ostream& os, const Vector& v);
    std::ostream& operator<<(std::ostream& os, const Trial& t);
    std::ostream& operator<<(std::ostream& os, const Run& r);

    void from_json(const nlohmann::json& j, Vector& v);
    void from_json(const nlohmann::json& j, Trial& t);
    void from_json(const nlohmann::json& j, Run& r);

}

Each unique Run is created for every unique participant. The parameters are controlled via an external json configuration file. Each Run contains a vector of Trials, which is a single question with its own parameters.

I also have a basic Vector class to model the position parameter of the Trial, as well as enums for both Option and Mode.

I'm fairly new to C++, so I was mainly wondering if my operator<< and from_json functions are standard, as well as my use of the friend tag. Any other suggestions are also very welcome.


texts: Find the lengths of strongly connected components in a graph

texts:
I wrote a code to calculate the lengths of strongly connected components in a graph. The results I get are correct but it scales horribly.

This is the code I have. I understand that the runtime complexity of a graph traversals should be O(V+E) and as far as I understand, I am not visiting any node twice. And yet it takes forever for bigger graphs (875714 nodes and 5105043 edges)

class Graph:
    def __init__(self):
        self.graph = {}
        self.rev_graph = {}
        self.num_vertices = 0
    def addEdge(self, tail, head):
        if tail in self.graph:
            self.graph[tail].append(head)
        else:
            self.graph[tail]=[head]
        if head in self.rev_graph:
            self.rev_graph[head].append(tail)
        else:
            self.rev_graph[head] = [tail]
    def dfs(self, visited, start_node, stack):
        visited[start_node] = True
        if start_node in self.graph:
            for i in self.graph[start_node]:
                if not visited[i]:
                    self.dfs(visited, i, stack)
            # del self.rev_graph[start_node]
        stack.append(start_node)
    def dfs_counter(self, visited, start_node, delim='  '):
        l1 = sum(visited)
        visited[start_node] = True
        if start_node in self.rev_graph:
            # print(delim, 'rev graph neighbors: ', start_node, self.rev_graph[start_node])
            for i in self.rev_graph[start_node]:
                if not visited[i]:
                    self.dfs_counter(visited, i, 2*delim)
        l2 = sum(visited)
        return l2 - l1
        # print(stack)
    def find_scc_lens(self):
        self.num_vertices = len(set(list(self.graph.keys()) + list(self.rev_graph.keys())))
        visited = [False]*self.num_vertices
        stack = []
        self.dfs(visited, 0, stack)
        # stack = stack[::-1]
        # print(stack)
        # del(self.graph)
        visited = [False] * self.num_vertices
        scc_lengths = []
        for k,i in enumerate(stack[::-1]):
            if not visited[i]:
                # print("rev graph node count", k, i)
                scc_lengths.append(self.dfs_counter(visited, i))
        return scc_lengths

This exercise is from an online course I am taking. I tried a few other solutions online I found elsewhere and they are really fast compared to my runtimes.

What parts of the code can I optimize to improve the runtimes?

Example:

g = Graph()
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(3, 4);
g.find_scc_lens()


texts:
I have to set up a new JavaScript library for a big project, which isn't Object Oriented yet. So I built a small file to test some needs. The result is the following:

var Module =
{
    Config: (function()
    {
        //- private members
        var _systemName =   'mySystem',
            _version    =   '1.1.4';

        //- private methods
        //...

        //- public methods
        var api =
        {
            getSystemInfo: function()
            {
                return "system: '"+_systemName+"' @ version "+_version;
            }
        };

        return api;
    })(),

    Dialog:
    {
        _: (function(){
            $(document).ready(function()
            {
                $('.showDialog').on('click',function()
                {
                    var obj = {
                        element:    this,
                        foo:        'foo',
                        bar:        'bar',
                        target:     $('#title')
                    };

                    Module.Dialog.setParam(obj);
                    Module.Dialog.show();
                })
            });
        })(),

        setParam: function(config)
        {
            console.log('config set for dialog box');
            console.log(config);
        },

        show: function()
        {
            console.log('dialogbox show | '+Module.Config.getSystemInfo());
        },

        close: function()
        {
            console.log('dialogbox close');
        }
    },

    Savescreen:
    {
        setParam: function(config,foo)
        {
            console.log('config set for savescreen');
        },

        show: function()
        {
            console.log('savescreen show | '+Module.Config.getSystemInfo());
        }
    }
}

Goals:

access via Module.Object.Function()
no instantiation via keyword new
private members and methods (in config section or event-listner)
easy structured and object orientated
each section must have its own scope (section = savescreen, config,
dialogbox, etc)
each section should hold its event-listner


texts: A ViewModel using ReactiveUI 6 that loads and sends data

texts:
Most of the Rx Compelling Examples™ load and store data locally, which I don't find that Compelling.

I spent some time coming up with how to best perform the following actions but want to make sure I am not Doing It Wrong™.

Here are the cases I am trying to solve:

Load data from cache and remote server when view model is instantiated
Save data to server when UI interaction happens (some button press)
Handle error cases (network down)

Some items I am trying to avoid:

Errors being swallowed (async in ctor for example)
Incorrect use of Rx patterns (is there a more 'correct' way)
Loss of data either through out of sync lists, not using cache correct, other.

public class CommonViewModel : ReactiveObject, IRoutableViewModel
{
    private readonly RemoteHttpService _remoteClient;

    private ReactiveList<Item> _items;
    public ReactiveList<Item> ItemsFromServer
    {
        get { return _items; }
        set { this.RaiseAndSetIfChanged(ref _items, value); }
    }

    public ReactiveCommand<List<Item>> LoadItems{ get; protected set; }
    public ReactiveCommand<object> SendItemsToServerCommand { get; protected set; }

    public string UrlPathSegment
    {
       get { return "CommonViewModel View"; }
    }

    public IScreen HostScreen { get; private set; }

    public CommonViewModel(IScreen screen)
    {
        HostScreen = screen;
        ItemsFromServer = new ReactiveList<Item>();
        _remoteClient = new RemoteHttpService(); //using refit and polly behind the scenes.

        SendItemsToServerCommand = ReactiveCommand.CreateAsyncTask((_, ctx) => InternalSendItemsToServer());
        SendItemsToServerCommand.ThrownExceptions.Subscribe(ex => UserError.Throw("Could not send data to server", ex));

        LoadItems = ReactiveCommand.CreateAsyncObservable(_ =>     this.InternalGetItemsFromCacheAndServer());
        LoadItems.Subscribe(list =>
        {
             _items.Clear();
            foreach (var item in list){
                 //using AddRange throw Presentation Exception
                _items.Add(item);
            }
         });
        LoadItems.ThrownExceptions.Subscribe(ex => UserError.Throw("Could not get data from server"));
        LoadItems.ExecuteAsyncTask();
    }

    private IObservable<List<Item>> InternalGetItemsFromCacheAndServer()
    {
        return BlobCache.LocalMachine.GetAndFetchLatest("items",
        InternalGetRemoteItems,
        dt => true,
        RxApp.MainThreadScheduler.Now + TimeSpan.FromMinutes(5));
    }

    private async Task<List<Item>> InternalGetRemoteItems()
    {
        var conferences = await _remoteClient.GetItems().ConfigureAwait(false);
        return conferences;
    }

    private async Task<object> InternalSendItemsToServer()
    {
        var itemsToSendToServer = ItemsFromServer.SomeLinq().Maybe();
        return await _remoteClient.SendDataToServer(itemsToSendToServer);
    }
}


texts:
I have picked up a problem from Codility website and tried to work it out.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

Write a function:

class Solution { public int solution(int N); }

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

I would appreciate guidance of how to refactor it and what to look for in terms of efficiency?

Optimisation I'd like to achieve would be, less type conversion, no zero items in the list, would there be a better way to find the max number in a list, or .Sort(); is good enough?

Any ideas welcome, thank you.

using System;
using System.Collections.Generic;

namespace rec
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(FindGap(777)); //
        }

        public static int FindGap(int number)
        {
            string toBinary = Convert.ToString(number, 2);

            char[] toChar = toBinary.ToCharArray();

            string previous = "";
            string current = "";
            int count = 0;
            int answer = 0;
            List<int> lastGap = new List<int>();

            for (int i = 0; i < toChar.Length; i++)
            {
                if (toChar[i].ToString() == "1")
                {
                    // temp becomes 1
                    current = toChar[i].ToString();

                    if (current == "1")
                    {
                        lastGap.Add(count);
                        count = 0;
                        continue;
                    }
                }
                if (toChar[i].ToString() == "0" && current == "1")
                {
                    current = "0";

                    count++;

                    previous = current;
                }
                else if (toChar[i].ToString() == "0" && previous == "0")
                {
                    current = "0";
                    count++;
                    previous = current;
                }
            }
            lastGap.Sort();
            answer = lastGap.Last();

            if (answer > 1)
            {
                return answer;
            }
            else return 0;
        }
    }
}


texts:
This is a console application that generates the factorial of a given number. Is there any way I can improve my code ?

        int number = Convert.ToInt32(Console.ReadLine());
        int digitFactorial = number;
        for (int counter = number - 1; counter > 0; counter--)
        {
            digitFactorial *= counter;
        }
        Console.WriteLine(digitFactorial);
        Console.ReadLine();


texts: Prettifying URLs for a PHP-based club website

texts:
I have a website for my car enthusiast club ("example.org") whose content can be divided into three main sections: Startseite (the "front page" of the site), Mitglieder (membership directory), and Vereinsinfos ("about us").  For each section, the content is handled by a corresponding PHP script: /home.php, /mitglieder.php, and /verein.php.

I'd like to prettify the URLs to eliminate the .php extensions, so that the URLs look like

http://example.org/home (maps to /home.php)
http://example.org/home/ (also maps to /home.php)
http://example.org/home/1 (maps to /home.php with a data=1 query string)

After reading all documentation, I formed my .htaccess like this (repeated for the mitglieder and verein sections):

RewriteRule ^home\/$ /home.php [L]
RewriteRule ^home$ /home/ [L]
RewriteRule ^home\/([^/]*)$ /home.php?data=$1 [L]

This works, but I can't figure out how to improve it further after reading all the documentation on the Internet.  (I have difficulty understanding regular expressions.)

In addition to the content above, I also have static resources under /images/, /js/, /css/, etc. which should be left alone.


texts: Evaluation of insert method from within a class using PDO

texts:
I am learning PDO. I have a class -  User...

class User {
    protected static $table_name="users";
    public $id;
    public $first_name;
    public $last_name;

    public function pdo_create() {
        global $handler;
        $sql = " INSERT INTO users (first_name, last_name)";
        $sql .= " VALUES (?, ?)";
        $query = $handler->prepare($sql);;
        $query->execute(array($this->first_name ,$this->last_name));
    }
}

When I run this...

$user= new User();
$user->first_name = "test";
$user->last_name = "test";
$user->pdo_create();

It works fine. I know it's a bit odd posting when things are working, but I have suspicions that this is not the best approach. I am still learning PDO and about the convert my MySQLi site over to PDO. I want to make sure the PDO veterans think this is a reasonable approach.


texts: Using Func instead of helper methods in a class

texts:
I really like functional programming in C#, it gives you a lot of flexibility.
I am wondering if it is the right idea to use functions instead of helper methods, and to make the code more readable.

So here is what I want, I have a method that needs to find Saturday and do something with it:

public void SomeMethod()
{
    var saturday = DateTime.Today;
    while (saturday.DayOfWeek != DayOfWeek.Saturday)
            saturday = saturday.AddDays(-1);

    //rest of the code
}

The problem I am having with this code is readability. I have to scan through 3 lines of code to understand that it needs to find Saturday. Plus seeing var saturday = DateTime.Today;, it really bugs my eyes.

Of course I can write a helper method

private DateTime GetSaturday()
{
    var saturday = DateTime.Today;
    while (saturday.DayOfWeek != DayOfWeek.Saturday)
            saturday = saturday.AddDays(-1);
    return saturday;
}

Now I know exactly what the method does but my problem now is that I know that I won't be calling this method anywhere in the class so it kind of pollutes my class.

So here we are at my favorite:

public void SomeMethod()
{
    Func<DateTime> GetSaturdayFunc = () =>
        {
            var date = DateTime.Today;
            while (date.DayOfWeek != DayOfWeek.Saturday)
                date = date.AddDays(-1);
            return date;
        };

   var saturday = GetSaturdayFunc();
   //rest of the code
}

Although it's a bit more code now my class is not polluted with a lot of utility methods and it is more readable.

What do you think? Is this a good way, are there any better ways?

EDIT

I could also create an extension method which in this case would be appropriate, something like

DateTime.Saturday()

but that's not what I am referring to in my question. I am asking if it is a good practice to wrap a portion of the code as a function inside that method (since that peace of the code will only be used inside that method and might not apply anywhere else), just for readability purposes.


texts:
Moved from Programmers.SE.

I have written a new version of the PBKDF2 algorithm in Haskell. It passes all of the HMAC-SHA-1 test vectors listed in RFC 6070, but it is not very efficient. How can I improve the code? I plan to upload it to Github (and maybe Hackage) once it is improved.

{-# LANGUAGE BangPatterns #-}
{- Copyright 2013, G. Ralph Kuntz, MD. All rights reserved. LGPL License. -}

module Crypto where

import Codec.Utils (Octet)
import qualified Data.Binary as B (encode)
import Data.Bits (xor)
import qualified Data.ByteString.Lazy.Char8 as C (pack)
import qualified Data.ByteString.Lazy as L (unpack)
import Data.List (foldl')
import Data.HMAC (hmac_sha1)
import Text.Bytedump (dumpRaw)

-- Calculate the PBKDF2 as a hexadecimal string
pbkdf2
  :: ([Octet] -> [Octet] -> [Octet])  -- pseudo random function (HMAC)
  -> Int  -- hash length in bytes
  -> String  -- password
  -> String  -- salt
  -> Int  -- iterations
  -> Int  -- derived key length in bytes
  -> String
pbkdf2 prf hashLength password salt iterations keyLength =
  let
    passwordOctets = stringToOctets password
    saltOctets = stringToOctets salt
    totalBlocks =
      ceiling $ (fromIntegral keyLength :: Double) / fromIntegral hashLength
    blockIterator message acc =
      foldl' (\(a, m) _ ->
        let !m' = prf passwordOctets m
        in (zipWith xor a m', m')) (acc, message) [1..iterations]
  in
    dumpRaw $ take keyLength $ foldl' (\acc block ->
      acc ++ fst (blockIterator (saltOctets ++ intToOctets block)
                      (replicate hashLength 0))) [] [1..totalBlocks]
  where
    intToOctets :: Int -> [Octet]
    intToOctets i =
      let a = L.unpack . B.encode $ i
      in drop (length a - 4) a

    stringToOctets :: String -> [Octet]
    stringToOctets = L.unpack . C.pack

-- Calculate the PBKDF2 as a hexadecimal string using HMAC and SHA-1
pbkdf2HmacSha1
  :: String  -- password
  -> String  -- salt
  -> Int  -- iterations
  -> Int  -- derived key length in bytes
  -> String
pbkdf2HmacSha1 =
  pbkdf2 hmac_sha1 20


texts:
This is very artificial problem
Each sock has exactly 1 match.
Can only take one random sock out of the Laundry basket.
Can only compare to the last random sock.
If it matches you put the match aside.
It is like you have a stack of socks and you can only match on the top sock.
So if the match is down the sock pile you are not going to find a match.
But you don't even get to look down the sock pile to even know if the match is in the sock pile. You only get to match to the top sock.
You will eventually need to put the sock pile back in the Laundry basket.
You can throw the unmatched socks back in the Landry basket at any time but they come out random

On CS there is a guy telling me he has a better algorithm but he cheats and searches the sock pile for a match down the pile.

public static void MatchSocks()
{
    Random rand = new Random();
    List<int> Laundry = new List<int>();
    List<int> Matched = new List<int>();
    List<int> Unmatched = new List<int>();
    int? LastUnmatched = null;
    int Sock;
    int count = 0;
    for (int i = 0; i < 500; i++)
    {
        Laundry.Add(i);
        Laundry.Add(i);
    }
    while (true)
    {
        count++;
        if(Laundry.Count == 0)
        {
            if (Unmatched.Count == 0)
                break;
            Laundry = new List<int>(Unmatched);
            Unmatched.Clear();
            LastUnmatched = null;
        }
        Sock = Laundry.ElementAt(rand.Next(Laundry.Count));
        Laundry.Remove(Sock);
        if (LastUnmatched == null)
        {
            Unmatched.Add(Sock);
        }
        else
        {
            if (Sock == LastUnmatched)
            {
                Matched.Add(Sock);
                Unmatched.Remove(Sock);
            }
            else
            {
                Unmatched.Add(Sock);
            }
        }
        LastUnmatched = Sock;
    }
    Debug.WriteLine(count);
}


texts: Eval is evil: Dynamic method calls from named regex groups in Python 3

texts:
I'm working on a simple dice roller for a Python IRC bot. The particular game this roller is for uses six different kinds of dice, which I've defined using a simple base class, and created six instances of it, passing a string array with the possible values of each dice.

class DiceBag(object):
    def __init__(self, dice: List[str]):
        self.bag = dice

    def draw(self, count: int) -> str:
        return [random.choice(self.bag) for _ in range(0, count)]

An example of the instances:

proficiency_dice = DiceBag(['', 'S', 'S', 'SS', 'SS', 'A', 'AS', 'AS', 'AS', 'AA', 'AA', '!'])
boost_dice = DiceBag(['', '', 'AA', 'A', 'SA', 'S'])

Now for a user to actually access this function, they must write a textual dice expression in the IRC channel. An example usage:

<user> ?roll 2p1b
<bot>  Result:  P(A, AA)  B(S)

So I need a way to quickly convert from the dice expression provided by the user, to call the draw method on the appropriate class.

I'm using a regular expression to evaluate the dice expression, so named capture groups seem like the most straightforward way to handle this - at the possible cost of my immortal soul, since I'm eval-ing the group name to the proper instance of DiceBag.

#User's input comes in as a string on the dice var
rex = (r'(?P<setback>\ds)?'
       r'(?P<ability>\da)?'
       r'(?P<difficulty>\dd)?'
       r'(?P<proficiency>\dp)?')

to_roll = re.match(rex, dice).groups()
    for group in to_roll:
        if group:  # We don't care about the Nones
            dicetype = group.split('')[1]
            dicecnt = group.split('')[0] # handle the extra rolls later
            eval(dicetype + "_dice" + ".draw(" + dicecnt + ")")

Is there a better, or saner, or more pythonic, or perhaps less evil way I could be handling this use case?


texts:
I have two jQuery Ajax callbacks in succession, to fetch two sets of data from two different URLs, before combining them.

    $.ajax({
      type: "GET",
      url: numeratorUrl,
      error: function(request, status, error) {
        _this.showErrorMessage(request.status, error);
      },
      success: function(data) {
        parse(data,
             {columns: true },
             function(err, output){
                _this.globalOptions.data.numeratorData = output;
                $.ajax({
                  type: "GET",
                  url: denominatorUrl,
                  error: function(request, status, error) {
                    _this.showErrorMessage(request.status, error);
                  },
                  success: function(data) {
                    parse(data,
                         {columns: true },
                         function(err, newOutput){
                            _this.globalOptions.data.denominatorData = newOutput;
                            // combine the two datasets here
                         }
                    );
                  }
                });
             }
        );
      }
    });

It works fine, but I think it's unwieldy and hard to read. Is there a way to make it cleaner?


texts:
My code has mutiple checks for if staments which I think could be optimized into few lines if I take id into varibable. To give some background I want to disable a button based on length of characters in input box. But the thing is out of two buttons only one will be rendered at a time.
Below is my working version of code which I am hoping to optimize.

  var sortcodeError = document.getElementById("sortcodeError")
         var accountnameError = document.getElementById("accountnameError")
          if (sortcodeError != null) {
                  document.getElementById("sortcodeError").disabled = false;
               }
               if (accountnameError != null) {
                  document.getElementById("accountnameError").disabled = false;
               }
         if ($scope.data.branchTransitNumber && $scope.data.depositAccountNumber) {
            if ($scope.data.branchTransitNumber.length < 6) {
               if (sortcodeError != null) {
                  document.getElementById("sortcodeError").disabled = true;
               }
               if (accountnameError != null) {
                  document.getElementById("accountnameError").disabled = true;
               }

            }
            if ($scope.data.depositAccountNumber.length < 8) {
               if (sortcodeError != null) {
                  document.getElementById("sortcodeError").disabled = true;
               }
               if (accountnameError != null) {
                  document.getElementById("accountnameError").disabled = true;
                  // angular.element($('#btnSubmi')).addClass("gray");
               }

            }
         }

My initial thought is if I could take id as varibale but then I don't think it is the best way


texts:
I am learning Python online on Stepik platform, and unfortunately I don't have any opportunity to get reviews from the tutor. The platform only checks the correctness of the answer that my program gives. So I decided to share the code here. Comments and corrections would be much appreciated.

  Write a program that print multiplication table
  fragment for all numbers in the interval [a; b] for all of the
  interval [c; d]

def print_mult_table(a, b, c, d):
    """
    Print multiplication table fragment for all numbers in the interval
    [:param a; :param b] for all of the interval [:param c; :param d]
    """
    m = list(list([i] + list(range(c * i, (d + 1) * i, i))) for i in ([1] + list(range(a, b + 1))))
    m[0][0] = ""    # This is done, because it is the desired output format
    max_width = len(str(m[-1][-1])) + 1
    for i in m:
        i = [str(j).rjust(max_width) for j in i]
        print('\t'.join(i))


texts: Testing input integers for the palindrome property

texts:
3.23 Palindromes

  A palindrome is a number that reads the same forwards
  and backwards, like 12321. Write a
  program that tests input integers for
  the palindrome property.

  Hint: This should not be done with the numbers in
  their input (character) format.

For the task above, I have written the following program.  Rather than converting the number to a string, I recursively divide the number to create a list of individual digits and then compare the digits from outside to in to determine if it's a palindrome.  What do you think of my strategy and of my code in general?  I understand that tail recursion is not guaranteed to work in Common Lisp - should I rewrite this code to use loops instead?

(defun collect-digits (candidate &OPTIONAL (digit-list ()))
  ; make a list out of the digits of the number
  ; example: (= (collect-digits 12321) (1 2 3 2 1)) is true
  (if (< candidate 10)
    (cons candidate digit-list)
    (multiple-value-call
      (lambda (sub-candidate onesdigit)
        (collect-digits sub-candidate (cons onesdigit digit-list)))
      (floor candidate 10))))

(defun reflection-p (candidate-list &OPTIONAL (len (length candidate-list)))
  ; if c-l[first] = c-l[last]
  (and (= (car candidate-list) (car (last candidate-list 1)))
       ; and the list is 3 or smaller ex. (3 1 3), it is a reflection
       (if (<= len 3) t
     ; if longer, keep looking
     (reflection-p (subseq candidate-list 1 (1- len)) (- len 2)))))

(defun palindrome-p (candidate)
    (reflection-p (collect-digits candidate)))

(format t "12321: ~a ~%3456789 ~a ~%" (palindrome-p 12321) (palindrome-p 3456789))


texts:
Requirements (Installed using Scoop)

scoop install nasm dosbox

Build (Using NASM)

nasm -g tasks.asm -o tasks.com

  -g enables debugging capabilities

Execute (Using DOSBox)

mount H: C:\com\parent\path
H:
tasks.com

tasks.asm

Sections are added for clarity.

[org 100h]

section .text

main:
    lea     si, [task_a]
    call    spawn_new_task

    lea     si, [task_b]
    call    spawn_new_task

.loop_forever:
    lea     si, [main_str]
    call    putstring
    call    yield
    jmp     .loop_forever

task_a:
.loop_forever:
    lea     si, [main_a]
    call    putstring
    call    yield
    jmp     .loop_forever

task_b:
.loop_forever:
    lea     si, [main_b]
    call    putstring
    call    yield
    jmp     .loop_forever

spawn_new_task:
    ; find a free task, start pointers off at -1
    xor     cx, cx
    lea     bx, [stack_status]
.loop:
    cmp     cx, 3                 ; change this to add more tasks
    jl      .continue
    ret                           ; no free task, return immediately
.continue:
    cmp     byte [bx], 0
    je      .done                 ; if equal, tasks is free
    inc     cx
    inc     bx
    jmp     .loop
.done:
    mov     byte [bx], 1          ; task was free, reserve it

    lea     bx, [stack_pointers]
    mov     [bx], sp              ; save main's stack pointer
                                  ; switch to free stack
    add     bx, cx
    add     bx, cx                ; free stack is list of words (not bytes) and add is cheaper than mul
    mov     sp, [bx]              ; change to free stack
    push    si                    ; push stuff
    pusha
    pushf
    mov     [bx], sp              ; save new stack's new pointer
    mov     sp, [stack_pointers]  ; change back to main
    ret

yield:
    ; ret already saved by call
    pusha
    pushf
    movzx   cx, byte [current_task]
    ; save current stack pointer
    lea     bx, [stack_pointers]
    add     bx, cx
    add     bx, cx
    mov     [bx], sp
    ; loop through stack status looking for a 1
    lea     bx, [stack_status]
    add     bx, cx                ; make sure we start looking at next task
.loop:
    inc     bx
    inc     cx
    cmp     cx, 3                 ; increment this for more tasks
    jl      .continue
    xor     cx, cx                ; clear cx
    lea     bx, [stack_status]    ; reset bx back to start
.continue:
    cmp     byte [bx], 1          ; is this stack active
    je      .found_one
    jmp     .loop
.found_one:
    mov     [current_task], cl
    ; switch to new stack
    lea     bx, [stack_pointers]
    add     bx, cx
    add     bx, cx
    mov     sp, [bx]
    popf
    popa
    ret

    ; takes an address to write to in si
    ; writes to address until a null term is encountered
    ; returns nothing
putstring:
    mov     ah, 0Eh
.continue:
    lodsb                         ; put char to write in al
    test    al, al                ; simulate and
    je      .done                 ; was al 0?
    int     10h                   ; call interrupt
    jmp     putstring
.done:
    ret

section .rdata

    main_str: db "I am task main", 13, 10, 0
    main_a: db "I am task a", 13, 10, 0
    main_b: db "I am task b", 13, 10, 0

section .data

    current_task: db 0

    stack_status:
    status_1: db 1                ; this is for Main
    status_2: db 0
    status_3: db 0

    stacks: times 256 * 2 db 0

    stack_pointers:
    dw 0                          ; this is for Main
    dw stacks + 256
    dw stacks + 512


texts: C++ member function wrapper for interfacing with C APIs

texts:
Some C API interfaces use callbacks. Often these callbacks have a user-defined parameter of type void * which can be used as a class instance pointer in C++. Usually in order to call the member function you need to write a static class function which would cast the void * parameter to an instance pointer and call the member function. I wanted to write a wrapper that would instantiate a static function which takes void * as a parameter and the rest of arguments is exactly like in the member function passed to wrapper.

template<
    typename Result,
    typename Function,
    auto Func
>
struct instance_call_helper;

template<
    typename Result,
    typename Base,
    typename... Args,
    auto Func
>
struct instance_call_helper<
    Result,
    Result(Base::*)(Args...),
    Func
> {
    static Result call(void * ref, Args ... args) {
        Base * instance = reinterpret_cast<Base *>(ref);
        return (instance->*Func)(std::forward<Args>(args)...);
    }
};

template <
    typename Base
> struct instance_type_helper;
template <
    typename Result, typename Base, typename... Args
>
struct instance_type_helper<Result(Base::*)(Args...)> {
    using result_t = Result;
};

template<auto Func>
#if __cpp_concepts >= 201507
requires std::is_member_function_pointer<decltype(Func)>::value
#endif
class instance_call {
    using functor_t = decltype(Func);
    using type_helper = instance_type_helper<functor_t>;

public:
    using helper = instance_call_helper<
        typename type_helper::result_t,
        functor_t,
        Func
    >;
};

Intended usage:

class Bar {
private:
    int m_a1;

public:
    Bar(int a1):
        m_a1(a1) {}

    int baz(int a2) {
        return m_a1 + a2;
    }
};

int foo() {
    Bar b { 3 };
    // Pointer we are going to pass somewhere as a callback
    // f has signature int (*)(void*, int)
    auto * f = &instance_call<&Bar::baz>::helper::call;
    // Intended way of calling it — returns 5
    return f(&b, 2);
}


texts: Create a two-dimensional Gaussian kernel

texts:
In my code I have a function that generate a 2D gaussian function given sigma like so:

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>
int main(int argc, char* argv[])
{
  cv::Mat kernel = getGaussianKernel(rows, cols, 50, 50 );
  //Then I use that kernel for some processing

  //return 0;
}
cv::Mat getGaussianKernel(int rows, int cols, double sigmax, double sigmay )
    {
        cv::Mat kernel = cv::Mat::zeros(rows, cols, CV_32FC1);

        float meanj = (kernel.rows-1)/2,
              meani = (kernel.cols-1)/2,
              sum = 0,
              temp= 0;

        int sigma=2*sigmay*sigmax;
        for(unsigned j=0;j<kernel.rows;j++)
            for(unsigned i=0;i<kernel.cols;i++)
            {
                temp = exp( -((j-meanj)*(j-meanj) + (i-meani)*(i-meani))  / (sigma));
                if (temp > eps)
                    kernel.at<float>(j,i) = temp;

                sum += kernel.at<float>(j,i);
            }

        if(sum != 0)
            return kernel /= sum;
        else return cv::Mat();
    }

That function takes, after profiling, ~14% of my time and sigma parameter for most of the cases is constant, also rows and cols don't change because I'm using a camera and its resolution won't change.

I want to know if there is a way to use that kernel without wasting 14% of the time or to optimize its function?

I tried to save all the data generated in a file (.yml .txt 13mb) and read them but it takes the same time or little bit more


texts:
I need to pass some int32_t values into and later retrieve them from a local storage API that uses void* and size_t parameters. Nothing else interprets the void* values.

I hand-made some simple functions to translate back and forth between the types, which work, but I wonder if anyone would care to let me know if they see any problems, weaknesses or improvements I should make.

int32_t Char4ToInt(char* pChar4)
{
    return (pChar4[3] << 24) | (pChar4[2] << 16) | (pChar4[1] << 8) | (pChar4[0]);
}

void StuffIntIntoChar4(char* pIntoChar4, int32_t val)
{
    pIntoChar4[3] = val>>24;
    pIntoChar4[2] = val>>16;
    pIntoChar4[1] = val>>8;
    pIntoChar4[0] = val;
}

If they were for more general use, I'd probably check the char* parameters for errors, but I only use them where they are passed

char valBuf[4];

as valBuf, so I know it always points to 4 allocated chars.

The API I am doing this for is s3eSecureStoragePut and s3eSecureStorageGet from the Marmalade API - the documentation doesn't go into great detail about guarantees, but it seems to work to store and retrieve a blob of bytes of the supplied size. This is a smartphone App and I just save my blob before exit and load it on entry, copying the data over if there is no error, otherwise using default data. The data just goes into UI controls (in this case, slider position values). However if there are weaknesses in using these functions more broadly, I'd be interested in any suggestions, as I might end up using them (or whatever gets pointed out as better) for some later project if they seem reasonable.


texts: Repeatedly multiplying digits until a single digit is obtained

texts:
I've written code that solves a problem from codewars.com. My code passes all the tests on the codewars site. It's a simple enough problem to solve naïvely, but I would love to improve the structure.

The prompt for the problem is as follows:

  Write a function, persistence, that takes in a positive parameter num
  and returns its multiplicative persistence, which is the number of
  times you must multiply the digits in num until you reach a single
  digit.

  For example:

persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                      # and 4 has only one digit.

So my solution follows:

def get_digits(num, digits=[]):
    while num > 0:
        digits.append(num % 10)
        return get_digits(num / 10, digits)
    if num == 0:
        return digits

def multiply_all(digits, multiplier=1):
    while len(digits) > 0:
        multiplier = multiplier * digits.pop(0)
        return multiply_all(digits, multiplier)
    if len(digits) == 0:
        return multiplier

def persistence(num, count=0):
    while num >= 10:
        num = multiply_all(get_digits(num))
        count += 1
        return persistence(num, count)
    if num < 10:
        return count

I was thinking I might consolidate these three little recursive functions into one function containing all three... but I'd really like input from more seasoned programmers, so I very much appreciate you taking the time to make any suggestions.


texts: A faster way to compute largest prime factor (Again, but a lot better)

texts:
I came up with this code after implementing the feedback given by @200_success. The previous one (A faster way to compute the largest prime factor) tested my patience, but still failed to give the answer on time. This one is an improvement as it gives the answer without much delay.

The question (Euler project problem #3)

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

Logic:

Keep dividing the number n by all the factors, starting from the smallest one. The value of n left in the end will be the largest prime factor of the original value of n.

My code:

function problem3(n){
    for(let i=2; i<n; i++){
        if(n%i === 0)n = n/i;
        }
    return n;
}
console.log(problem3(600851475143));

Improvement:

No need to loop through all the numbers below n
Remove the nested for loops, replacing them by only one
No need to check if a number is prime or not

My question: Even though it is a lot better*, but still, how can it be improved further?

* Really, it's a lot than the previous one as it used to be so slow that I never saw the output for 600851475143


texts: Using synchronized blocks and volatile variables to ask a Java thread to terminate gracefully

texts:
Edit: Just to clarify, this isn't my original code, I've simplified it to make it smaller/easier to understand what I'm trying to do.

It's my first time working with threads in Java, and I was wondering if I'm synchronizing correctly. I did some quick research on locks, synchronized and volatile, but I'm still not sure where/how to use them. Basically I have a thread that executes some process, and I can cancel it from an outside thread (calling cancelProcess()). Between each step I check if the process should be canceled.

public final class ExecuteProcess {
    private volatile boolean processShouldCancel;
    private volatile boolean processKilled;
    private final Object processLock = new Object();
    private Process process;

    public boolean run() {
        initialize();

        if (processShouldCancel) {
            showCanceledMsg();
            return false;
        }

        synchronized (processLock) {
            process = new Process();
            process.Start();
        }

        if (processShouldCancel) {
            if (!processKilled)
                cancelProcess();

            showCanceledMsg();
            return false;
        }

        process.waitForResponse();

        if (processKilled) {
            showCanceledMsg();
            return false;
        }

        if (process.finished()) {
            process.getResult();
            return true;
        }

        return false;
    }

    public void cancelProcess() {
        processShouldCancel = true;
        synchronized (processLock) {
            if (process != null && !processKilled) {
                boolean killed = process.kill();

                if (killed)
                    processKilled = true;
            }
        }
    }
}


texts:
I am trying to make a page background for my website. Is this a good way to do it?

This is my HTML:

And this is my CSS:

#page-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}


texts: Rotate an N × N matrix 90 degrees clockwise

texts:
Given the problem from "Cracking the coding interview"

  Given an image represented by an NxN matrix, where each pixel in the
  image is 4 bytes, write a method to rotate the image by 90 degrees clockwise.

For simplicity I assumed a matrix of strings for my example so

[["a", "a", "a", "a"],
["b", "b", "b", "b"],
["c", "c", "c", "c"],
["d", "d", "d", "d"]]

becomes

[["d", "c", "b", "a"],
["d", "c", "b", "a"],
["d", "c", "b", "a"],
["d", "c", "b", "a"]]

Here's my JavaScript solution

var rotate = function(matrix) {
    // Copy the original matrix
    var origMatrix = matrix.slice();
    for(var i=0; i < matrix.length; i++) {
        // Map each row entry to its rotated value
        var row = matrix[i].map(function(x, j) {
            var k = (matrix.length - 1) - j;
            return origMatrix[k][i];
        });
        matrix[i] = row;
    }
    return matrix;
};


texts: Dijkstra algorithm implementation in Swift

texts:
I've implemented Dijkstra's algorithm to find the minimum path between two nodes.

class Node : CustomStringConvertible {
    // unique identifier required for each node
    var identifier : Int
    var distance : Int = Int.max
    var edges = [Edge]()
    var visited = false

    var description: String {
        return "identifier: " + identifier.description + ", Edges: " + edges.count.description
    }

    init(visited: Bool, identifier: Int, edges: [Edge]) {
        self.visited = visited
        self.identifier = identifier
        self.edges = edges
    }

    static func == (lhs: Node, rhs: Node) -> Bool {
        return lhs.identifier == rhs.identifier
    }
}

class Edge {
    var from: Node // does not actually need to be stored!
    var to: Node
    var weight: Int
    var description : String {
        return "from: " + from.description + ", to: " + to.description
    }
    init(to: Node, from: Node, weight: Int) {
        self.to = to
        self.weight = weight
        self.from = from
    }
}

class Graph {
    var nodes: [Node] = []
}

// Complete the quickestWayUp function below.
func setupGraphwith(edges: [[Int]]) -> Graph {
    let graph = Graph()

    // create all the nodes
    // The first and last node need to be included, so need nodes from "to" and "from"
    let nodeNames = Set ( edges.map{ $0[0] } + edges.map{ $0[1]} )
    for node in nodeNames {
        let newNode = Node(visited: false, identifier: node, edges: [])
        graph.nodes.append(newNode)
    }

    // create all the edges to link the nodes
    for edge in edges {
        if let fromNode = graph.nodes.first(where: { $0.identifier == edge[0] }) {
            if let toNode = graph.nodes.first(where: { $0.identifier == edge[1] }) {
                let edge = Edge(to: toNode, from: fromNode, weight: edge[2])
                fromNode.edges.append(edge)
            }
        }
    }
    return graph
}

func shortestPath (source: Int, destination: Int, graph: Graph) -> Int {
    print (graph.nodes)
    var currentNode = graph.nodes.first{ $0.identifier == source }!
    currentNode.visited = true
    currentNode.distance = 0
    var toVisit = [Node]()
    toVisit.append(currentNode)
    while ( !toVisit.isEmpty) {
        toVisit = toVisit.filter{ $0.identifier != currentNode.identifier }
        currentNode.visited = true
        // Go to each adjacent vertex and update the path length
        for connectedEdge in currentNode.edges {
            let dist = currentNode.distance + connectedEdge.weight
            if (dist < connectedEdge.to.distance) {
                connectedEdge.to.distance = dist
                toVisit.append(connectedEdge.to)
                if (connectedEdge.to.visited == true) {
                    connectedEdge.to.visited = false
                }
            }
        }

        currentNode.visited = true

        //set current node to the smallest vertex
        if !toVisit.isEmpty {
            currentNode = toVisit.min(by: { (a, b) -> Bool in
                return a.distance < b.distance
            })!
        }

        if (currentNode.identifier == destination) {
            return currentNode.distance
        }
    }

    return -1
}

class dfsTests: XCTestCase {
    var simpleGraph = Graph()
    override func setUp() {
        simpleGraph = setupGraphwith(edges: [[1,2,4], [1,3,4], [3,4,3], [2,3,2], [3,5,1], [4,6,2], [5,6,3], [3,6,6] ])

    }
    func testbfsReturnVals() {

        XCTAssertEqual(shortestPath(source: 1, destination: 6, graph: simpleGraph), 8 )
    }
}

dfsTests.defaultTestSuite.run()

This is just to practice the implementation of the code, with a view to interviews. Any comments are appreciated.


texts: vuejs: best practices with vuex when you call multiple actions

texts:
I am working on a project in which I am using vue js 2 and electron ,
to manage the state I use vuex  , I have at least 20 actions to call
 methods: {
        ...mapActions('Store1', ['FETCH_AB',...]),
        ...mapActions('Store2', ['FETCH_DS',...]),
        ...mapActions('Store3', ['FETCH_SD']),
        ...mapActions('Store4', ['FETCH_XD']),
        ...mapActions('Store5', ['FETCH_SD']),
        ...mapActions('Store6', ['FETCH_AZ'])
}

I use ...mapActions in my file vue
and to call it :
async mounted(){
  this.FETCH_AZ()
  this.FETCH_DS()
  ....
}

I created an method mounted
but i don't know if it's the best way to use vuex when you have enough actions to call
and there are actions that need getter or data from  actions
i mean by example :
const actions = {
 async FETCH_AZ(){
    const valueM8 = vm.$store.getters['Store1/GET_AB']
   ....
 }
}

i.e. an action can use the result of another action to do other operations


texts:
I have created a program that turns a decimal into a fraction:

package main

import (
        "fmt"
        "github.com/retep-mathwizard/utils/convert"
        "github.com/retep-mathwizard/utils/input"
        "math"
        "strings"
)

func main() {
        fmt.Println("Input your decimal")
        num := input.StringInput(" > ")
        digits := num[strings.Index(num, ".")+1:]
        decimal := num[strings.Index(num, "."):]
        numbers := num[:strings.Index(num, ".")]
        denom := convert.FloatToInt(math.Pow(10, convert.IntToFloat(len(digits))))
        numer := convert.FloatToInt(convert.StringToFloat(decimal) * convert.IntToFloat(denom))
        var gcf int
        for i := numer/2 + 1; i >= 0; i-- {
                if (numer%i == 0) && (denom%i == 0) {
                        gcf = i
                        break
                }

        }
        newnum := numer / gcf
        newdum := denom / gcf
        fmt.Println(numbers+" and ", newnum)
        fmt.Println("    -------")
        fmt.Println("      ", newdum)
}

I need to implement repeating fractions, and a maximum decimal length. Over 13 digits, and it takes a while. Feel free to butcher my code!


texts: remove kth last element from singly-linked list - Follow up

texts:
This code is a revised version of implementation which asked for an improvement. Original question is asked here:
remove kth last element from singly-linked list
credits to: Toby, Andreas, Arkadiusz
What has changed:

remove length from xllist struct
check if k is bigger than list length on the fly

Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>

typedef struct llnode
{
    int value;
    struct llnode *next;
} llnode;

typedef struct xllist
{
    llnode * head;
    llnode * tail;
} xllist;

bool create_node(xllist *list, int value)
{
    llnode *node = malloc(sizeof *node);
    if(!node)
    {
        return false;
    }

    node->value = value;
    node->next = NULL;
    if(!list->head)
    {
        list->head = node;
        list->tail = node;
    }
    list->tail->next = node;
    list->tail = node;
    return true;
}

bool del_element_from_last(xllist *llist, int k)
{
    //window with 2 pointers, length of k
    //prev is the prev node to the window
    llnode *prev;
    llnode *last;
    int len;  //list length

    if(llist->head)
    {
        last = llist->head;
        prev = llist->head;
        len = 1;
    }

    for(; last; last=last->next)
    {
        len++;
        if(len > k+1)
            prev = prev->next;
    }

    if(len < k) //len is smaller than k
    {
        return false;
    }

    if(len == k)  //means del 1st element from the list
    {
        llist->head = llist->head->next;
    }

    //remove first node of the window
    printf("deleted element:%d \n", prev->next->value);
    prev->next = prev->next->next;
    return true;
}

int main(void)
{
    xllist llist = {NULL, NULL};

    for(int i=0; i<100; i++)
    {
        if(!create_node(&llist, 100+i))
            printf("create fail\n");
    }

    del_element_from_last(&llist, 15);
}


texts:
I created this class which supposed to take a method and try to execute it. If it fails lets say 10 times, it will throw the original exception thrown by the delegate.

Do you have any ideas for improvement about that code?

I am particularly interested, in where to put this code. Right now it is within a FileHandler assembly because the code was used for serialization.
But since it can be used generally I want to move it to a different assembly. Unfortunately I did not come up with a better name (other than "Utility" or "Helper"). Unfortunately I did not come with a really meaningful name...maybe something related to "invoke" or so?

public static class FileHandler
{
  private const int MAX_TRIES = 10;
  private const int WAIT_FOR_RETRY_DELAY = 250;

  public static T ExecuteFuncWithRetry<T>(Func<T> func, string errorMessage)
  {
    var retryFunc = new FuncWithRetry<T>(errorMessage, func);
    var ret = retryFunc.PerformAction();
    return ret;
  }

  private class FuncWithRetry<T>
  {
    private readonly string _errorMessage;

    private readonly Func<T> _func;

    public FuncWithRetry(string errorMessage, Func<T> func)
    {
      _errorMessage = errorMessage;
      _func = func;
    }

    public T PerformAction()
    {
      var tries = 1;
      Exception exception = null;
      do
      {
        try
        {
          var retval = _func();
          return retval;
        }
        catch (Exception e)
        {
          exception = e;
          Thread.Sleep(WAIT_FOR_RETRY_DELAY);
        }
        finally
        {
          tries++;
        }
      } while (tries <= MAX_TRIES);

      throw new Exception(_errorMessage, exception);
    }
  }
}


texts:
Is there a better way to check if a number is a prime?

#include <iostream>
#include <math.h>

using namespace std;

bool doAgain();
bool isPrime(int num);

int main()
{
    do {
        int num = 0;
        do {
            cout << "Enter a positive integer to check: ";
            cin >> num;
        } while(num < 1);
        if(isPrime(num)) {
            cout << "Prime!!!" << endl;
        } else {
            cout << "Not a prime." << endl;
        }
    } while(doAgain());
    cout << "Bye!" << endl;
}

bool doAgain() {
    while(true) {
        cout << "Again? (Y/N) ";
        char again;
        cin >> again;
        if(again == 'Y') {
            return true;
        } else if(again == 'N') {
            return false;
        }
    }
}

bool isPrime(int num) {
    if(num < 2) {
        return false;
    } else if(num == 2) {
        return true;
    } else if(num % 2 == 0) {
        return false;
    }
    for(int i = 3, max = sqrt(num); i < max; i += 2) {
        if(num % i == 0) {
            return false;
        }
    }
    return true;
}


texts:
This was a challenge for reddit #202 Easy /u/learnprogramming ...I wish that someone reviews my code and let me know your opinion about my way of thinking beacause I am a total beginner in Ruby:

class BinaryChar
  attr_accessor :binaryString

  def convertToChar
    binaryString.scan(/.{1,8}/) { |part| print part.to_i(2).chr }
    puts
  end

end

bc = BinaryChar.new
speak = 0
loop do
  print "Enter string: "
  speak = gets
  bc.binaryString=(speak)
  bc.convertToChar
end