texts: Improving CSV filtering with Python using regex

texts:
Consider a .csv file that contains a set of video names like so:

"There are happy days","1204923"
"Beware of ignorance","589636"
"Bloody Halls MV","258933"
"Dream Theater - As I Am - Live in...","89526"

The intent of the code I built is to filter items in the csv depending on the list of excluded items. Therefore, if the name of the video contains a word in the list of excluded items, it'll be rejected for saving. The following is the code:

exclude_list = ["mv","live","cover","remix","bootleg"]

data_set = []

with open('video_2013-2016.csv', 'rb') as f:

    reader = csv.reader(f)

    for row in reader:
        # Only record videos with at least 100 views
        if int(row[1]) > 99:

            # A test list that holds whether the regex passes or fails
            test_list = []

            for ex in exclude_list:
                regex = re.compile(".*("+ex+").*")

                if regex.search(row[0]):
                    test_list.append(False)
                else:
                    test_list.append(True)

            # Depending on the results, see if the row is worthy of saving
            if all(result for result in test_list):
                data_set.append(row)

I know the code I wrote above is quite inefficient, and I've seen examples of list comprehensions that can do a better job, but I do not quite understand how list comprehension can work in this case. I just hate it that I have to create the regex variable many times and it feels like a waste of resource.


texts:
Previously in the Settings JAVA_HOME with batch post, I had created a script in bash to change my JAVA_HOME env variable. Since then, I have been trying to use more and more PowerShell so I recreated the script with PowerShell.

The script has several options that provide different functionalities:

e or echo : output the current value of JAVA_HOME.
s or set : option to change the current value of JAVA_HOME. You must provide the key you want to change to.
a or add : add a key value pair to the store file that you can later on changed to.
l or list : list the current value in the file.
r or remove : remove the key-value pair from the store file.

This is still a script that I use for my personal use so there are still things that are not robust. You can add a key with an empty value or an invalid one and the script will not stop you. I've tested every option and all the "happy paths" are working.

This is my first script in PowerShell, so there were a lot of googling and patching all around the script to make it work.

<#
    Name: javaenv
    Date: 12 September 2016
    Author: Marc-Andre Girard
    Purpose: Modify the JAVA_HOME env variable based on Java installations on the computer.
#>

Param(
  [Parameter(Mandatory=$True)]
  [string]$action,
  [string]$key,
  [string]$value
)

<#
    Show the JAVA_HOME variable to the screen
#>
function Output() {
    Get-ChildItem Env:JAVA_HOME
}

<#
    Set the JAVA_HOME variable in the Process scope to only influence the current process.
#>
function SetJavaHome([string]$value_to_set) {
    [Environment]::SetEnvironmentVariable("JAVA_HOME", $value_to_set, "Process")
}

<#
    Get a value from the version file, based on a key provided.
#>
function GetValueFromFile([string]$key_in_file) {
    $javaVersions = GetVersionsFromFile
    if($javaVersions.ContainsKey($key_in_file)) {
        $javaVersions.$key_in_file
    } else {
        Write-Host "The key does not exit in this file"
        exit
    }
}

<#
    Add a version to the version file, based on a key-value provided.
#>
function AddVersionToFile([string]$key_in_file, [string]$value_to_add) {
    $javaVersions = GetVersionsFromFile
    if (!$javaVersions.ContainsKey($key_in_file)) {
        Add-Content $dir/java_versions.store "$key_in_file=$value_to_add"
    } else {
        Write-Host "Key already exist in the file"
        exit
    }
    Write-Host "$key_in_file=$value_to_add"

}

function GetVersionsFromFile() {
    ConvertFrom-StringData (Get-Content $dir/java_versions.store | Out-String)
}

function RemoveVersionFromFile([string]$key_to_remove) {
    Write-Host $key_to_remove
    $javaVersions = GetVersionsFromFile
    $javaVersions.remove($key_to_remove)
    $content = HashConvertToString $javaVersions
    $content | Out-File $dir/java_versions.store
}

function HashConvertToString($ht) {
    $content_file = ""
    foreach($pair in $ht.GetEnumerator()) {
        $content_file += "{0}={1}`n" -f $($pair.key),$($pair.Value)
    }

    $content_file
}

Set-StrictMode -Version Latest

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath

if($action -eq "e" -or $action -eq "echo") {
    Output
}

if($action -eq "s" -or $action -eq "set") {
    if(![string]::IsNullOrEmpty($key)) {
        $value_from_file = GetValueFromFile($key)
        SetJavaHome($value_from_file)
        Output
    } else {
        Write-Host "You must provide the key to set with -key or provide the second argument"
    }

}

if($action -eq "a" -or $action -eq "add") {
    AddVersionToFile $key $value
}

if($action -eq "l" -or $action -eq "list") {
    GetVersionsFromFile
}

if($action -eq "r" -or $action -eq "remove") {
    RemoveVersionFromFile $key
}

This is an example of what a store file should look like :

JAVA6=C:/Program Files/Java/jdk1.6.0_43
JAVA7=C:/Program Files/Java/jdk1.7.0_79
JAVA8=C:/Program Files/Java/jdk1.8.0_73


texts: Decompose a value as a sum of square numbers

texts:
My daughter had a question on her maths homework which was to write a value as a sum of 4 or fewer square numbers.

For example, x = 73 could be 36 + 36 + 1.

I came up with a really brute force algorithm that shows all combinations but when the values get above 1000 it becomes quite slow.

Is there a clever way of achieving this?
Here is my algo in F#

let squares = [ 0.. 100 ] |> Seq.map (fun x -> x * x) |> Seq.toList

let rec calc total attempts squares accu results =
  match (total, attempts, squares) with
  | (0, _, _) -> accu :: results
  | (_, 0, _) -> [] :: results
  | (x, _, _) when x < 0 -> [] :: results
  | (_, _, []) -> [] :: results
  | total, attempts, squares ->
    let filteredSquares = squares |> Seq.filter ((>=) total )
    filteredSquares
      |> Seq.collect(fun sq ->
                          calc (total - sq)
                               (attempts - 1)
                               (filteredSquares |> Seq.toList)
                               (sq :: accu)
                               results) |> Seq.toList

let res =
  calc 8058 4 squares [] []
  |> Seq.filter(fun lst -> lst <> [])
  |> Seq.sortBy (fun lst -> lst.Length)
  |> Seq.take 1
  |> Seq.toList

Additional comments on better F# code would be appreciated as well.
One thing I was wondering was whether I could make it lazy using sequences.


texts: Finding the greatest common factor of a list of numbers in JavaScript

texts:
The goal of this code is to take an array of two or more positive integers and return their greatest common factor, or GCF. (This is the biggest number that can be divided into all the numbers in the array without any remainder).

I feel like my code is much too long and complicated. Surely there's a more efficient way to do this. Also, I know it's best practice to avoid global variables, and I used one here.

Codepen

/* Test whether a number is a factor of another number */
function isFactor(num, fact){
    if(num % fact == 0){
        return true;
    }
    else{
        return false;
    }
}

/* List all the factors of a number */
function listFactors(number){
    factors = [1];
    var i = 2;
    while(i <= number){
        if(isFactor(number, i)){
            factors.unshift(i);
        }
        i++;
    }
    return factors;
}

var toTest = 1;

/* Find the GCF (greatest common factor) of the numbers in an array */
function GCF(intList){
    var GCF = 1;
    var factorsOfEach = [];
    for(item in intList){
        var num = intList[item];
        var factors = listFactors(num);
        factorsOfEach.push(factors);
    }
    var count = 0;
    factorsOfFirst = factorsOfEach[0];
    var length = factorsOfFirst.length;
    while(count < length){
        var toTest = factorsOfFirst[count];
        var passTest = factorsOfEach.every(arrayContains);
        if(passTest){
            GCF = toTest;
            return GCF;
        }
        else{
            count += 1;
        }
    }
    return GCF
}

/* Check whether an array contains the variable "toTest" */
function arrayContains(array){
    if(array.indexOf(toTest) != -1){
        return true}
    else{
    return false}
}


texts:
I have written a simple stack implementation and would like some feedback as to what I could improve in my code and coding practices.

# A simple stack in python with ints.
class stack():
    def __init__(self, maxSize=16):
        self.maxSize = maxSize
        self.data = []

    def isEmpty(self):
        if len(self.data) == 0:
            return True
        else:
            return False

    def isFull(self):
        if len(self.data) == self.maxSize:
            return True
        else:
            return False

    def push(self, data):
        if not self.isFull():
            self.data.append(data)
            return "OK"
        else:
            return "ERR_Stack_Full"

    def pop(self):
        if not self.isEmpty():
            output = self.data[len(self.data) -1]
            del self.data[len(self.data) -1]
            return output, "OK"
        else:
            return "ERR_Stack_Empty"

    def npop(self, n):
        output = []
        if len(self.data) >= n:
            for i in range(n):
                output.append(self.pop()[0])
            return output, "OK"

Based on the input given here is my modified code (Sorry about the entire thing being indented, the code sample button was being difficult):

    class EmptyStackError(Exception):
        def __init__(self):
                super().__init__("Stack is empty: cannot pop from an empty stack!")

    class FullStackError(Exception):
            def __init__(self):
                    super().__init__("Stack is full: cannot push to a full stack!")

    # A simple stack in python with ints.
    class Stack():
        def __init__(self, max_size=16):
            self.max_size = max_size
            self.data = []

        def is_empty(self):
            if len(self.data) == 0:
                return True

        def is_full(self):
            if len(self.data) == self.max_size:
                return True

        def push(self, data):
            if not self.is_full():
                self.data.append(data)
                return data
            else:
                raise FullStackError()

        def pop(self):
            if not self.is_empty():
                output = self.data[len(self.data) -1]
                del self.data[len(self.data) -1]
                return output
            else:
                raise EmptyStackError()


texts: Truncate text to some number of words when clicked

texts:
I am currently using the code below to truncate text:

 function truncate($elem, wordNum){

var words = $elem.find('p').text().trim().split(/\s+/).slice(0,wordNum);
var replacement = $("<p/>").text(words.join(" ") + "...");
$elem.find('.read-more').click(function(){
   if($(this).text() == 'Read More'){
    replacement.hide();
    $elem.find('p:eq(1)').show();
   } else if($(this).text() == 'Read Less'){
       replacement.show();
    $elem.find('p:eq(1)').hide();
   }
    $(this).text(function(i,old){
    return old=='Read More' ?  'Read Less' : 'Read More';
});
return false
});

$elem.find('p:first').before(replacement);
$elem.find('p:eq(1)').hide();
}

truncate($("p"), 5);

Works, but it's not the most efficient solution. Is there a better way ?


texts:
Question

Any way I can optimize this further with C++11 or C++17 features?

Would also like feedback on my variable naming, memory management, edge case handling (in this someone calling my function with an nullptr or int overflow with my rearranged equation to calculate the mid), and coding style. If there are other data structures I can use to implement this instead of basic arrays and raw pointers I'd like some feedback there too.

For my return type on the binary_search function, does it matter if I return a bool versus an int?

Code

#include <cassert>
#include <iostream>

bool binary_search(int* data, int num_elements, int target)
{
    int low = 0;
    int high = num_elements - 1;
    int mid;

    if(data == nullptr) { throw std::exception(); }

    while(low <= high) {
        mid = low + (high - low) / 2;
        if(data[mid] == target) {
            return 1;
        } else if(data[mid] > target) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return 0;
}

int main()
{
    int num_elements = 6;

    int data[] = { 5, 8, 10, 15, 26, 30 };
    int target[] = { 5, 4, 12, 15, 35, 30 };
    int expected[] = { 1, 0, 0, 1, 0, 1 };

    for(int i=0; i < num_elements; ++i) {
        try {
            assert(expected[i] == binary_search(data, num_elements, target[i]));
            std::cout << expected[i] << " returned for search on " << target[i] << '\n';
        } catch(std::exception& e) {
            std::cout << "Exception " << e.what() << '\n';
        }
    }

    return 0;
}


texts: A simple Pygame that has a square move and jump

texts:
How does this Pygame code look? Is the run loop usually in a class? I'm a beginner and was wondering what the best format and structure is for using OOP in Pygame.

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Game")

class Game:

    def __init__(self):
        self.x = 250
        self.y = 250
        self.width = 50
        self.height = 50
        self.vel = 5
        self.isJump = False
        self.jumpCount = 10

    def run(self):
        run = True
        while run:
            pygame.time.delay(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            keys = pygame.key.get_pressed()

            if keys[pygame.K_LEFT] and self.x > 0:
                self.x -= self.vel

            if keys[pygame.K_RIGHT] and self.x < 500 - self.width:
                self.x += self.vel

            if not self.isJump:
                if keys[pygame.K_UP] and self.y > 0:
                    self.y -= self.vel

                if keys[pygame.K_DOWN] and self.y < 500 - self.height:
                    self.y += self.vel

                if keys[pygame.K_SPACE]:
                    self.isJump = True
            else:
                if self.jumpCount >= -10:
                    self.y -= (self.jumpCount * abs(self.jumpCount)) * 0.5
                    self.jumpCount -= 1
                else:
                    self.jumpCount = 10
                    self.isJump = False

            win.fill((0, 0, 0))
            self.draw()

        pygame.quit()

    def draw(self):
        pygame.draw.rect(win, (0, 0, 255), (self.x, self.y, self.width, self.height))
        pygame.display.update()

g = Game()
g.run()


texts:
Seeking to improve upon my high score 'module' code. It saves users' high score in a pickle database and if needed prints out the current scores in the database.

import pickle
import os
global high_scores

def setup_scores():
    global high_scores
    high_scores = {}

    if os.path.isfile('highscores.pkl'):
        with open("highscores.pkl", "rb") as h:
            high_scores = pickle.load(h)
    else:
        high_scores = {"Adam Smith": 65536, "John Doe": 10000}

def save_score(name, score):
    new_score = (name, score)

    if new_score[0] in high_scores:
        if new_score[1] > high_scores[new_score[0]]:
            high_scores[new_score[0]] = new_score[1]
    else:
        high_scores[new_score[0]] = new_score[1]

    with open("highscores.pkl","wb") as out:
        pickle.dump(high_scores, out)

def print_scores():
    for name, score in high_scores.items():
        print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))

setup_scores()
save_score(raw_input('Name:'), raw_input('Score:')) # inputs only for testing, can use variables instead
print_scores()


texts:
I am trying to extend the JSON format (for private use) to include an include statement. This could be used to include other .json files into a master file, for example.

#! /usr/bin/perl

use warnings;
use strict;
use File::Slurp 'read_file';

my $str=parseFile('t.json');

sub parseFile {
  my ($fn)=@_;

  my $str=read_file($fn);
  my $res='';
  my $i=0;
  while (1) {
    if ($str=~/include\s+"(.*?)"/) {
      $res=$res.$`.parseFile("include/$1.json");
      $str=$';
    } else {
      $res=$res.$str;
      last;
    }
  }
  return $res;
}

It seems to be working for some simple test cases. But is it too complicated or is it too simple?


texts:
Given an input text that is a combination of {, }, [, ], (, ) characters, check whether the input text has balanced brackets or not.

This was a question from hackerrank, and the code below solves it in a little bit complicated way while favoring generality.

#include <stack>
#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>

template<typename T>
class balancedBrackets
{
    enum class bracketType { OPENING, CLOSING };
    std::unordered_map<T, bracketType> mBracketIdentifiers;//which bracket symbol is the opening character and which is the closing character
    std::unordered_map<T, T> mBracketPairs;//which bracket symbol matches with which other
public:
    balancedBrackets(){}
    balancedBrackets(std::initializer_list< std::pair<T, T> > pairs)
    {
        addBracketPairs(pairs);
    }

    void addBracketPairs(std::initializer_list< std::pair<T, T> > pairs)
    {
        for (auto elem : pairs)
        {
            if (mBracketIdentifiers.find(elem.first) != mBracketIdentifiers.end() ||
                mBracketIdentifiers.find(elem.second) != mBracketIdentifiers.end())
            {
                continue;//if any member of this bracket pair already exist, skip.
            }
            mBracketPairs.emplace(elem);
            mBracketIdentifiers.emplace(elem.first, bracketType::OPENING);
            mBracketIdentifiers.emplace(elem.second, bracketType::CLOSING);
        }
    }

    void removeBracketPairs(std::initializer_list< std::pair<T, T> > pairs)
    {
        for (auto elem : pairs)
        {
            auto search = mBracketPairs.find(elem.first);
            if (search != mBracketPairs.end() && search->second == elem.second)//is this a valid pair?
            {
                mBracketPairs.erase(search);
                mBracketIdentifiers.erase(elem.first);
                mBracketIdentifiers.erase(elem.second);
            }
        }
    }

    void clearBracketPairs()
    {
        mBracketPairs.clear();
        mBracketIdentifiers.clear();
    }

    bool isBalanced(std::vector<T> expression)
    {
        if (mBracketPairs.empty())//no bracket rules
        {
            throw std::logic_error("no bracket rules");
        }

        std::stack<T> myStack;
        for (auto elem : expression)
        {
            if (mBracketIdentifiers[elem] == bracketType::OPENING)
            {
                myStack.push(elem);
            }
            else
            {
                if (mBracketIdentifiers[elem] == bracketType::CLOSING)
                {
                    if (!myStack.empty() && mBracketPairs[myStack.top()] == elem)//do not call top on an empty stack
                    {
                        myStack.pop();
                    }
                    else //imbalanced text
                    {
                        return false;
                    }
                }
                else //invalid characters
                {
                    return false;
                }
            }
        }
        return myStack.empty();
    }
    bool isBalanced(std::basic_string<T> expression)//make this class work with std::string family too.
    {
        return isBalanced(std::vector<T>(expression.begin(), expression.end()));
    }
};

int main()
{
    balancedBrackets<char> a({ { '{','}' } ,{ '[',']' },{ '(',')' } });
    a.isBalanced(std::string("{{[[(())]]}}"));
    return 0;
}

I have tried to write an idiomatic and generalized version that can easily work with new bracket styles without changing the code. Moreover, a bracket pair is not necessarily be a char in this version.


texts:
Question is quite simple, I am using dingo package, Currently below is my code for an API call.

public function publishApplicant(Request $request,$id){
    $changeStatus = \App\User::where('id', $id)->update(array('admin_published' => 1));

    if($changeStatus){
        return response()->json([
            'message' => 'Applicant published.',
            'code' => 200,
            'status' => 1
        ], 200);
    }

    return response()->json([
        'message' => 'Applicant published.',
        'code' => 500,
        'status' => 0
    ], 200);
}

What can be improved in the above code?


texts:
I'm learning OOP and the first exercise of the course was to made a Stopwatch class. I did it really fast and decided to make an interface for this little app.
I created the interface. Basically I want to know if the aproach that I used is fine, if I needed to create another class to control the ui, etc. I'm really lost with this OOP-UI integration thing.
The app is available in https://nacho-p5.github.io/
Here's the code:
Repo: https://github.com/nacho-p5/nacho-p5.github.io
index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="normalize.css">
    <link href="https://fonts.googleapis.com/css2?family=Lato:wght@100;300;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <title>Online Stopwatch</title>

        0.00

            <button type="submit" id="btnStart" class="btn">Start</button>
            <button type="submit" id="btnStop" class="btn">Stop</button type="submit">
            <button type="submit" id="btnReset" class="btn">Reset</button type="submit">

stopwatch.js
// SW class
function Stopwatch() {
    let counter = 0;
    let intervalID = 0;
    const screen = document.getElementById('sw-screen');

    const addMiliseconds = () => {
        counter += 0.01
        updateScreen();
    };
    const updateScreen = () => {
        screen.innerHTML = counter.toFixed(2);
    }

    // start()
    this.start = function() {
        if (intervalID != 0) {
            throw new Error('Stopwatch has already started.')
        }
        intervalID = setInterval(addMiliseconds, 10);
    };
    // stop()
    this.stop = function() {
        if (intervalID == 0) {
            throw new Error('Stopwatch has already stoped.')
        }
        clearInterval(intervalID);
        intervalID = 0;
    };
    // reset()
    this.reset = () => {
        if (intervalID != 0) {
            this.stop();
        };
        counter = 0;
        updateScreen();
    };
    // duration()
    Object.defineProperty(this, 'duration', {
        get: function() {
            console.log(intervalID);
            return counter
        }
    });
};

// UI class
function UI(arrayOfbuttons) {
    this.toggleClass = function(elem) {
        arrayOfbuttons.forEach(e => e.classList.remove('activeBtn'))
        elem.classList.add('activeBtn');
    };
    this.removeClass = function() {
        arrayOfbuttons.forEach(e => e.classList.remove('activeBtn'))
    };
};

// HTML components
const screen = document.getElementById('sw-screen');
const btnStart = document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');
const btnReset = document.getElementById('btnReset');

// Initialize classes
const sw = new Stopwatch();
const ui = new UI([btnStart, btnStop]);

// Add event listeners
btnStart.addEventListener('click', function() {
    sw.start();
    ui.toggleClass(this);
});
btnStop.addEventListener('click', function() {
    sw.stop();
    ui.toggleClass(this);
});
btnReset.addEventListener('click', function() {
    sw.reset();
    ui.removeClass();
});


texts:
My method getProjectDir() will return an Optional which contains the path to the project directory, or an empty container:

Optional<Path> getProjectDir() { ... }

I have another method, getSrcDir() which depends on getProjectDir():

Optional<Path> getSrcDir() {
    Optional<Path> projectDir = getProjectDir();
    if (projectDir.isPresent()) {
        return Optional.of(projectDir.get().resolve("src"));
    }

    return Optional.empty();
}

Everything works, but I feel the if statement is clunky. Is there any single statement which says "If the project dir exists, append "/src" to it, else return an empty optional. Please let me know if and how it can be done.


texts: Generic util method to convert in single map from list of array of Object generally result of JPQL/ hibernate

texts:
I have designed a generic method to convert list of array of Objects to result into single map.  This is working fine, but I want to check weather a key object is valid key (whether it is overriding equals and hashcode method or immutable instance). Am I missing anything else in my code?

/**
@parms
objects : list of array of object generally result of HQL select
keyIndx : index of key object in the array
valueIndex: index of value object in the array
*/

public static Map<? extends Object, ? extends Object> getSingleMapFromLisOfArrayOfObject(List<? extends Object[]> Objects, int keyIdex, int valueIndex)
        throws Exception
    {
        Map<Object, Object> map = null;
        if (Objects != null) {
            map = new HashMap<Object, Object>(Objects.size());
            for (Object[] array : Objects) {
                if (Math.max(keyIdex, valueIndex) > (array.length - 1)) {
                    throw new IndexOutOfBoundsException(keyIdex + " OR " + valueIndex + " out of bound for array");
                }
                if (array[keyIdex] != null) {
                    map.put(array[keyIdex], array[valueIndex]);
                }
            }
        }
    return (map == null ? Collections.EMPTY_MAP : map);

}


texts:
I have been writing a discord.py bot, running on replit.com. I gotten to the music bot part after finishing the queue part. My code is logically correct; however, the code is way too inefficient causing the bot to crash when someone adds another song to the queue. How can I program my bot to be more efficient? If my code must be completely different, then a short explanation would be appreciated.
The code for play:
@bot.command(name='play', aliases=['sing', 'p'])
async def _play(ctx, url : str):
    queueurls = [] #list with the urls
    vc = ctx.voice_client
    if not vc:
      channel = ctx.author.voice.channel
      await channel.connect()
    url = ctx.message.content
    url = ttourl(url) #the message is processed to an url
    queueurls.append(url) #add the url to the list
    voicec = ctx.voice_client
    if not voicec.is_playing(): #when nothing is going on
      while queueurls != []: #as long as the url list isn't empty I want the process to repeat
        voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
        url = queueurls[0] #url is the first item in the list
        queueurls.pop(0) #now erase the now used first item (url)
        with youtube_dl.YoutubeDL(ytdlopts) as ydl:
          ydl.download([url]) #download the song
        voice.play(discord.FFmpegPCMAudio("songstemp/song.mp3")) #play the song
        vcs = ctx.voice_client
        while vcs.is_playing: #wait for the song to be over
          continue
        if os.path.exists("songstemp/song.mp3"):
          path = "songstemp/song.mp3"
          os.remove(path)
    else: #if the bot is already playing, then don't disturb the loops above
      pass


texts: Find minimum window size which includes the subset of characters

texts:
Given a set T of characters and a string S, find the minimum window in S which will contain all the characters in T in complexity O(n).

eg,
S = “ADOBECODEBANC”
T = “ABC”

Minimum window size is 4 - “BANC”.

public final class MinSubstringWindow {

    private MinSubstringWindow() {}

    private static void addCharCount(Map<Character, Integer> map, Character ch) {
        if (!map.containsKey(ch)) {
            map.put(ch, 1);
        } else {
            int val = map.get(ch);
            map.put(ch, val + 1);
        }
    }

    private static Map<Character, Integer> toFindMap(String subset) {
        Map<Character, Integer> toFind  = new HashMap<Character, Integer>();
        for (char ch : subset.toCharArray()) {
            addCharCount(toFind, ch);
        }
        return toFind;
    }

    public static int mindWindowSize(String str, String subset) {
        final Map<Character, Integer> toFind = toFindMap(subset);
        final Map<Character, Integer> hasFound  = new HashMap<Character, Integer>();

        char[] ch  = str.toCharArray();

        int matchCtr = 0;
        boolean matchFound = false;
        char currLeftMostChar = 0;

        int j = 0; // the trailing position of the sliding window
        int i = 0; // the leading position of the sliding window.

        int min = Integer.MAX_VALUE;

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

            if (!toFind.containsKey(ch[i])) continue;

            if (!matchFound) {
                currLeftMostChar = ch[i];
                matchFound = true;
                j = i;
            }

            addCharCount(hasFound, ch[i]);

            matchCtr++;

            // check if match has been completed.
            if (matchCtr >= subset.length()) {
                if ((i - j + 1) < min) {
                    min = i - j + 1;
                }
            }

            // does the first element exceed value ?
            if (hasFound.get(currLeftMostChar) > toFind.get(currLeftMostChar)) {
                // advance the left pointer, such the window (i-j) is as small as possible.
                while (!toFind.containsKey(ch[j]) || hasFound.get(ch[j]) > toFind.get(ch[j])) {
                    if (hasFound.containsKey(ch[j])) {
                        int val = hasFound.get(ch[j]);
                        hasFound.put(ch[j], val - 1);
                    }
                    j++;
                }
                currLeftMostChar = ch[j];
            }
        }

        if (matchCtr < subset.length()) {
            throw new IllegalArgumentException("The subset is not found in the input string.");
        }

        // note: here we dont do (i-j+1) since i has been incremented additionally in a for loop.
        return min > (i - j) ? i - j : min;
    }
}

And test section

public class MinSubstringWindowTest {

    @Test
    public void test1() {
        assertEquals(3, MinSubstringWindow.mindWindowSize("apbqcbsa", "ab"));
        assertEquals(4, MinSubstringWindow.mindWindowSize("apbqcbsa", "abc"));
        assertEquals(3, MinSubstringWindow.mindWindowSize("apbqcbsa", "pq"));
    }

    @Test
    public void test2() {
        assertEquals(2, MinSubstringWindow.mindWindowSize("ameya", "ay"));
        assertEquals(3, MinSubstringWindow.mindWindowSize("ameya", "my"));
        assertEquals(3, MinSubstringWindow.mindWindowSize("ameya", "ae"));
    }

}


texts: Overloading Java function (insert into binary tree)

texts:
I have a binary tree below and it seems to make sense to overload the insert() method. If insert() is called without a Node specified, it will just work with head, otherwise if it receives a Node, it will do the insert in the subtree starting with that Node. This second variant is then called recursively, see below.

The repetition that happens in the code below seems wrong to me (not DRY). Is there a better way to do this or is this a limitation in Java?

public class probBinaryTree {
    public Node head;

    public probBinaryTree() {
        this.head = null;
    }

    private class Node {
        int data;
        Node left;
        Node right;
        int size;

        public Node(int d) {
            this.data = d;
            this.left = null;
            this.right = null;
            this.size = 1;
        }
    }

    public Node insert(int d) {
        if (head == null) {
            head = new Node(d);
            return head;
        }
        head.size++;
        if (head.left == null) return insert(head.left, d);
        if (head.right == null) return insert(head.right, d);
        if (head.left.size <= head.right.size) return insert(head.left, d);
        if (head.left.size > head.right.size) return insert(head.right, d);
        return null;
    }

    private Node insert(Node n, int d) {
        if (n == null) {
            n = new Node(d);
            return n;
        }
        n.size++;
        if (n.left == null) return insert(n.left, d);
        if (n.right == null) return insert(n.right, d);
        if (n.left.size <= n.right.size) return insert(n.left, d);
        if (n.left.size > n.right.size) return insert(n.right, d);
        return null;
    }
}


texts: Handling exceptions from async call in synchronous caller

texts:
I am using this pattern to easily handle exceptions from async code in a non-async caller. Is this a reasonable thing to do, or am I missing something? In this relatively simply case, I have a function called "SendCommand" that does nothing more than call ProcessCommand, which is an async function. I'm doing this because SendCommand is exported in a Xamarin Android project so that it can be called from my Main.axml layout file (via a reference from onClick), which, as far as I can tell, cannot call async functions.

[Java.Interop.Export("SendCommand")]
public void SendCommand(View view)
{
   try
   {
      ProcessCommand().ContinueWith((t) =>
      {
         try
         {
            t.Wait();
         }
         catch (Exception ex)
         {
            ShowMessage(ex.Message);
         }
      });
   }
   catch(Exception ex)
   {
      ShowMessage(ex.Message);
   }
}

The odd thing about this is that I'm calling wait on a task I already know is complete just to throw any exceptions that may need yet to be handled (converted into proper exceptions in this stack).


texts:
I just finished the Pluralsight courses about Inversion of Control and Mirco-ORMs, and I am struggling with the implementation aspect of some of the concepts.

This is my (simplified) repository implementation using Dapper:

public class AppRepository : IAppRepository
{

    public string TableName { get; } = "apps";
    private IDbConnection _db;

    public AppRepository(IDbConnection db = null)
    {
        if (db == null)
            _db = Bootstrap.container.Resolve<IDbConnection>(); // Default: connection from the simple injector container
        else
            _db = db;
    }

    public List<App> GetAll() => _db.Query<App>(QueryBuilder.BuildGetAll(TableName)).ToList();

}

QueryBuilder is a static class, shared among all repositories, which creates the different sql strings.

The Bootstrap class exposes a UnityContainer:

public static class Bootstrap
{
    public static UnityContainer container;

    private static IDbConnection _db;
    public static void Start(string connectionStringId)
    {
        container = new UnityContainer();

        _db = GetDbConnection(connectionStringId);

        // Register your types:
        container.RegisterInstance<IDbConnection>(_db);
    }

    public static IDbConnection GetDbConnection(string connectionStringId)
    {
        var connectionString = ConfigurationManager.ConnectionStrings[connectionStringId].ConnectionString;
        IDbConnection db = new MySqlConnection(connectionString);
        return db;
    }
}

Then I read a post about NOT to use this kind of pattern:

  by far the most common IoC mistake is to wrap up the container in a public static or singleton class that is referenced throughout the code base. It is important to realize that this is not dependency injection, it is service location which is widely regarded as an anti-pattern. I cannot over-emphasize how important it is to move away from this design and to inject your dependencies from the root of your application. In fact, virtually all other IoC mistakes come about as a direct result of this misunderstanding.

I've used IDbConnection db = null because 99% of the time I will be using a single thread with a single connection, but the other 1% I will be transfering data from one server to another.

I have ~60 models (60 tables), so constantly injecting the IDbConnection connection seems like a hassle, specially if further down the path I have to change it somehow. At the same time, Unity is doing nothing useful at this point in time. I could just let the connection be a public property of the static Bootstrap class. I've read some opinions about injectors being more more annoying than helpful.

For the moment I am building a console application, and in the Main function there is a Bootstrap.Start() that lets me forget about IDbConnection for the rest of the code.

I've been trying to find some examples with good patters using Dapper + dependency injection, but I haven't found anything yet that clarifies my doubts.


texts: AdventOfCode Day 1 : find X element matching a criteria in haskell

texts:
This problem is from https://adventofcode.com/2020/ day 1.
I need to find the N entries of inputs that sum to 2020 and then multiply those N numbers together.
inputs = [1721, 979, 366, 299, 675, 1456]

I have 2 cases N = 2 and N = 3
I have done this with list comprehension
N = 2 :
main = print $ head [ i * j |
                      i <- inputs ,
                      j <- inputs ,
                      i+j == 2020]

N = 3 :
main = print $ head [ i * j * k  |
                      i <- inputs ,
                      j <- inputs ,
                      k <- inputs ,
                      i+j+k == 2020]

But it scales badly, if y need N = 100 that's a lot of <-.
So I have done this :
solution n =  foldl1 (*) $ head [ x | x <- sequence $ replicate n inputs , (foldl1 (+) x == 2020 )]

main = print $ solution 3

I wonder if there is a more idiomatic way to do this and if there is a way of using list comprehension with N variables ?
Note : I know that with these solutions, the same entries can be used multiple times, and I am ok with it.


texts: Implementing hash table in Python using Tuples

texts:
I am trying to implement a basic hash table using a list of tuples. The code produce the desired output. Please help me improve my code as I feel there are a lot of while loops.
#global variables to keep track of the hash table
count = 0
size = 1000

def hash_table(size):
    return [None] * size

def hash_item(key, value):
    return (key,value)

def hash_func(key):         #simple hash function
    index = hash(key) % 1000
    return index

def insert_hash(table,key,value):
    index = hash_func(key)
    item = hash_item(key,value)
    global count
    global size
    if count == size:
        raise Exception("Hash table limit reached")
    if table[index] == None:
        table[index] = item
    else:
        collision_handler(table, index, item)
    count = count + 1

def print_hash(table,key):
    index = hash_func(key)
    while table[index][0] != key:      #in case there is a collision:
        index = index + 1
    print(table[index])

def delete_hash(table,key):
    index = hash_func(key)
    while table[index][0] != key:
        index = index + 1
    table.pop(index)

def collision_handler(table,index,item):         #handling collisions using open addressing
        while table[index] != None:
            index = index + 1
        table[index] = item

a = hash_table(size)

b = hash_func('1')

insert_hash(a, '1','john')

print_hash(a,'1')

delete_hash(a,'1')

insert_hash(a,'1','edward')

print_hash(a,'1')


texts:
I'm trying to re-implement the C stdlib function qsort using a median of 3 quicksort.

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

This is my first major project in C, and I'd like to know how my style looks and what techniques I might be missing out on. Thanks for the help.

In sort.h, I have

/* returns > 0 if arg1 is greater than arg2, 0 if equal, < 0 if less*/
typedef int (*compare_func)(void *, void *);
/*Median of 3 quicksort Function*/
void quick_sort(void * arr, size_t nitems, size_t size,  compare_func compare);

And in quick_sort.c I have

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

void swap_mem(void * ptr1, void * ptr2, size_t size){
    /*
     * Swaps the values at the addresses pointed at by ptr1 and ptr2
     */
    void * tmp = malloc(size);
    memcpy(tmp, ptr1, size);
    memcpy(ptr1, ptr2, size);
    memcpy(ptr2, tmp, size);
    free(tmp);
}

void median_of_3(void * arr, size_t start, size_t stop, size_t size, compare_func compare){
    /*
     * Performs median of 3 partitioning on an array starting at start and ending
     * at stop
     */
    int mid;

    /*determine midpoint of array to nearest integer multiple of size*/
    mid = ((start + stop)>>1)/size * size;

    /*sort the 3 item array by comparing middle value to first and last value*/
    if(compare(arr + stop, arr + start) < 0)
        swap_mem(arr + stop, arr + start, size);
    if(compare(arr + mid, arr + start) < 0)
        swap_mem(arr + mid, arr + start, size);
    if(compare(arr + stop, arr + mid) < 0)
        swap_mem(arr + stop, arr + mid, size);

    /*swap the second to last value of arr with the median value*/
    swap_mem(arr + mid, arr + stop - size, size);
}

void quick_sort_aux(void * arr, size_t start, size_t stop, size_t size, compare_func compare){
    /*
     * Recursive median-of-3 quick sort
     */

    /*Base Case 1: 1 item in array (already sorted)*/
    if(start >= stop) return;

    /*Base Case 2: sort 2 or 3 item array*/
    median_of_3(arr, start, stop, size, compare);

    if(stop - start <=2*size) return;

    /*Recursively sort larger arrays*/
    int l_ptr = start;
    int r_ptr = stop - 2*size;

    /*move all values to the proper side of the pivot*/
    while(l_ptr <= r_ptr){
        while(compare(arr + l_ptr, arr + stop - size) < 0 && l_ptr <= r_ptr)
            l_ptr+=size;
        while(compare(arr + r_ptr, arr + stop - size) >= 0 && l_ptr <= r_ptr)
            r_ptr-= size;
        if(l_ptr <= r_ptr)
            swap_mem(arr + l_ptr, arr + r_ptr,size);
    }
    /*swap the pivot back into place*/
    swap_mem(arr + l_ptr, arr + stop - size,size);

    /*recursively sort the two halves*/
    quick_sort_aux(arr, start, l_ptr - size, size, compare);
    quick_sort_aux(arr, l_ptr + size, stop, size, compare);
}

void quick_sort(void * arr, size_t nitems, size_t size,  compare_func compare){
    /*
     * wrapper for recursive quick_sort_aux
     */
    quick_sort_aux(arr, 0, size*(nitems-1), size, compare);
}

This is my first time posting to StackExchange. Let me know how I can improve my question.


texts: Module for converting between three currencies

texts:
I am creating a simple currency converter, which accepts only 3 currencies. Everything is working fine, just my code doesn't look so good.

I tried to wrap it revealing module pattern, and still looks poor. So my question is should I use if/else statements inside fetch, or should I, maybe, rewrite the code, using ES6 classes and OOP? Please review and suggest.

var request = new Request('test.json', {
    method: 'GET',
    mode: 'cors',
    redirect: 'follow',
    headers: new Headers({
        'Content-Type': 'application/json'
    })
});

//initate app
 function calculateCurrency() {
    let currVal  = Number(placeholderCurrency.value),
        firstValue = getSelected(selectCurrency).value,
        secondValue = getSelected(currentCurrency).value;

    //fetch data from api
     fetch(request).then(resp=> resp.json())
        .then((data) => {
            const mainObj = data.result;
            const eur = mainObj['eur'].pro;
            const usd = mainObj['usd'].pro;
            const rsd = 1;

            function calculusBiger(cur1,cur2,val1,val2) {
                if(firstValue == cur1 && secondValue == cur2) {
                        calculatedCurrency.value = currVal*(val1*val2);
                    }
            }

            function calculusSmaller(cur1,cur2,val1,val2) {
                if(firstValue == cur1 && secondValue == cur2) {
                    calculatedCurrency.value = currVal*(val1/val2);
                }
            }

            calculusSmaller("eur","usd",eur,usd);
            calculusBiger("eur","rsd",eur,rsd);
            calculusBiger("usd","rsd",usd,rsd);
            calculusSmaller("usd","eur",usd,eur);
            calculusSmaller("rsd","eur",rsd,eur);
            calculusSmaller("rsd","usd",rsd,usd);

            return (function() {
            return   {
            first:firstValue,
            second:secondValue,
            val:currVal
            }
        }());

        })
        .catch((err) =>{
            console.log(err);
        })
}

    //get option selected
    function getSelected(elem) {
            let opts = elem.children;
            for(i=0; i < opts.length; i++) {
            if(opts[i].selected) {
                 return opts[i];
            }

        }
    }


texts:
I've just started working with SQLite in C# to test various features of an application. In building my first SQLite example I wanted to insert a large .csv into a table (Person) with two columns, A and B. The .csv file is 50MB in size and contains multiple rows of the same data ("abc, def").

I wrote the following code, but I think this is fairly inefficient and am looking for advice on a better method(s) to optimize this code to read the file and finally insert it into SQLite.

Regex splitRx = new Regex(@",\s*", RegexOptions.Compiled);
ArrayList al = new ArrayList();

using (StreamReader sr = new StreamReader(@"c:\Temp\test.csv"))
{
    string line = null;
    int ln = 0;
    while ((line = sr.ReadLine()) != null)
    {
        string[] fields = splitRx.Split(line);
        if (fields.Length != 2)
        {
            Console.WriteLine("Invalid Input on line:" + ln);
            continue;
        }
        ln++;
        al.Add(fields);
    }
}

using (var conn = new SQLiteConnection(@"Data Source=C:\Temp\test.sqlite"))
{
    conn.Open();

    using (var cmd = new SQLiteCommand(conn))
    {
        using (var transaction = conn.BeginTransaction())
        {
            foreach (string[] sa in al)
            {
                cmd.CommandText =
                    "INSERT INTO Person (FirstName, LastName) VALUES ('" + sa[0] + "', '" + sa[1] + "');";
                cmd.ExecuteNonQuery();
            }

            transaction.Commit();
        }
    }

    conn.Close();
}


texts: Working with abstract classes and multiply servers with TX and RX interchange

texts:
I have different servers (TCP, Named Pipe, RS232, ...) in one program and I want that all the received data coming from one server are send to all the other servers (resp. clients of these servers)

To do this I created an abstract class with an AutoResetEvent onNewDataRX wich is set if new data received and then in the main method I register a callback method which gets called when onNewDataRX is set. Furthermore I created an TxRx class so the callback methods only needs to know where the data is from and where to write the data to without the need of knowing if its the tcp class or the pipe class.

using System;
using System.Threading;

public abstract class SensaJoint
{

    public AutoResetEvent onNewDataRX;  //Reset event for new data received
    public char[] RxBuffer { get; protected set; }//recive buffer
    public int RxLen { get; protected set; }//recived length
    const int BufferSize = 257;
    public SensaJoint()
    //[...]
    {
        onNewDataRX = new AutoResetEvent(false);
        //RxBuffer = new char[BufferSize]; ;
        RxLen = 0;
        //[...]
    }
    //write to all clients connected to the server

    public void Start()
    {
        new Thread(SendTest).Start();
    }
    public abstract void SendTest();
    public abstract void WriteToAll(char[] Bytes, int Length);

}

public class TxRx
{
    public SensaJoint TX;//TX Class, later this should be an array so there could be more then one TX
    public SensaJoint RX;//RX Class
}

class Program
{
    static void Main(string[] args)
    {

        TcpServer TCP = new TcpServer();//TCPServer (abstract SensaJoint Class)
        PipeServer PS = new PipeServer();//Named Pipe Server (abstract SensaJoint Class)
        //Set up TX/RX
        TxRx[] txrx = new TxRx[2];
        txrx[0] = new TxRx();
        txrx[1] = new TxRx();
        txrx[0].RX = TCP;
        txrx[0].TX = PS;
        txrx[1].RX = PS;
        txrx[1].TX = TCP;

        //Register async OnNewRX function

        //Question: Is "new WaitOrTimerCallback(OnNewRX)" needed or am I allowed to just write the method as below? It works both ways
        //~ ThreadPool.RegisterWaitForSingleObject(TCP.onNewDataRX, new WaitOrTimerCallback(OnNewRX), txrx[0], -1, false);

        ThreadPool.RegisterWaitForSingleObject(TCP.onNewDataRX, OnNewRX, txrx[0], -1, false);
        ThreadPool.RegisterWaitForSingleObject(PS.onNewDataRX, OnNewRX, txrx[1], -1, false);

        TCP.Start();
        PS.Start();

        //Wait till the sun burns us all
        while (true)
            Thread.Sleep(500);
    }
    private static void OnNewRX(object o, bool timedOut)
    {
        TxRx txrx = (TxRx)o;//The object is a TxRx class object
        //Write to all TX Clients the data recived from the RX
        txrx.TX.WriteToAll(txrx.RX.RxBuffer, txrx.RX.RxLen);
    }
}

//Please don't review after this line, it's just a quick'n'dirty implementation

class TcpServer : SensaJoint
{
    public override void SendTest()
    {
        RxBuffer = "Hello from TCP".ToCharArray();
        RxLen = RxBuffer.Length;
        while (true)
        {
            onNewDataRX.Set();
            Thread.Sleep(1500);
        }
    }
    public override void WriteToAll(char[] Bytes, int Length)
    {
        Console.WriteLine("-Write on TCP " + Length + " bytes: " + new String(Bytes));
        //do the write things
    }
}
class PipeServer : SensaJoint
{
    public override void SendTest()
    {
        RxBuffer = "Hello from Pipe".ToCharArray();
        RxLen = RxBuffer.Length;
        while (true)
        {

            onNewDataRX.Set();
            Thread.Sleep(1300);
        }
    }
    public override void WriteToAll(char[] Bytes, int Length)
    {
        Console.WriteLine("+Write on Pipe " + Length + " bytes: " + new String(Bytes));
        //do the write things
    }
}


texts:
A schoolmate is going through the interview process, and was given the question of detecting if a linked list data structure has an infinite loop in it. I wrote this example, and wanted to see what experience programmers thought of it.

/*
* detecting loops in a linked list, java
*
* This linked list doesn't have a payload, but that is irrelevant to
* this problem, although might be useful for debugging.
*
*/

import java.util.*;

class Node
{
  Node n = null;
  Node()
  {
  }
  Node(Node n)
  {
    setNext(n);
  }
  void setNext(Node n)
  {
    this.n = n;
  }
  boolean hasNext()
  {
    return n!=null;
  }
  Node next()
  {
    return n;
  }
  boolean isLoopy(Set<Node> visited)
  {
    if(visited.contains(this))
    {
      return true;
    }else
    {
      if(hasNext())
      {
        visited.add(this);
        return next().isLoopy(visited);
      }else
      {
        return false;
      }
    }
  }
  boolean isLoopy()
  {
    return isLoopy(new HashSet<Node>());
  }
  // test harness
  public static void main(String[] args)
  {
    Node n1 = new Node();
    Node n2 = new Node(n1);
    n1.setNext(n2);

    System.out.println("loopy list is loopy:");
    System.out.println(n1.isLoopy());

    Node n4 = new Node();
    Node n3 = new Node(n4);

    System.out.println("non loopy list is loopy:");
    System.out.println(n3.isLoopy());
  }
}


texts: Calculate work progress in percentage of batches that contain tasks and task contain sub tasks

texts:
I am trying to calculate work progress in percentage.  I have multiple batches, and each batch contains a set of tasks and each task also contains a set of sub tasks.  Below code is the best I could do.  Is there any more efficient way to do this?

I just edited the code using the Math static method to do help with rounding and getting the next up value.

    double numOfBatches = 3;
    double weightOfEachBatch = (1*100)/numOfBatches;

    double numOfTasksInEachBatch = 1;
    double weightOfEachTask =
        (1*weightOfEachBatch)/numOfTasksInEachBatch;

    double numOfSubTasksInEachTask = 2;
    double weightOfEachSubTask =
        (1*weightOfEachTask)/numOfSubTasksInEachTask;

    System.out.println("Weight of each batch: " + weightOfEachBatch + "%");
    System.out.println("Weight of each task: " + weightOfEachTask + "%");
    System.out.println("Weight of each sub task: " + weightOfEachSubTask + "%");

    double fromBatchWeight = 0;
    for(int i = 1; i <= numOfBatches; i++) {

        double toBatchWeight = weightOfEachBatch * i;
        System.out.println(
                "Batch " + i +
                " from " + Math.floor(fromBatchWeight) +
                "% to " + Math.floor(toBatchWeight) + "%");

        double fromTaskWeight = fromBatchWeight;
        for(int j = 1; j <= numOfTasksInEachBatch; j++) {

            double toTaskWeight = (weightOfEachTask * j) + fromBatchWeight;
            System.out.println(
                    "\tTask " + j +
                    " from " + Math.floor(fromTaskWeight) +
                    "% to " + Math.floor(toTaskWeight) + "%");

            double fromSubTaskWeight = fromTaskWeight;
            for(int k = 1; k <= numOfSubTasksInEachTask; k++) {

                double toSubTaskWeight = (weightOfEachSubTask * k) + fromTaskWeight;
                System.out.println(
                        "\t\tSub Task " + k +
                        " from " + Math.floor(fromSubTaskWeight) +
                        "% to " + Math.floor(toSubTaskWeight) + "%");

                fromSubTaskWeight = Math.nextUp(toSubTaskWeight);
            }

            fromTaskWeight = Math.nextUp(toTaskWeight);
        }

        fromBatchWeight = Math.nextUp(toBatchWeight);
    }

The output looks like this

Weight of each batch: 33.333333333333336%
Weight of each task: 33.333333333333336%
Weight of each sub task: 16.666666666666668%
Batch 1 from 0.0% to 33.0%
    Task 1 from 0.0% to 33.0%
        Sub Task 1 from 0.0% to 16.0%
        Sub Task 2 from 16.0% to 33.0%
Batch 2 from 33.0% to 66.0%
    Task 1 from 33.0% to 66.0%
        Sub Task 1 from 33.0% to 50.0%
        Sub Task 2 from 50.0% to 66.0%
Batch 3 from 66.0% to 100.0%
    Task 1 from 66.0% to 100.0%
        Sub Task 1 from 66.0% to 83.0%
        Sub Task 2 from 83.0% to 100.0%


texts:
I got bored and decided to write my own function to verify if a string contains another string.

I was wondering if there's any major difference between these two function except the one I wrote being more complicated.

bool Contains(string str, string find){
    for (int i = 0; i < str.length() - (find.length()-1); i++){
        if (find.length() > 0){
            int CharactersFound = 0;
            for (int x = 0; x < find.length(); x++){
                if (str[i + x] == find[x]){
                    CharactersFound++;
                }
                else {
                    CharactersFound = 0;
                }
            }
            if (CharactersFound == find.length()) return true;
        } else {
            return true;
        }
    }
    return false;
}
bool StrContains(string str, string find){
    if (str.find(find) != string::npos) return true;
    return false;
}


texts:
if (isset($_POST['submit'])) {
    if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {
        $errors = array();
        $error = 0;

        if (!preg_match('/^[A-Za-z](?=[A-Za-z0-9_.]{3,20}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/i', $_POST['username'])) {
            $errors[] = 'Your username must start with a letter (A-Z) and be between 3-20 characters and may only contain alphanumeric characters (A-Z, 0-9 _ ) or a period (1) (".")';
            $error = 1;
        }

        $STH = $DBH->prepare("SELECT username FROM users WHERE username = ?");
        $STH->execute(array($_POST['username']));

        if ($STH->rowCount() > 0) {
            $errors[] = 'The username is already taken!';
            $error = 1;
        }

        if (strlen($_POST['password']) < 3) {
            $errors[] = 'Your password must be longer than 3 characters!';
            $error = 1;
        } else if ($_POST['password'] != $_POST['passconf']) {
            $errors[] = 'You didn\'t verify your password correctly!';
            $error = 1;
        }

        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
           $errors[] = 'The e-mail is not valid!';
           $error = 1;
        } else {
            $STH = $DBH->prepare("SELECT email FROM users WHERE email = ?");
            $STH->execute(array($_POST['email']));

            if ($STH->rowCount() > 0) {
                $errors[] = 'The email is already taken!';
                $error = 1;
            }
        }
    }
}

This is my current validation for a registration page it works, but I'd like to improve it, give me some tips


texts:
I rewrote some code I posted earlier this month. It attempts to mimic C#'s nameof() by extracting names from bytecode instructions.

This seems more reliable than looking into the previous frame's locals and asserting that there is an id match between some value in the current scope. However, I'm unsure just how much because it uses dis:

  Use of this module should not be considered to work across Python VMs
  or Python releases.

I tried reducing the amount of bad input possible, but there is a quirky case where if I pass the function name_of((Cls.member(), var)) it returns 'member', if I remove the parentheses it will raise a SyntaxError because it no longer mistakes them for the end of the function call, and attribute access has been broken, so what the hell does it make of var.

import dis as _dis
from itertools import dropwhile as _dropwhile, takewhile as _takewhile

__all__ = ['name_of']

_LOAD = (
    'LOAD_CONST',
    'LOAD_NAME',
    'LOAD_ATTR',
    'LOAD_GLOBAL',
    'LOAD_FAST',
    'LOAD_CLOSURE',
    'LOAD_DEREF',
    'LOAD_CLASSDEREF'
)

class _Scopes:
    known = {}

def _dis_f(frame):
    return iter(_dis.Bytecode(frame.f_code))

def _known():
    def scope():
        return scope.cached[scope.no]

    scope.cached = []
    scope.no = 0
    return scope

def _not_eq(instruction):
    return instruction.argrepr != 'name_of'

def _in_load(instruction):
    return instruction.opname in _LOAD

def _invalidate(name):
    _Scopes.known.clear()
    raise SyntaxError('Invalid: {!r}'.format(name))

def _is_ident(name):
    if not name.isidentifier():
        _invalidate(name)

def _eq(instruction):
    return instruction.opname == _LOAD[2]

def _all_attr(instructions, name):
    if instructions[:-1] and not all(
            _eq(instruction) for instruction in instructions[1:]
    ):
        _invalidate(name)

def _cache(bytecode, scope):
    while True:
        instructions = _dropwhile(_not_eq, bytecode)
        if next(instructions, None) is None:
            break
        instructions = list(_takewhile(_in_load, instructions))
        name = instructions[-1].argrepr
        _is_ident(name)
        _all_attr(instructions, name)
        scope.cached.append(name)

def _pos(frame_id, scope):
    scope.no += 1
    if scope.no == len(scope.cached):
        del _Scopes.known[frame_id]

def name_of(_):
    try:
        raise NameError
    except Exception as exc:
        frame = exc.__traceback__.tb_frame.f_back
    frame_id = id(frame)
    if frame_id not in _Scopes.known:
        bytecode = _dis_f(frame)
        scope = _Scopes.known[frame_id] = _known()
        _cache(bytecode, scope)
    else:
        scope = _Scopes.known[frame_id]
    name = scope()
    _pos(frame_id, scope)
    return name

Overall it seems to work as intended, in both 3.4.4 and 3.6.3.


texts:
A few days ago, I posted my version of a wildcard search algorithm, which you can see here: Wildcard search in C

Today I'm showing version 2. I didn't want to make it in the same post because the code is quite different.

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

#define MULTICHAR '*'
#define ONECHAR '?'
#define null NULL

bool wildcard(const char *value, char *wcard) {

  int vsize = (int)strlen(value);
  int wsize = (int)strlen(wcard);
  bool match = false;

  if (vsize == 0 && wsize == 0) {
  match = true;
  }

  else {
  int v = 0;
  int w = 0;
  int lookAhead = 0;
  bool searchMode = false;
  char search = '\0';

  while (true) {
      if (wcard[w] == MULTICHAR) {
      //starts with * and the value matches the wcard
      if (w == 0 && strcmp(wcard+1,value) == 0) {
          match = true;
          break;
      }
      //the * is the last character in the pattern
      if (!wcard[w+1]) {
          match = true;
          break;
      }
      else {
          //search for the next char in the pattern that is not a ?
          while (wcard[++w] == ONECHAR) {
          lookAhead++;
          }

          //if the next char in the pattern is another * we go to the start (in case we have a pattern like **a, stupid I know, but it might happen)
          if (wcard[w] == MULTICHAR) {
          continue;
          }

          search = wcard[w];
          searchMode = true;
      }
      }

      else {
      if (!value[v] && !wcard[w]) {
          if (searchMode) {
          match = false;
          }
          break;
      }
      if (searchMode) {
          char currentValue = value[v+lookAhead];
          if (currentValue == search) {
          match = true;

          searchMode = false;
          search = '\0';
          lookAhead = 0;
          w++;
          }

          else if (currentValue == '\0') {
          match = false;
          break;
          }

          v++;
          continue;
      }
      else if ((wcard[w] == ONECHAR && value[v] == '\0') || (wcard[w] != value[v] && wcard[w] != ONECHAR)) {
          match = false;
          break;
      }
      else {
          match = true;
      }

      w++;
      v++;
      }
  }
  }

  return match;
}

I think there is still room for improvements, so any advice, tips or critiques are all welcome.

You can find the tests I ran here.

The project can be viewed here.

To compile, just do make wildcard.


texts: Absolute-difference function for std::size_t

texts:
Because std doesn't provide an overloaded version of std::abs for std::size_t, I built a version to calculate distance between unsigned numbers.

It subtracts the smaller one from the larger one, to prevent a negative result, since in unsigned integer it would wrap around.

std::size_t size_type_abs(std::size_t a, std::size_t b)
{
    return std::max(a, b) - std::min(a, b);
}

Is this implementation correct and efficient?


texts:
I've implemented a simple C++ STL like queue. (I've tried to follow @LokiAstari stack implementation code fashion)

#ifndef QUEUE_H
#define QUEUE_H

#include <iostream>
#include <stdexcept>

using std::cout;

template <typename T>
class queue {
public:
    struct node {
        T data;
        node *next;

        node()
            : data(0)
            , next(nullptr) {
        }

        node(T const& data, node* next)
            : data(data)
            , next(next) {
        }

        node(T&& data, node* next)
            : data(std::move(data))
            , next(next) {
        }
    };
    ~queue();
    bool empty() const;
    size_t size() const;
    T front() const;
    void push(T const& data);
    void push(T&& data);
    //void emplace (T&&... args);
    // void swap (queue& x);
    void pop();

private:
    size_t elements = 0;
    node *head = nullptr;
    node *tail = nullptr;
};

template <typename T>
queue<T>::~queue() {
    node *curr = new node();
    while(head) {
        curr = head;
        head = head->next;
        delete curr;
    }
    delete tail;
}

template <typename T>
bool queue<T>::empty() const {
    return elements == 0;
//    return head == nullptr;
}

template <typename T>
size_t queue<T>::size() const {
    return elements;
}

template <typename T>
T queue<T>::front() const {
    if(elements == 0)
        throw std::runtime_error("Invalid Action");
    return head->data;
}

template <typename T>
void  queue<T>::push(T const& data) {
    node *newNode = new node(data, nullptr);
    if(!elements) head = newNode;
    else tail->next = newNode;
    tail = newNode;
    ++elements;
}
template <typename T>
void  queue<T>::push(T&& data) {
    node *newNode = new node(std::move(data), nullptr);
    if(!elements) head = newNode;
    else tail->next = newNode;
    tail = newNode;
    ++elements;
}
template <typename T>
void  queue<T>::pop() {
    if(elements == 0)
        throw std::runtime_error("Invalid Action");
    node *tmp = new node();
    if(elements != 0) tmp = head;
    head = head->next;
    --elements;
    delete tmp;
}

#endif // QUEUE_H

I would appreciate all criticism relevant to code, style, flow, camelCase vs underscore, and so forth.


texts:
This is a Tic Tac Toe game in Java in preparation for my seconds personal project (chess game). I'm having a little problem though and am thinking that my for loop to create those buttons is a mistake. I believe I should instantiate all 9 JButtons implicitly instead of using a for loop because then I know for sure I will be able to compare each and every button. What are your thoughts?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by Usman on 5/17/2016.
 */
public class TicTacToeGUI extends JPanel {

    boolean turn = true;

    public TicTacToeGUI() {
        setLayout(new GridLayout(3,3));

        for(int i=0 ; i<9 ; i++) {
            JButton btn = new JButton("");
            btn.setPreferredSize(new Dimension(70,60));
            btn.setFont(new Font("Arial", Font.PLAIN, 40));
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if(btn.isEnabled()){
                        if(turn){
                            btn.setText("X");
                            turn = !turn;
                        }
                        else{
                            btn.setText("O");
                            turn = true;
                        }
                        btn.setEnabled(false);
                    }
                }
            });
            add(btn);
        }
    }

    public static void main(String []args){
        TicTacToeGUI game = new TicTacToeGUI();
        JFrame frame = new JFrame("Tic Tac Toe");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(game);
        frame.pack();
        frame.setVisible(true);
    }
}


texts: Predicate class implementation in TypeScript

texts:
I am have created a predicate builder that takes predicates (functions with a single input and produce a boolean) and can chain them using boolean logic, so AND, OR and NOT. It is inspired by the Java Predicate class. This is mostly to practice my TypeScript, so general feedback is of course appreciated. However, I am interested in few points:

Naming. I don't like the Builder suffix here as it doesn't seem to fit. Although, I cannot exactly explain why it feels wrong. Partly, I'm used to builders producing an object as a result, not to be containers for the logic that will be later applied. This seems more of a Functor. Furthermore "predicate" is the mathematical and general term for a function of type (x: any) => boolean, so I don't want to name the class that way. Java gets away with it because it has functional interfaces.
Repetition. When using .and() and .or() the return is the same aside from the operator being used. This feels off. When I add a new method like .xor(), then on one hand, I don't want to repeat this. On the other, .xor() will not be implemented using a single operator. There should be a way to generalise the logic that I simply don't see.
Overloaded methods. Since you can't actually have method overloading in TypeScript/JavaScript you need to accept all possible signatures and sort out what to do in the method. Is .extractPredicate() a decent way to go about this in my case? Or is there something more idiomatic or clearer?

interface Predicate<T> {
  (x: T) : boolean
}

class PredicateBuilder<T> {
  condition: Predicate<T>;

  constructor(condition: Predicate<T>) {
    this.condition = condition;
  }

  public and(input: PredicateBuilder<T> | Predicate<T>): PredicateBuilder<T> {
    const p: Predicate<T> = this.condition;
    const q: Predicate<T> = this.extractCondition(input);

    return new PredicateBuilder((x: T) => p(x) && q(x));
  }

  public or(input: PredicateBuilder<T> | Predicate<T>): PredicateBuilder<T> {
    const p: Predicate<T> = this.condition;
    const q: Predicate<T> = this.extractCondition(input);

    return new PredicateBuilder((x: T) => p(x) || q(x));
  }

  public not(): PredicateBuilder<T> {
    return new PredicateBuilder((x: T) => !this.condition(x));
  }

  public apply(x: T): boolean {
    return this.condition(x);
  }

  private extractCondition(input: PredicateBuilder<T> | Predicate<T>): Predicate<T> {
    let condition: Predicate<T>;
    if ("condition" in input) {
      condition = input.condition;
    } else {
      condition = input;
    }

    return condition;
  }
}

Playground Link including a small set of unit tests


texts:
I try to split URLs into segments. These segments got two information, their name and their own URL.

The last segment in the segments list should not have the URL property because it's the current URL from the browser. There is no need for it.

I created this code which works really fine

const directoryPath = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const segments = directoryPath.split('/');

const info = segments.map((segment, index) => {

  const item = {
    name: segment
  };

  if (index < segments.length - 1) {
    let route = '';

    for (let i = 0; i <= index; i++) {
      route += `/${segments[i]}`;
    }

    item.url = route;
  }

  return item;
});

console.log(info);

I don't know if this is the only way doing this, maybe there is a more optimized way. I don't know if I really need the for-loop because at the top of the code I split the URL into segments and after that I create smaller URLs out of it.

Is there a better / easier way?


texts: Make To and From date range picker using jQuery UI

texts:
I implemented date range picker logic using the jQUery UI datepicker component:

var onDocumentReady = function () {
        var datepickerConfiguration = {
            dateFormat: "dd/mm/yy"
        };

        var startDatepickerHandler = function () {
            var selectedDate = $(this).val();
            var newConfiguration = Object.create(datepickerConfiguration);
            newConfiguration.minDate = moment(selectedDate, "DD/MM/YYYY").toDate();
            $("#End").datepicker('destroy');
            $("#End").datepicker(newConfiguration);
        };

        var endDatepickerHandler = function () {
            var selectedDate = $(this).val();
            var newConfiguration = Object.create(datepickerConfiguration);
            newConfiguration.maxDate = moment(selectedDate, "DD/MM/YYYY").toDate();
            $("#Start").datepicker('destroy');
            $("#Start").datepicker(newConfiguration);
        };

        ///--- Component Binding ---///
        $('#Start').datepicker(datepickerConfiguration);
        $('#End').datepicker(datepickerConfiguration);

        $('#Start').on('change', startDatepickerHandler);
        $('#End').on('change', endDatepickerHandler);

    };
    $(document).ready(onDocumentReady);

But I am not satisfied with this approach of setting the min and max values of datepicker, because in this case, it always destroys and creates a new datepicker on every date change. It also creates an object for configuration which may cause lot of memory waste. Please tell what would be a better approach of setting the min and max values of datepicker.


texts:
I'm new to programming (1.5 years experience at university), and I'm working on my first computer vision related project! My goal is to take a file which might have CSV (comma separated) or txt format with XYZ coordinates and process the data. I want to round the X and Y coordinates into integers and leave the Z coordinate as a floating point.

Each file ranges from 200000 to 1400000 lines of XYZ data is is formatted as so:

# information about .txt file
253.9999929 58.0428367 -21.3930063253
.9999929 59.0435773 -21.2499391255
etc.....

Do note that the file might have commas, like a CSV file.

The function that is my main bottleneck is:

Loadfile(string filename);

I'm pretty sure my bottleneck is from the ifstream for reading the file one line at a time, but I'm having trouble finding ways to improve it. One idea I had was to convert the file into an array of bytes and read split it up into different domains and give it to multiple threads to read concurrently, but I'm not sure if that's a good practice.

Here is the my code so far:

class XYZCoordinate{
public:
    int x;
    int y;
    float z;

    XYZCoordinate(int X, int Y, float Z){
    x = X;
    y = Y;
    z = Z;
    }
};

class Loadfileoutput
{
public:
    int xmin;
    int xmax;
    int ymin;
    int ymax;
    vector<XYZCoordinate> values;

    Loadfileoutput(int xmn, int xmx, int ymn, int ymx, vector<XYZCoordinate> val){
    xmin = xmn;
    xmax = xmx;
    ymin = ymn;
    ymax = ymx;
    values = val;
    }
};

Loadfileoutput Loadfile(string filename)
{
    std::ifstream in(filename);
    if (!in) {
        cout << "Cannot open input file.\n";
        exit(EXIT_FAILURE);
    }

    std::string str;
    bool isfirst = true;
    int xmin, xmax, ymin, ymax;
    vector<XYZCoordinate> file = vector<XYZCoordinate>();
    while (std::getline(in, str)) //potential cause of bottleneck
    {
        if (str[0] == '#') //.skipping the .txt file header
            continue;
        vector<string> v = vector<string>();

        boost::split(v, str, boost::is_any_of(" ,"));

        string xstr = v[0];
        string ystr = v[1];
        string zstr = v[2];
        int xint, yint;
        float x,y,z;

        stringstream(v[0]) >> x;
        xint = (int)round(x);

        stringstream(v[1]) >> y;
        yint = (int)round(y);

        stringstream(v[2]) >> z;

        XYZCoordinate temp = XYZCoordinate(xint, yint, z);
        file.push_back(temp);

        //get bounds
        if (isfirst)
        {
            xmin = xint;
            xmax = xint;
            ymin = yint;
            ymax = yint;
            isfirst = false;
        }
        else
        {
            //set xmin/max for scaling
            if (xint > xmax)
                xmax = xint;
            else if (xint < xmin)
                xmin = xint;
            //set ymin/max for scaling
            if (yint > ymax)
                ymax = yint;
            else if (yint < ymin)
                ymin = yint;
        }
    }
    Loadfileoutput output = Loadfileoutput(xmin,xmax,ymin,ymax,file);

    return output;
}


texts:
I am trying to create a function prime-factors that returns the prime factors of a number. To do so, I created is-prime function, and prime-factors-helper that will do a recursive check of the prime factors.

(defun is-prime (n &optional (d (- n 1)))
  (if (/= n 1) (or (= d 1)
          (and (/= (rem n d) 0)
               (is-prime  n (- d 1)))) ()))

(defun prime-factors-helper (x n)
   (if (is-prime x)
       (list x)
       (if (is-prime n)
            (if (AND (= (mod x n) 0) (<= n (/ x 2)))
                (cons n (prime-factors-helper (/ x n) n))
                (prime-factors-helper x (+ 1 n)))
            (prime-factors-helper x (+ 1 n)))))

(defun prime-factors (x)
    (prime-factors-helper x 2))

I have a problem of optimisation. When I have a big number such as 123456789, I get this error message "Stack overflow (stack size 261120)". I believe because the correct answer of (prime-factors 123456789) is (3 3 3607 3803), my program will take so long to find the next prime factor once it constructs the list with the two first elements (3 3). How can I optimise my code?

 CL-USER 53 > (prime-factors 512)
 (2 2 2 2 2 2 2 2 2)

 CL-USER 54 > (prime-factors 123456789)

 Stack overflow (stack size 261120).
   1 (abort) Return to level 0.
   2 Return to top loop level 0.

 Type :b for backtrace or :c <option number> to proceed.
 Type :bug-form "<subject>" for a bug report template or :? for other options


texts:
It has been very hard to use recursion, but I think that it made the code shorter and cleaner.

import doctest
import operator as op

START_FOR_SYMBOLS = {'+': 0,
                     '*': 1,
                     '/':1,
                     '-':0
                     }

OP_FOR_SYMBOL = {'+': op.add,
                 '*': op.mul,
                 '/': op.truediv,
                 '-': op.sub
                 }

def innermost_parens(text):
    """
    Returns the text inside the innermost parenthesis.

    >>> innermost_parens("1 + (2 * (4 - 1))")
    '4 - 1'
    >>> innermost_parens("1 + (2 * (4 * (2 + (8 * 7)) - 1))")
    '8 * 7'
    """
    if not '(' in text and not ')' in text:
        return text
    open_ = text.index('(')
    close_ = text.rindex(')')
    return innermost_parens(text[open_+1:close_])

def polish_eval(expr,start=None):
    """
    Unlimited polish eval, works for any number of arguments.

    >>> polish_eval('+ 4 1 6')
    11.0
    >>> polish_eval('* 4 5 5')
    100.0
    """
    tokens = expr.split(' ')
    if start is None:
        start = START_FOR_SYMBOLS[tokens[0]]
    if len(tokens) == 1:
        return start
    return polish_eval(' '.join(tokens[:-1]),
                       start = OP_FOR_SYMBOL[tokens[0]](start,float(tokens[-1]))
                       )

def infix_eval(expr):
    """
    Reduced infix eval, only works with 2 numbers.

    >>> infix_eval('9 + 4')
    13.0
    >>> infix_eval('2 * -6')
    -12.0
    """
    a, oper, b = expr.split()
    return OP_FOR_SYMBOL[oper](float(a),float(b))

def full_eval(expr, eval_type):
    """
    Evals by the rules of eval_type starting from the inner
    parenthesis.

    >>> full_eval("(* 4 5 (+ 4 1))", polish_eval)
    100.0
    >>> full_eval("(* 4 (/ 10))", polish_eval)
    0.4
    >>> full_eval("(1 + (5 * 2))", infix_eval)
    11.0
    """
    if len(expr.split(' ')) == 1:
        return float(expr)
    inn = innermost_parens(expr)
    new_expr = expr.replace('('+str(inn)+')',str(eval_type(inn)))
    return full_eval(new_expr, eval_type)

def interface():
    which_expr = input("Polish or infix? ")
    if 'polish' in which_expr.lower():
        evaller = lambda expr: full_eval(expr, polish_eval)
    else:
        evaller = lambda expr: full_eval(expr, infix_eval)
    while True:
        result = evaller(input('> '))
        print(result)

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


texts: Finding the object and the URL associated with a notification

texts:
I have a Notification model which inherits from the ActiveRecord class. Each notification is associated with a specific type of action, which is determined by an integer field (action) whose value is between 0 and 6. A notification is also associated with a model (e.g. User or Project) whose ID is stored as the object_id field.

Inside a view, I am trying to prepare the notification text and url, which looks something like this:

# notif_string prepares the text of notification.
# For example: "username commented on"
= link_to(notif_string(notification) + notification.objectname,
            notification.url)

The following methods in the Notification class where flagged as complex by Code Climate:

# Finds the object on which action is performed.
# Action can be of following types:
# 0: Commented on Project,
# 1: Followed Project,
# 2: Forked,
# 3: Followed User,
# 4: Created Project,
# 5: Commented on Issue
# 6: Created Issue
def objectname
  case action
  when 0
    return Project.find(Comment.find(object_id).polycomment_id.to_i).name
  when 5
    return Issue.find(Comment.find(object_id).polycomment_id.to_i)
                .friendly_text
  when 3
    return User.find(object_id).username
  when 1, 2, 4
    return Project.find(object_id).name
  when 6
    return Issue.find(object_id).friendly_text
  end
end

# Find the url to which user which be directed when they click on the
# notification item
def url
  case action
  when 0
    return Project.find(Comment.find(object_id).polycomment_id.to_i).urlbase
  when 5
    return Issue.find(Comment.find(object_id).polycomment_id.to_i).show_url
  when 1, 2, 4
    return Project.find(object_id).urlbase
  when 6
    return Issue.find(object_id).show_url
  else
    return "/#{actor.username}"
  end
end

Yes, my cases are almost repeated but I am not sure how can reduce them. Most of the blogs suggest that I use polymorphism but again I don't know how I can apply it here.


texts: Counting combinations of consecutive symbols in Java

texts:
Let's assume we have an array that contains the following elements:

-1, 0, 0, 1, 0, -1, 0, -1, 1

I would like to count the combinations of consecutive elements such that

-1,0 & 0,0 & 0,1 & 1,0 & 0,-1 & -1,0 & 0,-1 & -1&1

In this case:

The count of -1,0 = 2
The count of 0,1 = 1
The count of 1,0 = 1
and so on

I implemented the following:

List<Double> sixProbabilites = new ArrayList<Double>();

        int count_neg10 = 0, count_neg11 = 0, count_10 = 0, count_1neg1 = 0, count_0neg1 = 0, count_01 = 0;

        for(int i=0; i<slopeChanges.size(); i++) {
            if(i+1 != slopeChanges.size()) {
                if((slopeChanges.get(i) == -1) && (slopeChanges.get(i) == 0)) {count_neg10++;}
                else if((slopeChanges.get(i) == -1) && (slopeChanges.get(i+1) == 1)) {count_neg11++;}
                else if((slopeChanges.get(i) == 1) && (slopeChanges.get(i+1) == 0)) {count_10++;}
                else if((slopeChanges.get(i) == 1) && (slopeChanges.get(i+1) == -1)) {count_1neg1++;}
                else if((slopeChanges.get(i) == 0) && (slopeChanges.get(i+1) == -1)) {count_0neg1++;}
                else if((slopeChanges.get(i) == 0) && (slopeChanges.get(i+1) == 1)) {count_01++;}
            }
        }

There is no problem with the code but I am just wondering if there is a way to enhance the code especially the if statement. Is there any way to reduce the code size to few lines?


texts:
This is a program that generates a random hex value.

# How this works:
#   uses random to get a random number
#   checks what hash method to use
#   uses that method to hash the random number
#   returns the value

import hashlib
import random as rand

def hexrandom(minint, maxint, shamode="sha1"):
    x = str(rand.randint(int(minint), int(maxint)))
    reval = None
    if shamode == "sha1":
        reval = hashlib.sha1(x.encode()).hexdigest()
    elif shamode == "sha224":
        reval = hashlib.sha224(x.encode()).hexdigest()
    elif shamode == "sha256":
        reval = hashlib.sha256(x.encode()).hexdigest()
    elif shamode == "sha384":
        reval = hashlib.sha384(x.encode()).hexdigest()
    elif shamode == "sha512":
        reval = hashlib.sha512(x.encode()).hexdigest()

    return reval

How it works is simple.
It creates a random number.
It then hashes that number.
Then, it .hexdigest()s that.
And then returns that.

By the way, I tried being descriptive with explaining it, but it kept saying that there was unformated code. Sorry about that. The big description will be in a .md file on the repository. MarkDown file here

Development of the module this will be here.


texts: What's the optimal 'pythonic' way to make dot product of two lists of numbers?

texts:
I just filled in the first assignment on course which involves learning Python. The assignment was to make vector class which supports scalar multiplication through operator overloading.

The instructions included these constains:

  There will be one class called MyVector
  Nothing will be imported in file within that file which contains the class
  The class will accept one argument in constructor, which must be list of numbers
  The class will have two methods:

  get_vector which returns list of numbers of the vector
  __mul__ (overloaded * operator) which performs scalar multiplication of two vectors

This is what I have sent:

class MyVector:
    """Vector class"""
    coordinates = None
    def __init__(self, coordinates):
        if not isinstance(coordinates, list):
            raise TypeError("Coordinates of vector must me single dimensional array.")
        self.coordinates = coordinates
    def f(self):
        return 'hello world'
    def get_vector(self):
        return self.coordinates
    def dimensions(self):
        return len(self.coordinates)
    def __mul__(self,other):
        if other.dimensions() != self.dimensions():
            raise ValueError("Number of dimensions of multiplied vectors must be equal.")
        tmp = 0
        for index in range(self.dimensions()):
            tmp += self.coordinates[index] * other.coordinates[index]
        return tmp

''' Just a testing section recommended in the assignment '''
if __name__ == "__main__":
    vec1 = MyVector([1,2,5,5,5]) # vektory mohou byt i jine dimenze nez 3!
    vec2 = MyVector([1,2,5,5,5])
    print(vec1.get_vector()) # Test getting the list of items
    dot_product = vec1*vec2  # Multiplication test
    print(dot_product)

The homework was OK, but the validation system is bragging that their implementation is faster:

  Message: module file vectors.py found
  Result ok
  Your elapsed time for 10,000 trials, vectors length 300: 0.675 seconds
  Our elapsed time for the same setting: 0.383 seconds

  Points: 2 out of 2

I'll repeat the relevant section of code here:

    def __mul__(self,other):
        if other.dimensions() != self.dimensions():
            raise ValueError("Number of dimensions of multiplied vectors must be equal.")
        tmp = 0
        for index in range(self.dimensions()):
            tmp += self.coordinates[index] * other.coordinates[index]
        return tmp

As you can see, as a seasoned C++ programmer I took naïve approach with indexed for loop. I know that Python has some famous tools to deal with array operation.

Is there some really pythonic way to loop over those two arrays and multiply their elements? Note that primarily I'm looking for pythonic way (since I'm learning Python), optimalization is secondary. I got my 2 points for homework, I'm not submiting it again.


texts: Is this the right way to use TcpListener in the background?

texts:
I have a server application using TcpListener in BackgroundWorker, where my application is doing some work, and in the background listening to a IP:PORT.

The DoWork of the BackgroundWorker:

private void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
    while (true) //infinit loop : listen
    {
        var clientSocket = _serverSocket.AcceptTcpClient();
        e.Result = clientSocket;
        m_oWorker.ReportProgress(1, clientSocket);
    }
}

At the progress change event, I do notify the form (launcher of the BackgroundWorker) that a new TcpClient is available:

The ProgressChanged of the BackgroundWorker:

private void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    _luncher.NotifyFormNewTcpClient((TcpClient)e.UserState);
    MessageBox.Show("new TcpClient Connected...");
}

Now for each form that wants to use that background worker, I need to add the method NotifyFormNewTcpClient, and in that method, I have a list of TcpListening, and I added the returned TcpClient to that list:

public void NotifyFormNewTcpClient(TcpClient tcpClient)
{
    TcpClientsList.Add(tcpClient);
    lNumberOfClient.Text = TcpClientsList.Count.ToString()  " Clients";
}

Question:

What I am doing works until now, but I wanted to know if I am doing it the right way.  I want my application to keep doing some work, while it's listening in a LAN for clients that request it, and have a list of the clients (TcpClient) at any moment.  Any ideas are welcome.


texts: Casting const pointer to non-const pointer when using struct iovec

texts:
struct iovec is defined in <uio.h> by the following way:

/* Structure for scatter/gather I/O.  */
struct iovec
  {
    void *iov_base; /* Pointer to data.  */
    size_t iov_len; /* Length of data.  */
  };

Now I do ugly casting from const void* to void*:

int send_frame_once( int fd, const struct iovec* iov, size_t iovlen );

int send_frame( int fd, const void* buffer, size_t len )
{
    struct iovec iov;
    iov.iov_base = (void*)buffer;       /* const iov cast */
    iov.iov_len  = len;
    return send_frame_once( fd, &iov, 1 );
}

Is that necessary kludge?
Or should I remove const keyword from declaration of send_frame function. Like this:

int send_frame( int fd, void* buffer, size_t len )


texts: Conditional statements with doctor and patient information

texts:
I'm focusing on trying to write clean, modular Python 2.7.5 code.

def main():
  type = sys.argv[1]
  dataPatient = parseJSONFile(fileName)

  if(type == "type 1"):
    patient = [d['patient_family_member_id'] for d in dataPatient if d['id'] == sys.argv[2]]
    displayList(flatten(patient), "Msg1")

  elif(type == "type 2"):
    doctor = [d['doctor_id'] for d in dataPatient if sys.argve[2] in set(d['patient_id'])]
    displayList(doctor, "Msg2")

  elif(type == "type 3"):
    dataDoctor = parseData(fileName2)
    doctor = [d['doctor_id'] for d in dataDoctor if sys.argv[2] in set(d['year_graduated'])
    #notice this is doing nearly the same thing as the "type 1" case for each doctor
    patient = [d['patient_family_member_ids'] for d in doctor for p in dataPatient if d == p['doctor']]
    displayList(flatten(patient), "Msg3")

  elif(type == "type 4"):
    patient = [d['patient'] for p in dataPatient if sys.argv[2] in set(d['age'])
    displayList(flatten(patient), "Msg4")

Most of this code in the if else statements are very similar. I feel like I might be able to use a lambda to clean this code up but I'm not sure that will work. I'm trying to make this code easy for someone to read and add more cases. What is the best way of avoiding a lot of the repetition in this code?


texts:
Problem

  Determine whether an array is "Rainbow", i.e. it has the following
  structure:

  First a1 elements equal 1.
  Next a2 elements equal 2.
  Next a3 elements equal 3.
  Next a4 elements equal 4.
  Next a5 elements equal 5.
  Next a6 elements equal 6.
  Next a7 elements equal 7.
  Next a6 elements equal 6.
  Next a5 elements equal 5.
  Next a4 elements equal 4.
  Next a3 elements equal 3.
  Next a2 elements equal 2.
  Next a1 elements equal 1.

  ai can be any positive integer. There are no other elements in array.

Solution

(defn palindrome? [items]
  "Efficient algorithm: loops through only (array-size/2)"
  (loop [i 0
         j (-> items count dec)]
    (cond (>= i j)
          true
          (not= (nth items i)
                (nth items j))
          false
          :else
          (recur (inc i) (dec j)))))

(let [test-cases-count (Integer/parseInt (read-line))
      test-cases       (for [i (range test-cases-count)]
                         (let [nums-count (read-line)
                               nums-temp (-> (read-line) (clojure.string/split #"\s+"))
                               nums (map #(Integer/parseInt %) nums-temp)]
                           nums))]
  (for [t test-cases]
    (if (palindrome? t)
      (println "Yes")
      (println "No"))))

Not able to figure out how to optimize this.


texts: Method to remove outliers from a set of values

texts:
I'm removing outliers from a set of data using the method described here.

The method removes the outliers and returns the quartile values of the set after all outliers have been removed.

(Quartiles is a class I wrote with properties for Q1, Q2, Q3, and the Inter-quartile range, IQR. The .Quartiles() returns these values for a sequence of decimals.)

public Quartiles RemoveOutliers(ICollection<MyObject> objects)
{
    if (objects.Count == 0)
    {
        return new Quartiles();
    }

    // Calculate Mean value of the set.
    decimal meanValue = objects.Average(o => o.MyProperty);

    // Find the Object whose value is farthest from the Mean.
    MyObject objectFarthestFromMean = objects.OrderByDescending(o => Math.Abs(o.MyProperty - meanValue)).First();
    Quartiles quartiles = objects.Quartiles(o => o.MyProperty);

    // Remove Object if its value is more than 1.5*IQR from the Mean.
    decimal minValue = meanValue - (1.5m * quartiles.IQR);
    decimal maxValue = meanValue + (1.5m * quartiles.IQR);

    if ((objectFarthestFromMean.MyProperty < minValue) || (objectFarthestFromMean.MyProperty > maxValue))
    {
        objects.Remove(objectFarthestFromMean);

        return RemoveOutliers(objects);
    }

    // No outlier found, we're finished.
    return quartiles;
}

Looking for any ways to improve or fix any pitfalls I haven't encountered in testing.


texts: Cleaner way to construct a name using Immutable.js

texts:
This is what I've come up with to construct a name using a javascript object and immutable.js:
const getFullName = ({ user }) => {
    if (!user || !user.get('response')) {
        return '';
    }
    return `${user.getIn(['response', 'firstName']) || ''} ${user.getIn(['response', 'lastName']) ||
        ''}`;
};

As you can see, it looks pretty ugly. I'm wondering if there is a way to clean this code up. This function is called in loop to show all the names in the dataset. I can imagine that this solution may not be a very efficient in such case.


texts: Recursive trim() function to handle arrays and objects

texts:
I have come up with a recursive function which applies trim() recursively to all string members of an array/object.

I don't have any specific quandaries about my code so I am receptive to all feedback.

My goal is maximum compatibility for all PHP versions: past, present, and future.

<?php
/**
 * trim_r
 *
 * Recursively trim an array's or object's string values
 * Preserves all non-string values
 *
 * @access  public
 * @param   mixed
 * @param   mixed
 * @return  mixed
 */
function &trim_r( &$o, $character_mask = null )
{
    // Only apply trim() to strings
    if( is_string( $o ) )
    {
        // Respect the $character_mask; cannot pass null as 2nd parameter for some HHVM versions
        $o = ( $character_mask === null ? trim( $o ) : trim( $o, $character_mask ) );
    }
    elseif( is_array( $o ) || is_object( $o ) )
    {
        // Loop this array/object and apply trim_r() to its members
        foreach( $o as &$v )
        {
            trim_r( $v );
        }
    }

    // Supply this just in case the invoker wishes to receive result as a reference
    return $o;
}


texts: Print the next smallest and next largest number that have the same number of 1 bits in their binary representation

texts:
Given an integer , print the next smallest and next largest number that have the same number of 1 bits in their binary representation.

How can I improve this?

void printNextNumber(int num){
    int inputNumOfBits = calcBits(num);

    int  nextLargest = num + 1, nextSmallest = num - 1;

    //nextLargest
    while (true){
        if (calcBits(nextLargest) == inputNumOfBits){
            break;
        }
        nextLargest++;
    }

    //nextSmallest
    while (true){
        if (calcBits(nextSmallest) == inputNumOfBits){
            break;
        }
        nextSmallest--;
    }
    System.out.println("Next largest: " + nextLargest);
    System.out.println("Next smallest: " + nextSmallest);
}

private int calcBits(int x){
    int count = 0;
    int i = 0;

    while (i < 32){
        if ((x & (1<<i)) != 0){
            count++;
        }
        i++;
    }
    return count;
}