texts: Making EmployeeHistory ViewModel immutable as code analysis suggested

texts:
I want to display on a view the EmployeeHistory view model sorted by elements.assignEffDateNext and I want to instantiate and populate the view model from the controller. The code analysis is saying that the IList<IDMSElementDate> EmployeePositionsOverTime should be read only.  I kind of understand why.

This is what I started with.

public class EmployeeHistory
{
    public int EmployeeID { get; set; }
    public string EmployeeName { get; set; }
    public IList<IDMSElementData> EmployeePositionsOverTime { get; set; }

}

public async Task<ActionResult> EmployeeHistory(int? employeeID)
    {...//this part retrieves the elements from an api...

        Employee emp = db.Employees.Find(employeeID);
        string employeeName = emp.EmployeeFullName;

        var sortedList = elements.Elements.OrderByDescending(e => e.assignEffDateNext).ToList();

        EmployeeHistory empHist = new EmployeeHistory
        {
            EmployeeID = (int)employeeID,
            EmployeeName = employeeName,
            EmployeePositionsOverTime = sortedList,
        };

        return View("EmployeeHistory", empHist);
    }

This is what I have changed it to. I added a constructor and changed the properties to be read-only so the type is immutable now and the analyzer is no longer giving me a warning. I was wondering whether this is better now and whether there is anything else about it that I should change?

 public class EmployeeHistory
{

    public EmployeeHistory(int employeeID, string employeeName, IList<IDMSElementData> employeePositionsOverTime)
    {
        EmployeeID = employeeID;
        EmployeeName = employeeName;
        EmployeePositionsOverTime = employeePositionsOverTime;
    }

    public int EmployeeID { get; }
    public string EmployeeName { get;  }
    public IList<IDMSElementData> EmployeePositionsOverTime { get;  }

}

public async Task<ActionResult> EmployeeHistory(int? employeeID)
        {...//this part retrieves the elements from an api...

            Employee emp = db.Employees.Find(employeeID);
            string employeeName = emp.EmployeeFullName;

            var sortedList = elements.Elements.OrderByDescending(e => e.assignEffDateNext).ToList();

            EmployeeHistory empHist = new EmployeeHistory((int)employeeID,employeeName,sortedList);

            return View("EmployeeHistory", empHist);
        }


texts: Make a dict class from scratch in Python

texts:
Here's the API my teacher assigned:

and here is what I came up with:

class MyMap:
    def __init__(self,size=10):
        self.size = size
        self.internal_list = [None] * size
    def _getHash(string,size):
        total = 0
        for ch in string:
            total += ord(ch)
        total = total % size
        return total
    def set(self,key,value):
        listnum = MyMap._getHash(key,self.size)
        if key in self.internal_list:
            print("already there")
            return None
        if self.internal_list[listnum] == None or self.internal_list[listnum] is type(tuple):
            self.internal_list[listnum] = (key, value)
        else:
            pass
    def get(self,key):
        listnum = MyMap._getHash(key,self.size)
        if self.internal_list[listnum] == None:
            return None
        else:
            return self.internal_list[listnum][2]
    def size(self):
        sizecount = 0
        count = 0
        while len(self.internal_list)-count != 0:
            if self.internal_list[count] != None:
                sizecount += 1
            count += 1
        return sizecount
    def getKeys(self):
        keylist = []
        count = 0
        while len(self.internal_list) - count != 0:
            if self.internal_list[count] != None:
                keylist.append(self.internal_list[count][0])
            count += 1
        return keylist

Just wondering

if it will fulfill the requirements of the assignment
what I can do to clean up the code

Here's what I've tested:

x = MyMap()
x.set('test',2)
x.set('crest',3)
x.set('best',5)
print(MyMap.size(x))
print(x.get('test'))
print(MyMap.getKeys(x))
print(x.internal_list)

and the results...


texts: Closest distance between points in a list

texts:
In a course I'm doing, I was given the task of finding the closest pair of points among the given points. The program that passed all test cases was the following:

import math

if __name__ == '__main__':
    n = int(input())
    P = []
    for i in range(n):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        p = (x, y)
        P.append(p)
    print(closest(P, n))

def square(x):
    return x * x

def square_distance(p0, p1):
    return square(p0[0] - p1[0]) + square(p0[1] - p1[1])

def closest(P, n):
    P.sort() # sort by x coordinates
    return math.sqrt(_closest_square_distance(P, n))

def _closest_square_distance(P, n):
    if n == 2:
        return square_distance(P[0], P[1])
    if n == 3:
        return min(square_distance(P[0], P[1]), square_distance(P[0], P[2]), square_distance(P[1], P[2]))

    mid = n // 2
    dl = _closest_square_distance(P[:mid], mid)
    dr = _closest_square_distance(P[mid:], n - mid)

    closest_square_distance = min(dl, dr)
    closest_distance_so_far = math.sqrt(closest_square_distance)

    mid_x = P[mid][0]
    strip = []
    strip_length = 0
    for i in range(n):
        p = P[i]
        if abs(p[0] - mid_x) < closest_distance_so_far:
            strip.append(p)
            strip_length += 1

    strip.sort(key=lambda x: x[1]) # sort strip by y coordinates

    for i in range(strip_length):
        js = min(strip_length, i + 7) # sufficient to compute next 6 neighbors
        for j in range(i + 1, js):
            ds = square_distance(strip[i], strip[j])
            if ds < closest_square_distance:
                closest_square_distance = ds

    return closest_square_distance

This code was based on the algorithm found at https://en.wikipedia.org/wiki/Closest_pair_of_points_problem#Planar_case . What do you think I can do better? Is there a more efficient way to implement this algorithm? (In this one, I just tried to delay the sqrt computation as long as possible, and avoided to calculate len where I could). Is there an even more efficient algorithm?


texts:
I am making a few wrapper classes for the C++ standard library and was wondering if the following code is good practice.

#pragma once

#include <random>

namespace LibraryName
{
    class RandomBase
    {
    protected:
        RandomBase()
            : m_RandomGenerator(m_RandomDevice()) {}

        std::random_device m_RandomDevice;
        std::mt19937 m_RandomGenerator;
    };

    template<typename T>
    class IntRandom : public RandomBase
    {
    public:
        IntRandom(T minValue, T maxValue)
            : m_Distribution(minValue, maxValue), m_MinValue(minValue), m_MaxValue(maxValue) {}

        T Next()
        {
            return m_Distribution(m_RandomGenerator);
        }

        inline T GetMinValue() const { return m_MinValue; }
        inline T GetMaxValue() const { return m_MaxValue; }

    private:
        std::uniform_int_distribution<T> m_Distribution;
        T m_MinValue;
        T m_MaxValue;
    };

    template<typename T>
    class FloatRandom : public RandomBase
    {
    public:
        FloatRandom(T minValue, T maxValue)
            : m_Distribution(minValue, maxValue), m_MinValue(minValue), m_MaxValue(maxValue) {}

        T Next()
        {
            return m_Distribution(m_RandomGenerator);
        }

        inline T GetMinValue() const { return m_MinValue; }
        inline T GetMaxValue() const { return m_MaxValue; }

    private:
        std::uniform_real_distribution<T> m_Distribution;
        T m_MinValue;
        T m_MaxValue;
    };

    class BoolRandom : public RandomBase
    {
    public:
        BoolRandom() : BoolRandom(0.5f) {}
        BoolRandom(float trueChance)
            : m_Distribution(trueChance), m_TrueChance(trueChance) {}

        bool Next()
        {
            return m_Distribution(m_RandomGenerator);
        }

        inline bool GetTrueChance() const { return m_TrueChance; }

    private:
        std::bernoulli_distribution m_Distribution;
        float m_TrueChance;
    };
}


texts:
I sometimes save nice fortune outputs to my Evernote. The data looks like this:

/ Abou Ben Adhem (may his tribe increase!)                    \
| Awoke one night from a deep dream of peace,                 |
| And saw, within the moonlight in his room,                  |
| Making it rich, and like a lily in bloom,                   |
| An angel writing in a book of gold.                         |
| Exceeding peace had made Ben Adhem bold,                    |
| And to the presence in the room he said,                    |
| "What writest thou?"  The vision raised its head,           |
| And with a look made of all sweet accord,                   |
| Answered, "The names of those who love the Lord."           |
| "And is mine one?" said Abou. "Nay not so,"                 |
| Replied the angel.  Abou spoke more low,                    |
| But cheerly still; and said, "I pray thee then,             |
| Write me as one that loves his fellow-men."                 |
| The angel wrote, and vanished.  The next night              |
| It came again with a great wakening light,                  |
| And showed the names whom love of God had blessed,          |
| And lo!  Ben Adhem's name led all the rest.                 |
\                 -- James Henry Leigh Hunt, "Abou Ben Adhem"

I am using the following regex:

$ cat abcd | sed -r 's/^[/|\\]\s?([-A-Za-z ()!,?".;'"'"']*)[/|\\]?/\1/'

Abou Ben Adhem (may his tribe increase!)
Awoke one night from a deep dream of peace,
...

How do I improve it?


texts: An implementation of Levenshtein Distance algorithm in modern C++

texts:
Below is an implementation of Levenshtein Distance algorithm.

I am trying to use modern C++ features as much as I can, i.e. auto, no pointer / raw memory but I feel like it is a constant struggle.

Code:

#include <string_view>
#include <memory>
#include <vector>

namespace utils
{
    auto getLevenshteinDistance(std::string_view string_1, std::string_view string_2)
    {
        const auto size_1{ string_1.size() };
        const auto size_2{ string_2.size() };

        if (size_1 == 0) return size_2;
        if (size_2 == 0) return size_1;

        std::vector<std::size_t> costs(size_2);
        for (std::size_t k{ 0 }; k <= size_2; ++k) costs[k] = k;

        std::size_t i{ 0 };
        for (const auto& itr_1 : string_1)
        {
            ++i;
            costs[0] = i + 1;
            auto corner{ i };

            std::size_t j{ 0 };
            for (const auto& itr_2 : string_2)
            {
                ++j;
                auto upper{ costs[j + 1] };

                if (itr_1 == itr_2)
                {
                    costs[j + 1] = corner;
                }
                else
                {
                    auto t{ upper < corner ? upper : corner };
                    costs[j + 1] = (costs[j] < t ? costs[j] : t) + 1;
                }

                corner = upper;
            }
        }

        return costs[size_2];
    }
}

For instance, I can't use auto when declaring my vector, because there is no std::make_vector (like make_tuple for instance).

Also I'm developing anxiety for implicit conversions; for instance I could have written

auto i{ 0 };

instead of

std::size_t i{ 0 };

But given that the value will be put into an array containing type std::size_t, I'd rather just have it be of the right type immediately. Lots of stuff like that is bothering me.

Even looping through the array by const auto& seems weird when I'm still having a count variable.. Doesn't advantage disappear, and I might as well just for (int i = 0; ..)

Any suggestions for improvements in the way of modern, good practice, and performance is appreciated.


texts:
I am starting my adventure with Python and object oriented programming.

I wrote a script for salting and hashing password. My main goal is practice with OOP, not cryptography.
I know there is no error handling.

Wonder how improve my code it and make more object oriented.
It would be nice if someone more experienced can take a look and give me some advice how to make it better.
Any help for newbie would be great!

Description:

The script is not really useful in real life.

1st part:
Hash and salt password and next encode to base64 with added salt (needed for future comparing hashes). Algorithm: base64( SHA256(password + salt) + salt)
Salt is X random bytes where X can be specify but by default it is 16.

2nd part (some kind of authorization):
Compare input hash (e.x. from database) with new created hash from input plain password.
New salt is created from  salt taken from input hash.

Code:

import base64
import hashlib
import os

class Hashing(object):

    # base64( SHA256(password + salt) + salt)

    # generate new salt (default 16 bytes)
    def generate_new_salt(self, salt_ln=16):

        self.new_salt = os.urandom(salt_ln)

        print(f'new salt: {self.new_salt}')

        return self.new_salt

    # get salt from hash
    def get_old_salt(self, input_hash, salt_ln=16):

        self.old_salt = base64.b64decode(input_hash)[-salt_ln:]

        print(f'old salt: {self.old_salt}')

        return self.old_salt

    # compute hash using parameters
    def compute_hash(self, password, salt):

        self.salt = salt
        self.enc_password = password.encode()

        # hashing SHA256(password + salt)
        hash_object = hashlib.sha256(self.enc_password + salt)

        # add salt to hash and encode to base64
        hash_b64 = base64.b64encode(hash_object.digest() + salt)

        print(f'new_hash: {hash_b64}')
        return hash_b64

    # create hash from new or old salt
    def create_hash(self, password, salt_ln=16,old_salt=None):

        if old_salt:    #if old salt then use it
            self.salt = old_salt
        else:           #else generate new salt
            self.salt = Hashing().generate_new_salt(salt_ln)

        hash = Hashing().compute_hash(password, self.salt)

        return hash

    # compare input hash with created using salt get from input
    def compare_hashes(self, password, old_hash, salt_ln=16):

        self.enc_password = password.encode()

        #get salt from input hash
        self.old_salt = Hashing().get_old_salt(old_hash, salt_ln)

        #recreat input hash
        re_hash = Hashing().create_hash(password,salt_ln, self.old_salt)

        print(f'Compare: old_hash: {old_hash}')
        print(f'Compare: new_hash: {re_hash}')

        #compare
        if re_hash.decode() == old_hash.decode():
            return True
        else:
            return False

#code below is just for testing

NewSalt = Hashing().generate_new_salt()

Hash = Hashing().create_hash('pass')

OldSalt = Hashing().get_old_salt(Hash)

CompareHash = Hashing().compare_hashes('pass', Hash)

if CompareHash:
    print('HASHES THE SAME')
else:
    print('NOT THE SAME')

print(CompareHash)

Questions:

What is a real difference between these two? With and w/o self.X works

def generate_new_salt(self, salt_ln=16):
        self.new_salt = os.urandom(salt_ln)
        print(f'new salt: {self.new_salt}')
        return self.new_salt

def generate_new_salt(self, salt_ln=16):
    new_salt = os.urandom(salt_ln)
    print(f'new salt: {new_salt}')
    return new_salt

I have problem with passing default value of salt length, salt_ln = 16. For me it does not look nice when it is replicated in every method. Is there any way to do it more global?


texts: Prompting for a positive integer and validating user input in Java

texts:
I'm just starting out with Java, and trying to make a method to get a positive integer input from the console. My currently working implementation is this:

public static Scanner sc = new Scanner(System.in);

public static int getPositiveIntInput(String message) {

    int n;

    String error_message = "Error: input must be a positive integer.";

    System.out.print(message);
    while (true) { // This is often frowned upon?

        // Check that input is integer
        while (!sc.hasNextInt()) {

            System.out.print(error_message + "\n" + message); // Gets repeated
            sc.next();

        }

        n = sc.nextInt();
        sc.nextLine();

        // Check that input is positive
        if (n > 0) {

            return n;

        } else {

            System.out.print(error_message + "\n" + message);

        }
    }

}

In order to make my code more readable and concise, I attempted to rid myself of the while (true) and several error message prints by combining the integer and positivity checks into one loop, but I'm not getting the behaviour I would expect:

public static int getPositiveIntInput(String message) {

    String error_message = "Error: input must be a positive integer.";

    System.out.print(message);

    // Check that input is integer and positive
    while (!sc.hasNextInt() || sc.nextInt() <= 0) {

        System.out.print(error_message + "\n" + message);
        sc.next();

    }

    int n = sc.nextInt();
    sc.nextLine();

    return n;

}

What would be an effective way of improving the readability and reducing repetition while achieving the same functionality as in my original implementation? Particularly regarding the while(true) loop - I've seen it's use being discouraged in other SO threads. Would this be a case where a different looping structure could/should be considered?


texts: Interfacing between workbooks (Exporting data Table and key properties)

texts:
So I recently rebuilt a worksheet we have for tracking our clients who take income from their portfolios (here). I intend to be pulling this data into other workbooks for various reporting functions.

To facilitate this, I decided to write methods in the "workbook" module to return:

The codenames of the sheets holding data tables
The headers used in the data tables
The data table from a specific sheet (specified by codename)

Is this an effective way of achieving my goal (reducing potential problems interfacing between workbooks)?

Module "A1_Public_Variables"

Option Explicit

Public Const TOP_LEFT_CELL_STRING As String = "Client Name"

Public Const CLIENT_NAME_HEADER As String = "Client Name"
Public Const INCOME_AMOUNT_HEADER As String = "Income"
Public Const PAYMENT_FREQUENCY_HEADER As String = "Frequency"
Public Const PAYMENT_DAY_HEADER As String = "Date Paid"
Public Const BASE_MONTH_HEADER As String = "Base Month"
Public Const ASCENTRIC_WRAPPER_HEADER As String = "Wrapper"
Public Const ASCENTRIC_ACCOUNT_NUMBER_HEADER As String = "Ascentric Acc #"
Public Const ACCOUNT_TO_PAY_FROM_HEADER As String = "Account to pay from?"

Public Const WS_2015_CODENAME As String = "ws_2015"
Public Const WS_2016_CODENAME As String = "ws_2016"

"Workbook" Module

Option Explicit

Public Sub GetDataTableHeaders(Optional ByRef topLeftCellString As String, Optional ByRef clientNameHeader As String, Optional ByRef incomeAmountHeader As String _
                                , Optional ByRef paymentFrequencyHeader As String, Optional ByRef paymentDayHeader As String, Optional ByRef baseMonthHeader As String _
                                , Optional ByRef ascentricWrapperHeader As String, Optional ByRef ascentricAccountNumberHeader As String, Optional ByRef accountToPayFromHeader As String)

    topLeftCellString = CLIENT_NAME_HEADER

    clientNameHeader = CLIENT_NAME_HEADER
    incomeAmountHeader = INCOME_AMOUNT_HEADER
    paymentFrequencyHeader = PAYMENT_FREQUENCY_HEADER
    paymentDayHeader = PAYMENT_DAY_HEADER
    baseMonthHeader = BASE_MONTH_HEADER
    ascentricWrapperHeader = ASCENTRIC_WRAPPER_HEADER
    ascentricAccountNumberHeader = ASCENTRIC_ACCOUNT_NUMBER_HEADER
    accountToPayFromHeader = ACCOUNT_TO_PAY_FROM_HEADER

End Sub

Public Sub GetWorksheetCodenames(Optional ByRef ws2015 As String, Optional ByRef ws2016 As String)

    ws2015 = WS_2015_CODENAME
    ws2016 = WS_2016_CODENAME

End Sub

Public Function GetDataArrayFromSheetByCodename(ByVal strCodeName As String) As Variant
    '/ returns the datatable, or an error if could not find worksheet

    Dim dataTable As Variant
        dataTable = Array()

    Dim wsWasFound As Boolean
    Dim ws_target As Worksheet, ws As Worksheet

    wsWasFound = False
    For Each ws In ThisWorkbook.Worksheets
        If ws.codeName = strCodeName Then
            Set ws_target = ws
            wsWasFound = True
        End If
    Next ws

    If wsWasFound Then

        Dim tableRange As Range
        Set tableRange = GetTableRange(ws_target)

            dataTable = tableRange

            GetDataArrayFromSheetByCodename = dataTable

        Else

            GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error
    End If

End Function


texts: Sonar: Move constants to a class or enum

texts:
I found one project on Internet and after I downloaded it, I got this message from SonarQube:

Move constants to a class or enum.

But, when I downloaded SonarLint, it did not report any code smell.
This is the code:
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {

    String QUERY = "update Task t set t.isDeleted = true where t.id = :taskId";

    @Modifying
    @Query(QUERY)
    void deleteTaskById(@Param(value = "taskId") long taskId);
}

My question is: Should I remove constant QUERY and write it directly into @Query or I can leave it like this?
Note: This is a short query and it can easily be put inside @Query. But I am also interested what would be the best practice if this query was longer(ex. if it had 300 characters or more).


texts: Generating a selection box for the day of the month

texts:
<select name="checkInDay" tabindex="3" onchange="calcDay();" class="ffe selectform" id="checkInDate">
    <?php for($i=1;$i<=31;$i++) {
        $value = $i < 10 ? "0".$i : $i;
     ?>
     <option value="<?= $value ?>" <?php if($i == 12) {?> selected="selected" <?php } ?> > <?= $i ?> </option>
     <?php } ?>

  </select>


texts:
I am using the following code to rename the uploaded files for any future name clashes. Please tell if my approach is right or I should follow some other approach or approach which is better.

[HttpPost]
    public ActionResult Upload(HttpPostedFileBase fileData)
    {
        if (fileData != null && fileData.ContentLength > 0)
        {
            //var fileName = Server.MapPath("~/Content/Images/" + Path.GetFileName(fileData.FileName));
            int pictureCount = 800000;
            pictureCount += db.Pictures.Count();
            string extension = Path.GetExtension(fileData.FileName);
            string renamedImage = Server.MapPath("~/Content/Images/Categories/cat" + pictureCount + extension);
            fileData.SaveAs(renamedImage);
            return Json(Path.GetFileName(renamedImage));
        }
        return Json(false);
    }


texts: any better way than using old servlet api for downloads

texts:
I am wondering if the following code can be modified to be used with latest version of spring APIs?
The following code works fine. However, I wanted to know if servlet APIs can be avoided which i have used in the code below.
public void download (HttpServletRequest request, HttpServletResponse response, @PathVariable String filename, @PathVariable String user) throws IOException{

            String param1 = filename;
            String param2 = user;

            //The following URL will need to be updated with "prod" or "dev" or "test" depending upon the environment
            final String FILE_LOCATION = "/mnt/nfs/myfolder/prod/documents/custom_documents/"+param2;

            if(param1 == null || param2 == null) {
                // The Request Parameters Were Not Present In The Query String. Do Something Or Exception Handling !!
                System.out.println("Request Parameter Not Found in first if!");
            } else if ("".equals(param1) || "".equals(param2)) {
                // The Request Parameters Were Present In The Query String But Has No Value. Do Something Or  Exception Handling !!
                System.out.println("Request Parameter Not Found in second if!");
            } else {

                String fileName = (String) param1;
                String contentType = getContentType(fileName.split("\\.")[1]);
                File file = new File(FILE_LOCATION + "/" +fileName);
                response.setContentType(contentType);
                response.addHeader("Content-Disposition","attachment; filename=" + fileName);
                response.setContentLength((int) file.length());
                ServletOutputStream servletOutputStream = response.getOutputStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                int bytesRead = bufferedInputStream.read();
                while (bytesRead != -1) {
                    servletOutputStream.write(bytesRead);
                    bytesRead = bufferedInputStream.read();
                }
                if (servletOutputStream != null) servletOutputStream.close();
                if(bufferedInputStream != null) bufferedInputStream.close();

            }

    }

private String getContentType(String fileType) {
        String returnType = null;
        for(int i = 0; i < contentTypes.length; i++) {
            if(fileType.equals(contentTypes[i][0])) returnType = contentTypes[i][1];
        }
        return returnType;
    }


texts:
I decided to help @Matt out a bit and ask a PowerShell question.  This is a simple guess-the-number game learning how to use functions with and without parameters, and use the input and output functions.  All comments are welcome.

Function GetNumber([int]$min, [int]$max) {
    Return Get-Random -minimum $min -maximum ($max + 1)
}

Function PlayGame() {
    Write-Host "This is a guess-the-number game.`r`nYou have 6 guesses to guess a number between 1 and 100."

    $secretNum = GetNumber 1 100

    [int]1..6 | ForEach {
        $guess = Read-Host
        If ($guess -eq $secretNum) {
            Write-Host "Correct!"
            Return
        }
        ElseIf ($guess -gt $secretNum) {
            Write-Host "Too high!"
        }
        Else {
            Write-Host "Too low!"
        }

        $remainingGuesses = 6 - $_
        Write-Host "You have $remainingGuesses guesses left"
    }

    Write-Host "The number was $secretNum"
}

PlayGame

# Borrowed from https://technet.microsoft.com/en-us/library/ff730938.aspx
Write-Host "Press any key to continue ..."
$host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")


texts: JavaScript: Better way to sort an array by setting custom index

texts:
I'm trying to create a sorted array based on the below input data:
Input:
[{"title": "100_baz"}, {"title": "01_foo"}, {"title": "05_bar"}]
function indexSort (input) {
    let output = [];
    input.forEach(value => {
        if (value.title && value.title.indexOf('_') !== -1) {
            let targetIndex = parseInt (value.title.split('_')[0]);
            let title = value.title.substring(value.title.indexOf('_') + 1, value.title.length); // extract the string next to '_'
            output[targetIndex] = title;
        }
    })
    console.log(output)
}

Desired Output:

I'm able to get the desired output using the above code snippet, however, I'm looking for a better way to achieve this in terms of good practice, or a concise and clear method in ES5 or ES6.


texts: Safely setting object properties with dot notation strings in JavaScript

texts:
What my function does:
Safely sets object properties with dot notation strings in JavaScript.
That is to say, it allows setting a nested property on an object using a string such as "a.b.c".
For example: set(obj, "a.b.c", value) would be equivalent to a.b.c = value
Some notes on intended behavior

When setting a property at a given path, if any portion of that path doesn't exist, it should be created
When creating a path portion, if the next key in the path is NOT an integer, the current portion should be created as an object
When creating a path portion, if the next key in the path is an integer, the current portion should be created as an array

Why?
I'd like to be able to set deeply nested properties on an object in an environment where I can't be sure that all the properties in the path will always exist and I don't want to deal with the logic of checking for and setting each key manually in more than one place. This allows me to quickly set the needed value without caring if the keys were present previously or not.

/**
 * Set the value for the given object for the given path
 * where the path can be a nested key represented with dot notation
 *
 * @param {object} obj   The object on which to set the given value
 * @param {string} path  The dot notation path to the nested property where the value should be set
 * @param {mixed}  value The value that should be set
 * @return {mixed}
 *
 */
function set(obj, path, value) {
    // protect against being something unexpected
    obj = typeof obj === 'object' ? obj : {};
    // split the path into and array if its not one already
    var keys = Array.isArray(path) ? path : path.split('.');
    // keep up with our current place in the object
    // starting at the root object and drilling down
    var curStep = obj;
    // loop over the path parts one at a time
    // but, dont iterate the last part,
    for (var i = 0; i < keys.length - 1; i++) {
        // get the current path part
        var key = keys[i];

        // if nothing exists for this key, make it an empty object or array
        if (!curStep[key] && !Object.prototype.hasOwnProperty.call(curStep, key)){
            // get the next key in the path, if its numeric, make this property an empty array
            // otherwise, make it an empty object
            var nextKey = keys[i+1];
            var useArray = /^\+?(0|[1-9]\d*)$/.test(nextKey);
            curStep[key] = useArray ? [] : {};
        }
        // update curStep to point to the new level
        curStep = curStep[key];
    }
    // set the final key to our value
    var finalStep = keys[keys.length - 1];
    curStep[finalStep] = value;
};

/** Usage **/

console.log('setting non existant a.b.c to "some value":');
var test = {};
set(test, 'a.b.c', 'some value');
console.log(test);

console.log('updating a.b.c to "some new value":');
set(test, 'a.b.c', 'some new value');
console.log(test);

console.log('setting non existant a.b.0 to "some value":');
var test = {};
set(test, 'a.b.0', 'some value');
console.log(test);

console.log('updating a.b.0 to "some new value":');
set(test, 'a.b.0', 'some new value');
console.log(test);


texts: Outputting an inverted index to a text file

texts:
When I run this function for outputting an inverted index to a text file in Debug Configuration, it takes nearly two minutes (96 seconds) with a comparatively tiny dataset, 1252 records with the longest being 76 entries.

std::ostream& operator<<(std::ostream& out_stream, const InvertedIndex& rhs) {
    std::ostringstream output_buffer;
    auto& rhs_index = rhs.GetIndex();
    for(auto map_elem : rhs_index) {
        output_buffer << map_elem.first;
        auto& cur_postingset = map_elem.second;
        for(auto set_elem : cur_postingset) {
            output_buffer << " <" << set_elem.GetDocumentId() << ' ' << set_elem.GetTokenFrequency() << ">";
        }
        output_buffer << '\n';
    }
    output_buffer.flush();
    out_stream.write(output_buffer.str().c_str(), output_buffer.str().size());
    return out_stream;
}

The index is a std::map<std::string, std::vector<std::pair<unsigned long, std::string>>> data type. It makes debugging other portions of the program tedious and time-consuming. Is there any way to speed it up or am I going to have to live with it?


texts:
I'm trying to generate secure randomness in Node as a personal challenge. I was wondering if the following implementations are correctly random or they have some flaws.

const crypto = require('crypto');

const secureRandomFloat = (bytes = 6) => {
  const size = Math.pow(2, bytes * 8);
  const hexString = crypto.randomBytes(bytes).toString('hex');
  const randInt = parseInt(hexString, 16);
  return randInt / size;
}

export const secureRandomIntRange = (min, max) => {
  const range = max - min; // max is the first not included integer [min, max)
  if (range > Number.MAX_SAFE_INTEGER) return null;
  // use an amount of bytes that will cover the range we need
  const bytes = Math.ceil(Math.log(range) / Math.log(256));
  const size = Math.pow(2, bytes * 8);
  // this is the "tail" of possible numbers. Using them that would
  // give us more chances to get lower values when using modulo
  const excess = size % range;

  let validRand = false;
  let hexString;
  let randInt;
  while (!validRand) {
    hexString = crypto.randomBytes(bytes).toString('hex');
    randInt = parseInt(hexString, 16);
    validRand = randInt + excess < size;
  }

  return min + randInt % range;
}

const secureRandomChoice = arr => {
  // This is to check that the "arr" is iterable, like an array
  // or a string, etc.
  if (arr == null) return null;
  if (typeof arr[Symbol.iterator] !== 'function') return null;
  if (!arr.hasOwnProperty('length')) return null;

  // use an amount of bytes that will cover the range we need
  const bytes = Math.ceil(Math.log(arr.length) / Math.log(256));

  const randIdx = secureRandomIntRange(0, arr.length);
  if (randIdx === null) return null;
  return arr[randIdx];
}

I've done some testing with a million iterations and results seem to be random, but I don't know if I'm missing something.

Are these implementations going to give me pseudo-randomness?

Culling

@Blindman67 has commented that culling, which I do in the while loop at secureRandomIntRange, is not going to give me random values. I don't have a strong argument to say that culling will give me random numbers, but I don't see why it won't.

I used culling because I remembered once I needed to generate random points in a sphere. To do that I took a random point in a cube (much simpler), and discarded the point if it was out of the sphere. I think it gave me a random distribution of points in the sphere.

I tried to apply this same idea to this problem. If I have 1 byte I can generate 256 possible combinations at random, say from number 0 to 255. If I wanted to select an integer from 0 to 99 (100 possible numbers), the naive way using modulo would give me the following relations:

randomByte:     0   1   2 ... 99 100 101 ... 199 200 201 ... 254 255
secureRandInt:  0   1   2 ... 99   0   1 ...  99   0   1 ...  54  55

But that way all numbers from 0-55 can be drawn from 3 different bytes, whereas numbers from 56-99 can only be drawn from 2 different bytes. Then, the way I thought could give me a random distribution in the range was assigning the numbers as follows:

randomByte:     0   1   2 ... 99 100 101 ... 199 200 201 ... 254 255
secureRandInt:  0   1   2 ... 99   0   1 ...  99   x   x ...   x   x

Where x means that the byte is not valid (!validRand) and I have to discard it and get a new byte at random.

In this example, the values for the different variables would be as follows:

range = 100
size = 256
excess = 56
isValid = randInt + excess < size
// isValid = randInt + 56 < 256 --> isValid = randInt < 200
// T for true and F for false
randomByte:  0   1   2 ... 99 100 101 ... 199 200 201 ... 254 255
isValid:     T   T   T ...  T   T   T ...   T   F   F ...   F   F

Do you think that approach is invalid to get random numbers?


texts:
Following my previous question about a FIFO for embedded systems and the very detailed answer I got, I made some modifications to convert a simple FIFO to double-ended queue for Embedded Systems.
It is using a circular buffer.
How it works: When an element is added and the queue is not empty, the corresponding index is increased or decreased according to the side the element is added. When the queue is empty, and an element is added, neither index is changed so that the element can be accessed from either side.
The size of the queue is constant and it must be defined at compile time.
The data pointer must point to a static array that is also defined at compile time with the same size.
So here it is:
queue.h
#ifndef QUEUE_H
#define QUEUE_H

#include <inttypes.h>

typedef uint16_t QueueDataType_t;

struct queue
{
    QueueDataType_t * data;
    QueueDataType_t front_idx;
    QueueDataType_t back_idx;
    const QueueDataType_t size;
    QueueDataType_t elements;
};

#endif

queue.c
/**
 * \file queue.c
 *
 * \brief   A double-ended queue (deque). Elements can be added or removed from
 *          either the front or the back side.
 * \warning The current implementation is NOT interrupt safe. Make sure interrupts
 *          are disabled before access the QUEUE otherwise the program might yield
 *          unexpected results.
*/

#include "queue.h"
#include <stdbool.h>

/**
 * Initializes - resets the queue.
*/
void queue_init(struct queue * queue)
{
    memset(queue->data, 0, queue->size);
    queue->back_idx = 0;
    queue->front_idx = 0;
    queue->elements = 0;
}

/**
 * Checks if queue is full.
 *
 * \returns true if queue is full.
*/
bool queue_is_full(struct queue * queue)
{
    return (queue->elements == queue->size);
}

/**
 * Checks if queue is empty
 *
 * \returns true if queue is empty.
*/
bool queue_is_empty(struct queue * queue)
{
    return (queue->elements == 0);
}

/**
 * Adds one byte to the front of the queue.
 *
 * \returns false if the queue is full.
*/
bool queue_add_front(struct queue * queue,
                     QueueDataType_t data)
{
    if (queue_is_full(queue))
    {
        return 0;
    }

    if (queue_is_empty(queue) == 0)
    {
        queue->front_idx = (queue->front_idx + 1) >= queue->size ? 0 : (queue->front_idx + 1);
    }

    queue->data[queue->front_idx] = data;
    queue->elements++;
    return 1;
}

/**
 * Adds one byte to the back of the queue.
 *
 * \returns false if the queue is full.
*/
bool queue_add_back(struct queue * queue,
                    QueueDataType_t data)
{
    if (queue_is_full(queue))
    {
        return 0;
    }

    if (queue_is_empty(queue) == 0)
    {
        queue->back_idx = (queue->back_idx == 0) ? (queue->size - 1) : (queue->back_idx - 1);
    }

    queue->data[queue->back_idx] = data;
    queue->elements++;
    return 1;
}

/**
 * Reads one byte from the front of the queue.
 *
 * \returns false if the queue is empty.
*/
bool queue_get_front(struct queue * queue,
                     QueueDataType_t * data)
{
    if (queue_is_empty(queue))
    {
        return 0;
    }

    *data = queue->data[queue->front_idx];
    queue->front_idx = (queue->front_idx == 0) ? (queue->size - 1) : (queue->front_idx - 1);
    queue->elements--;
    return 1;
}

/**
 * Reads one byte from the back of the queue.
 *
 * \returns false if the queue is empty.
*/
bool queue_get_back(struct queue * queue,
                    QueueDataType_t * data)
{
    if (queue_is_empty(queue))
    {
        return 0;
    }

    *data = queue->data[queue->back_idx];
    queue->back_idx = (queue->back_idx + 1) >= queue->size ? 0 : (queue->back_idx + 1);
    queue->elements--;
    return 1;
}

Initializing the queue
#define MY_QUEUE_DATA_SIZE  50
static QueueDataType_t q_data[MY_QUEUE_DATA_SIZE];
static struct queue my_queue =
{
    .data = q_data,
    .size = MY_QUEUE_DATA_SIZE,
};

queue_init(&my_queue);


texts: Different return types with same function

texts:
I'm implementing my own time unit class. This class provides a function for fetching a specific time value (milliseconds, seconds etc.). In order to prevent defining several get() functions for each time unit, I tried to implement a single function to serve this purpose.

typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned long long u_ll;
typedef u_ll DAYS_DTYPE;
typedef u_char HOURS_DTYPE;
typedef u_char MINUTES_DTYPE;
typedef u_char SECONDS_DTYPE;
typedef u_short MILLISECONDS_DTYPE;

// used class members; max. values are handled class-internal
DAYS_DTYPE          m_days;         // max.: 18.446.744.073.709.551.615
HOURS_DTYPE         m_hours;        // max.: 23
MINUTES_DTYPE       m_minutes;      // max.: 59
SECONDS_DTYPE       m_seconds;      // max.: 59
MILLISECONDS_DTYPE  m_milliseconds; // max.: 999

// class-internal enum
enum TimeUnit { Milliseconds, Seconds, Minutes, Hours, Days };

// used member function
template <typename T>
T getTime(TimeUnit unit)
{
    switch (unit)
    {
    case Milliseconds: return m_milliseconds;
    case Seconds: return m_seconds;
    case Minutes: return m_minutes;
    case Hours: return m_hours;
    case Days: return m_days;
    default:
        break;
    }
}

In order to fetch a specific time unit I have to use sth. like this:

getTime<MILLISECONDS_DTYPE>(Time::Milliseconds))

Is this approach acceptable? In case it's not, what should I change?


texts:
I have defined some DataTemplates are similar. The templates are like this:

    <DataTemplate x:Key="DefaultCellTemplate">
    <TextBlock Text="{Binding Value}">
        <i:Interaction.Behaviors>
            <beh:AddErrorButtonAdornerToControlsBehavior
                DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
                FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
        </i:Interaction.Behaviors>
    </TextBlock>
</DataTemplate>

<DataTemplate x:Key="TimeCellTemplate">
    <TextBlock Text="{Binding Value, Converter={StaticResource TimeConverter}}">
        <i:Interaction.Behaviors>
            <beh:AddErrorButtonAdornerToControlsBehavior
                DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
                FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
        </i:Interaction.Behaviors>
    </TextBlock>
</DataTemplate>

<DataTemplate x:Key="StationCellTemplate">
    <TextBlock Text="{Binding Value, Converter={StaticResource StationConverter}}">
        <i:Interaction.Behaviors>
            <beh:AddErrorButtonAdornerToControlsBehavior
                DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
                FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
        </i:Interaction.Behaviors>
    </TextBlock>
</DataTemplate>

<DataTemplate x:Key="ProductionCategoryCellTemplate">
    <TextBlock Text="{Binding Value, Converter={StaticResource ProductionCategoryConverter}}">
        <i:Interaction.Behaviors>
            <beh:AddErrorButtonAdornerToControlsBehavior
                DoOnButtonClick="{Binding RelativeSource={RelativeSource AncestorType={x:Type dxg:GridControl}}, Path=DataContext.ShowErrorDialogCommand}"
                FieldDescriptionId="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type dxg:GridCellContentPresenter}}, Path=Column.Tag}"/>
        </i:Interaction.Behaviors>
    </TextBlock>
</DataTemplate>

I don't know, if I can define a template base. The template base should be a TextBlock with the behavior and the derived templates should be use a converter for the TextBlock value. Any idea?


texts: Basic T-SQL to compare two same length strings

texts:
I've come up with the following T-SQL to compare similar same length strings.

Example usage would be:

OCR returns a value which is expected to be in the database.
PATINDEX is used to check the value's in the database, including matching for common errors (e.g. 0/O, I/1/l).
If multiple values are found, each match is scored for likeness to the original.

declare @t table (solution nvarchar(32), score bigint)

insert @t(solution)
select 'Portugal'
union select '9ortugal'
union select '9ortu8al'
union select 'Portu8al'
union select 'P0rtugal'
union select '90rtugal'
union select '90rtu8al'
union select 'P0rtu8al'
union select 'Portuga1'
union select '9ortuga1'
union select '9ortu8a1'
union select 'Portu8a1'
union select 'P0rtuga1'
union select '90rtuga1'
union select '90rtu8a1'
union select 'P0rtu8a1'

declare @answer nvarchar(32) = 'Portugal'

update @t
set score = cast(cast(cast(@answer as varchar) as varbinary(max)) as bigint) - (cast(cast(cast(solution as varchar) as varbinary(max)) as bigint) & cast(cast(cast(@answer as varchar) as varbinary(max)) as bigint))

select * from @t order by score --first result is the most similar

Results:

solution    score
Portugal    0
Portuga1    76
Portu8al    4653056
Portu8a1    4653132
P0rtugal    22236523160141824
P0rtuga1    22236523160141900
P0rtu8al    22236523164794880
P0rtu8a1    22236523164794956
9ortugal    4611686018427387904
9ortuga1    4611686018427387980
9ortu8al    4611686018432040960
9ortu8a1    4611686018432041036
90rtugal    4633922541587529728
90rtuga1    4633922541587529804
90rtu8al    4633922541592182784
90rtu8a1    4633922541592182860

SQL Fiddle

Notes:

Conversion to varchar because nvarchar seems to cause a loss of precision
Conversion to varbinary because doing varchar straight to numeric would result in a non-numeric issue for non-numeric characters.
Conversion to bigint to allow bitwise & arithmetic comparison
Use of - and & may be superfluous; perhaps just the - would be sufficient, but I feel (superstitious guess/don't have a strong enough understanding) that the & will help.

Concerns:

Errors at the start of the string have more impact than those later in the string.
Results look quite good on my test data, but not sure how predictable this would be in reality.
It would be nice to be able to weight the errors; e.g. O for 0 is very common; 6 for G or 8 for g less so; so the former should have a greater weighting (i.e. P0rtugal should be preferential to Portu8al; not just because of the character's position in the string).


texts:
I have this generalization of FizzBuzz in Java:

import java.util.Map;
import java.util.TreeMap;

public class GeneralFizzBuzz {

    public static void generalFizzBuzz(Map<Integer, String> map,
                                       int start,
                                       int stop) {
        String startString = String.valueOf(start);
        String stopString = String.valueOf(stop);

        // Find the width which can accommodate any line number:
        int lineNumberWidth = Math.max(startString.length(),
                                       stopString.length());

        // Create the format string for printing line numbers:
        String lineNumberFormat = "%" + lineNumberWidth + "d: ";

        for (int i = start; i <= stop; ++i) {
            // Print the line number and the colon with a space:
            System.out.printf(lineNumberFormat, i);

            for (Map.Entry<Integer, String> entry : map.entrySet()) {
                if (i % entry.getKey() == 0) {
                    System.out.print(entry.getValue());
                }
            }

            System.out.println();
        }
    }

    public static void main(String[] args) {
        Map<Integer, String> map = new TreeMap<>();

        map.put(2, "Foo");
        map.put(7, "Bar");
        map.put(11, "Baz");

        generalFizzBuzz(map, -200, 200);
    }

}

As always, please tell me whatever comes to mind.


texts: Python CSV file import and object manipulation

texts:
I am trying to import a .csv file and save data in objects for later manipulation in Python. I am very new to coding so please do let me know my fundamental errors.

import csv
import os
import time
import numpy
import itertools

def __init__(p):
    p.playerFile = csv.reader(open("dk.csv", "rb"))
    p.playerList = []
    p.playerName = ''
    p.playerPosition = ''
    p.PlayerGameInfo = ''
    p.playerPrice = 0

def loadCSV(p):
    for row in p.playerFile:
        playerObject = Player()
        playerObject.setPlayerName(row[1])     # Store player name
        playerObject.setPlayerPosition(row[0]) # Store player position
        playerObject.setPlayerGameInfo(row[3]) # Store player team
        playerObject.setPlayerPrice(row[2])    # Store player price

def getPlayerName(p):
    return p.PlayerName

def getPosition(p):
    return p.playerPosition

def getGameInfo(p):
    return p.PlayerGameInfo

def getPrice(p):
    return p.PlayerPrice

def setPlayerName(p, player):
    p.playerName = name

def setPlayerPosition(p, playerPosition):
    p.playerPosition = position

def setPlayerGameInfo(p, PlayerGameInfo):
    p.PlayerGameInfo = team

def setPlayerPrice(p, playerPrice):
    p.playerPrice = price

with open('~/dk.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print (row)


texts:
I'm trying to reduce the complexity of some methods, and I'm not exactly sure what approach to take. I'm currently building a PHP wrapper for a REST API, and the main problematic class is here:

https://github.com/petrepatrasc/blizzard-starcraft-api/blob/master/Service/ApiService.php

In short, since data retrieved from the API is not always consistent, I have to do this:

$portrait = new Portrait();
$portrait->setXCoordinate(isset($apiData['portrait']['x']) ? $apiData['portrait']['x'] : null)
    ->setYCoordinate(isset($apiData['portrait']['y']) ? $apiData['portrait']['y'] : null)
    ->setWidth(isset($apiData['portrait']['w']) ? $apiData['portrait']['w'] : null)
    ->setHeight(isset($apiData['portrait']['h']) ? $apiData['portrait']['h'] : null)
    ->setOffset(isset($apiData['portrait']['offset']) ? $apiData['portrait']['offset'] : null)
    ->setUrl(isset($apiData['portrait']['url']) ? $apiData['portrait']['url'] : null);
return $portrait;

What would be a better way of handling the problem, so that the method complexity goes down? I suppose that I can try and catch an "undefined index exception", but I kind of wanted to see if there's something a bit more elegant that I can use.


texts: Download a file and update the current downloaded percentage

texts:
I am not a big fan of JS, but have been forced to use it in this situation for various reasons.

My task: Download a URL to a target file, and update another part of the application with the current percentage.

I've run jslint and jshint over the code, and it seems happy, but I am sure there is still plenty of suboptimal stuff in my code. My code currently looks like this:

Match.prototype.downloadURL = function (url, target, next) {
    winston.info("Downloading url %s to %s", url, target);
    var tmpFilename = target + ".tmp",
        tmpFile = fs.createWriteStream(tmpFilename);
    http.get(url, function (resp) {
        var fullSize = +resp.headers["Content-Length"],
            currentSize = 0,
            currentPercentage = -1;
        // Write the file
        resp.pipe(tmpFile);
        resp.on('end', function () {
            tmpFile.close();
            this.registerDownloadFinished();
            fs.rename(tmpFilename, target, function (err) {
                if (err !== null) {
                    return next(err);
                }
                next(null, target);
            });
        });
        // Update when we hit a new percentage
        resp.on('data', function (chunk) {
            currentSize += chunk.length;
            var percentage = parseInt(currentSize / fullSize * 100, 10);
            if (percentage === currentPercentage) {
                return;
            }
            currentPercentage = percentage;
            this.updateDownloadingPercentage(percentage);
        });
    });
};

Problems I can see:

updateDownloadingPercentage and registerDownloadFinished are networked operations; I should probably be doing something to make sure these things arrive in order
I have a feeling I should be checking for errors a lot more; createWriteStream can fail, so where do I get its error message from.

Again, I only ask because I am a very poor JavaScript coder.  Please enlighten me as to any way I can improve this snippet.


texts: Scraping weather conditions for mountain peeks

texts:
I have built a website in Django in which I tried for the first time to create a complex app. It's an app that scrapes weather conditions on a peak in mountains, which are 17. I wanted to show a detailed forecast in separate templates, so I have 17 views which look almost the same.
Only 4 views:
class KasprowyWierchForecastView(TemplateView):
    """
    class for rendering view of detailed weather forecast for
    Kasprowy Wierch peak
    """
    template_name = 'mountain_base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Peak'] = PeakForecast.objects.filter(
            name_of_peak='Kasprowy').order_by('date')
        print(context['Peak'])
        return context

class KoscielecForecastView(TemplateView):
    """
    class for rendering view of detailed weather forecast for
        Koscielec peak
    """
    template_name = 'mountain_base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Peak'] = PeakForecast.objects.filter(
            name_of_peak='Koscielec').order_by('date')
        return context

class KrivanForecastView(TemplateView):
    """
    class for rendering view of detailed weather forecast for Krivan peak
    """
    template_name = 'mountain_base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Peak'] = PeakForecast.objects.filter(
            name_of_peak='Krivan').order_by('date')
        return context

class MieguszowieckiForecastView(TemplateView):
    """
    class for rendering view of detailed weather forecast for
    Mieguszowiecki peak
    """
    template_name = 'mountain_base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Peak'] = PeakForecast.objects.filter(
            name_of_peak='Mieguszowiecki').order_by('date')
        return context

class MnichForecastView(TemplateView):
    """
    class for rendering view of detailed weather forecast for
    Mnich peak
    """
    template_name = 'mountain_base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Peak'] = PeakForecast.objects.filter(
            name_of_peak='Mnich').order_by('date')
        return context

Only the name of the view class and context['Peak'] are different. The rest of the code is redundant. As my experience is based only on my self learning process I've not found any nice solution on how to fix or refactor.


texts: Creating an array of strings from a text file

texts:
I'm try to create array of strings from a text file. I need a review from experienced programmers about my program. (MinGW gcc, Win7)

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

main()
{
FILE *file;
char *fname = "lines.txt";
file = fopen(fname, "r");

if(file == NULL)
    printf("Can't read %s", fname);

char cbuff;

int nlines = 0; //counter of new lines
int chr = 0; //counter of chars (except new line char)

int maxlen = 0;
while( (cbuff = fgetc(file) - 0) != EOF )
{
    if(cbuff == '\n')
    {
        if (chr > maxlen)
        {
            maxlen = chr + 1;
        }

        chr = 0;
        nlines++;
    }

    else
    {
    chr++;
    }
}

printf( "lines: %d\nmax string len: %d\n\n", nlines, maxlen );
rewind(file);

char *list[nlines];

int buffsize = maxlen * sizeof(char);
char buff[buffsize];

int i = 0;
while(fgets(buff, buffsize, file))
{

    list[i] = malloc(strlen(buff) * sizeof(char));
    strcpy(list[i], buff);
    i++;
}

fclose(file);

int c = 0;
for(c; c < nlines; c++)
{
    printf( "%s", list[c] );
}
}//main

I'm trying to control size of array and items in array. Maybe I have errors somewhere, do not judge strictly.


texts: Low level string manipulation functions in C

texts:
I'm working with a legacy program that does a bunch of markup manipulation, some of it higher-level and specific to the proprietary markup, some of it lower level string stuff.

I rewrote and documented the customized low level stuff (and used string.h stuff where applicable). I'm not not usually a C-coder, but I'm trying to learn.

Am I duplicating core functionality of a standard library?
Am I following conventions/best practices?
Is the code efficient?

string_plus.h

/**
 * @file
 *
 * A small library of additional low level string manipulation functions. If any
 * functionality is duplicated from any of the normal libraries, it is due to
 * ignorance.
 */

#ifndef STRING_PLUS_H
#define STRING_PLUS_H

#include <string.h>

/**
 * Returns 1 if the front of @p text matches @p search_key, else 0.
 */
int begins_with(char const *text, char const *search_key);

/**
 * Condenses a string buffer by sliding all contents at @p p2 down to @p p1. In
 * other words, anything in between @p p1 and @p p2 is deleted. Returns @p p1.
 */
char *condense_buffer(char *p1, char *p2);

/**
 * Modifies @p text, removing all occurrences of @p c. Returns @p text.
 */
char *remove_char_occurrences(char *text, char const c);

/**
 * Inserts @p content into a buffer at @p p by shifting the buffer's data by @p
 * content's size. Returns a pointer at the end of the newly modified buffer.
 *
 * @warning Caller is responsible for guarding against a buffer overrun.
 */
char *insert_content(char *p, char const *content);

#endif /* Header load-once guard clause */

string_plus.c

#include "string_plus.h"

int begins_with(char const *text, char const *search_key) {
  int result = 1;
  while (*search_key != '\0' && (result = *search_key++ == *text++));
  return result;
}

char *condense_buffer(char *p1, char *p2) {
  while (*(p2-1) != '\0') *p1++ =*p2++;
  return p1;
}

char *remove_char_occurrences(char *text, char const c) {
  char *lead = text;
  char *tail = text;
  while (*lead != '\0') {
    while (*lead == c) ++lead;
    *tail++ = *lead++;
  }
  *tail = *lead;
  return text;
}

char *insert_content(char *p, char const *content) {
  int content_len = strlen(content);
  for (char *end = p + strlen(p); end >= p; end--) *(end + content_len) = *end;
  while (*content != '\0') *p++ = *content++;
  return p;
}

test functions

void test_begins_with() {
  Assert(begins_with("Theory", "The") == 1);
  Assert(begins_with("theory", "The") == 0);
  Assert(begins_with("T", "The") == 0);
  Assert(begins_with("Theory", "") == 1);
}

void test_condense_buffer() {
  char buff[] = "hello world";
  condense_buffer(&buff[7], &buff[10]);
  Assert(strcmp("hello wd", buff) == 0);
}

void test_remove_char_occurrences() {
  char s1[] = "hello world";
  Assert(strcmp("hello world", remove_char_occurrences(s1, 'x')) == 0);

  char s2[] = "hello world";
  Assert(strcmp("heo word", remove_char_occurrences(s2, 'l')) == 0);
}

void test_insert_content() {
  char buff[50] = "hello world";
  char *p = insert_content(&buff[5], "BRAVENEW");
  Assert(strcmp("helloBRAVENEW world", buff) == 0);
  Assert(strcmp(" world", p) == 0);
}


texts: JPEG compression and DCT algorithm verification

texts:
Here is the code I am using to apply DCT on 8x8 blocks, which I'm not sure is correct. I have tried to follow Wikipedia's discrete cosine transformation (DCT) formula as closely as possible. Please let me know if there are any changes to be made.

//round up a float type and show two decimal places
double rndup(double n)
{
  double t;
  double temp;
  t=n-floor(n);
  if (t>=0.5)
  {
          n*=100.0;//where n is the multi-decimal float
          n=ceil(n);
          temp = floor(n);
          temp = n - temp;
          n-=temp;
          n/=100.0;
          }
  else
  {
          n*=100.0;//where n is the multi-decimal float
          n=floor(n);
          temp = floor(n);
          temp = n - temp;
          n-=temp;
          n/=100.0;
  }
  return n;
}
//two functions that work together to apply DCT to a 8x8 block
void a_check(int u,int v, double *Cu, double *Cv)
{
if (u == 0) *Cu = sqrt(1.0 / 8.0); else *Cu = sqrt(2.0 / 8.0);
if (v == 0) *Cv = sqrt(1.0 / 8.0); else *Cv = sqrt(2.0 / 8.0);
}
void applyDCT(double *DCTMatrix, double *Matrix,int x, int y)   //arguments: DCTMatrix = matrix where DCT values go, Matrix = input Matrix which needs to be processed
{
double Cu=0,Cv=0,cos_x=0,cos_y=0, DCT_value = 0;
for(int u=0;u<8;u++)
{
    for(int v=0;v<8;v++)
    {
        a_check(u,v,&Cu,&Cv);
        cos_x = cos( (3.14/8) * (double)u * ( (double) ( (x+u) + (1.0/2.0))));
        cos_y = cos( (3.14/8) * (double)v * ( (double) ( (y+v) +(1.0/2.0))));
        DCT_value = Cu * Cv * Matrix[u*8 + v] * cos_x * cos_y;
        DCT_value = rndup(DCT_value);
        DCTMatrix[u*8 + v] = DCT_value;
    }
}
}


texts:
I have this RPG game and this has elements such as the map, the monsters and the items. The monsters and the items are stored in Lists and every time I want to show the map around the player, I have to check if the element is within the bounds of the camera.

public void ShowCamera()
    {
        int size = cameraSize/2;
        int topY = player.GetY() - size, bottomY = player.GetY() + size, topX = player.GetX() - size, bottomX = player.GetX() + size;
        int setX = 0, setY = 0;

        //Print Map
        Console.SetCursorPosition(0,0);
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        for (int i = topX; i < bottomX; i++)
        {
            for (int j = topY; j < bottomY; j++)
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.SetCursorPosition(setY,setX);
                Console.Write(map[i, j]);
                if (monstros.Count > 0)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    foreach (var elem in monstros)
                    {
                        if (elem.ReX() == i && elem.ReY() == j)
                        {
                            Console.SetCursorPosition(setY, setX);
                            Console.Write(elem);
                        }
                    }
                }
                if (items.Count > 0)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    foreach (var elem in items)
                    {
                        if (elem.ReX() == i && elem.ReY() == j)
                        {
                            Console.SetCursorPosition(setY, setX);
                            Console.Write(elem);
                        }
                    }
                }
                setY++;
            }
            Console.Write("\n");
            setY = 0;
            setX++;
        }

So, this works but it is very unoptimized and flickers a lot. I was wondering if there's a way to improve this cycle in any way.


texts: Webscraping code to import logs from a website which is about to die

texts:
We all know that the famous twitch log site OverRustleLogs is getting shut down. So I decided to do some web scraping to download my favourite streamer's logs using BeautifulSoup. How can make this code run more efficient?

import requests
import os
import shutil
from bs4 import BeautifulSoup

URL = 'https://overrustlelogs.net/'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser').findAll('div', {'class': 'list-group'})
names_3 =  [i.text.replace('\n ', '/').replace('\n', '') for i in soup[0].findAll('a',{'class':'list-group-item list-group-item-action'})]

for name in names_3:
    url_n = 'https://overrustlelogs.net'+str(name)
    page = requests.get(url_n)
    soup_n = BeautifulSoup(page.content, 'html.parser').findAll('div', {'class': 'list-group'})
    names_3_n =  [i.text.replace('\n ', '/').replace('\n', '') for i in soup_n[0].findAll('a', {'class':'list-group-item list-group-item-action'})]

for file in names_3_n:
    try:
            os.makedirs(f'./files{name}{file}')
    except:
        if FileExistsError:
            shutil.rmtree(f'./files{name}{file}')
            os.makedirs(f'./files{name}{file}')

    url_n1 = 'https://overrustlelogs.net'+str(name)+str(file)
    print(url_n1)
    page = requests.get(url_n1)
    soup_n1 = BeautifulSoup(page.content, 'html.parser').findAll('div', {'class': 'list-group'})
    names_3_n1 =  [i.text.replace('\n ', '/').replace('\n', '') for i in soup_n1[0].findAll('a', {'class':'list-group-item list-group-item-action'})]

    for filename in names_3_n1:
        f = open(f'./files{name}{file}{filename}', 'wb')
        r = requests.get(url_n1+str(filename))
        f.write(r.content)


texts: Adding or Replacing a Page item in a QueryString in C#.

texts:
Can this code be improved?  I'm avoiding using the QueryString collection because the query string may contain eg: OrderBy=Column1&OrderBy=Column2 and it didn't seem helpful to start with those switched into QueryString["OrderBy"]=="Column1,Column2";

    var query = "";
    if (urlHelper.RequestContext.HttpContext.Request.Url != null)
    {
        query = urlHelper.RequestContext.HttpContext.Request.Url.Query.TrimStart('?');
        if (query.Length > 0)
        {
            var kvp =
                query.Split('&').Select(x => x.Split('='))
                    .Select(x => new { Key = x[0], Value = (x.Length > 0) ? x[1] : ""})
                    .Where(x => x.Key != "page")
                    .ToList();
            kvp.Add(new { Key = "page", Value = number.ToString() });
            query = String.Join("&", kvp.Select(x => x.Key + "=" + x.Value).ToArray());
        }
        else query = String.Format("page={0}", number);
    }


texts:
I wrote my first python code to conduct PSO. I am wondering about the best practices for Python. While my code works, I want to make sure it's orthodox as well. For example, here is my class I use followed by a function that initializes the list of Particles that I use for the algorithm:

########### data representation
pList = []
class Particle:
    #value, x_pos, y_pos
    gBest     = [0.0, 0, 0]
    bestIndex = 0

    #takes index in pList as constructor argument
    def __init__(self, i):
        #x,y coords, randomly initialized
        self.x          = randint(-worldWidth/2,worldWidth/2)
        self.y          = randint(-worldHeight/2,worldHeight/2)
        #x,y velocity
        self.velocity_x = 0.0
        self.velocity_y = 0.0
        #personal best
        #[fitness value, x coord, y coord]
        self.pBest      = [Q(self.x, self.y), self.x, self.y]
        self.index      = i
        #local best
        self.lBest      = []
        self.lBestIndex = 0
        #array for neighbor indicies
        self.neighbors  = []
    #for printing particle info
    def __str__(self):
        if k > 0:
            return '  i: '+str(self.index)+'\n  x: '+str(self.x)+'\n  y: '+str(self.y)+'\nv_x: '+str(self.velocity_x)+'\nv_y: '+str(self.velocity_y)+'\n  b: '+str(self.pBest[0])+'\n  l: '+str(self.lBest)+'\n'
        else:
            return '  i: '+str(self.index)+'\n  x: '+str(self.x)+'\n  y: '+str(self.y)+'\nv_x: '+str(self.velocity_x)+'\nv_y: '+str(self.velocity_y)+'\n  b: '+str(self.pBest[0])+'\n'

###########

def createParticles():
    global pList
    global numParticles
    global k
    #create particle list
    for i in range(0,numParticles):
        pList.append(Particle(i))

    #fill neighbor lists
    if k > 0:
        for p in pList:
            for x in range(p.index-(k/2),p.index+(k/2)+1):
                if x > numParticles:
                    p.neighbors.append(x%numParticles)
                elif x < 0:
                    p.neighbors.append(numParticles+x)
                elif x == numParticles:
                    p.neighbors.append(0)
                else:
                    p.neighbors.append(x)
        updatelBest()

    #initialize global and local bests
    updategBest()

My main questions are:

Is this a correct class structure?
Should I have made createParticles() part of the class?

If anyone would care to see the whole code, I'd love to get any feedback you'd care to provide. The code is on Github here. Also, if anyone cares to comment on my .md file, I wouldn't mind!


texts:
I have a user model.

It basically forwards get/create/delete requests into my database client.

The problem I have is the error handling, it screams not DRY to me, but I can't find an elegant way to clean it up.

var UserModel = pd.make(Model, {
    get: function _get(id, cb) {
        // nano is a database client
        this.nano.get(id,
            // whitelist runs every error through the white list,
            // if it fails (false) throw it
            // if it succeeds (true) pass it to cb
            // if the return value is undefined it does nothing
            error.whitelist(function _errors(err) {
                // getaddrinfo is a random DNS error I have to swallow
                // no clue where the bug comes from, trying again is the easy fix
                if (err.syscall === 'getaddrinfo') {
                    UserModel.get(id, cb);
                } else if (err.error === "not_found") {
                    return true;
                } else {
                    return false;
                }
            }, cb)
        );
    },
    insert: function _create(json, cb) {
        this.nano.insert(json, json._id,
            error.whitelist(function _errors(err) {
                if (err.syscall === 'getaddrinfo') {
                    UserModel.insert(json, cb);
                } else if (err.error === "conflict") {
                    return true;
                } else {
                    return false;
                }
            }, cb)
        );
    },
    delete: function _delete(name, cb) {
        var that = this;
        this.get(name, function _getRev(err, body) {
            that.nano.destroy(name, body._rev,
                error.whitelist(function _errors(err) {
                    if (err.syscall === 'getaddrinfo') {
                        UserModel.delete(name, cb);
                    } else {
                        return false;
                    }
                }, cb)
            );
        });
    }
});

pd, error, nano


texts:
I have been studying front-end development for 2 .5 months, I decided to switch to practice and wrote a todo list in 8 hours

Please write your opinion about the code and how it can be improved (preferably in html, css too, but JS is a priority)
I want to start learning React, is it already possible to start or is it better to practice some more JS?

Link to code: https://codepen.io/domarchuk77/pen/xxRoMBY
class Task {
    constructor(){
        counter++
        this.taskText = document.querySelector(".todo__settings__input").value
        this.task = pattern.cloneNode(true)
        this.taskList = document.querySelector(".todo__list")
        this.taskList.prepend(this.task)
        this.taskName = document.querySelector(".todo__list__item__text")
        this.itemProgress = document.querySelector(".todo__list__item")
        this.taskName.innerHTML = this.taskText
        this.itemProgress.classList.add("in-progress")
        this.taskDelete()
        this.taskComplete()
        this.taskFilter()
        input.value = ""
    }
    taskDelete(){
        this.buttonDelete = document.querySelector(".todo__list__item__buttons__finish")
        this.buttonDelete.addEventListener("click",() => {
            this.task.remove()
            counter--
            console.log(counter)
            if(counter == 0){
                this.filter.disabled = true
                this.filter.value = "all"
            }
        })
    }
    taskComplete(){
        this.buttonComplete = document.querySelector(".todo__list__item__buttons__complete")
        this.buttonComplete.addEventListener("click",() => {
           this.buttonComplete.remove()
           this.itemProgress.classList.add('task-complete')
           this.filterCheckActive()
           if(this.itemProgress.classList.contains('in-progress')){
               this.itemProgress.classList.remove('in-progress')
           }
        })
    }
    taskFilter(){
        this.filter = document.querySelector(".todo__settings__filter")
        this.filter.disabled = false
        this.filter.addEventListener("change",() => {
            if(this.filter.value == "all"){
                this.itemProgress.classList.add('show')
            }else{
                this.itemProgress.classList.remove('hide')
            }
            this.filterCheckActive()
            if(this.filter.value == "complete"){
                this.itemProgress.classList.remove('show')
                this.itemProgress.classList.remove('hide')
                if(this.itemProgress.classList.contains('in-progress')){
                    this.itemProgress.classList.add('hide')
                }else{
                    this.itemProgress.classList.remove('show')
                }
            }
        })
    }
    filterCheckActive(){
        if(this.filter.value == "active"){
            this.itemProgress.classList.remove('show')
            this.itemProgress.classList.remove('hide')
            if(this.itemProgress.classList.contains('task-complete')){
                this.itemProgress.classList.add('hide')
            }else{
                this.itemProgress.classList.remove('show')
            }
        }
    }
    checkText(){

    }
}
let counter = 0
let pattern = document.querySelector(".todo__list__item")
pattern.remove()
let input = document.querySelector(".todo__settings__input")
document.querySelector(".todo__settings__button").addEventListener("click", function(){
    if(!(input.value.length == 0)){
        new Task
    }
})


texts:
Please review my code for 'JWT' authentication.

Are there any security issues?
Where should I store the secret's key, DB or InMemory?
What's a good 'JWT' Lifetime?
Should I send the 'JWT' in Header for every request?
What should be done when a 'JWT' Expires?

Token Manager

using System;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Procoor_V4_Model.SecurityModel;

namespace Procoor_V4_Security
{
    public class TokenManager
    {
        public static string EncodeToken(JwtPayload jwtPayload, string secret)
        {
            const string algorithm = "HS256";

            var header = new JwtHeader
            {
                Typ = "JWT",
                Alg = algorithm
            };

            var jwt = Base64Encode(JsonConvert.SerializeObject(header)) + "." + Base64Encode(JsonConvert.SerializeObject(jwtPayload));

            jwt += "." + Sign(jwt, secret);

            return jwt;
        }

        public static JwtPayload DecodeToken(string token, string secret)
        {
            var segments = token.Split('.');

            if(segments.Length != 3)
                throw new Exception("Token structure is incorrect!");

            JwtHeader header = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(Base64Decode(segments[0])), typeof(JwtHeader));
            JwtPayload jwtPayload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(Base64Decode(segments[1])), typeof(JwtPayload));

            var rawSignature = segments[0] + '.' + segments[1];

            if(!Verify(rawSignature, secret, segments[2]))
                throw new Exception("Verification Failed");

            return jwtPayload;
        }

        private static bool Verify(string rawSignature, string secret, string signature)
        {
            return signature == Sign(rawSignature, secret);
        }

        private static string Sign(string str, string key)
        {
            var encoding = new ASCIIEncoding();

            byte[] signature;

            using (var crypto = new HMACSHA256(encoding.GetBytes(key)))
            {
                signature = crypto.ComputeHash(encoding.GetBytes(str));
            }

            return Base64Encode(signature);
        }

        public static string Base64Encode(dynamic obj)
        {
            Type strType = obj.GetType();

            var base64EncodedValue = Convert.ToBase64String(strType.Name.ToLower() == "string" ? Encoding.UTF8.GetBytes(obj) : obj);

            return base64EncodedValue;
        }

        public static dynamic Base64Decode(string str)
        {
            var base64DecodedValue = Convert.FromBase64String(str);

            return base64DecodedValue;
        }
    }
}

How I currently use it:

var secret = TokenManager.Base64Encode(SecurityConstants.KeyForHmacSha256);
var currentTime = (long)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()).TotalSeconds;
var payload = new JwtPayload
{
    iss = SecurityConstants.TokenIssuer,
    sub = "46897484",
    iat = currentTime,
    exp = currentTime + 1800
};

var jwt = TokenManager.CreateJwtToken(payload, secret);


texts:
I have this function that should merge two array of classes when id of array1 is equal to id of array2.

For simplicity I converted one array into an ArrayList so I can remove the occurrence merged into the other one..

I'm looking a way to improve it, also in cpu-time, because the two arrays can have more then 20000rows.
The actual way, should take some time..

public Asset[] merge(Asset[] a2, ArrayList<countR> a)
{
        while (a.size()!=0){
            int i=0;
            Boolean b=false;
            while (i<a2.length && b==false)
            {
                if (a.get(0).id.equals(a2[i].id)){
                    a2[i].TotaleRegistrazioni = a.get(0).tot;
                    b=true;
                }
                i++;
            }
            a.remove(0);
        }
return a2;
}


texts: Sorting a list of phone numbers by teleconference provider and location

texts:
I'm looking to order an array of phone numbers with a primary sorting criteria of whether the teleconference provider is correct and a secondary criteria of whether the the location of the phone number matches the location of the user.

Example:

If UserLocation = US, meetingProvider = AT&T, the order should be:

US AT&T Number
UK AT&T Number
US Unknown number
UK Unknown number
US Webex number
UK Webex number

I've made two solutions for this problem. The sort function used in my 2nd attempt appears to be the function to use but I find the long winded closures impact readability. Although filtering repeatedly seems somewhat inefficient. With readability in mind, how can I can improve this function and which attempt is the better way to go about this?

1st attempt

///Orders parsed numbers by correctProvider -> unknownProvider -> incorrectProvider. If the users location can be idenitified we then order these subsets so the numbers for the users location are on top.
private static func sortParsedNumbers(meeting: Meeting) -> [String] {
    let unknownProviderNumbers = meeting.phoneNumbers.filter { ConferenceNumberDirectory.findProvider(forNumber: $0) == .unknown }
    var correctProviderNumbers = meeting.phoneNumbers.filter { ConferenceNumberDirectory.findProvider(forNumber: $0) == meeting.conferenceProvider }
    let incorrectProviderNumbers = meeting.phoneNumbers.filter { !unknownProviderNumbers.contains($0) && !correctProviderNumbers.contains($0) }

    if let userCountry = getUserLocation() {
        let userAndNumberLocationMatch = {ConferenceNumberDirectory.findCountryISOCodes(forNumber: $0).contains(userCountry)}
        let matchingLocationNumbers = correctProviderNumbers.filter(userAndNumberLocationMatch)
        let nonMatchingLocationNumbers = correctProviderNumbers.filter {matchingLocationNumbers.contains($0)}
        correctProviderNumbers = matchingLocationNumbers + nonMatchingLocationNumbers
    }
    return correctProviderNumbers + unknownProviderNumbers + incorrectProviderNumbers

2nd attempt

///Orders parsed numbers by correctProvider -> unknownProvider -> incorrectProvider. If the users location can be idenitified we then order these subsets so the numbers for the users location are on top.
    private static func sortParsedNumbers(meeting: Meeting) -> [String] {

    guard let userCountry = getUserLocation() else {
        let numbersOrderedByProvider = meeting.phoneNumbers.sorted {element,_ in ConferenceNumberDirectory.findProvider(forNumber: element) == .unknown }
            .sorted {element,_ in ConferenceNumberDirectory.findProvider(forNumber: element) == meeting.conferenceProvider}
        return numbersOrderedByProvider
    }

    let numbersOrderedByLocation = meeting.phoneNumbers.sorted(by: {x,_ -> Bool in ConferenceNumberDirectory.findCountryISOCodes(forNumber: x).contains(userCountry)} )
    let numbersOrderedByLocationAndProvider = numbersOrderedByLocation.sorted {ConferenceNumberDirectory.findProvider(forNumber: $0) == .unknown && ConferenceNumberDirectory.findProvider(forNumber: $1) != .unknown }
        .sorted {ConferenceNumberDirectory.findProvider(forNumber: $0) == meeting.conferenceProvider && ConferenceNumberDirectory.findProvider(forNumber: $1) != meeting.conferenceProvider}
    return numbersOrderedByLocationAndProvider
}


texts:
I am currently writing some generic functions to make working with vectors a little "cleaner". Working with the "erase-remove idiom" can be a little confusing sometimes, and make the code look a little dirty, so why not throw it into a function? I have four individual function I wish to have reviewed and made better. I know that there are tons of examples online (trust me, I've looked at most of them).

1. Simply Remove All Instances of a Value From a Vector

template<class T>
void Vec_RemoveAll(vector<T>& vec, T val)
{
    vec.erase(remove(vec.begin(), vec.end(), val), vec.end());
}

This function is the simplest of all four.

2. Remove All Instances of a Container of Values From a Vector

template<class Container, class T>
void Vec_RemoveAll(vector<T>& vec, const Container& vals)
{
    for (const T& val : vals) vec.erase(remove(vec.begin(), vec.end(), val), vec.end());
}

Simply loops through the container checking the vector for occurrences of each value.

3. Remove All Elements That Meet Unary Predicate's Condition

template<class T, class UnaryPredicate>
void Vec_RemoveAll_If(vector<T>& vec, UnaryPredicate* predicate)
{
    vec.erase(remove_if(vec.begin(), vec.end(), predicate), vec.end());
}

I'm not familiar with remove_if, I'm worried I may have not implemented this correctly.

4. Remove Elements That Meet Any of the Predicates' Conditions

template<class T, class UnaryPredicate>
void Vec_RemoveAll_If(vector<T>& vec, const vector<UnaryPredicate> predicates)
{
    for (const UnaryPredicate& predicate : predicates)
        vec.erase(remove_if(vec.begin(), vec.end(), predicate), vec.end());
}

How would one generalize the type of container that the unary predicates are stored in?


texts:
I'm creating an application that reads in data from a CSV file and creates an XML file using LXML. The below code works as expected. However, before I develop it further I would like to refactor it and make it more DRY. I will need to start creating the additional XML snippets for the other code types in the CSV file and I believe, in its current state, there is too much duplication.

I am attempting to learn Python while using a real user case, please can someone provide any guidance on how I could make the code more eloquent and more DRY. Do I need to be using classes and functions or is my approach OK for the type of file (XML) and creating?

import pandas as pd
from lxml import etree as et
import uuid

df = pd.read_csv('assets.csv', sep=',')

root = et.Element('SignallingSchemeData', xmlns='boo')
timeframe = et.SubElement(root,'TimeFrame')
timeframe.attrib["fileUID"] = str(uuid.uuid4())
timeframe.attrib["name"] = str("timeframe 1")

for index, row in df.iterrows():
    if row['CODE'] == 'S1':
        equipment = et.SubElement(root, 'Equipment')
        signalEquipment = et.SubElement(equipment, 'SignalEquipment')
        signalEquipment.attrib["fileUID"] = str(row["ID"])
        signalEquipment.attrib["name"] = str(row["DESC"])
        equipment = et.SubElement(root, 'Equipment')
        equipmentSupportEquipment = et.SubElement(equipment, 'EquipmentSupportEquipment')
        equipmentSupportEquipment.attrib["fileUID"] = str(uuid.uuid4())
        equipmentSupportReference = et.SubElement(signalEquipment, 'EquipmentSupportReference').text = equipmentSupportEquipment.attrib["fileUID"]
    else:
        equipment = et.SubElement(root, 'Equipment')

source = et.SubElement(root, 'Source')
view = et.SubElement(root, 'View')
view.attrib["fileUID"] = str(uuid.uuid4())
view.attrib["name"] = str('Coordinates')

for index, row in df.iterrows():
    viewCoordinatesList = et.SubElement(view, 'ViewCoordinatesList')
    viewCoordinates = et.SubElement(viewCoordinatesList, 'ViewCoordinates')
    itemFileUID = et.SubElement(viewCoordinates, 'ItemFileUID')
    itemFileUID.attrib['fileUID'] = str(row['ID'])
    viewCoordinatePairLon = et.SubElement(viewCoordinates, 'ViewCoordinatePair', name = 'longittude')
    viewCoordinatePairLon.attrib['Value'] = str(row['Y'])
    viewCoordinatePairLat = et.SubElement(viewCoordinates, 'ViewCoordinatePair', name = 'latitude')
    viewCoordinatePairLat.attrib['Value'] = str(row['X'])
    viewCoordinatePairH = et.SubElement(viewCoordinates, 'ViewCoordinatePair', name = 'height')
    viewCoordinatePairH.attrib['Value'] = str(row['Z'])

et.ElementTree(root).write('test.xml', pretty_print=True, xml_declaration = True, encoding='UTF-8', standalone = None)

assets.csv is as follows:

ID,CODE,ELR,TRID,DIR,MILEAGE,X,Y,Z,DESC,IMAGE
30734,S1,LEC1,1100,,008+0249 (9-1497),518169.12,185128.27,37.52,,Asset30734.jpg
31597,S10,LEC1,1100,,008+0286 (9-1460),518151.38,185157.1,36.7,IRJ at 8 miles and 0289 yards,Asset31597.jpg
31598,S10,LEC1,1100,,008+0286 (9-1460),518150.4,185156.11,36.7,IRJ at 8 miles and 0289 yards,Asset31598.jpg
31596,S10,LEC1,1100,,008+0287 (9-1458),518149.76,185157.14,36.7,IRJ at 8 miles and 0289 yards,Asset31596.jpg


texts:
As part of a larger Java application I'm working on, I have to retrieve emails and parse the data for the emails' content (subject, date, text, attachments, sender). In the method below, I pass a Message as a parameter, which is the Javamail abstract representation of an email. The details of the Message are recovered and then returned as a MailList. A MailList is just a holder for the five objects that describe each email.

public MailList getContent(Message message) throws MessagingException, IOException
{
    String body = "";
    String from = "";
    ArrayList<MimeBodyPart> attachments = new ArrayList<MimeBodyPart>();
    String contentType = message.getContentType();
    Address[] addresses = message.getFrom();
    if(addresses.length == 1)
        from = addresses[0].toString();
    else
    {
        for(int num = 0; num < addresses.length - 1; num++)
            from += addresses[num].toString() + ", ";
        from += addresses[addresses.length].toString();
    }
    if(contentType.contains("TEXT/PLAIN"))
    {
        Object content = message.getContent();
        if(content != null)
            body += content.toString();
    }
    else if(contentType.contains("TEXT/HTML"))
    {
        Object content = message.getContent();
        if(content != null)
            body += Jsoup.parse((String)content).text();
    }
    else if(contentType.contains("multipart"))
    {
        Multipart mp = (Multipart)message.getContent();
        int numParts = mp.getCount();
        for(int count = 0; count < numParts; count++)
        {
            MimeBodyPart part = (MimeBodyPart)mp.getBodyPart(count);
            String content = part.getContent().toString();
            if(MimeBodyPart.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
                attachments.add(part);
            else if(part.getContentType().contains("TEXT/HTML"))
                body += Jsoup.parse(content).text();
            else
                body += content;
        }
    }
    return new MailList(from, message.getSubject(), body,
            message.getSentDate().toString(), attachments);
}

This code works exactly as intended, but is very slow. Each method run can range from 0.5s to 1.5s depending on the content of the email. This means that parsing 10 emails might take up to 15s. Up to around 100 emails might be expected to be parsed at any given time, and 2 to 3 min is too long for such a process. Not sure if this could be improved to be more efficient but any advice is greatly appreciated.


texts:
I am trying to hack together a simple promise implementation.

Is the following approach of maintaining a single async call and linking nested promises dynamically using their then method a viable approach?

const PromiseStatus = {
    pending: 'pending',
    fulfilled: 'fulfilled',
    rejected: 'rejected',
};
const DEFAULT_ERR = 'An unhandled exception occurred in Promise...';
var id = 0;
var scheduleId;

function Promise(executor) {

    var p, thens = [], catchCb = err=>console.error(DEFAULT_ERR, err), result;

    try {
        p = {
            id: id++,
            then,
            ['catch']: catchh, // 'catch' is reserved
        };

        p['__isSettled__'] = false;
        p['__PromiseStatus__'] = PromiseStatus.pending;
        p['__PromiseValue__'] = undefined;
        executor((...args) => schedule(resolve, ...args), reject);
        return p;

        function then(cb) {
            thens.push(value => thenCb(cb, value));
            return p;

            function thenCb(cb, value) {
                result = cb ? cb(value) : value;

                // Non-promise results...
                if (!isPromise(result)) {

                    if(!thens.length) {
                        p['__isSettled__'] = true;
                        p['__PromiseValue__'] = result;
                        p['__PromiseStatus__'] = PromiseStatus.fulfilled;
                        return p;
                    }

                    return thens.shift()(result);
                }

                // Promise results...
                if ((p['__isSettled__'] && !thens.length)) {
                    p['__PromiseValue__'] = result;
                    p['__PromiseStatus__'] = PromiseStatus.fulfilled;
                    return p;
                }

                // If the result Promise is fulfilled, use its value
                if(result.__PromiseStatus__ === PromiseStatus.fulfilled) {
                    return result.__PromiseValue__;
                }

                // "Bind" the Promise to the sub-promise
                p['__isSettled__'] = true;
                result.then(result => {
                    return thenCb(undefined, result);
                });
                return p;
            }
        }
        function catchh(cb) {
            catchCb = cb;
            return p;
        }
        function resolve(value) {
            try {
                return thens.shift()(value);
            } catch (err) {
                reject(err);
            }
        }
        function reject(err) {
            catchCb(err);
        }

    } catch (err) {
        p['__PromiseValue__'] = err;
        setTimeout(()=>catchh(err));
    }
}

function isPromise(o) {
    return o && o.then;
}

function schedule(fn, ...args) {
    clearTimeout(scheduleId);
    scheduleId = setTimeout(()=>fn(...args));
}

var p = new Promise(resolve=> {
    resolve('this is the result of a0');
})
.then(result=> {
    return new Promise(resolve=> {
        resolve('this is the result of b0');
     })
     .then(result => {
        return new Promise(resolve => {
            resolve('this is the result of c0');
        });
     });
})
.then(result=> {
    console.log('final result is: \'', result, '\'');
return result;
}).catch(err=>{
    console.log('error: ', err);
});


texts: Sorts and data structures: a bucket sort

texts:
I am currently going through and implementing basic algorithms and data structures as I feel I didn't learn enough about this during my Data Structures and Algorithms unit. So far I've done the following algorithms, yet to get to data structures.
Sorting

Bucket

import random
#toSort = [round(random.uniform(0.10, 0.99), 2) for _ in range(20)]
toSort = [round(random.uniform(0.10, 0.99), 2) for i in range(10, 0, -1)]
print(toSort)

def bucket_sort(array):
    buckets = [[] for i in range(len(array))]
    sorted_buckets = []

    for index in range(len(array)):
        bucket_num = len(array) * array[index]
        print(bucket_num)
        buckets[int(bucket_num)].append(array[index])

    for bucket in buckets:
        insertion_sort(bucket)

    for bucket in buckets:

        if len(bucket) == 0:
            continue

        elif len(bucket) > 1:
            for num in bucket:
                sorted_buckets.append(num)
        else:
            sorted_buckets.append(bucket[0])

    return sorted_buckets

def insertion_sort(array):

    for unsorted_val in range(1, len(array)):
        val = array[unsorted_val]
        val_index = unsorted_val

        while val_index > 0 and array[val_index - 1] > val:
            array[val_index] = array[val_index - 1]
            val_index -= 1
        array[val_index] = val

toSort = bucket_sort(toSort)

Insertion
Merge
Quick
Selection

Searching

Binary
Linear

Merging

ArrayMerge

I was planning to include the code for the rest of the algorithms I've implemented but I have found code reviews for those already so I do not want to double up on the questions.
However, I did want to ask this on the meta page but I didn't have enough reputation to post. If I were to go through and update my code with the suggestions in the other code reviews, would it be okay for me to post here with my implementation and ask for further review?


texts:
I think my code has too many functions... can it be written better?

Please help reviewing my jQuery functions.

HTML

        xxx
        <input type="radio" name="event_owner" id="xxx">

        yyy
        <input type="radio" name="event_owner" id="yyy">

<input type="text" name="_event_owner[name]" autocomplete="off" value="">

jQuery

$(".event_owner").click(function(){
    $(".event_owner input[type='text']").val($('.event_owner :radio:checked').attr("id"));
    $('.event_owner p').css({"opacity":"1"});
    $('.event_owner input').not(":checked").parent("p").css({"opacity":"0.3"});
});

// when page loaded and input(radio) saved

if($(".event_owner input[type='text']").length) {
    $("input[id="+$(".event_owner input[type='text']").val()+"]").attr("checked","checked");
    $('.event_owner input').not(":checked").parent("p").css({"opacity":"0.3"});

}

Playground

http://jsfiddle.net/Zf4UE/


texts: String validation based on multiple criteria

texts:
I had me a code challenge and I was thinking: is there a way to make this more efficient and short? The challenge requires me to scan a string and ...

In the first line, print True if it has any alphanumeric characters. Otherwise, print False.

In the second line, print True if it has any alphabetical characters. Otherwise, print False.

In the third line, print True if it has any digits. Otherwise, print False.

In the fourth line, print True if it has any lowercase characters. Otherwise, print False.

In the fifth line, print True if  has any uppercase characters. Otherwise, print False.

Below is my approach :
def func_alnum(s):
    for i in s:
        if i.isalnum():
            return True
    return False

def func_isalpha(s):
    for i in s:
        if i.isalpha():
            return True
    return False

def func_isdigit(s):
    for i in s:
        if i.isdigit():
            return True
    return False

def func_islower(s):
    for i in s:
        if i.islower():
            return True
    return False

def func_isupper(s):
    for i in s:
        if i.isupper():
            return True
    return False
if __name__ == '__main__':
    s = input()
    s=list(s)
    print(func_alnum(s))
    print(func_isalpha(s))
    print(func_isdigit(s))
    print(func_islower(s))
    print(func_isupper(s))

It feels like I made a mountain out of a molehill. But I would defer to your opinions on efficiency and shortness before I live with that opinion.


texts:
I was trying to refactor the following Python code (keeping the same time-complexity) which is an implementation of Z-Algorithm for pattern matching in strings.

def compute_z(string):
   n = len(string)
   z = [n]

   L = R = 0
   for i in xrange(1,n):
        if (i > R):
            L = R = i
            while (R < n and string[R-L] == string[R]): R+=1
            z.append(R-L)
            R -= 1
        else:
            k = i-L
            if (z[k] < R-i): z.append(z[k])
            else:
                L = i
                while (R < n and string[R-L] == string[R]): R += 1
                z.append(R-L)
                R -= 1

I was thinking of using lambda but it returns expressions and I need to store the values in z array. So I could not think of a way of using lambda.

The max I could refactor was this:

def g(L,R,string):
    L=i
    while (R < len(string) and string[R-L] == string[R]): R += 1
    return L,R

def compute_z(string):
   n = len(string)
   z = [n]

   L = R = 0
   for i in xrange(1,n):
        if (i > R):
            R = i
            L,R = g(L,R,string)
            z.append(R-L+1)
        else:
            k = i-L
            if (z[k] < R-i): z.append(z[k])
            else:
                L,R = g(L,R,string)
                z.append(R-L+1)

Could it be any further refactored?

NOTE: Z-Algorithm is defined as z(i) = number of characters in the prefix of s(i) that matches the prefix of S.

For example, a string S = 'abaab'. The substrings of S are

s(0) = 'abaab' = S
s(1) = 'baab'
s(2) = 'aab'
s(3) = 'ab'
s(4) = 'b'

The z values are respectively

z(0) = 5 = length(S)
z(1) = 0
z(2) = 1
z(3) = 2
z(4) = 0

For more details, see this video.