texts:
Compute the number of connected component in a matrix, saying M. Given
  two items with coordinates [x1, y1] and [x2, y2] in M, if

  M(x1, y1) == -1 and
  M(x2, y2) == -1 and
  |x1-x2| + |y1-y2| == 1

  then they are connected.

  Example:

-1  0 -1  0  0
-1 -1  0 -1 -1
 0  0  0  0 -1
 0  0  0 -1 -1
 0  0  0 -1  0
 0 -1  0  0  0
 0 -1  0  0  0

  Output: 4. And they are:

-1
-1 -1

-1

-1 -1
   -1
-1 -1
-1

-1
-1

My idea is to scan the matrix.

Initialization:
count = 0.

For every item in the matrix, do the following three tests.

  If it's 0, skip
  If it's -1, check its four neighbors. If there is a neighbor whose
  value is not 0 and -1, assign the value of this neighbor to the current item. Otherwise, count++, ant then assign count to the current item.
  If it's not 0 and -1, assign the value of current item to its four
  neighbors whose value is -1.

The following is my code:

int num_cc(int m[][COLS])
{
    int count = 0;
    int r;
    int c;

    for(r = 0; r < ROWS; ++r)
    {
        for(c = 0; c < COLS; ++c)
        {
            if(m[r][c] == 0)
                continue;

            if(m[r][c] == -1)
            {
                if(r-1>=0 && m[r-1][c] > 0)
                    m[r][c] = m[r-1][c];
                else if(r+1<ROWS && m[r+1][c] > 0)
                    m[r][c] = m[r+1][c];
                else if(c-1>=0 && m[r][c-1] > 0)
                    m[r][c] = m[r][c-1];
                else if(c+1<COLS && m[r][c+1] > 0)
                    m[r][c] = m[r][c+1];
                else
                {
                    count++;
                    m[r][c] = count;
                }
            }

            if(m[r][c] > 0)
            {
                if(r-1>=0 && m[r-1][c] == -1)
                    m[r-1][c] = m[r][c];
                if(r+1<ROWS && m[r+1][c] == -1)
                    m[r+1][c] = m[r][c];
                if(c-1>=0 && m[r][c-1] == -1)
                    m[r][c-1] = m[r][c];
                if(c+1<COLS && m[r][c+1] == -1)
                    m[r][c+1] = m[r][c];
            }

        }
    }

    return count;
}

Can anyone help me verify it? Is it correct? Or is there any other solutions?


texts:
I've created software in Go to create a presigned URL:

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/minio/minio-go"
    "github.com/kelseyhightower/envconfig"
)

type AWS struct {
  Endpoint          string
  Access_Key_Id     string
  Secret_Access_Key string
  SSL               bool
  Bucket            string
  Bucket_Key        string
  Bucket_Expiry     string
}

func main() {
    var aws AWS
    // Add configurations from environment variable
    // e.g:
    //    AWS_ENDPOINT         -> aws.Endpoint
    //    AWS_ACCESS_KEY_ID    -> aws.Access_Key_Id
    //    ...
    if err := envconfig.Process("aws", &aws); err != nil {
        log.Fatal(err.Error())
    }

    svc, err := minio.New(aws.Endpoint, aws.Access_Key_Id, aws.Secret_Access_Key, aws.SSL)
    if err != nil {
    }

    fmt.Println(aws)
    url, err := svc.PresignedPutObject(aws.Bucket, aws.Bucket_Key, aws.Bucket_Expiry)

    if err != nil {
        log.Fatalln(err)
    }

    fmt.Println("Successfully generated presigned URL", url)
}

I would like to know if it is possible to avoid all the if statements for error validations. This is my second program in Go, and I have mainly a Node.js background, so I don't know exactly how to handle errors in Go-style, and also how to make the code more idiomatic.


texts: Program to retrieve key/message from a multiple times used one time pad

texts:
I wrote a program to retrieve the key/messages from 10 different ciphers which were all encrypted with the same key with an xor one-time-pad method via crib dragging.

To do this, I wrote a python script which turns a string to test to hex code. Then it xors the 10 cipher strings (200 hex characters each), two at a time. After that it, xors the test string with the 5 xor hashes on each position and then looks via a website whether this is a reasonably good string to go further and try again.

I already tested it and got positive results.

Now when I do it with the real ciphers I got nowhere so far, and I am not sure whether this is because of the script or me not being able to expand on retrieved valid string fragments.

Here is the code, I know that the website lookup is very bad, but I found no other way this fast/easy (to implement, not to run).

EDIT: Since I do not think overwriting the code is good, I put it here in case somebody wants to see it: Gist link

# -*- coding: UTF-8 -*-
import codecs
from urllib.error import URLError
import urllib.request

forbiddenSigns = ['{', '}', '[', ']', '(', ')', '?', '=', '%', '_', ';', '-', '^', ':', '<', '>', '|', '!', '`', '´', "'", '\\']

with open("testCiphers.txt") as f:
    ciphers = f.readlines()

ciphers = [s.strip() for s in ciphers]

crib = "the"
cribList = []

for c in crib:
    cribList.append(hex(ord(c))[2:])

cribHash = ''.join(cribList)
cribLength = len(cribHash)

cipherHashList = []
for i in range(0, len(ciphers) - 1):
    cipherHashList.append(int(ciphers[i], 16) ^ int(ciphers[i + 1], 16))

hashResultList = [str(hex(hr))[2:] for hr in cipherHashList]

hexList = []

for hashResultString in hashResultList:
    for i in range(0, len(hashResultString) - cribLength + 1, 1):
        hexList.append(hashResultString[i:i + cribLength])

for ha in hexList:
    cribAttempt = int(cribHash, 16) ^ int(ha, 16)
    cribAttempt = (hex(cribAttempt))[2:].zfill(cribLength)
    clearText = codecs.decode(cribAttempt, "hex")
    if any(s not in str(clearText) for s in forbiddenSigns) and "\\x" not in str(clearText):
        url = 'http://www.morewords.com/contains/' + str(clearText, "ASCII")
        try:
            siteRequest = str(urllib.request.urlopen(url).read())
            if "words found.
" in siteRequest:
                print(str(clearText, "ASCII"), end="\n")
        except URLError :
            "error getting webpage"


texts: Get count of credit cards that are expired

texts:
Below is a sample implementation for getting the expired credit cards in the credit card list.I wrote a property and initialized it in the constructor. Need an opinion on if this is a proper way to implement it.

   public class User
    {
        private readonly List<CreditCard> creditCards;

        public int CountOfCreditCards
        {
            get
            {
                return counter;
            }
        }

        private static int counter;

        private User()
        {
            creditCards = new List<CreditCard>();
            counter = GetCountOfExpiredCreditCards();
        }

        public int GetCountOfExpiredCreditCards()
        {
            return creditCards.Count(x => x.ExpirationMonth <= DateTime.Now.Month);
        }
    }


texts: Use NPOI to read string value of all cells in a row in xlsx file, including merge cell

texts:
I'm currently using NPOI library to read the value of all cells in one row of a xlsx file and return a List<string>. However, if a cell is part of a merged cell, then I need to get the value of that merged cell instead of a blank value. (In NPOI, if a cell is part of a merged cell but is not the top-most and left-most cell in that merged region, then when using FormatCellValue on that cell, we got a empty string).

Let say that I have already retrieved the necessary row and get an IRow object, and there is no empty cell at the left of this row. Also, my data will always be string, there will be no other data type.

This is what I came up with:

private List<string> readRow(IRow row)
{
    var rs = new List<string>();

    // Since there would be no emtpy cell,
    // we start from the left-most cell and read until the end.
    for (int colIndex = 0; colIndex < row.LastCellNum; colIndex++)
    {
        var cell = row.GetCell(colIndex);

        // Get the value of this cell, whether it is part of a merged cell or not.
        var cellValue = getCellValue(cell);

        rs.Add(cellValue);
    }
    return rs;
}

And the method to get cell value:

private string getCellValue(ICell cell)
{
    var dataFormatter = new DataFormatter(CultureInfo.CurrentCulture);

    // If this is not part of a merge cell,
    // just get this cell's value like normal.
    if (!cell.IsMergedCell)
    {
        return dataFormatter.FormatCellValue(cell);
    }

    // Otherwise, we need to find the value of this merged cell.
    else
    {
        // Get current sheet.
        var currentSheet = cell.Sheet;

        // Loop through all merge regions in this sheet.
        for (int i = 0; i < currentSheet.NumMergedRegions; i++)
        {
            var mergeRegion = currentSheet.GetMergedRegion(i);

            // If this merged region contains this cell.
            if (mergeRegion.FirstRow <= cell.RowIndex && cell.RowIndex <= mergeRegion.LastRow &&
                mergeRegion.FirstColumn <= cell.ColumnIndex && cell.ColumnIndex <= mergeRegion.LastColumn)
            {
                // Find the top-most and left-most cell in this region.
                var firstRegionCell = currentSheet.GetRow(mergeRegion.FirstRow)
                                        .GetCell(mergeRegion.FirstColumn);

                // And return its value.
                return dataFormatter.FormatCellValue(firstRegionCell);
            }
        }
        // This should never happen.
        throw new Exception("Cannot find this cell in any merged region");
    }
}

I was surprised to find that there is no simpler way to get value of merged cell using NPOI. What can I improve here?


texts: Select Queries From Parent-Child Tables Model

texts:
I have two tables (parent-child model): Loans & Transactions.

Each Loan row has multiple Transaction rows.

I want to select all rows from Loans together with most recent row from Transactions.

Here is my select to achieve this.

SELECT
    L.*, T.*
FROM Loans L
CROSS APPLY
(
    SELECT TOP 1 * FROM Transactions AS T
    WHERE L.LoanID = T.LoanID
    ORDER BY CRTime DESC
) T

Another approach

SELECT
    L.*, T.*
FROM Loans L
INNER JOIN
(
    SELECT MAX(TransactionID) AS TransactionID, LoanID FROM Transactions AS T
    GROUP BY LoanID
) T
ON T.LoanID = L.LoanID
INNER JOIN Transactions TS
ON TS.TransactionID = T.TransactionID

Any ideas on improving it?

Side question: Can you suggest best practices for comparing two queries running times?


texts:
Is there an alternative possibly cleaner way (without so much repetition) to write the following? I'm thinking about the headache it's going to be when I have to remove all of my even listers.

customCursor() {
const prevButton = document.querySelector('.previous');
const nextButton = document.querySelector('.next');
const brandLogo = document.querySelector('.brand-logo');
const navButton = document.querySelector('.nav-button');
const carouselCellLink = document.querySelectorAll('.carousel-cell__link');

const cursorContainer = this.cursorContainer;
const cursorOffset = {
  left : 50,
  top  : 50
}

document.querySelector('.page-flickity').addEventListener("mousemove", function (e) {
  cursorContainer.style.left = (e.pageX - cursorOffset.left) + 'px';
  cursorContainer.style.top = (e.pageY - cursorOffset.top) + 'px';
}, false);

prevButton.addEventListener('mouseover', () => {
  cursorContainer.classList.add('previous');
});

prevButton.addEventListener('mouseleave', () => {
  cursorContainer.classList.remove('previous');
});

nextButton.addEventListener('mouseover', () => {
  cursorContainer.classList.add('next');
});

nextButton.addEventListener('mouseleave', () => {
  cursorContainer.classList.remove('next');
});

brandLogo.addEventListener('mouseover', () => {
  cursorContainer.classList.add('hidden');
});

brandLogo.addEventListener('mouseleave', () => {
  cursorContainer.classList.remove('hidden');
});

navButton.addEventListener('mouseover', () => {
  cursorContainer.classList.add('hidden');
});

navButton.addEventListener('mouseleave', () => {
  cursorContainer.classList.remove('hidden');
});

for(var i = 0; i < carouselCellLink.length; i++) {
  carouselCellLink[i].addEventListener('mouseover', () => {
    cursorContainer.classList.add('link');
  });

  carouselCellLink[i].addEventListener('mouseleave', () => {
    cursorContainer.classList.remove('link');
  });
}
}


texts: Algorithm X implementation for Minimum Dominating Set

texts:
As as final project for a MOOC I wanted to write a program that finds the exact cover set/minimum dominating set from the given social network data. So I did end up with writing this. I kinda followed this algorithm.(https://www.geeksforgeeks.org/exact-cover-problem-algorithm-x-set-1/)

I did test with the picture below it worked fine

"keys is a sorted list by their number of 'followers'"

    HashSet <Integer> exactCoverSet = new HashSet <>();
    HashSet <Integer> dominatingSet = new HashSet <>();
    while (keysCopy.size() > 0) {
        int col = keysCopy.removeLast();
        LinkedList <Integer> selectedRows = new LinkedList <>();
        selectedRows.addAll(G.exportGraph().get(col));

        exactCoverSet = findCoverSet(G, nv, selectedRows, keysCopy, dominatingSet);

        if (exactCoverSet != null) {    // if all columns are removed from the matrix then found
            break;
        }

    }
    return exactCoverSet;

above is loop to find the MDS, there are a few more classes these are the cores

public static HashSet <Integer> findCoverSet(Graph G, int[][] matrix,
                                             LinkedList <Integer> selectedRows,
                                             LinkedList <Integer> keys, HashSet <Integer> dominatingSet) {
    if (selectedRows.size() == 0) {
        return null;
    }

    LinkedList <Integer> keysCopy = new LinkedList <>();
    keysCopy.addAll(keys);

    LinkedList <Integer> rowValues = new LinkedList <>();
    rowValues.addAll(G.exportGraph().get(selectedRows.getFirst()));     //add all values of the chosen row
    dominatingSet.add(selectedRows.removeFirst());                      //remove the chosen row from loop

    ArrayList <Integer> removeRows = new ArrayList <>();                //remove the rows from matrix
    for (int num : keys) {                                              //that are sharing the same columns with chosen row
        for (int val : rowValues) {
            if (G.exportGraph().get(num).contains(val)) {
                removeRows.add(num);
                keysCopy.removeFirstOccurrence(num);
                break;
            }
        }
    }

    for (int col : rowValues) {                             //remove the columns from matrix
        matrix = removeCol(matrix, col - 1);
    }

    if (keysCopy.size() == 1) {                         //if there is 1 left row check if its all elements are 1s
        int key = keysCopy.getFirst();                  //if so MDS found, otherwise return null
        for (int j = 0; j < matrix[key - 1].length; j++) {
            if (matrix[key - 1][j] == 0) {
                return null;
            }
        }
    }

    if (keysCopy.size() > 0) {                      //if remaining columns are more than 0 then select/remove
        int tempKey = keysCopy.removeFirst();       //the column with the least 1s
        selectedRows.add(tempKey);
        return findCoverSet(G, matrix, selectedRows, keysCopy, dominatingSet);
    }
    return dominatingSet;

}


texts: Merging predicted values into measured values

texts:
I created the following function below to merge the real values with the predicted values (when real are absent) in a new column in data.frame. The function actually works, but I would like to optimize it, because with the dataset that I work with, the function takes about two hours to run.

The function seems to be slowed down by the loop.

p <-
  function(object, newdata = NULL, type = c("link", "response", "terms"),
           rse.fit = FALSE, dispersion = NULL, terms = NULL,
           na.action = na.pass, ...)
  {
{
    pred <- predict (object,newdata)

      }

    vetor1 <- (newdata$ALT)         # Creates a column vector from the actual heights of the data.frame
    vetor1[is.na(vetor1)] <- 0      # Replaces the NA's present in the vector created above the numeric value 0
    vetor2 <- c(pred)           # Creates a vector from the predicted data
    for(i in 1:length(vetor1)){     # The loop is executed until all values vector1 pass the following condition
      if(vetor1[i]==0.00){      # If a value of the first vector has the value 0, ie, if it is absent
        vetor1[i]=vetor2[i]     # Then the predicted value will replace the missing value
        newdata$ALTMISTA <- vetor1  # The vector1, already possessing the actual values and the predicted values merged into the same vector goes                   on to become a new column in data.frame, this column is called a ALTMISTA
      }
    }
    return (newdata)
  }


texts: Linq sorting on sort order of inner group

texts:
Is this the best way to do this sort?

assets.OrderBy(a =>
    a.GalleryItems != null &&
    a.GalleryItems.FirstOrDefault() != null
        ? a.GalleryItems.OrderBy(gi => gi.SortOrder).First().SortOrder
        : 1000)

Basically I have a group of assets, which contain a group of gallery items with a sort order.  I need to get the lowest sort order from this group and sort the assets by that.  Gallery items can be null (it is coming through a service so I am unable to change this).


texts: Calculate mean, median, and mode in Rust

texts:
I'm learning Rust using The Rust Programming Language. I'm trying the assignment at the end of chapter 8 — Hash Maps.

The task is:

  Given a list of integers, use a vector and return the mean (average), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list.

The average value and the median were very easy for me, but I struggle solving the last part of the task. I do have a working solution (see below), but I'm sure there must be some more elegant and readable way (using the standard library?) for this.

use std::collections::HashMap;
fn main() {
  let  mut numbers = vec![42, 1, 36, 34, 76, 378, 43, 1, 43, 54, 2, 3, 43];

  let avg: f32;
  let median: i32;
  let mode: i32;

  { // calculate average
      let mut sum: i32 = 0;
      for x in &numbers {
          sum = sum + x;
      }

      avg = sum as f32 / numbers.len() as f32;
  }

  { // calculate median
      numbers.sort();
      let mid = numbers.len() / 2;

      median = numbers[mid];
  }

  { // calculate mode
      // new HashMap
      let mut times = HashMap::new();

      // count
      for x in &numbers {
          let cnt = times.entry(*x as usize).or_insert(0);
          *cnt += 1;
      }

      let mut best: (i32, i32) = (*times.iter().nth(0).expect("Fatal.").0 as i32, *times.iter().nth(0).expect("Fatal.").1 as i32);

      for x in times.iter() {
          if *x.1 > best.1 {
              best = (*x.0 as i32, *x.1);
          }
      }
      mode = best.0;
  }

  println!("AVERAGE: {}", avg);
  println!("MEDIAN: {}", median);
  println!("MODE: {}", mode)

}


texts: More simplified way of creating page links dynamically?

texts:
A little birdie suggested I bring this question here, so here it goes.

Well I have a working script (see below) but it seems quite clunky and redundant; in my defense I wrote this code many moons ago, but that's not the point. I was curious if anyone has an idea on a more efficient way of writing this code, with less loops and conditionals and, well, noise in the code.

Code in question:

private function pageLinks($num, $page = 1, $search = false, $ne = false) {
    $query = ($search) ? '&query='.$search : null;
    $by = (is_numeric($ne)) ? '&by='.$ne : null;
    $links = 'Page(s):1';
    $count = 1;
    $npp = $this->numPerPage;
    $buttons = 9;
    $half = 4;
    for($i = 1; $i <= $num; $i++) {
        if(($i%$npp) === 0) {
            $count++;
        }
    }
    if($count < $buttons) {
        for($i = 2; $i <= $count; $i++) {
            $links .= '' . $i . '';
        }
    } elseif($page <= ($half + 2)) {
        for($i = 2; $i <= $buttons; $i++) {
            $links .= '' . $i . '';
        }
        $links .= '...' . $count . '';
    } elseif($page <= ($count - ($half + 2))) {
        $links .= '...';
        for($i = $half; $i > 0; $i--) {
            $links .= '' . ($page - $i) . '';
        }
        $links .= '' . ($page - $i) . '';
        for($i = 1; $i <= $half; $i++) {
            $links .= '' . ($page + $i) . '';
        }
        $links .= '...' . $count . '';
    } else {
        $links .= '...';
        for($i = $buttons - 1; $i >= 0; $i--) {
            $links .= '' . ($count - $i) . '';
        }
    }
    return($links);
}

The method is called like so:

$links = $this->pageLinks($count, $page, $url, $ne);

And the variables are as such:

$count = total number of clients in database (int)
$page = current page to build from (int)
$url = the name or email for the search (String)
$ne = is for the search string either by name (1) or email (2) (int)

And the output is something like (as links):

Page(s):1 2 3 4 5 6 7 8 9...33

Or if you're in the middle (page 20):

Page(s):1...16 17 18 19 20 21 22 23 24...33

Now this isn't always called through a search function, hence the default values for $url and $ne, but that's not very important. My question is there a cleaner way to handle building of these links? Or am I stuck with this cluster of loops?


texts: Spam detection in PHP for comment system

texts:
I'am trying to build a PHP/MySQL/jQuery comment system.  Off late I started to realize that manual spamming is a serious issue that need to be addressed carefully. So I thought of building a PHP function (initially, later can be implemented in OOPS concept) that will sniff the content and give points (spam points) based on some criteria.  Getting a spam point less than will make the content inactive and send for moderation, whereas posts with spam points greater than 2 won't make the content eligible to be inserted in DB. This is a very basic piece of codes, so I want you to give me your valuable suggestion as how to make this code much better and if I am doing something wrong here.

<?php

#spam points < 2 { will be send for moderation}
#spam points > 2 { wont be posted , ie wont be inserted in DB}

function sniffSpams($content)
{
    $spam_points    =    0;
    $url_pattern    =   '#(www\.|https?://)?[a-z0-9]+\.[a-z0-9]{2,4}\S*#i';

    preg_match_all($url_pattern, $content, $matches, PREG_PATTERN_ORDER);

    if(! empty($matches))
    {
        //url is/are present

        $get_number_of_urls    =   count($matches[0]);       //get the number of urls/emails present in content

        if($get_number_of_urls > 2)
            $spam_points += $get_number_of_urls;            //1 point per link
        else
        {
            $spam_words_uri  = array('free', 'vote', 'play');

            //if less thamn 2 , check for length of url
            foreach ($matches[0] as $url)
            {
                if(strlen($url) > 150) //long url mostly are spam
                   $spam_points += 1;

                foreach($spam_words_uri as $spam)
                {
                    if(stripos($url, $spam) !== false )
                        $spam_points += 1;
                }

            }

        }

    }

   $spam_words  = array('Levitra', 'viagra', 'casino', '*');

   foreach($spam_words as $spam)
   {
        if(stripos($content, $spam) !== false )
            $spam_points += 1;

   }

    return $spam_points;

}

echo sniffSpams('the * dsjdjsd ');


texts: MIPS program to find the sum and square sum of 10 integers

texts:
I wrote a program (hard-code) in MIPS that gets an array of 10 integers and calculates the sum and the square sum of them.
The array is {23,-2,45,67,89,12,-100,0,120,6}

.data
array: .word 23,-2,45,67,89,12,-100,0,120,6 # array = {23,-2,45,67,89,12,-100,0,120,6}
length: .word 10 # the length of the array is 10
sum: .word 0 # the sum of the integers (in array) is 0
squareSum: .word 0 # the square sum of the integers (in array) is 0
sumMessage: .asciiz "The sum of the array(sign) is: "
squareMessage: .asciiz "The sum of the squares(sign) is: "
newLine: .asciiz "\n"

# Algorithm being implemented to sum an array
# sum = 0 (use $t0 for sum)
# squarSum = 0 (use %t5 for squarSum)
# for i = 0 to length-1 do (use $t1 for i)
# sum = sum + array[i] (use $t2 for length-1)
# squareSum = squareSum + array[i]*array[i]
# end for (use $t3 for base addr. of array)

.text
main:

li $t0, 0 # load immediate 0 in register $t0 (sum)
li $t5, 0 # load immediate 0 in register $t0 (squarSum)
la $t3, array # load base addr. of array into $t3
lw $t2, length # load length in register $t2
addi $t2, $t2, -1 # $t2 = length - 1
li $t1, 0 # initialize i in $t1 to 0

loop:

bgt $t1, $t2, exit # exit loop when i > (length-1)
mul $t4, $t1, 4 # multiple i by 4 to get offset within array
add $t4, $t3, $t4 # add base addr. of array to $t4 to get addr. of array[i]
lw $t4, 0($t4) # load value of array[i] from memory into $t4
add $t0, $t0, $t4 # update sum
mul $t6, $t4, $t4 # temp register %t6
add $t5,$t5,$t6 # update squareSum
addi $t1, $t1, 1 # increment i
j loop

exit:

# print sum message
li $v0, 4
la $a0, sumMessage
syscall
# print value of sum
li $v0, 1
addi $a0,$t0,0
syscall
# print new line
li $v0, 4
la $a0, newLine
syscall
# print square sum message
li $v0, 4
la $a0, squareMessage
syscall
# print value of squareSum
li $v0, 1
addi $a0,$t5,0
syscall

Is this a good implementation?  How can I improve it?


texts: Meshing algorithm for generating faces in Minecraft

texts:
To generate faces of a Minecraft-like world from a three dimensional array, I developed the following meshing algorithm. The faces are given vertices and indices. A vertex consists of a position in space, a normal vector and a texture coordinate. Indices point to vertices to consecutively define faces.

Those variables are used:

// dimensions of the world
#define SIZE 32

// voxel grid representing the world, where 0 means air
uint8_t data[SIZE][SIZE][SIZE];

// results are stored in those vectors
vector<float> positions, normals, texcoords;
vector<unsigned int> elements;

This is the algorithm:

int n = 0;
for(int X = 0; X < SIZE; ++X)
for(int Y = 0; Y < SIZE; ++Y)
for(int Z = 0; Z < SIZE; ++Z)
{
    if(data[X][Y][Z])
    {
        uint8_t tile = clamp((int)data[X][Y][Z], 0, TILES_U * TILES_V - 1);
        for(int dim = 0; dim < 3; ++dim) { int dir = -1; do {
            ivec3 neigh = Shift(dim, ivec3(dir, 0, 0)) + ivec3(X, Y, Z);

            if(Inside(neigh, ivec3(0), ivec3(SIZE) - 1))
                if(data[neigh.x][neigh.y][neigh.z])
                    goto skip;

            {
                for(float i = 0; i <= 1; ++i)
                for(float j = 0; j <= 1; ++j)
                {
                    vec3 vertex = vec3(X, Y, Z) + vec3(Shift(dim, ivec3((dir+1)/2, i, j)));
                    positions.push_back(vertex.x); positions.push_back(vertex.y); positions.push_back(vertex.z);
                }

                /*
                 * the normal vector is not important for this question
                 *
                 * vec3 normal = normalize(vec3(Shift(dim, ivec3(dir, 0, 0))));
                 * for(int i = 0; i < 4; ++i)
                 * {
                 *  normals.push_back(normal.x); normals.push_back(normal.y); normals.push_back(normal.z);
                 * }
                 */

                /*
                 * texture coordinates are not important for this question
                 *
                 * vec2 coords(tile % TILES_U, tile / TILES_U);
                 * vec2 position = coords * GRID;
                 * texcoords.push_back(position.x          + GAP); texcoords.push_back(position.y          + GAP);
                 * texcoords.push_back(position.x + GRID.x - GAP); texcoords.push_back(position.y          + GAP);
                 * texcoords.push_back(position.x          + GAP); texcoords.push_back(position.y + GRID.y - GAP);
                 * texcoords.push_back(position.x + GRID.x - GAP); texcoords.push_back(position.y + GRID.y - GAP);
                 */

                if(dir == -1) {
                    elements.push_back(n+0); elements.push_back(n+1); elements.push_back(n+2);
                    elements.push_back(n+1); elements.push_back(n+3); elements.push_back(n+2);
                } else {
                    elements.push_back(n+0); elements.push_back(n+2); elements.push_back(n+1);
                    elements.push_back(n+1); elements.push_back(n+2); elements.push_back(n+3);
                }
                n += 4;
            }

        skip: dir *= -1; } while(dir > 0); }
    }
}

And here are the two helper functions.

bool Inside(ivec3 Position, ivec3 Min, ivec3 Max)
{
    if(Position.x < Min.x || Position.y < Min.y || Position.z < Min.z) return false;
    if(Position.x > Max.x || Position.y > Max.y || Position.z > Max.z) return false;
    return true;
}

ivec3 Shift(int Dimension, ivec3 Vector)
{
    if      (Dimension % 3 == 1) return ivec3(Vector.z, Vector.x, Vector.y);
    else if (Dimension % 3 == 2) return ivec3(Vector.y, Vector.z, Vector.x);
    else                         return Vector;
}

As you can see, the algorithm uses a goto statement to skip faces which adjacent blocks first, are inside the world bounds and second, are not filled with air. Those faces shouldn't be generated since they are not visible to the player.

How can I restructure the statement to not use goto anymore?


texts: Check if an entity exists in a Azure Table Storage

texts:
I want to check as fast as possible if an entity, based on PartitionKey and RowKey, exists in an Azure Table Storage.

I can do a standard TableOperation.Retrieve and check the result, like:

TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");
TableResult retrievedResult = table.Execute(retrieveOperation);

but that would return the complete entity.

By using a DynamicTableEntity I reduce the amount of data that is returned.
More code, but I assume better...

public async Task<bool> EntityExists(string partitionKey, string rowKey)
{
    var tableQuery = new TableQuery<DynamicTableEntity>();
    tableQuery.FilterString = TableQuery.CombineFilters(
            TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, paritionKey),
            TableOperators.And,
            TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey));

    var dynamicTableEntities = await CloudTable.ExecuteQuerySegmentedAsync(tableQuery, null, TableRequestOptions, OperationContext);
    return dynamicTableEntities.Results.Any();
 }

Any suggestions/criticisms to my solution are welcome


texts: Make a list's elements consecutive by an integer n

texts:
Write a method makeConsecutiveByN that could be added to the
  ArrayIntList class that takes an integer n as a parameter, removes any
  list element that does not differ from the previous element by exactly
  n. For example, both 8 and 2 differ from 5 by exactly 3. Your method
  should return true if the list was changed and false if not. For
  example, suppose elementData stores the following element values: [1,
  3, -6, 1]. We need to compare every set of pairs. If we remove an
  element we need to compare the next element in the list to the last
  non-removed element. If n were 2 and we made a call on the previous
  list we would compare 1 and 3, keep 3 and then compare 3 and -6. We
  would discard -6 and so then compare 3 and the last 1. Our call would
  return true. You may not use any other arrays, lists, or other data
  structures to help you solve this problem, though you can create as
  many simple variables as you like.

I'm looking for better/other ways to write this code. I noticed that I wasn't able to iterate from the right-to-left because this problem depends on the direction of traversal. With that in mind, are there other ways I can think about solving this problem? Also looking for general feedback to cleaning up my code for the future. It is also worth noting that this is code that would be added to a custom ArrayIntList class.

public boolean makeConsecutiveByN(int n) {
    boolean isChanged = false;
    for (int i = 0; i + 1 < size; i++) {
        if (Math.abs(elementData[i] - elementData[i + 1]) != n) {
            remove(i + 1);
            i--;
            isChanged = true;
        }

    }
    return isChanged;
}


texts: Multiple inheritance pattern for vehicle information

texts:
I wanted an easy way to augment objects, by adding functionality from any other object(s). More importantly, I needed a way to augment the object from multiple sources in a clean one-line solution.

The inheritance is done with this:

function extend(proto, args){
    this[proto.id] = Object.create(proto);
    proto.constructor.call(this[proto.id], args);
}

extend.call(this, vehicle, args); // one-liner

I can invoke as many objects as needed; with this pattern it's easy to swap and change the prototype chain, so I could just put the above extend code in the vehicle object, if that's where I want augmentation.

It's now easy to create a car by pulling in whatever you need:

extend.call(this, vehicle, args);
extend.call(this, sunroof, args);
extend.call(this, tyres, args);
extend.call(this, wings, args);
extend.call(this, rocket, args);
etc...

Questions:

Plausibility: is it flawed in some way?
Optimisation: can I enhance the pattern?
clunky: I had to create an id property for each object, so the extend function knows how to create a property on the executing context. It seems like a hack. Is there a way to get a prototype name from a named constructor?

var manufacturer = {
    id:'manufacturer',
    constructor : function (args) {
        this.boss = args.boss || 'Bernie Ecclestone';
      this.country = args.country || 'UK';
        return this;
    }
};

var vehicle = {
    id:'vehicle',
    constructor : function (args) {
        this.colour = args.colour || 'blue';
      this.wheels = args.wheels || 2;
        extend.call(this, manufacturer, args);
        return this;
    }
};

var driver = {
    id:'driver',
    constructor : function (args) {
        this.name = args.name || 'John';
        return this;
    },
    info : function () { console.log(this.name); }
};

var engine = {
    id:'engine',
    constructor : function (args) {
        this.type = args.type || 'V6';
        this.fuel = args.fuel || 'petrol';
        return this;
    },
    tune : function () {
        this.type = 'super-charged';
        this.fuel = 'ethanol';
        console.log('Car now ' + this.type + ' with ' + this.fuel);
    }
};

var car = {
    id:'car',
    constructor : function (args) {
        extend.call(this, vehicle, args);
      extend.call(this, driver, args);
        extend.call(this, engine, args);
        return this;
    },
    info : function () {
        console.log('boss: ' + this.vehicle.manufacturer.boss);
        console.log('country: ' + this.vehicle.manufacturer.country);
        console.log('driver: ' + this.driver.name);
        console.log('colour: ' + this.vehicle.colour);
      console.log('wheels: ' + this.vehicle.wheels);
      console.log('type: '   + this.engine.type);
      console.log('fuel: '   + this.engine.fuel);
        console.log('\n');
  }
};

function extend(proto, args){
  this[proto.id] = Object.create(proto);
  proto.constructor.call(this[proto.id], args);
}

var ferrari = Object.create(car).constructor({
    boss: 'Maurizio Arrivabene',
    country:'Italy',
    name: 'Steve',
    colour: 'red',
    wheels: 4,
    type:'100cc',
    fuel:'diesel'
});

var lotus = Object.create(car).constructor({
    name: 'Jenson Button'
});

var mclaren = Object.create(car).constructor({
  type:'hybrid',
    fuel:'battery/petrol'
});

ferrari.engine.tune();
ferrari.info();
/*
Car now super-charged with ethanol
boss: Maurizio Arrivabene
country: Italy
driver: Steve
colour: red
wheels: 4
type: super-charged
fuel: ethanol
*/

lotus.info();
/*
boss: Bernie Ecclestone
country: UK
driver: Jenson Button
colour: blue
wheels: 2
type: V6
fuel: petrol
*/

mclaren.info();
/*
boss: Bernie Ecclestone
country: UK
driver: John
colour: blue
wheels: 2
type: hybrid
fuel: battery/petrol
*/


texts: Creating abstraction to validate complex objects

texts:
I am trying to create a validator abstraction layer. These are the points I am trying to achieve:

My abstraction should be open for extension but closed for modification
The clients should not have a if...else block to handle success or failure scenario.

Validation statuses

public interface ValidationStatus {
    default void process() {

    }

    public static ValidationStatus fail(ValidationFailureCause cause, String messages) {
        ValidationFailure validationFailure = new ValidationFailure();
        validationFailure.setCause(cause);
        validationFailure.setErrorMessages(messages);
        return validationFailure;
    }

    public static ValidationStatus success() {
        return new ValidationSuccess();
    }
}

public class ValidationFailure implements ValidationStatus {
    private ValidationFailureCause cause;
    private String errorMessages;

    public void setCause(ValidationFailureCause cause) {
        this.cause = cause;
    }

    public void setErrorMessages(String errorMessages) {
        this.errorMessages = errorMessages;
    }

    @Override
    public void process() {
        if (ValidationFailureCause.MISSING_MANDATORY_FIELDS.equals(cause)) {
            throw new MandatoryElementsMissing(errorMessages);
        }
    }

}

public class ValidationSuccess implements ValidationStatus {

}

public enum ValidationFailureCause {
    MISSING_MANDATORY_FIELDS
}

The validators

public interface Validator<T> {
    /**
     * Validate an object and return the validation result as a Status.
     *
     * @param request
     *            Data to be validated
     * @return can be ValidationFailure or ValidationSuccess class instance
     */
    ValidationStatus validate(T request);

    boolean isValid(T request);
}

public class StringValidator implements Validator<String> {

    @Override
    public ValidationStatus validate(String request) {
        if (isValid(request)) {
            return ValidationStatus.success();
        }

        return ValidationStatus.fail(ValidationFailureCause.MISSING_MANDATORY_FIELDS, "Missing mandatory parameter");
    }

    @Override
    public boolean isValid(String request) {
        return StringUtils.isNotBlank(request);
    }
}

public class PersonValidator implements Validator<FlightProposalRequest> {

    @Override
    public ValidationStatus validate(FlightProposalRequest request) {
        if (isValid(request)) {
            return ValidationStatus.success();
        } else {
            return ValidationStatus.fail(ValidationFailureCause.MISSING_MANDATORY_FIELDS, "Request is null");
        }
    }

    @Override
    public boolean isValid(FlightProposalRequest request) {
        if (request == null) {
            return false;
        }

        Validator<String> requestValidator = RequestValidatorFactory.getRequestValidator(String.class);

        boolean result = requestValidator.isValid(request.getArrivalAirport());
        result = result && requestValidator.isValid(request.getDepartureAirport());
        result = result && requestValidator.isValid(request.getDepartureDate());
        result = result && requestValidator.isValid(request.getReturnDate());

        return result;
    }
}

This is my attempt at this problem. Kindly provide your feedback on my approach. With the current setup as mentioned here, my tests are passing.


texts:
Disclaimer: This question is very much like the one posted here. I gathered some opinions about my options from the answer there. Here, I just want validation about the choices I'm deciding to stick to and see what people think about the decisions specifically. Also, gather suggestions about other parts of the code I'm not specifically asking about, since I'm new to Python OOP.

Scenario: I'm writing a program that will send emails. For an email, the to, from, text and subject fields will be required and other fields like cc and bcc will be optional. Also, there will be a bunch of classes that will implement the core mail functionality, so they will derive from a base class (Mailer).

Following is my incomplete code snippet:

class Mailer(object):
    __metaclass__ == abc.ABCMeta

    def __init__(self,key):
        self.key = key

    @abc.abstractmethod
    def send_email(self, mailReq):
        pass

class MailGunMailer(Mailer):
    def __init__(self,key):
        super(MailGunMailer, self).__init__(key)

    def send_email(self, mailReq):
        from = mailReq.from
        to = mailReq.to
        subject= mailReq.subject
        text = mailReq.text
        options = getattr(mailReq,'options',None)
        if(options != None):
            if MailRequestOptions.BCC in options:
                #use this property
                pass
            if MailRequestOptions.CC in options:
                #use this property
                pass

class MailRequest():
    def __init__(self,from,to,subject,text):
        self.from = from
        self.to = to
        self.subject = subject
        self.text = text

    def set_options(self,options):
        self.options = options

class MailRequestOptions():
    BCC = "bcc"
    CC = "cc"

I've made the following decisions about code designs. What do you think about them?

The send_email() method will take four required parameters - to, from, subject and text, and bunch of other optional parameters like cc, bcc etc. So I decided to create the MailRequest wrapper, which will take the 4 required fields in the constructor, and the other optional parameters will go in the options dict.

Is this an acceptable way of doing this?  Why not use **kwargs?

Because if you define something like:

def foo(**kwargs):
    pass

Then to call it, you can't do something like:

options = []
options["one"] = 1
options["two"] = 2
foo(options)

Right?

You'd have to do something like:

foo(one=1,two=2)

Now if I have 15 parameters that foo accepts, then **kwargs isn't a good way to do this right?
I've created the MailRequestOptions class to contain static strings. The reason behind the existence of this class is, even if the user knows he has to pass some options in the options dict of the MailRequest object, how would he know which options can he set. This class could probably help the user know about what options can be set. This will also be helpful if the user has auto complete in an IDE or something. Do you think I'm thinking right? Or is this a somewhat unusual way of doing things?


texts:
The source code, or rather the concept I'd like to get reviewed is what now allows me to do the following during reflection:

object validator;  // An object known to implement IValidation<T>
object toValidate; // The object which can be validated by using the validator.

// Assume validator is IValidation<string> and toValidate string.

IValidation<object> validation
    = Proxy.CreateGenericInterfaceWrapper<IValidation<object>>( validator );

validation.IsValid( toValidate ); // This works! No need to know about the type.

// Assuming the validator validates strings, this will throw an InvalidCastException.
//validation.IsValid( 10 );

I no longer need to know about concrete types during reflection where I know types will match. It looks kind of like covariance but the result only works because types are guaranteed to match. This allows me to support any type, since no manual type checks need to be done to cast to the correct interface type.

The CreateGenericInterfaceWrapper method uses RunSharp to emit the code. This source code, and an extended explanation can be found on my blog.

My main concerns are:

Did anybody encounter such a use case before, and found a better way to solve it?
Did I write something which I could just have found in an existing library?

To further clarify why I wrote this solution, I copied the example from my blog of the code I would have to write to be able to use the IsValid method during reflection.

object validator;  // An object known to implement IValidation<T>
object toValidate; // The object which can be validated by using the validator.

// 'validator' can be any type validator which can validate 'toValidate'.

if ( validator is IValidation<string> )
{
    IValidation<string> validation = (IValidation<string>)validator;
    validation.IsValid( (string)toValidate );
}
else if ( validator is IValidation<int> )
{
    IValidation<int> validation = (IValidation<int>)validator;
    validation.IsValid( (int)toValidate );
}
else if ... // and so on to support any possible type ...


texts: Simple helper for making things "disposable"

texts:
I often write small classes to make undisposable things disposable so that .NET can handle something automatically, like stopwatches or logs. I thought why not write a small helper that can be used instead of implementing a full class for simple things.

The Usingifier requries two delegates, one for the initialization and the other one for cleaning-up. (null checks removed for brevity)

class Usingifier<T> : IDisposable
{
    private readonly Func<T> _initialize;
    private readonly Action<T> _cleanUp;
    private T _state;

    public Usingifier(Func<T> initialize, Action<T> cleanUp)
    {
        _initialize = initialize;
        _cleanUp = cleanUp;
    }

    public Usingifier<T> Initialize()
    {
        _state = _initialize();
        return this;
    }
    public virtual void Dispose()
    {
        if (_state != null)
        {
            _cleanUp(_state);
        }
    }
}

and here's an example with a Stopwatch

using (var autoStopwatch = new Usingifier<Stopwatch>(() => Stopwatch.StartNew(), sw => sw.Elapsed.Dump()))
{
    autoStopwatch.Initialize();
    Thread.Sleep(2000);
}


texts: PHP Shopping Website with Cart - Returning a HTML String

texts:
Edit

If there is a better way to ask this question to avoid negative votes, please let me know.
I have looked into https://codereview.stackexchange.com/help/how-to-ask

How would I implement a class dedicated to returning html strings for a list of products/cart items?

Written as part of an interview assignment.
Simply this is a shopping website with some items a user may add or remove from their shopping cart.
This function is responsible for returning the html to display for the list of cart items.
Currently there is no dedicated class for returning html strings.
I feel I would be moving most of this code into another class, defeating the point.

Code:

function listItems()
{
    $formatter = new Formatter();
    $html = "";
    $id = 0;
    foreach ($_SESSION["Cart"] as $item) {
        if ($item["quantity"] > 0) {
            $html = $html .
                '

'.$this>getName($item) .'

Price: $' . $formatter->formatPrice($item) . '

Quantity: ' . $item["quantity"] . '

Total: $' . $this->getTotal($item) . '

                    <form class="removeForm" method="POST">
                        <input class="removeInput" type="hidden" name="removeId" value=' . $id . ' />
                        <input class="removeInput"  type="submit" name="removeButton" value="Remove from Cart" />
                    </form>

';
        }
        $id++;
    }

    $html = $html .
        '

Overall Total: $' . $this->getOverallTotal() . '

';

    return $html;
}

Formatter class method returns a number with 2 decimal point format.

Full Repository here if you want more to critique:

https://github.com/NathanielPather/Basic-Shopping-Cart/blob/Post-Code-Review/ShoppingCart.php


texts: how to efficiently draw line numbers in edittext ondraw without causing lag in scrolling

texts:
I have an implementation of an edit text to show line numbers and also highlight the current line.
I think it needs more optimization because when I scroll through the edit text with about 500 lines of code, it lags, yet when I comment out the code, the scrolling is smooth.
I need help optimizing this onDraw method in which I do everything above.
The line numbers appear on the right with a custom separator e.g
  1|
...
 10|
..
100|
..

public class NumberedEditText extends AppCompatEditText {

  private Rect nRect;
  private Rect nRect_;
  private int nOffset;
  private Paint nPaint;
  private Paint nPaint_;
  private boolean nShow;
  private int nAlignment;
  private char nSeparator;
  private boolean nLineHlt;

  public NumberedEditText (Context context, AttributeSet attrs) {
    super (context, attrs);

    nRect = new Rect ();
    nRect_ = new Rect ();
    nPaint = new Paint ();
    nPaint_ = new Paint ();

    nAlignment = NUMBER_ALIGNMENT_LEFT_SEP_LEFT;
    nSeparator = '|';
    nLineHlt = true;
    nShow = true;
    nOffset = 2;

    nPaint_.setColor (Color.parseColor ("#222222"));

    nPaint.setColor (Color.LTGRAY);
    nPaint.setStyle (Paint.Style.FILL);
    nPaint.setTypeface (Typeface.MONOSPACE);
  }

  @Override
  public void onDraw (Canvas canvas) {
  // I use short variable names because i think
  // they are executed much faster.
    if (nShow) {
      nPaint.setTextSize (getTextSize () - nOffset);

      int bl = getBaseline ();
      int lc = getLineCount ();
      int lh = getLineHeight ();

      // i use an array here for efficient
      // random access to store the
      // positions where the line numbers
      // will be according to the number
      // of lines
      String lcs = Integer.toString (lc);
      int nl = lcs.length ();
      char[] ch = new char[nl + 1];
      int cl = ch.length;
      String s;

      // i fill the array with spaces
      // ready to be replaced with numbers
        for (int i = 0; i < nl; i++)
          ch [i] = 32;
       // set the last character to the separator
        ch [nl] = nSeparator;
        // now i loop thru all the numbers
        // replacing the characters in the array
        // (with spaces) with numbers
        // to form something like
        // '   1|'
        // '  10|'
        // ' 100|'
          for (int i = 1, j = cl - 2; i <= lc; i++, bl += lh) {
            if (i == 10 || i == 100 || 1 == 1000 || i == 10000 || i == 100000)
              j--;
            s = Integer.toString (i);
            if (j > -1)
              s.getChars (0, s.length (), ch, j);

            canvas.drawText (ch, 0, cl, nRect.left, bl, nPaint);
          }
          // now i set the padding and an
          // additional margin
      setPadding ((int) nPaint.measureText (lcs + "__"), getPaddingTop (), getPaddingRight (), getPaddingBottom ());
    }

    // this is to highlight the current line
    Layout l = getLayout ();
    if (nLineHlt && l != null) {
      int ln = l.getLineForOffset (getSelectionStart ());
      getLineBounds (ln, nRect_);
      canvas.drawRect (nRect_, nPaint_);
    }
    super.onDraw (canvas);
  }
}
```


texts:
I'm implementing this date class based on <ctime>
I'll appreciate your comments, critics and advice.

Please review, thank you!.

Date.h

/*
 * Date.h
 *
 * Usage:
 * Create object, and then call Set(day, month, year)
 * Throws invalid argument exception if Teb 29th is set with the wrong year (is not leap year)
 * TODO: throw invalid argument exception if date is invalid
 * Use GetDate() to get date formatted as "dd/mm/yyy"
 * Use GetAscTime() to get date formatted as "ddd mmm yy hh:mm:ss yyyy"
 * Substraction can be done between dates, it will return the differences in days
 *  i.e. Date today - Date yesterday = 1
 * TODO: overload + operator as Date + int
 * TODO: overload - operator as Date - int
 */
#include <ctime>
#include <string>

#ifndef DATE_H_
#define DATE_H_

class Date
{
public:
    Date();
    void Set(int day, int month, int year);
    int operator - (const Date& rhs);
    const char* GetDate() const;
    const char* GetAscTime() const;
    time_t GetDateValue() const;

private:
    std::time_t ttTime;
    std::tm tmTime;
    mutable char szTimeBuffer[255];
    static constexpr int nSecPerDay = 60 * 60 * 24;
};

#endif /* DATE_H_ */

Date.cpp

/*
 * Date.cpp
 */
#include "Date.h"
#include <stdexcept>

Date::Date()
    : ttTime(0), tmTime({0}), szTimeBuffer("")
{
    std::time(&ttTime);
    localtime_s(&tmTime, &ttTime);
}

void Date::Set(int day, int month, int year)
{
    tmTime.tm_mday = day;
    tmTime.tm_mon = month - 1;
    tmTime.tm_year = year - 1900;

    ttTime = std::mktime(&tmTime);

    // Temp date constructed to check if Feb 29th for the specified year exists
    // checks if the value of 29/Feb/YYYY is the same as 01/Mar/YYYY
    // if true, means that year is not leap year and should not have Feb 29th
    // throws invalid argument exception

    std::tm tmTemp = {0};
    std::time_t ttTemp = 0;

    // Specify march 1st, use same year as input
    tmTemp.tm_mday = 1;
    tmTemp.tm_mon = month;
    tmTemp.tm_year = tmTime.tm_year;

    ttTemp = std::mktime(&tmTemp);

    if(ttTemp == ttTime)
    {
        std::string errMsg("Error!, Feb 29th doesn't exist in year ");
        errMsg.append(std::to_string(tmTime.tm_year + 1900));
        errMsg.append("!!");
        throw( std::invalid_argument(errMsg) );
    }

}

int Date::operator -(const Date& rhs)
{
    return (std::difftime(ttTime, rhs.ttTime) / nSecPerDay);
}

const char* Date::GetDate() const
{
    std::strftime(szTimeBuffer, 255, "%d/%m/%y", &tmTime);
    return szTimeBuffer;
}

const char* Date::GetAscTime() const
{
    asctime_s(szTimeBuffer, 255, &tmTime);
    return szTimeBuffer;
}

time_t Date::GetDateValue() const
{
    return ttTime;
}


texts: Is it possible to do a realloc that does not deallocate an array first?

texts:
I have a simple utility to reallocate arrays of various kind and dimensions, an excerpt of which is reported below. I wonder however if one can avoid deallocate an array that just needs to be expanded, instead of deallocating it first. Also, I am interested in knowing what is a good strategy to avoid duplicating the code (e.g., due to different kind and dimensions of the array to be reallocated). Is it possible to return a reshaped array without allocating/deallocating it?
module ModuleSystemUtils

  implicit none

  private

  interface realloc
     module procedure realloc_integer_vec
     module procedure realloc_dble_vec
  end interface realloc
  public realloc

contains

  subroutine realloc_integer_vec(vec,n)
    integer, allocatable, intent(inout) :: vec(:)
    integer             , intent(in) :: n
    if(allocated(vec))then
       if(size(vec,1)/=n)then
          deallocate(vec)
          allocate(vec(n))
       endif
    else
       allocate(vec(n))
    endif
    vec=0
  end subroutine realloc_integer_vec

  subroutine realloc_dble_vec(vec,n)
    real(kind(1d0)), allocatable, intent(inout) :: vec(:)
    integer             , intent(in) :: n
    if(allocated(vec))then
       if(size(vec,1)/=n)then
          deallocate(vec)
          allocate(vec(n))
       endif
    else
       allocate(vec(n))
    endif
    vec=0.d0
  end subroutine realloc_dble_vec

end module ModuleSystemUtils

post scriptum:
For folks not familiar with the simple syntax of modern Fortran, I suggest the following quick modern Fortran tutorial.


texts:
Is there a way to shorten the conditional statement below? As you can see, there's a lot of repetition. Is the if-statement the best approach here? Bearing in mind that there will likely be more numbers to check for (not, just 2 and 3):

  var searchArea = function() {
    // Search the area around the current position for hidden doors
    if(detectWall('left') == 2) {
        status.innerHTML = "Hidden Door to the left";
    } else if (detectWall('right') == 2) {
        status.innerHTML = "Hidden door to the right";
    } else if (detectWall('up') == 2) {
        status.innerHTML = "Hidden door above you";
    } else if (detectWall('down') == 2) {
        status.innerHTML = "Hidden door below you";
    } else if (detectWall('right') == 3 || detectWall('left') == 3 || detectWall('up') == 3 || detectWall('down') == 3) {
        status.innerHTML = "You are close to a fountain";
    }

}

var detectWall = function(dir) {
    // Detect walls from the array
    switch(dir) {
        case 'right':
            return mapArray[parseInt(player.y/20)][parseInt((player.x+20)/20)]
        case 'left':
            return mapArray[parseInt(player.y/20)][parseInt((player.x-20)/20)]
        case 'up':
            return mapArray[parseInt((player.y-20)/20)][parseInt(player.x/20)]
        case 'down':
            return mapArray[parseInt((player.y+20)/20)][parseInt(player.x/20)]
        default:
            return false
    }

}


texts: Setting periodicity in the week in Google Calendar

texts:
I am trying to write a generic JavaScript subroutine to set the periodicity in the week:

var items = {"0": "none", "1":"Daily", "2": "Every weekday (Monday to Friday)", "3": "Weekly"};

I would like to improve this to make it more generic and readable if possible.

var callback = selectDay(idValue);
createSelect(items, idValue, callback);

var createSelect = function (items, idValue) {
    var selElem = document.createElement("select");
    $.each(items, function (key, value) {
        var ov = document.createElement("option");
        ov.value = key;
        ov.appendChild(document.createTextNode(value));
        selElem.appendChild(ov);
    });
    $(idValue).prepend(selElem);
};

var selectDay = function (idValue, element) {
    var element = $(idValue);
    var childElements = idValue + '_';
    element.find('select').change(function () {
        if($(this).val() === '0') {
            element.find('label').hide();
            $(this).closest('div').find('input').attr("checked", false);
        }
        if($(this).val() === '1') {
            element.find('label').hide();
            $(this).closest('div').find('input').attr("checked", true);
        }
        if($(this).val() === '2') {
            element.find('label').show();
            for (var i = 0; i < 5; i += 1) {
                $(childElements + i).attr("checked", true);
            }
            for (var i = 5; i < 7; i += 1) {
                $(childElements + i).attr("checked", false);
            }
        }
        if($(this).val() === '3') {
            element.find('label').show();
            $(this).closest('div').find('input').attr("checked", false);
            $(childElements + (new Date()).getDay()).attr("checked", true);
        }
    });
};

var items = {"0": "none", "1":"Daily", "2": "Every weekday (Monday to Friday)", "3": "Weekly"};
var idValue = '#contest_data_updatePeriodicity_days';
createSelect(items, idValue);
selectDay(idValue);

My questions are:

How can I ameliorate this piece of code?
How can make a callback in order to make something like this?

JSFiddle


texts:
I wrote a program to copy directories in Windows 10. I have tested copying a directory (696MB) in 3 different ways:

xcopy: time taken - 52 seconds
ctrl+c: time taken - 78 seconds
My program: time taken - 193 seconds

What can I do to improve the performance of my program to be as fast as xcopy?

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <io.h>
#include <Windows.h>

int copyfile(const char *inputfile, const char *outputfile);
void CopyDirectory(const char *src_dir, const char *dst_dir);

int main(void)
{
    clock_t t1 = clock();

    // src directory must end with \\*
    /* dst directory must end with \\ */
    CopyDirectory("C:\\Users\\green\\Downloads\\Folder1\\*",
                  "C:\\users\\green\\desktop\\Folder1\\");

    clock_t t2 = clock();
    printf("time elapsed : %.4f secs\n", (double)(t2 - t1) / CLOCKS_PER_SEC);

    puts("Press any key to continue...");
    getchar();
    return 0;
}

void CopyDirectory(const char *src_dir, const char *dst_dir)
{
    intptr_t hFile;
    struct _finddata_t c_file;

    char *ptr;
    char buf[MAX_PATH + 20];
    char tmp_dir[MAX_PATH + 20];
    char f_name[MAX_PATH + 20];

    strcpy(buf, src_dir);
    ptr = buf + strlen(buf) - 1;

    if ((hFile = _findfirst(src_dir, &c_file)) == -1L) {
        fprintf(stderr, "Failed to open directory %s\n", src_dir);
        return;
    }
    CreateDirectoryA(dst_dir, NULL);
    while (_findnext(hFile, &c_file) == 0) {
        if (c_file.attrib & _A_SUBDIR) {
            if (strcmp(c_file.name, "..")) {
                /*......*/
                strcpy(tmp_dir, dst_dir);
                strcat(tmp_dir, c_file.name);
                strcat(tmp_dir, "\\");
                /*......*/
                *ptr = '\0';
                strcat(buf, c_file.name);
                strcat(buf, "\\*");
                CopyDirectory(buf, tmp_dir);
            }
        }
        else {
            strcpy(tmp_dir, dst_dir);
            strcat(tmp_dir, c_file.name);

            *ptr = '\0';
            strcpy(f_name, buf);
            strcat(f_name, "\\");
            strcat(f_name, c_file.name);
            copyfile(f_name, tmp_dir);
            strcpy(tmp_dir, dst_dir);
        }
    }
    _findclose(hFile);
}

int copyfile(const char *inputfile, const char *outputfile)
{
    static FILE *fp_I;
    static FILE *fp_O;

    fp_I = fopen(inputfile, "rb");
    if (!fp_I) {
        perror(inputfile);
        return -1;
    }

    fp_O = fopen(outputfile, "wb");
    if (!fp_O) {
        fclose(fp_I);
        perror(outputfile);
        return -1;
    }

    static size_t nr;
    const static size_t bufsize = 512 * 512;
    static char buf[bufsize];

    while ((nr = fread(buf, 1, bufsize, fp_I)) > 0) {
        fwrite(buf, 1, nr, fp_O);
    }

    fclose(fp_I);
    fclose(fp_O);
    return 0;
}


texts: Dataset with optional addition to where statement

texts:
I am trying to generate a dataset from a query that has a where statement. If the user passes a value additional things need to be added to the where statement. Is this the best way to go about this?

class TableAdapters
{
    public class FindScriptByTargetVDN
    {
        public static DataSet Fill(SqlConnection connection, string parameter)
        {
            string conditional = string.Empty;
            if (parameter.Length > 0)
            {
                conditional = "and svce.PeripheralNumber= " + parameter + " ";
            }
            string query = "select svce.PeripheralNumber AS Service, "
                + "ms.EnterpriseName AS [Script Name], "
                + "p.EnterpriseName AS Peripheral, "
                + "sg.PeripheralNumber AS [Skill Mapping], "
                + "s.Version AS [Latest Version], "
                + "s.DateTime AS Created, "
                + "s.Author "
                + "from Script_Cross_Reference scr "
                + "LEFT OUTER JOIN Script s on s.ScriptID = scr.ScriptID "
                + "LEFT OUTER JOIN Master_Script ms on s.MasterScriptID = ms.MasterScriptID "
                + "LEFT OUTER JOIN Service svce on svce.SkillTargetID = scr.ForeignKey "
                + "LEFT OUTER JOIN Peripheral p on svce.PeripheralID = p.PeripheralID "
                + "LEFT OUTER JOIN Service_Member sm on svce.SkillTargetID = sm.ServiceSkillTargetID "
                + "LEFT OUTER JOIN Skill_Group sg on sg.SkillTargetID = sm.SkillGroupSkillTargetID "
                + "where s.Version = ms.CurrentVersion and scr.TargetType = 1 "
                + conditional
                + "order by svce.PeripheralNumber, ms.EnterpriseName, p.EnterpriseName";
            SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(new DataTable());
            adapter.Fill(dataSet.Tables[0]);
            return dataSet;
        }
    }
}

Here is an example of the call:

this.FindScriptsDataGrid.DataSource = TableAdapters.FindScriptByTargetVDN.Fill(connection, this.ValueTextBox.Text).Tables[0];

The connection is defined before the call. The reason for the some what round about method is the user has the option of defining what server they want to run this query on before they run it.


texts: class design improvement - user validation

texts:
I'm looking to improve this class - any suggestions?  It checks for empty, name, email, and password.
The regex for email is very simple.  A very lengthy article from the Linux Journal for improving upon this is here.  The character set for password I borrowed from the NASA signup page.  For name I allow letters, periods, and dashes.  Testing for empty was developed with in this SO Post

class check
  {
  static function empty_user($a)
    {
    return (int)!in_array('',$a,TRUE);
    }
  static function name($a)
    {
    return preg_match('/^[a-zA-Z-\.]{1,40}$/',$a);
    }
  static function email($a)
    {
    return preg_match('/^[a-zA-Z0-9._s-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$a);
    }
  static function pass($a)
    {
    return preg_match('/^[a-zA-Z0-9!@#$%^&*]{6,20}$/',$a);
    }
  }


texts:
One of my assignments was to create a chessboard. In this assignment I could not use an array, or a form of list or what not. Below is my code for the creation of the chessboard:

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Color;

public class Checkerboard
{
    private int xPositions;
    private int yPositions;
    private int squareSize;

    private Color tileColor;

    public Checkerboard()
    {
        xPositions = 0;
        yPositions = 0;
        squareSize = 50;

        tileColor = Color.WHITE;
    }

    public void draw(Graphics2D g2)
    {
        for(int i = 1; i <= 64; i++)
        {
            Rectangle tile = new Rectangle(xPositions, yPositions, squareSize, squareSize);

            g2.setColor(tileColor);
            g2.fill(tile);

            updateTileColor(i);
            updatePositions(i);
        }
    }

    private void updatePositions(int tileNumber)
    {
        if((tileNumber % 8) == 0)
        {
            xPositions = 0;
            yPositions = yPositions + squareSize;
        }
        else
        {
            xPositions = xPositions + squareSize;
        }
    }

    private void updateTileColor(int tileNumber)
    {
        if((tileNumber % 8) != 0)
        {
            tileColor = (tileColor == Color.WHITE) ? Color.BLACK : Color.WHITE;
        }
    }
}

Could anyone tell me as to whether this code is optimal for the assignment, if any bad practices have been made, or any way I can generally improve my code and my knowledge of the code?


texts: JavaScript on page load and on scroll functions

texts:
Would it serve much purpose to work at refactoring the latter parts of this code?

// This part is OK
function isScrolledIntoView(elem, trigger_height) {

  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();
  var elemTop = elem.offset().top;

  if (trigger_height == false) {
    trigger_height = elem.height()
  }
  var elemBottom = elemTop + trigger_height;

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

// This function happens when the page first loads
$("p").addClass('hidden').each(function() {
  $this = $(this);
  if (isScrolledIntoView($this, false)) {
    $this.removeClass("hidden");
  }
});

// This function happens on scroll, but basically repeats itself
$(window).off('scroll').scroll(function() {
  $("p.hidden").each(function() {
    $this = $(this);
    if (isScrolledIntoView($this, false)) {
      $this.removeClass("hidden")
    }
  });
});

To me, it seems like there isn't – but at the same time its repetitive:

$this = $(this);
if (isScrolledIntoView($this, false)) {
  $this.removeClass("hidden")
}

Is there a general rule that anyone follows such as "only refactor if you're looking at > 5 lines of repeated code", or should you be refactoring absolutely everything as you go?


texts: Returning an array containing values from two passed in arrays

texts:
This is a simple piece of code which takes two arrays supplied as parameters, then appends them to  a new array that contains the values from the supplied arrays. Any suggestions for improvement would be greatly appreciated.

public static int[] append(int[] list1, int[] list2) {
    int[] appendedList = new int[list1.length + list2.length];
    for(int i = 0; i < list1.length; i++) {
        appendedList[i] = list1[i];
    }
    for(int i = 0; i < list2.length; i++) {
        appendedList[i + list1.length] = list2[i];
    }
    return appendedList;
}


texts:
The things I'm interested the most from the review are:

The performance of the code
Overall review of the code structure, styling rules and naming conventions.

Problem: 2

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

import math
import itertools
#----------------------------------------------------------------------------------
def calc_fibonacci_num(n):
    """Calculates the fibonacci number at the given index.

    Arguments:
        type:<int> - Index value of the fibonacci sequence
    Return:
        type:<int> - Fibonacci number at the given index.
    """
    return int(((1 + math.sqrt(5))**n -(1 - math.sqrt(5))**n)/(2**n*math.sqrt(5)))

#----------------------------------------------------------------------------------
def calc_fibonacci_seq(n):
    """Generates the fibonacci sequence with the highest
    value equal to or less then the number provided by the user.

    Arguments:
        type:<int> - Thrshold value for the fibonacci sequence.
    Return:
        type:<arr> - An array holding the fibonacci sequence.
    """
    return [calc_fibonacci_num(x) for x in itertools.takewhile(lambda x: calc_fibonacci_num(x) <= n, itertools.count())]

#----------------------------------------------------------------------------------
def calc_fibonacci_sum(n, d = 0):
    """Calculates the sum of the numbers in fibonacci sequence.
    Filtering of the numbers to be added is controled with the module operator.

    Arguments:
        type:<int> - Thrshold value for the fibonacci sequence.
        type:<int> - Division value for module operation.
    Return:
        type:<int> - The sum of the numbers in the fibonacci sequence.
    """
    if d > 1 :
        return sum(x for x in calc_fibonacci_seq(n) if x % d == 0)
    return sum(x for x in calc_fibonacci_seq(n))

#----------------------------------------------------------------------------------
def main():

    print(' Fibonacci-seq : {}'.format(calc_fibonacci_seq(4000000)))
    print(' Fibonacci-sum : {}'.format(calc_fibonacci_sum(4000000, 2)))

#----------------------------------------------------------------------------------
if __name__ == "__main__":
    main()


texts:
Problem statement:

  Two singly linked lists join at a common node, making a Y shape. It is guaranteed that the common tail does not loop back. Find the junction node. Linear time, constant space.

It is an exercise for my students; nothing competitive.

This is what's provided:

list.h

#ifndef LIST_H
#define LIST_H

#include <stddef.h>

typedef struct node_s node_t;

size_t list_size(node_t * head, node_t ** tail);
node_t * list_tail(node_t * head);
node_t * list_reverse(node_t * head);
node_t * list_nth_node_unguarded(node_t * head, size_t n);
#ifdef EXERCISE_TEST
void list_link_node(node_t * from, node_t * to);
node_t * create_silly_list(size_t n);
#endif
#endif

list.c

#include "list.h"
#include <stdlib.h>

struct node_s {
    node_t * next;
};

void list_link_node(node_t * from, node_t * to)
{
    from->next = to;
}

size_t list_size(node_t * head, node_t ** tail)
{
    node_t dummy = { .next = head };
    head = &dummy;

    size_t size = 0;

    while (head->next) {
        size++;
        head = head->next;
    }

    if (tail) {
        *tail = head;
    }

    return size;
}

node_t * list_tail(node_t * head)
{
    node_t dummy = { .next = head };
    head = &dummy;

    while (head->next) {
        head = head->next;
    }

    return head;
}

node_t * list_reverse(node_t * head)
{
    node_t * prev = NULL;

    while (head) {
        node_t * next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }

    return prev;
}

node_t * list_nth_node_unguarded(node_t * head, size_t n)
{
    while (n--) {
        head = head->next;
    }
    return head;
}

#ifdef EXERCISE_TEST
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>

node_t * find_junction(node_t *, node_t *);

node_t * create_silly_list(size_t n)
{
    node_t * head = calloc(n, sizeof(*head));
    for (size_t i = 1; i < n; ++i) {
        head[i - 1].next = &head[i];
    }
    return head;
}

bool test_excersize(size_t size1, size_t size2, size_t junction_index)
{
    node_t * head1 = create_silly_list(size1);
    node_t * head2 = create_silly_list(size2);
    node_t * tail2 = list_tail(head2);
    node_t * real_junction = list_nth_node_unguarded(head1, junction_index);
    list_link_node(tail2, real_junction);
    node_t * junction = find_junction(head1, head2);
    free(head1);
    free(head2);
    return junction == real_junction;
}

int main()
{
    printf("%d\n", test(10, 20, 5));
    printf("%d\n", test(10, 20, 0));
    return 0;
}
#endif

Makefile

CFLAGS += --std=c99 -g -DEXERCISE_TEST

SRC := list.c main.c junction.c
OBJ := $(SRC:%.c=%.o)
DEP := $(SRC:%.c=%.d)

main: $(OBJ)
    $(CC) -o $@ $^

%.o: %.c
    $(CC) -c $(CFLAGS) -o $@ $<

%.d: %.c
    $(CC) -c -MM -MT $(CFLAGS) -o $@ $<

-include $(DEP)

This is what is expected:

junction.c

#include "list.h"
#include <assert.h>

node_t * find_junction(node_t * head1, node_t * head2)
{
    node_t * tail1;
    node_t * tail2;

    size_t x1_plus_y = list_size(head1, &tail1);
    size_t x2_plus_y = list_size(head2, &tail2);

    assert (tail1 == tail2);

    list_reverse(head1);
    size_t x1_plus_x2 = list_size(head2, 0);
    list_reverse(tail1);

    size_t x1_minus_x2 = x1_plus_y - x2_plus_y;
    size_t x1 = (x1_plus_x2 + x1_minus_x2) / 2;

    return list_nth_node_unguarded(head1, x1);
}

Students are fluent in c; in fact, a given part is mostly understood.

Questions:

Am I doing something wrong? I am mostly concerned with overflows in x1_minus_x2 = x1_plus_y - x2_plus_y.
Is it a good exercise, or the algebra jumps out like Jack off the box?
At the first glance, size_t list_size(node_t * head, node_t ** tail); violates the SRP. Really it does not, because tail computation comes free of cost. Is it obvious, or should I emphasize on it?


texts: pyramid numbers in alternative reverse order

texts:
I was asked to write code for the below structure:

     1
    3 2
   4 5 6
  10 9 8 7
11 12 13 14 15

And I tried the below code, which works, yet I'm wondering if there is any better approach than this:

public static void main(String[] args) {

    int n=5; // no of rows
    int c=0;

    for(int i=1;i<=n;i++){

        for(int k=i;k<n;k++){

            System.out.print(" ");
        }

        if(i%2!=0){
        for(int j=0;j<i;j++){
            c++;
            System.out.print(c +" ");
        }
        }
        else{
            int a[] = new int [i+1];
            for(int j=0;j<i;j++){
                c++;
                a[j]=c;
            }
            for(int j=i-1;j>=0;j--){
               System.out.print(a[j]+" ");
            }
        }

        System.out.println("");
    }
}

Is there any better implementation or am I doing it right?


texts: Building a minimal-height BST from a monotonically increasingly ordered array structure

texts:
Problem statement:

  Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.

Assumptions:

The array (and therefore BST) will only contain the type int. Other integral types are unsupported.

The problem statement's description is a precondition and can therefore be taken for granted. No checks of uniqueness and unsortedness will be needed.

The algorithm:

Divide and conquer. The midpoint of the array will be the root. Because BSTs are a recursive data structure, the left and right pointers of the root are also BSTs. Recurse on the (beginning, midpoint-1) and the (midpoint+1, end) of the array.

Any recommendations, tips, and corrections are welcome!

#include <iostream>
#include <vector>
#include <memory>

struct Node {
    int data;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;
    Node() : left(), right() {}
    Node(int data) : data(data), left(), right() {}
};

template <typename It>
It get_midpoint_iterator(It start, It end) {
    auto midpoint = std::distance(start, end) / 2;
    It mid = start;
    std::advance(mid, midpoint);
    return mid;
}

template <typename It>
void create_bst_helper(std::unique_ptr<Node>& root, It start, It end) {
    if(start >= end) {
        return;
    }

    if(!root) {
        It midpoint = get_midpoint_iterator(start, end);
        root = std::move(std::unique_ptr<Node>(new Node(*midpoint)));
        // left subtree is [start, midpoint)
        create_bst_helper(root->left, start, midpoint);
        // right subtree is [midpoint+1, end)
        create_bst_helper(root->right, std::next(midpoint, 1), end);
    }
}

template <typename It>
std::unique_ptr<Node> create_bst(It start, It end) {
    std::unique_ptr<Node> bst = nullptr;
    if(start != end) {
        create_bst_helper(bst, start, end);
    }
    return bst;
}

int main() {
    std::vector<int> v{1,2,3,4,5,6};
    std::unique_ptr<Node> bst = create_bst(std::begin(v), std::end(v));
}


texts:
I have created a script for article scraping - it finds title, subtitle, href-link, and the time of publication. Once retrieved, information is converted to a pandas dataframe, and the link for the next page is returned as well (so that it parses page after page).

Everything works as expected, though I feel there should be an easier -or more elegant- way of loading a subsequent page within main function.

import requests
import pandas as pd
from bs4 import BeautifulSoup
from time import sleep

def read_page(url):
    r = requests.get(url)
    return BeautifulSoup(r.content, "lxml")

def news_scraper(soup):
    BASE = "https://www.pravda.com.ua"
    container = []
    for i in soup.select("div.news.news_all > div"):
        container.append(
            [
                i.a.text,  # title
                i.find(class_="article__subtitle").text,  # subtitle
                i.div.text,  # time
                BASE + i.a["href"],  # link
            ]
        )

    dataframe = pd.DataFrame(container, columns=["title", "subtitle", "time", "link"])
    dataframe["date"] = (
        dataframe["link"]
        .str.extract("(\d{4}/\d{2}/\d{2})")[0]
        .str.cat(dataframe["time"], sep=" ")
    )
    next_page = soup.select_one("div.archive-navigation > a.button.button_next")["href"]

    return dataframe.drop("time", axis=1), BASE + next_page

def main(START_URL):
    print(START_URL)

    results = []

    soup = read_page(START_URL)
    df, next_page = news_scraper(soup)
    results.append(df)

    while next_page:
        print(next_page)

        try:
            soup = read_page(next_page)
            df, next_page = news_scraper(soup)
            results.append(df)
        except:
            next_page = False

        sleep(1)

    return pd.concat([r for r in results], ignore_index=True)

if __name__ == "__main__":
    df = main("https://www.pravda.com.ua/archives/date_24122019/")
    assert df.shape == (120, 4) # it's true as of today, 12.26.2019


texts:
What are some advantages and disadvantages of providing default implementations for dependencies. I have chosen to do this because it allows the objects to be easily used in the application but also allows me to mock for unit testing.

public class RoleProvider : RoleProviderBase
{
    private IRoleDataProvider _roleDataProvider;

    private IEntitlementsDataProvider EntitlementsDataProvider
    {
        get
        {
            if (_roleDataProvider == null)
            {
                _roleDataProvider = new RoleDataProvider();
            }
            return _roleDataProvider;
        }
    }

    public RoleProvider(IRoleDataProvider roleDataProvider)
    {
        _roleDataProvider = roleDataProvider;
    }

    public RoleProvider()
    {
    }
}


texts: Performing the Lychrel algorithm in Rust

texts:
A Lychrel number is a natural number that cannot form a palindrome through the iterative process of repeatedly reversing its digits and adding the resulting numbers.

In the code below I'm trying to calculate the palindrome that comes from the end of this algorithm up to some limit (as it is hypothesized to be infinite for some values).

extern crate num;
extern crate time;

use num::bigint::BigInt;
use num::FromPrimitive;
use time::PreciseTime;
use std::env;

// The limit for number of iterations to run.
static LIMIT: u64 = 5000;

// Return the "lychrel" number for a given input, or the number reached
// at iteration LIMIT, whichever comes first.
fn lychrel(number: u64) -> BigInt {
    let mut next = FromPrimitive::from_u64(number).unwrap();
    let mut iterations = 0;
    let mut rev;

    loop {
        // rev = reverse(&next, &zero);
        rev = reverse_str(&next);

        if &next == &rev {
            break;
        }

        next = &next + &rev;

        if iterations % 1000 == 0 { println!("{} iterations complete.", iterations) }
        if iterations == LIMIT { break; }

        iterations += 1;
    }

    next
}

// Integer function is nearly 4 (!) times slower.
// So this function has been removed, in favour of reverse_str()
// fn reverse(number: &BigInt, zero: &BigInt) -> BigInt {
//  let zero: BigInt = FromPrimitive::from_u64(0).unwrap();
//  let mut reverse = FromPrimitive::from_u64(0).unwrap();
//  let mut temp = number.clone();

//  while &temp > &zero {
//      reverse = reverse * 10 + &temp % 10;
//      temp = &temp / 10;
//  }

//  reverse
// }

// Transform a BigInt into a char array, reverse and parse back into a BigInt.
fn reverse_str(number: &BigInt) -> BigInt {
    let reverse_string: String = number.to_string().chars().rev().collect();
    let reverse_value: BigInt = reverse_string.parse().unwrap();
    number + reverse_value
}

fn main() {
    let args: Vec<_> = env::args().collect();
    let start = PreciseTime::now();

    let input = args[1].parse::<u64>().expect("Usage: ./lychrel <number>");

    lychrel(input);
    // println!("{}", lychrel(input));

    let end = PreciseTime::now();
    println!("Processed {} iterations in {} seconds.", LIMIT, start.to(end));
}

(Note that this requires the num and time crates to be installed)

This is my first time using Rust, so I'm finding the entire idea of "ownership" pretty new. Am I passing data by reference too much?  I seem to have a lot of ampersands.


texts:
I am just trying to apply a "mean filter" with C#. The working code below gets window size (3,5,7,9,...) from textBoxWinSize and applies the mean filter.

I am new and I want your comments and suggestions about my code so I can improve myself.

Can I make it faster? How? Is there any unnecessary or absurd part in the code? Can it be improved in any other way?

I do not care about border pixels for now.

private void buttonApplyFilter_Click(object sender, EventArgs e)
{
    int R, G, B,aveR,aveG,aveB;
    double sumR,sumG,sumB;
    Color pixel_value;
    Bitmap bmp = new Bitmap(bmpOrig);
    int WinSize = Int32.Parse(textBoxWinSize.Text);
    int col,row,n,m;
    for (col = (WinSize-1); col < (bmp.Width-WinSize); col++)
        for (row = (WinSize-1); row < (bmp.Height-WinSize); row++)
        {
            sumB = 0;
            sumG = 0;
            sumR = 0;
            for (m=-(WinSize-1)/2; m<=(WinSize-1)/2;m++)
                for (n=-(WinSize-1)/2;n<=(WinSize-1)/2;n++)
                {
                    pixel_value = bmp.GetPixel(col+m, row+n);
                    R = (pixel_value.R);
                    G =(pixel_value.G);
                    B = (pixel_value.B);
                    sumR = sumR + R;
                    sumG = sumG + G;
                    sumB = sumB + B;
                }
            aveR = (int)(sumR / (WinSize * WinSize));
            aveG = (int)( sumG / (WinSize * WinSize));
            aveB = (int)( sumB / (WinSize * WinSize));
            bmp.SetPixel(col, row, Color.FromArgb(aveR, aveG, aveB));
        }
    pictureBox1.Image = bmp;

}


texts:
As with other inputs, file paths should be validated before thay could be passed to operating system interfaces. Since chroot(2) has a bit more than some portability issues, oftentimes it is desireable to use a path-validating function.

The general idea, is that no path component should be .., and that if we chdir(2) to the path in question, we must make sure it doesn't begin with a <slash> ("/").

Also, for some application, files or directories with certain prefix (say <dot> (".")) should be outright rejected.

Here's my example of PHP code that does path-validation. I'd like some expertized opinion from the members of the site.

<?php
 function antitraversal($s)
 {
   if( !is_string($s) ) die("Invalid argument: $s");

   $components = explode("/", $s);
   foreach($components as $component) {
     if( $component[0] === "." ) die("Invalid argument: $s");
   }

   if( $s[0] === "/" ) { return ".$s"; } else { return $s; };
 }

For simplicity, we'll assume the script runs in Unix-like environments.


texts: Time Limit Exceeded for ETF - Euler Totient Function at Spoj

texts:
In number theory, the totient φ of a positive integer n is defined to be the number of positive integers less than or equal to n that are coprime to n.

Given an integer n (1 ≤ n ≤ 106), compute the value of the totient φ.

For the code written below, this is giving TLE. How i can optimize this code or should i prefer some other language for this problem.
Link of the problem at spoj

test = int(input())
for t in range(test):
    n = int(input())
    result = n
    i = 2
    while i*i <= n :
        if n %i == 0:
            while n%i == 0 :
                n /= i
            result -=result/i
        i +=1
    if n > 1:
        result -= result/n
    print(int(result))


texts:
I got a keylogger Powershell script to protocol my input, since I'm quite paranoid if someone uses my PC.

However, some letters (I have an anti-ghosting keyboard) are swallowed if I type them in fast. Does anyone see a bottleneck here? I believe it's either the fact that:

it can't recognize keys pressed at the same time, or
The Out-File causes the bottleneck so it doesnt write fast enough.

My question is, how I improve it to capture ALL key inputs?

function KeyLog {

    $MAPVK_VK_TO_VSC = 0x00

    $MAPVK_VSC_TO_VK = 0x01

    $MAPVK_VK_TO_CHAR = 0x02

    $MAPVK_VSC_TO_VK_EX = 0x03

    $MAPVK_VK_TO_VSC_EX = 0x04

    $virtualkc_sig = @'
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern short GetAsyncKeyState(int virtualKeyCode);
'@

    $kbstate_sig = @'
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int GetKeyboardState(byte[] keystate);
'@

    $mapchar_sig = @'
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int MapVirtualKey(uint uCode, int uMapType);
'@

    $tounicode_sig = @'
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);
'@
    $foreground_sig=@'
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
'@

    $getKeyState = Add-Type -MemberDefinition $virtualkc_sig -name "Win32GetState" -namespace Win32Functions -passThru
    $getKBState = Add-Type -MemberDefinition $kbstate_sig -name "Win32MyGetKeyboardState" -namespace Win32Functions -passThru
    $getKey = Add-Type -MemberDefinition $mapchar_sig -name "Win32MyMapVirtualKey" -namespace Win32Functions -passThru
    $getUnicode = Add-Type -MemberDefinition $tounicode_sig -name "Win32MyToUnicode" -namespace Win32Functions -passThru
    $getForeground = Add-Type -MemberDefinition $foreground_sig -name "Win32MyForeground" -namespace Win32Functions -passThru
    while ($true) {
        Start-Sleep -Milliseconds 40
        $gotit = ""

        for ($char = 1; $char -le 254; $char++) {
            $vkey = $char
            $gotit = $getKeyState::GetAsyncKeyState($vkey)

            if ($gotit -eq -32767) {

                $l_shift = $getKeyState::GetAsyncKeyState(160)
                $r_shift = $getKeyState::GetAsyncKeyState(161)
                $caps_lock = [console]::CapsLock

                $scancode = $getKey::MapVirtualKey($vkey, $MAPVK_VSC_TO_VK_EX)

                $kbstate = New-Object Byte[] 256
                $checkkbstate = $getKBState::GetKeyboardState($kbstate)

                $mychar = New-Object -TypeName "System.Text.StringBuilder";
                $unicode_res = $getUnicode::ToUnicode($vkey, $scancode, $kbstate, $mychar, $mychar.Capacity, 0)

                if ($unicode_res -gt 0) {
                try {
                $ActiveHandle = $getForeground::GetForegroundWindow()
                $Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle}

                $Process | Select ProcessName, @{Name="AppTitle";Expression= {($_.MainWindowTitle)}}

                $title = $Process.MainWindowTitle
                $logfile = "key.log"
                    $timestamp = (Get-Date -format MM/dd/yy` hh:mm:ss)

                    Out-File -FilePath $logfile -Encoding Unicode -Append -InputObject "$timestamp | $title | $mychar "
                } catch {
                 Write-Error "Failed to get active Window details. More Info: $_"
                }

                }
            }
        }
    }
}

KeyLog


texts:
I used saxon v9 to profile an XSL transformation which converts XML to JSON. The profiler tells me that the function which escapes certain characters takes about 70% of the total processing time. The conversion is important because otherwise the created JSON file will be invalid because of characters that break the strings.

java -jar saxon9he.jar -xsl:jsontransform.xslt -s:input.xml -o:output.json -TP

The "method" used to escape the values looks like this:

<xsl:template name="escapejson">
        <xsl:param name="string"/>
        <xsl:sequence select="replace(
                              replace(
                              replace(
                              replace(
                              replace(
                              replace(
                              replace(
                              replace(
                              replace($string, '\\','\\\\'),
                              '/', '\\/'),
                              '&quot;', '\\&quot;'),
                              '&#xA;','\\n'),
                              '&#xD;','\\r'),
                              '&#x9;','\\t'),
                              '\n','\\n'),
                              '\r','\\r'),
                              '\t','\\t')"/>
    </xsl:template>

Unfortunately, my XSL knowledge is too limited to create an optimum solution on my own. I assume the repeated call of replace is quite inefficient but don't know how to do it better.


texts:
Recently I have been busy with nodejs and I thought to create something like this Java input library, so I started with some rough code like below:

'use strict';
const readline = require('readline');
const fs = require('fs');

class StdIn {
  constructor(opt_name) {
    this.name = opt_name;
    this.rs = this.name ? fs.createReadStream(this.name) : process.stdin
  }

  readInt(callback) {
    this.rs.on('data', (chunk) => {
      let line = chunk.toString();
      let numbers = line.trim().split(/\s/);
      numbers.forEach(num => {
        callback.call(this, num);
      });
    });
    this.rs.on('end', () => {
      process.exit(0);
    });
  }

  readLine(callback) {
    this.rs.on('data', (chunk) => {
      let line = chunk.toString();
      callback.call(this, line);
    });
    this.rs.on('end', () => {
      process.exit(0);
    });
  }
}

const stdIn = new StdIn(process.argv[2]);

//stdIn.readInt(num => {
//  console.log(num);
//});

stdIn.readLine(line => {
  console.log(line);
});

Its working fine till now and buts its still incomplete and the code is too messy, the problem clearly visible here that I am trying to push event oriented code into my object oriented world, I am confused basically for two things:

It is practical to do so?
If yes then what would be the best way?


texts: YUIDoc syntax for optionally static constructor

texts:
In JavaScript, I wrote a class that can be optionally instantiated with the new keyword, but can also be called statically as well. What is the best way to demonstrate this behavior in comment syntax? I was thinking something like this:

// localize constant
var PI = Math.PI;

/**
 * Complex constructor
 * optionally instantiate with `new`
 *
 * @class Complex
 * @constructor
 * @static
 * @param r {Number} real part
 * @param i {Number} imaginary part
 * @param m {Number} optional, magnitude
 * @param t {Number} optional, argument
 * @return {Object} complex number
 */

function Complex(r, i, m, t) {
    if (!(this instanceof Complex)) {
        return new Complex(r, i, m, t);
    }

    if (typeof m === 'number') {
        this.m = Math.abs(m);
    } else {
        this.m = Math.sqrt(r * r + i * i);
    }

    if (typeof t === 'number') {
        this.t = (m >= 0 ? t : t + PI);
    } else {
        this.t = Math.atan2(i, r);
    }

    // limit argument between (-pi,pi]
    this.t = PI - (PI * 3 - (PI - (PI * 3 - this.t) % (PI * 2))) % (PI * 2);
    this.r = r;
    this.i = i;
}


texts: Setting unique code to model before creating (ruby/rails)

texts:
I have a Table model that needs a unique code. I have a method creating the code (and making sure it's unique), but I have the same line self.code = rand.to_s[2..5] twice. Is there a neat way to only have that line once?

class Table < ActiveRecord::Base
  before_create :set_code

  private
  def set_code
    self.code = rand.to_s[2..5]
    while(Table.find_by(code: code) != nil)
      self.code = rand.to_s[2..5]
    end
  end
end


texts:
I have an input element on one of the pages. This input is supposed to take a string of digits from a user. In order to enhance UX I'd like to mask input's value at any given time. Like so:

What came up with as a solution is the following piece of code:

(function () {
  var input = document.querySelector('input');

  var state = '';

  input.addEventListener('keyup', function (e) {
    if ( e.key.match(/\d/) )     state += e.key;
    if ( e.key === 'Backspace' ) state = state.slice(0, -1);

    var degree = state.slice(0,2),
        minute = state.slice(2,4),
        second = state.slice(4,6);

    if (degree) degree += '°';
    if (minute) minute += "'";
    if (second) second += '"';

    input.value = [degree, minute, second].join(' ');
  });
})();
<input type="text" />

I do not claim it to be perfect, so I very much appreciate any input.


texts: "Who are you, and where do you live?" — a Q&A exercise

texts:
This is my first attempt at a programme. Is it good form?  Does it follow best practice? Or am I completely off the mark?

#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;

string a;
string b;

string enterName()
{
    while (true)
    {
        cout << "what is your name?: ";
        getline(cin, a);
        if (a == "")
            cout << "Let's try that again." << endl;
        if (a != "")
            return a;
    }
}

string enterAge()
{
    while (true)
    {
       cout << "What is your age " << a << "?: ";
        getline(cin, b);
        if (b == "")
            cout << "You did not answer the question." << endl;
        if (b != "")
            return b;
    }
}

int verifyAge()
{
    while (true)
    {
        int x = atoi(enterAge().c_str());
        if (x > 0 && x < 95)
            return x;

        cout << "That is not possible, put your real age please." << endl;
    }
}

string address()
{
    while (true)
    {
        cout << "Where do you live " << a << "?: ";
        string c;
        getline(cin, c);
        if (c == "")
            cout << "You must live somewhere." << endl;
        if (c != "")
            return c;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    system("Color 1A");
    string a = enterName();
    cout << endl;
    int y = verifyAge();
    cout << endl;
    string c = address();
    cout << endl;
    system("cls");
    cout << endl << endl << endl;
    cout << "So your name is " << a << " you are " << y << " years old"
        << " and you live in " << c << endl << endl << endl;
    cout << "Press any key to exit";
    cin.get();
    return 0;
}


texts: Curry function with function constructor

texts:
Shall I make a curry function this way, or is it best to avoid Function constructor in all means? What I want to know is if this is "bad practice" and how else currying can be done. For instance, one can bind arguments to a function with Function.bind, but it is more like a partial application thing. And will doing currying by recursion impact on performance?

var curry = function(fn) {
    var fnString = fn.toString();
    var arity = fn.length;
    var paramList = fnString.substring(
            fnString.indexOf("(") + 1, fnString.indexOf(")")).split(",");
    var body = fnString.substring(
            fnString.indexOf("return"), fnString.indexOf("}"));
    var newBody = paramList.slice(1).reduce(function(p,c) {
        return p + "return function(" + c + ") {";
    },"") + body + ( new Array(arity).join("}") );

    return new Function(paramList[0], newBody);

 };

var test = function(a,b,c,d) {
    return a * b * c * d;
};

var curriedTest = curry( test );
console.log( curriedTest(1)(2)(3)(4) ); \\-> 24