texts: Webscraping application that collects metal prices and converts them from USD to MXN real-time using BeautifulSoup

texts:
from bs4 import BeautifulSoup
import requests
import re
import datetime

metal_translation = {"Aluminium": "Aluminio", "Copper": "Cobre", "Zinc": "Zinc", "Nickel": "Níquel", "Lead": "Plomo", "Tin": "Estaño",
                     "Aluminium Alloy": "Aleación de Aluminio", "Cobalt": "Cobalto", "Gold*": "Oro*", "Silver*": "Plata*",
                     "Steel Scrap**": "Chatarra de Acero", "NASAAC": "NASAAC", "Steel Rebar**": "Varilla de Acero"}

def get_metal_values():
    names = []
    prices = []
    metals = requests.get('https://www.lme.com/').text
    soup = BeautifulSoup(metals, 'lxml')
    metal_table = soup.find("table", attrs={"class": "ring-times"})
    metal_table_names, metal_table_prices = metal_table.tbody.find_all("th"), metal_table.tbody.find_all("td")
    for name in metal_table_names:
        names.append(name.text.replace("LME ", ""))
    for price in metal_table_prices:
        prices.append(price.text.strip())
    return names, prices

def get_peso_conversion():
    peso = requests.get('https://themoneyconverter.com/USD/MXN').text
    soup1 = BeautifulSoup(peso, 'lxml')
    conversion = soup1.find("div", class_="cc-result").text
    rate = re.search("\d{2}\.\d{4}", conversion).group()
    return rate

def get_time():
    date = datetime.datetime.now()
    time = (f'{date.day}/{date.month}/{date.year} | {date.hour}:{date.minute}')
    return time

def convert_values():
    names, prices = get_metal_values()
    rate = get_peso_conversion()
    metal_data = dict(zip(names, prices))
    for k, v in metal_data.items():
        v = (float(v.replace(",", "")) * float(rate))
        v = ("%.2f" % v)
        k = metal_translation[k]
        print(f'{k}: {v} $')

def program_run():
    print("Metal Prices by ETHAN HETRICK")
    print("================================================")
    print(f'{get_time()} | 1 USD = {get_peso_conversion()} MXN\n')
    print("Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)\n")
    convert_values()
    print("================================================")

program_run()
input("\nEscribe 'x' para terminar.\n")

EXAMPLE OUTPUT:

Metal Prices by ETHAN HETRICK
================================================
26/6/2020 | 18:28 | 1 USD = 23.0622 MXN

Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)

Aluminio: 36484.40 $
Cobre: 138038.80 $
Zinc: 47438.95 $
Níquel: 293097.50 $
Plomo: 41004.59 $
Estaño: 391826.78 $
Aleación de Aluminio: 27997.51 $
NASAAC: 27444.02 $
Cobalto: 657272.70 $
Oro*: 40711.70 $
Plata*: 410.74 $
Chatarra de Acero: 6065.36 $
Varilla de Acero: 9720.72 $
================================================

Escribe 'x' para terminar.

My fiances father owns a metal recycling business in Mexico City, Mexico which requires him to do a lot of calculations when negotiating with clients. Since he was doing this by hand, I decided to automate this for him. I used London Metal Exchange, which is his preferred site to get the current prices, for the metal prices and also got the exchange rate for USD to MXN and applied that as well. I also needed to translate everything to spanish so I used a dictionary. This is my first time utilizing webscraping and the datetime module so any advice to make this program run more efficiently or make the code more concise is much appreciated!


texts: Convert boolean array to integer in Typescript

texts:
I have a database object that has a field called workdays, it's a array boolean that contains 7 elements representing whether the user is active on the corresponding day.
I need to save this array into the database, I thought the bets way would be to convert the boolean array into a integer (bits) array and convert that into an integer which can be saved in the DB.
this is what I came up with, but I feel like I'm doing it the unnecessarily long way.
How can this be improved upon ?
    function serializeDays(days: boolean[]): number {
        // use (days || []) to avoid null pointer exception
        // concat it with Array(7).fill(false) to fill in missing values
        const d1 = (days || []).concat(Array(7).fill(false)).slice(0, 7);
        // map the boolean values to int values
        const d2 = d1.map(d => (d ? 1 : 0));
        // join the array to string
        const d3 = d2.join("");
        // parse the string into base 10 from base 2
        const n = parseInt(d3, 2);
        return n;
    }

    function parseDays(days: number): boolean[] {
        // use (days || 0) to avoid null pointer exception
        // convert the base 10 integer into base 2
        const d1 = (days || 0).toString(2);
        // split the string into an array
        // reverse it, concat it with Array(7).fill(0), reverse it again
        // this is just to zerofill the array from the left side
        const d2 = d1.split("").reverse().concat(Array(7).fill(0)).slice(0, 7).reverse();
        // parse the values from strings to actual integers to boolean
        const d3 = d2.map(d => (parseInt(d, 10) ? true : false));
        return d3;
    }

    // monday to friday
    serializeDays([true, true, true, true, true, false, false]); // outputs 124
    parseDays(124); // outputs [true, true, true, true, true, false, false]

```


texts: In AngularJS, create lots of directives or use ng-controller?

texts:
This is a question about whether my coding style follows AngularJS best practices.

One of the selling points to Angular is directives. Directives allow you to create custom DOM with elements or attributes you create. I've found myself creating lots of directives, thinking of each one as little controls to be placed on the page. Looking back, I'm wondering if I'm too directive focused and if Angular directives should only be used when you need a custom link method?

What I find myself doing a lot is wrapping up some HTML in a directive with a simple controller that does one or two basic things. I have a lot of code that looks like this code of mine from a blog post:

'use strict';

angular.module('solrAngularDemoApp')
  .directive('searchResults', function () {
    return {
      scope: {
        solrUrl: '=',
        displayField: '=',
        query: '&',
        results: '&'
      },
      restrict: 'E',
      controller: function($scope, $http) {
        console.log('Searching for ' + $scope.query + ' at ' + $scope.solrUrl);
        $scope.$watch('query', function() {
          $http(
            {method: 'JSONP',
             url: $scope.solrUrl,
             params:{'json.wrf': 'JSON_CALLBACK',
                    'q': $scope.query,
                    'fl': $scope.displayField}
            })
            .success(function(data) {
              var docs = data.response.docs;
              console.log('search success!');
              $scope.results.docs = docs;

            }).error(function() {
              console.log('Search failed!');
            });
        });
      },
      template: '<input ng-model="query" name="Search"></input>' +
                '
Search Results for {{query}}
' +
                '' +
                '
{{doc[displayField]}}
'  +
                ''
    };
  });

So now I can think of my search results as a little widget to embed on the page:

 <search-results solrUrl="..." etc></search-results>

OK Let's say I take the next step in my application and want to display more information about the individual documents from the search results. My inclination up to this point has been to create a custom directive, like a little "widget" that handles all the functionality here. If I need to say wrap-up how a document from the search results gets displayed, I'll add a directive like lets say "docDisplay". Something like:

angular.module('solrAngularDemoApp')
   .directive('docDisplay', function() {
         // same pattern as above
    });

Then in the template for search Results, I'll change out my template:

      template: '<input ng-model="query" name="Search"></input>' +
                '
Search Results for {{query}}
' +
                '' +
                '  <doc-display></doc-display>'  + // THIS LINE CHANGED
                ''

I may or may not use prototypical inheritance of $scope or use an isolate $scope, depending on how strongly I feel this directive is tied to the parent.

After writing a lot of code this way and learning more about Angular, I realized that I could just have

Thrown all this HTML into my main HTML
Used ng-controller on specific pieces of HTML

As nothing here takes advantage of the link functionality of the directive (binding DOM events to create some custome functionality) and my directives are just a bunch of HTML and controller code I'm left wondering the following two questions:

Is it ok to use directives like this to break up my UI? or am I thinking too much in the directives==controls mindset
Should I avoid directives when there's no link function? and just stick with plain-jane HTML with ng-controller?


texts: Ranking and storing scores to a database

texts:
I am developing a small website with PHP and am trying to receive user exam scores from the database. I rank it based on the highest score and then store the ranking to the database based on the user_id returned from the database with the score.

I have finished the code but it's too long. I need optimizations and reviews.

//=============init connection
$dbc = new mysqli('localhost','root','','test');

//==================database========================
CREATE TABLE IF NOT EXISTS `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(60) NOT NULL,
`score` int(11) NOT NULL,
`subposition` int(11) DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

//=========================functions=======================
function gradeScoreFormula($score1, $score2)
{
if ($score1 > $score2)
{
    return true;
}else{
    return false;
}
}

function gradeScore(array $values,$functionName, $dbc)
{
$newArr = array();
$dbc->autocommit(false);

uasort($values, $functionName);
$size = count($values);

foreach ($values as $k => $v)
{
    $newArr[] = array($k  => $v);
}

$reversedArr = array_reverse($newArr);
$complete = 0;
for($i=0; $i < $size; $i++)
{
    //echo 'POS = '.$a = $i + 1 .' --> ';
    $position = $a = $i + 1;
    foreach($reversedArr[$i] as $k => $v)
    {
        //echo "UID = ".$k."----------> score = ".$v.'<br>';
        $q = "UPDATE USERS set subposition = $position WHERE uid = $k AND score = $v";
        $r = $dbc->query($q);
        if ($dbc->affected_rows)
        {
            $complete +=1;
        }
    }
}

if ($complete == $size)
{
    $dbc->commit();
    echo 'succesfully stored';
}else{
    $dbc->rollback();
    echo 'not stored try again';
}
$dbc->autocommit(true);
}

//===============================program start========================
$q1 = "SELECT uid, score FROM users";
$r1 = $dbc->query($q1);
$returnedVal = [];

while(list($id, $scores) = $r1->fetch_array())
{
$returnedVal[$id] = $scores;
}

print_r($returnedVal);

gradeScore($returnedVal,'gradeScoreFormula', $dbc);


texts: Printing lines of "*" of various lengths

texts:
As a beginner, I tried a programming drill.  The method gets an Enumerable that contains numbers specifying how many "*" to print on each line.

public static void PrintStars(IEnumerable<int> neverEndingListOfInt)
{
    foreach (int item in neverEndingListOfInt)
    {
        Console.WriteLine(SetStars(item));
    }
}
private static string SetStars(int numberOfTimes)
{
    return string.Concat(Enumerable.Repeat("*", numberOfTimes));

}

I have another version here:

public static void PrintStars(IEnumerable<int> neverEndingListOfInt)
{

    foreach (int item in neverEndingListOfInt)
    {
        for (int i = 0; i < item; i++)
        {
            Console.Write("*");
        }
        Console.WriteLine();

    }
}

What impact on the GC will creating so many strings have?
Which way is more efficient, and how would you prefer to do it?


texts: Read multidimensional array from file in C

texts:
I want to read multidimensional double array from file into a single pointer variable. The number of rows and columns are not known and need to be determined when reading the file in order to allocate memory for the array. I wrote the following code and it works fine with me. I want to know if someone has more efficient solution for such case:

//Initialize variables and open the file
size_t count=1000;
char *line = malloc(1000);
FILE *file= fopen("g.txt", "r");
if(file==NULL)
{
    printf("Error in Opening file");
    return EXIT_FAILURE;
}
double *data=(double*) malloc(1000*sizeof(double));
if(data==NULL)
{
    printf("Error in allocating memory");
    return EXIT_FAILURE;
}

// Read number of columns and number of rows
getline(&line, &count, file);
int read=-1,cur=0,columCount=0;
while(sscanf(line+cur, "%lf%n", &data[columCount],&read)==1)
    {cur+=read;columCount=columCount+1;}

int rowCount=1;
while(getline(&line, &count, file)!=-1) {rowCount=rowCount+1;}

rewind(file);

// Reinitialize array using the number of rows and number of columns
free(data);
data=(double*) malloc(columCount*rowCount*sizeof(double));
if(data==NULL)
{
        printf("Error in allocating memory");
        return EXIT_FAILURE;
}

// Read file and store values
int i=0;
while(getline(&line, &count, file)!=-1)
{
    read=-1,cur=0;
    while(sscanf(line+cur, "%lf%n", &data[i],&read)==1)
    {cur+=read;i=i+1;}
}

fclose(file);
return EXIT_SUCCESS;


texts:
As I will be deploying this script on multiple machines with the very same system Linux Mint 18 with rather same configuration, I would like to be semi-sure I won't screw things up much. This little script will run every day from crontab and will be logged into syslog.

Conditions were:

Code Readability
Output Readability
Colored Headings
Attempt to correct things
Clean-up after update

My current idea is simple:

#!/bin/bash

RED="\033[1;31m"
GREEN="\033[1;32m"
NOCOLOR="\033[0m"

echo

echo -e "step 1: ${GREEN}pre-configuring packages${NOCOLOR}"
sudo dpkg --configure -a

echo

echo -e "step 2: ${GREEN}fix and attempt to correct a system with broken dependencies${NOCOLOR}"
sudo apt-get install -f

echo

echo -e "step 3: ${GREEN}update apt cache${NOCOLOR}"
sudo apt-get update

echo

echo -e "step 4: ${GREEN}upgrade packages${NOCOLOR}"
sudo apt-get upgrade

echo

echo -e "step 5: ${GREEN}distribution upgrade${NOCOLOR}"
sudo apt-get dist-upgrade

echo

echo -e "step 6: ${GREEN}remove unused packages${NOCOLOR}"
sudo apt-get --purge autoremove

echo

echo -e "step 7: ${GREEN}clean up${NOCOLOR}"
sudo apt-get autoclean

echo

Current visual output:


texts: Finding the minimum ratio out of many lines of input

texts:
This is my code. I am having a file, whose first line's second word contains a number. Let this number is $u. 2nd line is empty, and from third line, I am given with two numbers separated by a space in each line where let first number is $c and second is $w. Now I need to figure out the minimum $b where $b for a line is ceil($u  / $w) * $c. Is there anyway I can optimize my code.

<?php
$f = file($argv[1]);
list(, $u) = explode(" ", $f[0]);
list($c, $w) = explode(" ", $f[2]);
$b = ceil($u / $w) * $c;
unset($f[0], $f[1], $f[2]);

foreach($f as $l)
{
    list($c, $w) = explode(" ", $l);
    $b = min($b, ceil($u / $w) * $c);
}

echo "$b\n";
exit;
?>


texts: Count patterns that start and end with "1", with 0's in between

texts:
A string contains many patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0's. The patterns are allowed to overlap.

For example, consider string "1101001", we can see there are two consecutive sequences "1(0)1" and "1(00)1" which are of the form 1(0+)1.

public class Solution {

        static int patternCount(String s){
            String[] sArray = s.split("1");
            for(String str : sArray) {
                if(Pattern.matches("[0]+", str)) {
                    count++;
                }
            }
            return count;
        }

        public static void main(String[] args) {
            int result = patternCount("1001010001");
            System.out.println(result);//3
        }
    }

Sample Input:

100001abc101, 1001ab010abc01001, 1001010001

Sample Output:

2 2 3

But still something i feel might fail in future could you please help me to optimize my code as per the Requirement


texts: Is catching null pointer exception to handle it instead of null check beforehand always a bad practice or it depends?

texts:
I wrote a static method for an enum that returns the corresponding enum instance based on the source string, trimming any whitespaces and ignoring case as:

/**
 * Convert the passed {@code source} string value to respective {@link SomeEnum} instance.
 * Ignore any white-spaces present in the beginning/end of the passed {@code source} string.
 * Ignore casing of the {@code source} string.
 *
 * @param source {@link String}
 * @return converted {@link SomeUnit} instance if conversion is possible, null otherwise.
 */
public static SomeEnum fromString(String source) {
    try {
        return source == null ? null : SomeEnum.valueOf(source.trim().toUpperCase());
    } catch (IllegalArgumentException e) {
        return null;
    }
}

Then considering the fact that there is only one source for a NPE here, I changed the above to:

/**
 * Convert the passed {@code source} string value to respective {@link SomeEnum} instance.
 * Ignore any white-spaces present in the beginning/end of the passed {@code source} string.
 * Ignore casing of the {@code source} string.
 *
 * @param source {@link String}
 * @return converted {@link SomeUnit} instance if conversion is possible, null otherwise.
 */
public static SomeEnum fromString(String source) {
    try {
        return SomeEnum.valueOf(source.trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        return null;
    }
}

Question:

Is there any difference (significant/insignificant) between the two in terms of efficiency, best practices, coding style, readability or any other possible factor that I am unaware of? Or am I just overthinking?

I personally feel that instead of relying on exceptions (NPE here) to take some action, better to test it beforehand if possible, which favors the first approach. But then I feel that in this particular case I am anyway having a catch block here for IAE so better to club the exceptions together instead of performing a null check.

Update:
This code is a piece of already written application, and I have to return null in case there is no match, so as to respect the various client calls.

Edit:
This code is fully owned by me. When I stated its a piece of already written application, I meant, way earlier I wrote the code as first approach(where again returning null was needed), and just a few days back going through this I refactored it to second approach.

Also this is no pseudo code, this is the exact code being used with just the class and variables name changed.


texts:
I've written an algebraic notation to use for moves in a game and I'm currently writing code to parse the information from the notation.  I'm doing this using regExes.  This is coded in HaXe.

For example, two functions in the parser would look like this:

public function getMoveType(gameText:String):String
{
   var moveTypeRegEx:EReg = ~/MatchThis/;
   moveTypeRegEx.match(gameText);
   var moveType:String = moveTypeRegEx.matched(0); //this returns entire string that was matched.
   return moveType;
}

public function getPlayerName(gameText:String):String
{
    var playerNameRegEx:EReg = ~/MatchThis/;
    playerNameRegEx.match(gameText);
    var playerName:String = playerNameRegEx.matched(0);
    return playerName;
}

How could this be written better to make it more readable or more organized?
Would it be better to have a class file GameRegExes, which contains all the regexes I need with getter functions to those regexes?

Please let me know if I'm being too vague.


texts:
My code is working fine Could you please review how I can make it more accurate and efficient?

import java.util.Scanner;

public class LinearProbing {

    public static void hash(String store[],int index,int num){
        if (store[index].equals(" ")) {
            store[index] = String.valueOf(num);
        } else {
            index++;
            if(index==10){
                index=0;
            }
            hash(store,index,num);
        }

    }

    public static void main(String args[]) {
        String store[] = new String[10];
        for (int a = 0; a < store.length; a++) {
            store[a] = " ";
        }

        Scanner input = new Scanner(System.in);

        int num;
        int index;

        for (int a = 0; a < store.length; a++) {
            System.out.print("Enter Num: ");
            num = input.nextInt();
            index = num % 10;
            hash(store,index,num);
        }

        for (int a = 0; a < store.length; a++) {
            System.out.println("Index: "+a+ "Store: "+store[a]);
        }

    }

}


texts: Prepending a string to alternate elements in a Python tuple

texts:
So I have this piece of Python code that essentially takes a tuple, then modifies the second (and every other) element by prepending a string to it.  Unfortunately the only way I can think to do it is convert it to a list (as tuples are immutable), step through, edit and then convert back to a tuple.

It works so I can't put it on SO but it's ugly and I'm sure there's a more Pythonic way to do this using slices or something.

def prependPackageToEnpoints(urls, packageName):
    """Take web.py formatted url/endpoint tuples and prepend
    a packageName to each of the endpoints, e.g.
    ('/Test/(.*)', 'test') becomes ('/Test/(.*)', 'Test.test')"""
    lst = list(urls)
    for i in xrange(1, len(lst), 2):
        lst[i] = packageName + "." + lst[i]
    t = tuple(lst)

    return t

I don't get to decide what the structure is, I'm using web.py and the structure it uses is a tuple.

What's the prettiest, and perhaps the most efficient way to do something like this in Python?


texts: Brightness adjustment control for multiple UI elements

texts:
I have an application that basically exists as a map and some controls. The controls change the look and feel of the map. I have a slider which is used to change the brightness, for example. At the moment there is only one map but more might be added in future. This seems to me like a good situation for observer pattern. However, the instance Controller of the slider exists far away from an instance of the map component so I'm not sure how exactly to implement it. To propagate a reference to the map through lots of function calls seems like poor design. (Perhaps it's due to poor design that they are referenced so far apart but I don't have control of that)

To solve this, I've written some glue code which sits in between. I've called them services for lack of a better name. They both work, but I'm not sure it's as elegant as it could be. I'm also not sure as to whether the Java Observer/Observable are adding anything at all in the more complicated service. I wonder whether there's another design pattern that may be better suited here, too.

Any help would be great.

Map:

public class Map
{
    public void setBrightness(int i)
    {
        System.out.println("Brightness set to: " + i);
    }
}

Controller:

public class Controller
{
    public void brightnessChanged()
    {
        // Create an "event" and fire it to all listeners
        BrightnessService.update(11111);
        OtherBrightnessService.update(55555);
    }
}

A simple brightness service:

import java.util.LinkedList;
import java.util.List;

public abstract class BrightnessService
{
    private static final List<Map> OBSERVERS;

    static
    {
        OBSERVERS = new LinkedList<>();
    }

    public static void register(Map map)
    {
        OBSERVERS.add(map);
    }
    public static void update(int i)
    {
        for (Map obs : OBSERVERS)
        {
            obs.setBrightness(i);
        }
    }
}

A possibly too complicated brightness service

import java.util.Observable;
import java.util.Observer;

public abstract class OtherBrightnessService
{
    static class MyObserver implements Observer
    {
        private Map map;

        public MyObserver(Map m)
        {
            map = m;
        }

        @Override
        public void update(Observable o, Object o1)
        {
            map.setBrightness(((Brightness) o).get());
        }
    }
    static class Brightness extends Observable
    {
        private int brightness = 0;

        public void set(int i)
        {
            brightness = i;

            setChanged();
            notifyObservers();
        }

        public int get()
        {
            return brightness;
        }
    }

    static Brightness brightness;

    static
    {
        brightness = new Brightness();
    }

    public static void register(Map map)
    {
        MyObserver observer = new MyObserver(map);
        brightness.addObserver(observer);
    }
    public static void update(int i)
    {
        brightness.set(i);
    }
}

Main

public class ObserverTest
{
    public static void main(String[] args)
    {
        // Set up map
        Map m = new Map();
        BrightnessService.register(m);
        OtherBrightnessService.register(m);

        // Change the brightness, this would fire from a user event
        // and be implemented in a different file
        Controller c = new Controller();
        c.brightnessChanged();
    }
}


texts:
This problem is from [CCC2019]: https://dmoj.ca/problem/ccc19s5/ (Canadian Computing Contest 2019) and I have implemented it in C++.
I used sequence [A054237]: https://oeis.org/A054237/table to compute the indexes of sub-triangles.

In a parallel universe, the most important data structure in computer science is the triangle. A triangle of size M M consists of M M rows, with the i t h i^{th} row containing i i elements. Furthermore, these rows must be arranged to form the shape of an equilateral triangle. That is, each row is centred around a vertical line of symmetry through the middle of the triangle. For example, the diagram below shows a triangle of size 4:
A triangle contains sub-triangles. For example, the triangle above contains ten sub-triangles of size 1, six sub-triangles of size 2 (two of which are the triangle containing ( 3 , 1 , 2 ) (3,1,2) and the triangle containing ( 4 , 6 , 1 ) (4,6,1) ), three sub-triangles of size 3 (one of which contains ( 2 , 2 , 1 , 1 , 4 , 2 ) (2,2,1,1,4,2) ). Note that every triangle is a sub-triangle of itself.
You are given a triangle of size N N and must find the sum of the maximum elements of every sub-triangle of size K K .

Please review and suggest edits.
#include<stdio.h>

int rec(int x)
{
    return (x*(x+1))/2;             //sum of n natural numbers
}
int main()
{   int n,k;                   //n=height of triangle  k=height of sub-triangles   ne= number of elements
    int t1=0;
    int t2=0;
    std::scanf("%d %d",&n,&k);
    int ne=rec(n);
    int rk=rec(k);                  //rk=number of elements in sub-triangle
    int nt=ne-rk-1;         //ior[]=array to store index of row     nt=number of sub-triangles
    unsigned long int e[ne],gval,sum=0;  //e[]=array to store elements   gval=greatest element of sub-triangle    sum=sum of gvals
    gval=0;
    for(int i=0;i<ne;i++)
        scanf("%ld",&e[i]);
    for(int rt=0,ior=0;ior<nt;rt++)
    {
        for(int ioc,r=0; r<=rt && ior<nt; r++,ior++)
        {   ioc=0;
            for(int ct=0;ioc<rk;ct++)
            {
                for(int c=0;c<=ct && ioc<rk;ioc++,c++,t2++)
                {
                    if(gval<e[t2])gval=e[t2];
                }
                t2+=rt;
            }
            sum+=gval;
            t1++;
            t2=t1;
            gval=0;
        }
    }
    std::printf("%ld",sum);
    return 0;
}


texts:
I have been lurking on the C++ side of stack-overflow only long enough to know there are a lot of beginners and intermediate programmers baffled by multi-dimensional arrays. I've seen a lot of monstrosities : three-star programmers, cache-unfriendly implementations, vectors of vectors of vectors ..., etc.

I thought to provide them with a basic multi-dimensional array:

open for extensions,
fit for production and experimentation,
working without allocations,
and cache-friendly.

Before I do so, I'd like some advice from the community.

  What can I improve in the provided features of this class?
  What new feature could one add, and why would it be useful?

#include <array>
#include <numeric>

namespace ysc
{
namespace _details
{
    template<class InputIt, class OutputIt>
    OutputIt partial_product(InputIt first, InputIt last, OutputIt output)
    { *output++ = 1; return partial_sum(first, last, output, std::multiplies<>{}); }

    // cache-friendly:
    // neighbor objects within the right-most coordinate are neighbors in memory
    template<class TDim, class TCoord>
    auto coordinates_to_index(TDim const& dimensions, TCoord const& coords)
    {
        std::array<std::size_t, dimensions.size()> dimension_product;
        using std::crbegin, std::crend, std::prev;
        partial_product(crbegin(dimensions), prev(crend(dimensions)), begin(dimension_product));
        return std::inner_product(cbegin(dimension_product), cend(dimension_product), crbegin(coords), 0);
    }
}

constexpr struct matrix_zero_t {} matrix_zero;

template<class T, std::size_t... Dimensions>
class matrix
{
template<class, std::size_t...> friend class matrix;

public:
    static constexpr std::size_t order      = sizeof...(Dimensions);
    static constexpr std::array  dimensions = { Dimensions... };

private:
    std::array<T, (Dimensions * ...)> _data;

public:
    friend void swap(matrix& lhs, matrix& rhs)
    {
        using std::swap;
        swap(lhs._data, rhs._data);
    }

public:
    matrix()                          = default;
    matrix(matrix&& other)            = default;
    matrix& operator=(matrix&& other) = default;

    matrix(matrix_zero_t) : _data({}) {}

    template<class U>
    matrix(matrix<U, Dimensions...> const& other) { std::copy(cbegin(other._data), cend(other._data), begin(_data)); }

    template<class U>
    matrix& operator=(matrix<U, Dimensions...> const& other)
    {
        matrix o{other};
        swap(*this, o);
        return *this;
    }

public:
    template<class... Args>
    T const& operator()(Args... coordinates) const
    { return _data[_details::coordinates_to_index(dimensions, std::array{coordinates...})]; }

    template<class... Args>
    T& operator()(Args... coordinates)
    { return _data[_details::coordinates_to_index(dimensions, std::array{coordinates...})]; }
};
} // namespace ysc

Usage demo: http://coliru.stacked-crooked.com/a/1652451c78275436

This is a C++17 implementation; this itself is not set in stone.


texts:
How can I verify that ohterClassMock.MethodToTest() was called with contracts?

That it was called with contract, that have Id = 1 and Param2 = 34 and also with contract2, which has Id = 2 and Param2 = 56.

This is my code:

GoodClass goodClass = new GoodClass(ohterClassMock);
...
var contracts = new List<Contract>();
var contract = new Contract{ Id = 1, Param2 = 34 };
contracts.Add(contract);
var contract2 = new Contract { Id = 2, Param2 = 56 };
contracts.Add(contract2);

goodClass.DoSomething(contracts);

ohterClassMock.Verify(mock => mock.MethodToTest(It.IsAny<contracts>()));

I know that it can be tested for every item in the collection:

ohterClassMock.Verify(mock => mock.MethodToTest(It.Is<Contract>(contract => contract.Id == 1)));
...

but maybe there is some other syntax to call it in one line of code?

Updated:

goodClass.DoSomething(contracts);

calls

foreach(Contract contract in contracts)
{
   ohterClassMock.MethodToTest(contract);
}


texts: Is this jQuery Plugin for TreeView correct?

texts:
Looking for a review of my first published jQuery Plugin. It's for TreeViews, very basic example demo can be seen at: Demo

Everything works fine, just looking to see if I can get some feedback on things that I may be doing wrong best practices wise and/or things I could be doing better.

(function ( $ ) {

  var methods = {
    init : function(options) {

      // Default Settings
      var settings = $.extend({
          'expandIconClass' : 'closed',
          'contractIconClass' : 'open',
          'setFocus' : undefined,
          'classPrefix' : 'goodtree_',
        }, options);

      return this.each(function() {

        // Hide all of the children Elements
        $(this).find('ul').hide();

        // Add the plus minus buttons
        $(this).find('li').each(function() {
          if($(this).children('ul').length > 0)
            $(this).prepend($('<div />', {'class': settings.classPrefix + "toggle " + settings.expandIconClass}));
        });

        // Events
        $('.' + settings.classPrefix + 'toggle').click(function() {
          $(this).parent().children('ul').toggle();
          $(this).hasClass('open')
            ? $(this).removeClass(settings.contractIconClass).addClass(settings.expandIconClass)
            : $(this).removeClass(settings.expandIconClass).addClass(settings.contractIconClass);
        });

        if(undefined !== settings.setFocus)
        {
          $(this).goodtree('setFocus', settings.setFocus);
        }

      });
    },

    setFocus : function(obj) {
      return this.each(function() {
        var tree_parent = this;
        $(obj).parents('ul').each(function() {
          if($(this) === this)
            return;
          else
            $(this).show();
        });
      });
    }
  }

  $.fn.goodtree = function( method ) {
    if ( methods[method] ) {
        return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.goodtree' );
      }
  };
}) ( jQuery );


texts: Optimizing a function in R over 10000000 values - follow-up

texts:
This is a follow up: Optimization over 7 constants, running a function 10,000,000 times

My data can be downloaded here.

The only kink left is the betaema function, which is still a for loop and hence mildly inefficient, and correcttot which is 7 for loops nested. My current runtime is .352, which means over 50 days if I continue to use the current iteration of correcttot.

setwd("~/Desktop")
dat<-read.csv(file="dat.csv",sep=",",header=T)
attach(dat)
###################################################################################
voltoalph <- function(v,c) {
  # v: a data vector
  # c: a scalar constant
  vc<-max(v, na.rm=TRUE)
  c(0, c[1L] * (v / vc))
}
voltoenen <- function(v,c) {
  # v: a data vector
  # c: a scalar constant
  vc<-max(v, na.rm=TRUE)
  enhelp <- 1 / c(1, abs(v /vc))
  c[1L] * (enhelp / max(enhelp))
}
ema<-function(v,n,a){
  # v: a data vector
  # n: a scalar constant
  # a: a vector length v of contants
  expt<-c(0:(n-1))
  as<-c(1-a)
  avevec<-c(as^expt)
  sum(avevec*v)/sum(avevec)
}
betaema<-function(v,n,a,l){
  # v: a data vector
  # n: a vector length v of contants
  # a: a vector length v of contants
  # l: a contant, the first value that can have a moving average
  secondvec<-c(rep(0, (length(v)-l)))
  for(i in l:(length(v)-l)){
    secondvec[i+1-l]<-ema(v[(i-n[i]+1):i],n[i],a[(i-n[i]+1):i])
  }
  secondvec
}
#################################################################################################################
howright<-function(v,r,c,l){
  # v: a data vector
  # r: a data vector
  # c: a constant
  # l: a contant, the first value that can have a signal
  v2<-v[1:(length(v)-c)]
  returns2<-r[l+1+c:(length(v)-1)]
  fc <- rep(1/c, c)
  returnav <- filter(returns2, fc, sides=1)
  tot<-v2*returnav
  length(tot[which(tot>0)])/length(tot)
}
#################################################################################################################
percentcorrect<-function(ca1,ca2,cn1,cn2,e,d,c,v,p,r){
  # ca1: a constant
  # ca2: a constant
  # cn1: a constant
  # cn2: a constant
  # e:   a constant
  # d:   a constant
  # c:   a constant
  # v:   a data vector
  # p:   a data vector
  # r:   a data vector
  als<-c(voltoalph(v,ca1))
  als2<-c(voltoalph(v,ca2))
  n1<-c(voltoenen(v,cn1))
  n2<-c(voltoenen(v,cn2))
  mix<-max(cn1,cn2)
  mox<-max(d,e)
  anotherema1<-betaema(p,n1,als,mix)
  anotherema2<-betaema(p,n2,als2,mix)
  shift1<-c(anotherema1[1:(length(anotherema1)-d)])
  shift2<-c(anotherema2[1:(length(anotherema2)-e)])
  slope1h<-c(anotherema1[(1+d):length(anotherema1)]-shift1)
  slope2h<-c(anotherema2[(1+e):length(anotherema2)]-shift2)
  slope1<-c(slope1h/d)
  slope2<-c(slope2h/e)
  sig<-c(slope1-slope2)
  hvec<-howright(sig,r,c,(mix+mox))
  hvec
}
system.time(percentcorrect(.3,.6,100,200,5,5,1,v,p,r))
##########################################################################################
correcttot<-function(v,p,r){
  # v:   a data vector
  # p:   a data vector
  # r:   a data vector
  correct3<-array(0,dim=c(10,10,10,10,10,10,10))
  for(i in 1:10){
    for(j in 1:10){
      for(k in 1:10){
        for(l in 1:10){
          for(m in 2:10){
            for(n in 2:10){
              for(o in 1:10){
                correct3[i,j,k,l,m,n,o]<-percentcorrect((i/10),(j/10),(20*k),(20*l),m,n,o,v,p,r)
              }
            }
          }
        }
      }
    }
  }
  print(correct3)
}
newvec2<-correcttot(v,p,r)
which(newvec2==max(newvec2),arr.ind=TRUE)


texts: Try/catch block inside a method that returns String

texts:
Is this try/catch block written correctly?

public String execute() throws Exception{
    try{
        //Do blah
        return "success"; //Assuming everything goes well, return success.
    }catch (Exception e){
        e.printStackTrace();
    }
    return "error";
}

Should the return "error" be inside the catch clause?


texts: Create a stack implementation that handles the multi thread scenario

texts:
MyStack.h

@interface MyStack : NSObject

- (id)pop;
- (void)pushObject:(id)object;

@end

MyStack.m

@interface MyStack ()

@property (atomic) NSMutableArray *stackArray;

@end

@implementation MyStack

- (instancetype)init {
    self = [super init];
    if (self != nil)
    {
        _stackArray = [NSMutableArray new];
    }
    return self;
}

- (id)pop {
    id obj = nil; // can return statements be part of critical sections themselves?
    @synchronized(self) {
        if ([self.stackArray count] != 0) {
            obj = [self.stackArray lastObject];
            self.stackArray = [[self.stackArray mutableCopy] removeLastObject];
        }
    }
    return obj;
}

- (void)pushObject:(id)object {
    @synchronized(self) {
        [self.stackArray addObject:object];
    }
}

@end


texts: Displaying a table using DataTables and AngularJS

texts:
I am using DataTables to format and display a table. I started the project using AngularJS with a PHP backend but I needed to inject some Vanilla JS and JQuery code in order to use DataTables.

Is this approach/organization fine, or should I be trying to use AngularJS modules like ngTable to keep the project "pure".

AngularJS + JQuery snippet for pulling data in DataTable

$http.post('requests.php', data, config).then(
function(response) {
        var df = response.data['data'];

        // Put data into table
        $("#UserTable").DataTable( {
            pagingType: "full_numbers",
            processing : true,
            data: df,
            order: [[ 0, "desc" ]],
            columns:
       [
          { data: "user" },
          { data: "name" }
       ]
    } );
});

PHP BACKEND

if (isset($params['req']) && $params['req'] == "users") {

  $json = array();
  foreach ($cma_DB->query($sql) as $row) {

  //  MAKE ARRAY ASSOCIATIVE; THIS WAS BROKEN IN OTHER VERSIONS OF DATATABLES

    $json[] = array(
      'user'  => $row['user'],
      'name'  => $row['first_name'] . " " . $row['last_name']
    );
  }
    // MAKE RESPONSE HAVE 'data' ENTRY //
    $response = array();
    $response['success'] = true;
    $response['data'] = $json;

    echo json_encode($response);
}

VERSUS

Something written using ngTable


texts: A function for parsing words from a string without using whitespace

texts:
I'm trying to parse words from a badly garbled text file that contains many repeats. It's about 100k characters in length and was formed from joining many substrings in alphabetical order.

I'm curious about other methods for finding words without using whitespace.

def unique_words(string):
    words = dict()
    p1 = 0 # String slice position 1
    p2 = 1 # String slice position 2
    len_string = len(string)
    while p2 < len_string:
        p2 += 1
        sub1 = string[p1:p2] # A shorter sub
        sub2 = string[p1:(p2 + 1)] # A longer sub
        sub1_count = string.count(sub1) # Counts the frequency of the shorter sub
        sub2_count = string.count(sub2) # Counts the frequency of the longer sub
        if sub2_count * len(sub2) < sub1_count * len(sub1): # True if the frequency of sub1 * its length is greater
            words[sub1] = ('') # Add
            p1 = p2
    return words

The above code works when the number of unique words is small but fails when it is large. I've used the website TextMechanic to generate a random string like

'updownleftupdowndownleftupleftrightupdownleftup'

and the above code returns a dictionary exactly as desired:

{'up': '', 'down': '', 'left': '', 'right': ''}

Here's the problem:

When the number of unique words increases, there is a point where the occurrence of single letters out numbers the total character count of any word in a string.

My current solution uses the algorithm on short slices of the original string, but this involves trial-and-error and has artifacts.


texts:
I wrote the following groovy function for taking a string of multiple lines (or any other character for splitting the code into parts), and bringing each line/part to a specified number of characters, cutting too long lines and filling up too short lines with a fill character:

static final String adjustLineLength(Integer length, String filler, String token, String source) {
    source
    .tokenize(token)
    .collect{ String line ->
        if(line.size() > length)
            line.substring(0, length)
        else if(line.size() < length)
            line + (filler * (length - line.size()))
        else
            line
    }
    .join(token)
}

Is that a good approach? Any suggestions how this code can be improved in concerns of making it more easy to understand and maybe (but that has not priority over beeing easy to understand) improving performance?


texts: Sort a linked-list with only three distinct values

texts:
I am trying to solve this problem. The problem is to sort a linked list containing only 0s, 1s and 2s by changing their links.

  Sort a linked list of 0s, 1s and 2s by changing links Given a linked
  list of 0s, 1s and 2s, sort it.

  Examples:

  Input  : 2->1->2->1->1->2->0->1->0 Output : 0->0->1->1->1->1->2->2->2

  Input : 2->1->0 Output : 0->1->2

Here is my code:

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

typedef struct node* Node;
struct node
{
  int data;
  struct node* next;
};

void addnode(Node* head, int data)
{
  Node temp = (Node)malloc(sizeof(struct node));
  temp->data = data;
  temp->next = NULL;
  if( *head == NULL )
  {
      *head = temp;
      return;
  }
  Node p =(Node)malloc(sizeof(struct node));
  p = *head;
  while( p->next != NULL )
  {
    p = p->next;
  }
  p->next = temp;
}

void display(Node head)
{
  Node p =(Node)malloc(sizeof(struct node));
  p = head;
  while( p != NULL )
  {
    printf("%d ", p->data);
    p = p->next;

  }
}

void zeroonetwo(Node* head)
{
  if( *head == NULL )
  {
    return;
  }
  Node zero = (Node)malloc(sizeof(struct node));
  Node one = (Node)malloc(sizeof(struct node));
  Node two = (Node)malloc(sizeof(struct node));
  zero = NULL;
  one = NULL;
  two = NULL;
  Node p = (Node)malloc(sizeof(struct node));
  p = *head;

  Node temp1 = (Node)malloc(sizeof(struct node));
  Node temp2 = (Node)malloc(sizeof(struct node));
  Node temp3 = (Node)malloc(sizeof(struct node));
  temp1 = NULL;
  temp2 = NULL;
  temp3 = NULL;

  while( p != NULL  )
  {
    if( p->data == 0 )
    {
      if( temp1 == NULL )
      {
          temp1 = p;
          zero = temp1;
      }
      else
      {
          temp1->next = p;
          temp1 = temp1->next;
      }
    }

    else if( p->data == 1  )
    {
      if( temp2 == NULL )
      {
          temp2 = p;
          one = temp2;
      }
      else
      {
          temp2->next = p;
          temp2 = temp2->next;
      }

    }
    else
    {
        if( temp3 == NULL )
        {
            temp3 = p;
            two = temp3;
        }
        else
        {
            temp3->next = p;
            temp3 = temp3->next;
        }
    }

    p = p->next;
  }

  if( zero != NULL && one != NULL && two != NULL )
  {
    *head = zero;
    temp1->next = one;
    temp2->next = two;
    temp3->next = NULL;

  }
  else if( zero == NULL && one != NULL && two != NULL )
  {
    *head = one;
    temp2->next = two;
    temp3->next = NULL;
  }
  else if( zero == NULL && one == NULL && two != NULL )
  {
    *head = two;
    temp3->next = NULL;
  }
  else if( zero != NULL && one == NULL && two != NULL )
  {
    *head = zero;
    temp1->next = two;
    temp3->next = NULL;
  }
  else if( zero != NULL && one == NULL && two == NULL )
  {
    *head = zero;
    temp1->next = NULL;
  }
  else if( zero == NULL && one != NULL && two == NULL )
  {
    *head = one;
    temp2->next = NULL;
  }
  else
  {
    *head = zero;
    temp1->next = one;
    temp2->next = NULL;
  }

}

int main()
{
  int N;
  scanf("%d", &N);
  Node head = (Node)malloc(sizeof(struct node));
  head = NULL;
  for(int i = 0; i < N; i++)
  {
    int data;
    scanf("%d", &data);
    addnode(&head, data);
  }
  zeroonetwo(&head);
  display(head);
}

But I believe the code can be shortened. The 8 checks to check NULL for zero, one and two seem redundant. I would really appreciate if you someone could provide me suggestions and point any bugs if any exist.


texts:
I'm learning Lua. I decided to make a simple plain PPM decoder/encoder without error checks to familiarize myself with the language. I would appreciate any feedback on how could I make the following code simpler, shorter, more elegant and readable.

-- Load/save plain PPMs without error checking; img[img.w][img.h].r=img.maxVal
-- sets the red channel of pixel at the top-right corner to the reddest value

local p3 = {}

function p3.load(path)
    local file = io.open(path)
    local data = file:read('a')
    file:close()
    data = data:gsub('#[^\n]*', ' ') -- remove comments
    local w, h, maxVal = data:match('P3'..('%s*(%d+)'):rep(3))
    w, h, maxVal = tonumber(w), tonumber(h), tonumber(maxVal)
    data = data:sub(#data:match('P3'..('%s*%d+'):rep(3)) + 1) -- remove header
    local img = { w = w, h = h, maxVal = maxVal }
    for x = 1, w do
        img[x] = {}
        for y = 1, h do
            img[x][y] = {}
        end
    end
    local channels = { 'r', 'g', 'b' }
    local startIndex, endIndex = 1, 1
    for y = h, 1, -1 do
        for x = 1, w do
            for _, ch in ipairs(channels) do
                startIndex, endIndex = data:find('%d+', startIndex)
                img[x][y][ch] = tonumber(data:sub(startIndex, endIndex))
                startIndex = endIndex + 1
            end
        end
    end
    return img
end

function p3.save(img, path)
    local file = io.open(path, 'w')
    file:write('P3\n', img.w, ' ', img.h, '\n', img.maxVal, '\n')
    for y = img.h, 1, -1 do
        for x = 1, img.w do
            file:write(img[x][y].r, ' ', img[x][y].g, ' ', img[x][y].b, '\n')
        end
    end
    file:close()
end

return p3


texts: Nicer way to check if string contains all words from an array

texts:
Currently I check whether a string contains all words from an array like this:

function contains($string, array $array) {
    $count = 0;
    foreach($array as $value) {
        if (false !== stripos($string,$value)) {
            ++$count;
        };
    }
    return $count == count($array);
}

Example call:

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');

if (contains($string, $array)) {
    print 'This is true for the given example';
}

I wonder whether a more elegant, faster or even built-in way exists to improve this?


texts: proper structure of classes using interface classes

texts:
Given the following two interfaces what would the proper way to set up the two actual classes?

public interface IPortfolio
{
    string FirstName { get; set; }
    string LastName { get; set; }
    string Name { get; set; }
    int Id { get; set; }
    List<IDocument> Documents { get; set; }
}
public interface IDocument
{
    string ExtensionType { get; set; }
    int Id { get; set; }
    DateTime? DateFiled { get; set; }
    int? Size { get; set; }
    int? SortOrder { get; set; }
}

The actual classes:

 public class Portfolio : IPortfolio
{
    public Portfolio()
    {
        Documents = new List<IDocument>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Name { get; set; }
    public int Id { get; set; }
    public List<IDocument> Documents { get; set; }
}

public class Document : IDocument
{
     public Document()
     {
       Pages = new List<IPage>();
     }
     public string ExtensionType { get; set; }
     public int Id { get; set; }
     public DateTime? DateFiled { get; set; }
     public int? Size { get; set; }
     public List<IPage> Pages { get; set; }
     public int? SortOrder { get; set; }
}

When using the code above I get an error about not being able to implicitly convert List<Document> to List<IDocument>

This is a learning project to understand the concept of Interfaces and how they should best be used.


texts: Print out N by N Spiral Matrix in javascript

texts:
I got this question during my practice interview.
Matrices - N Spiral Matrix
Prompt
Given an integer N, output an N x N spiral matrix with integers 1 through N.
Examples:
Input:  3

Output: [[1, 2, 3],
         [8, 9, 4],
         [7, 6, 5]]

Input: 1

Output: [[1]]

My solution is below:
function spiralMatrix(n) {
  const matrix = [];
  let counter = 1,
    rowMin = 0,
    rowMax = n - 1,
    colMin = 0,
    colMax = n - 1;

  for (let i = 0; i < n; i++) {
    matrix.push(new Array(n).fill(0));
  }

  while (rowMin <= rowMax && colMin <= colMax) {
    for (let col = colMin; col <= colMax; col++) {
      matrix[rowMin][col] = counter++;
    }
    rowMin++;
    for (let row = rowMin; row <= rowMax; row++) {
      matrix[row][colMax] = counter++;
    }
    colMax--;
    for (let col = colMax; col >= colMin; col--) {
      matrix[rowMax][col] = counter++;
    }
    rowMax--;
    for (let row = rowMax; row >= rowMin; row--) {
      matrix[row][colMin] = counter++;
    }
    colMin++;
  }

  return matrix;
}

console.log(spiralMatrix(10));


texts: Calculating reverse dependencies of a Debian package

texts:
It works pretty well, but I suspect there's too many variables, and I wonder what else.

I'm using this library: Python APT.

#!/usr/bin/env python3

import argparse
import apt

def getdeps(deptype, pkg, otherpkg):
    deps = list()
    name = otherpkg.shortname
    otherpkg = otherpkg.candidate
    for deplist in otherpkg.get_dependencies(deptype):
        for dep in deplist.or_dependencies:
            if dep.name == pkg.shortname:
                deps.append(name)
    return deps

def reverse_dependencies(pkg):
    """Which packages have some kind of dependency on the given package"""

    cache = apt.cache.Cache()
    try:
        pkg = cache[pkg]
    except KeyError as e:
        print(str(e).strip('"'))
        return 1

    dependents = dict()
    recommends = list()
    suggests = list()
    replaces = list()
    enhances = list()
    depends = list()

    for key in cache.keys():
        otherpkg = cache[key]
        depends.append(getdeps("Depends", pkg, otherpkg))
        recommends.append(getdeps("Recommends", pkg, otherpkg))
        suggests.append(getdeps("Suggests", pkg, otherpkg))
        replaces.append(getdeps("Replaces", pkg, otherpkg))
        enhances.append(getdeps("Enhances", pkg, otherpkg))

    dependents["Depends"] = depends
    dependents["Recommends"] = recommends
    dependents["Suggests"] = suggests
    dependents["Replaces"] = replaces
    dependents["Enhances"] = enhances

    for deptype, deps in dependents.items():
        deps_output = list()
        for match in deps:
            if match:
                for item in match:
                    deps_output.append(item)
        if deps_output:
            print(deptype.upper(), end=": ")
            print(" ".join(deps_output))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("pkg", help="pkg to describe")
    args = parser.parse_args()
    reverse_dependencies(args.pkg)

Example terminal session:

$ ./rdeps.py python3-apt
DEPENDS: python3-apt-dbg wajig
ENHANCES: python-apt-common


texts: Executing two database queries concurrently in Go

texts:
I would like to execute two database queries concurrently for quicker response time. Since channels seemed to be too verbose, I came up with the solution below. However, I'm not very confident about it and wanted to head your opinion and ask if there is a better solution for this. Thank you.

go
var persistedOrganization models.Organization
var persistedProjects []models.Project

var fetchOrganizationError error
var fetchProjectsError error

var wg sync.WaitGroup

wg.Add(2)

go func() {
    persistedOrganization, fetchOrganizationError = organization.FindOne(bson.M{"_id": persistedUser.OrganizationID})
    wg.Done()
}()

go func() {
    persistedProjects, fetchProjectsError = project.Find(bson.M{"organizationId": persistedUser.OrganizationID})
    wg.Done()
}()

wg.Wait()

if fetchOrganizationError != nil || fetchProjectsError != nil {
    // Handle error
}


texts: Get ProductCode from MSI File using DTF in C#

texts:
I've created this function to grab the MSI ProductCode from the MSI file itself. i couldn't find any native method for it. So I've implemented it the following way:

public static string GetMSIProductCode(string msiFile)
{
    string _result = null;
    string productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
    Session product = Installer.OpenPackage(msiFile, true);
    Database msiDB = product.Database;
    View msiView = msiDB.OpenView(productCodeQuery);
    msiView.Execute();
    Record _record = msiView.Fetch();
    _result = _record.GetString(2);
    msiView.Close();
    msiDB.Dispose();
    return _result;
}

Would you do it any different?

Thanks.


texts: Efficiently calculate value of Pascal's Triangle using memoization and recursion(updated)

texts:
Follow up to Efficiently calculate value of Pascal's Triangle using memoization and recursion
Based on feedback given by jvwh in the answers
def pascal(c: Int, r: Int): Int = {
  if (c < 0 || r < 0 || c > r) throw new IllegalArgumentException()
  // use a cache; map (c,r) pair to value
  // fill in value recursively
  val cache: mutable.Map[(Int, Int), Int] =
    (0 to r).flatMap(n => Seq((0, n) -> 1, (n, n) -> 1))
    .to(collection.mutable.Map)

  def getPascalValue(c: Int, r: Int): Int =
    cache.getOrElseUpdate((c,r), getPascalValue(c, r-1) +
      getPascalValue(c-1, r-1))

  getPascalValue(c,r)
}

Adds obvious handling of invariants, flatMap method to populate the edges with 1 values rather then a for loop. Key difference is it uses a mutable map that saves previous values. Run time for pascal(5, 105) dropped from around 20s to 3ms. Pretty happy with the efficiency but more feedback is definitely welcome


texts: Creating enchantment objects based on configuration

texts:
I'm searching a way to literally shorten my code.
For the moment my code is this;

    if(getDashConfig().getBoolean("enchantments.multifirearrow.enabled")){
        MultiFireArrow fire = new MultiFireArrow();
        DashEnchant.getEnchants().put(1, fire);
        DashEnchant.getStringEnchants().put("multifirearrow", fire);
        if(debug()){
            getLogger().info("MultiFireArrow enchant registred");
        }
    if(getDashConfig().getBoolean("enchantments.bolt.enabled")){
        Bolt bolt = new Bolt();
        DashEnchant.getEnchants().put(2, bolt);
        DashEnchant.getStringEnchants().put("bolt", bolt);
        if(debug()){ getLogger().info("Bolt enchant registred"); }
        }
    if(getDashConfig().getBoolean("enchantments.randomspeed.enabled")){
        SpeedRandom speed = new SpeedRandom();
        DashEnchant.getEnchants().put(3, speed);
        DashEnchant.getStringEnchants().put("randomspeed", speed);
        if(debug()){ getLogger().info("RandomSpeed enchant registred"); }

Not that presentable.. uh?
How i would literally shorten it? I don't want 350 lines like that.


texts: Universal nested get/set for trees in Python

texts:
Based on this source, I've made the following universal get / set function, to make it possible to work on OrderedDict trees for example.

def nested_expand_and_get(d, keys):
    intermediate = d
    for key in keys:
        intermediate = intermediate.setdefault(key, d.__class__())
    return intermediate

def nested_set(d, keys, value):
    intermediate = nested_expand_and_get(d, keys[:-1])
    intermediate[keys[-1]] = value

I've tested it on some examples I could come up with, but I'm not sure in two things:

I've simplified quite a bit from the linked source, namely, I'm not using lambdas and I've removed the if line.
I've also introduced the tree type auto-detection, which I believe should work well for uniform trees.

Is this function correct as long as the given tree is uniform (by which I mean that it only contains all dict or OrderedDict or etc. elements)?
Would you recommend using something else for working on ordered trees (without external libs)?


texts:
Is there anything what could be improved on this code?

def factorial(n: Int, offset: Int = 1): Int = {
    if(n == 0) offset else factorial(n - 1, (offset * n))
}

The idea is to have tail-recursive version of factorial in Scala, without need to define internal function or alias.

This one is callable like this:

factorial(4)

So final solution looks like this:

import scala.annotation._

@tailrec
def factorial(n: Int, accumulator: Long = 1): Long = {
    if(n == 0) accumulator else factorial(n - 1, (accumulator * n))
}


texts:
Is this the best way to reverse a singly-linked list? Can it be done with two, or fewer pointers? Any other comments?

public class ReverseLL {
    Node start;
    ReverseLL()
    {
        start=null;
    }
    class Node
    {
        Node next;
        int data;

        Node(int newData)
        {
            next=null;
            data=newData;
        }
        public void setData(int newData)
        {
            data=newData;
        }
        public int getData()
        {
            return data;
        }
        public void setNext(Node n)
        {
            next=n;
        }
        public Node getNext()
        {
            return next;
        }

    }
    public void insert(int newData)
    {
        Node p=new Node(newData);
        if(start==null)
        {
            start=p;
        }
        else
        {
            Node temp=start;
            while(temp.getNext()!=null)
            {
                temp=temp.getNext();
            }
            temp.setNext(p);
        }
    }

    public void reverse()
    {
        Node temp=start;
        Node previous=null;
        Node previous1=null;
        while(temp.getNext()!=null)
        {
            if(temp==start)
            {
                previous=temp;
                temp=temp.getNext();
                previous.setNext(null);
            }
            else
            {
                previous1=temp;
                temp=temp.getNext();
                previous1.setNext(previous);
                previous=previous1;
            }
        }
        temp.setNext(previous);
        start=temp;
    }
    public void display() {
        int count = 0;

        if(start == null) {
            System.out.println("\n List is empty !!");
        } else {
            Node temp = start;

            while(temp.getNext() != null) {
                System.out.println("count("+count+") , node value="+temp.getData());
                count++;
                temp = temp.getNext();
            }
            System.out.println("count("+count+") , node value="+temp.getData());
        }
    }
    public static void main(String args[])
    {
        ReverseLL ll=new ReverseLL();
        ll.insert(1);
        ll.insert(2);
        ll.insert(3);
        ll.insert(4);
        ll.insert(5);
        ll.insert(6);
        ll.insert(7);
        ll.insert(8);
        ll.display();
        System.out.println();
        ll.reverse();
        ll.display();
    }
}


texts: Given two Binary trees, find whether the second is a sub tree of the first

texts:
Given two binary trees, you have to find whether the second is a sub tree of the first.

First attempt (brute force):

int issubtree(tree *tree1p, tree * tree2p)
{
    if (tree2p == NULL)
        return 1;

    if (tree1p == NULL)
        return 0;

    if (tree1p->data == tree2p->data)
        return (issubtree(tree1p->leftp,tree2p->leftp)
                && (issubtree(tree1p->leftp,tree2p->leftp));
    else
        return (issubtree(tree1p->leftp,tree2p) || (issubtree(tree1p->rightp,tree2p));
}

Please give feedback on correctness more efficient code.


texts: Dataset Copy, Change, then Write new Rows back

texts:
I have this code, but I think it is too clumsy. It feels like a 12 point turn, is there a way to optimize it?

Please note that this generates new rows from existing rows.

//Create New Dataset
DataSet myDataSet = new DataSet();
DataTable myDataTable = myDataSet.Tables.Add("Temp");
myDataTable.Columns.Add("ID");
myDataTable.Columns.Add("JobNumber");
myDataTable.Columns.Add("DirectoryName");
myDataTable.Columns.Add("DrawingName");
myDataTable.Columns.Add("DateAdded");
myDataTable.Columns.Add("LastAccessedDate");
myDataTable.Columns.Add("LastAccessedUserName");
myDataTable.Columns.Add("ClientName");
myDataTable.Columns.Add("ContentType");
myDataTable.Columns.Add("Description");

//Read From Database
nexusDBDataSet.Drawing_Table.Clear();
drawing_TableTableAdapter.FillByJobNumber(nexusDBDataSet.Drawing_Table, OldJobcardNumber);
foreach (DataRow myRow in nexusDBDataSet.Drawing_Table.Rows)
{
    //Read from database
    string DirectoryName = myRow["DirectoryName"].ToString();
    string DrawingName = myRow["DrawingName"].ToString();
    string DateAdded = myRow["DateAdded"].ToString();
    string LastAccessedDate = myRow["LastAccessedDate"].ToString();
    string LastAccessedUserName = myRow["LastAccessedUserName"].ToString();
    string ClientName = myRow["ClientName"].ToString();
    string ContentType = myRow["ContentType"].ToString();
    string Description = myRow["Description"].ToString();

    //write to temp data table
    DataRow DrawingDataRow = myDataTable.NewRow();
    DrawingDataRow["JobNumber"] = NewJobcardNumber;
    DrawingDataRow["DirectoryName"] = DirectoryName.Replace("\\" + OldJobcardNumber + "\\", "\\" + NewJobcardNumber + "\\");
    DrawingDataRow["DrawingName"] = DrawingName;
    DrawingDataRow["DateAdded"] = DateAdded;
    DrawingDataRow["LastAccessedDate"] = LastAccessedDate;
    DrawingDataRow["LastAccessedUserName"] = LastAccessedUserName;
    DrawingDataRow["ClientName"] = ClientName;
    DrawingDataRow["ContentType"] = ContentType;
    DrawingDataRow["Description"] = Description;
    myDataTable.Rows.Add(DrawingDataRow);

}

//Refresh DataBase
nexusDBDataSet.Drawing_Table.Clear();
drawing_TableTableAdapter.Fill(nexusDBDataSet.Drawing_Table);

foreach (DataRow myRow in myDataTable.Rows)
{
    //read from temp data table
    string JobNumber = myRow["JobNumber"].ToString();
    string DirectoryName = myRow["DirectoryName"].ToString();
    string DrawingName = myRow["DrawingName"].ToString();
    string DateAdded = myRow["DateAdded"].ToString();
    string LastAccessedDate = myRow["LastAccessedDate"].ToString();
    string LastAccessedUserName = myRow["LastAccessedUserName"].ToString();
    string ClientName = myRow["ClientName"].ToString();
    string ContentType = myRow["ContentType"].ToString();
    string Description = myRow["Description"].ToString();

    //Write back to DataBase
    DataRow DrawingDataRow = nexusDBDataSet.Drawing_Table.NewRow();
    DrawingDataRow["JobNumber"] = JobNumber;
    DrawingDataRow["DirectoryName"] = DirectoryName;
    DrawingDataRow["DrawingName"] = DrawingName;
    DrawingDataRow["DateAdded"] = DateAdded;
    DrawingDataRow["LastAccessedDate"] = LastAccessedDate;
    DrawingDataRow["LastAccessedUserName"] = LastAccessedUserName;
    DrawingDataRow["ClientName"] = ClientName;
    DrawingDataRow["ContentType"] = ContentType;
    DrawingDataRow["Description"] = Description;

    nexusDBDataSet.Drawing_Table.Rows.Add(DrawingDataRow);
}

myDataSet.Dispose();
//Updating
this.Validate();
drawing_TableBindingSource.EndEdit();
tableAdapterManager.UpdateAll(nexusDBDataSet);
RefreshData();


texts:
My code works but would take 160 days to run lol.

#prime factors - ex.3

primes = []
for possibleprime in range (2,100000,1):
    isPrime = True
    for num in range(2, possibleprime, 1):
        if possibleprime % num == 0:
            isPrime = False

    if isPrime:
        primes.append(possibleprime)

#print(primes)

def prime(n):
    prime_factors = []
    n = int(n)
    for x in primes:
        if n % x == 0:
            prime_factors.append(x)
    return prime_factors

# n = 13195
# print(prime(n))

n = 600851475143
print(prime(n))


texts:
Can you please provide some improvement advice for the following function?
It is working OK now, but as I have zero experience with PHP I guess there is a lot of room for improvement.

function addNewUser($ES_Client, $username, $password, $fullname, $email, $function, $department, $access){
    auditLog($ES_Client, "Creating new user: ".$username.", ".$fullname.", ".$email.", ".$function.", ".$department.", ".$access);
    $checkIfUserExists = getUserDetails($ES_Client,$username)['hits']['total'];
    if($checkIfUserExists != 0){
        auditLog($ES_Client, "User ".$username." already exists! Operation aborted.");
        return -1;
    } else {
        $hashed_password = crypt($password);
        $userAddQuery= [
            'index' => 'system',
            'type' => 'users',
            'body' => [
                'username' => $username,
                'password' => $hashed_password,
                'fullname' => $fullname,
                'email' => $email,
                'function' => $function,
                'department' => $department,
                'access' => $access,
                'lastlogin' => round(microtime(true) * 1000)
            ]
        ];
        try{
            $userAddResponse = $ES_Client->index($userAddQuery);
            if($userAddResponse['created'] == 1)
            {
                auditLog($ES_Client, "User ".$username." added successfully!");
                return 0;
            }
            else{
                auditLog($ES_Client, "Error adding user ".$username."! Did not receive acknowledgement from elastic.");
                return -1;
            }
        } catch(Exception $e) {
            auditLog($ES_Client, "Error adding user ".$username."! ".$e->getMessage());
            return -1;
        }
    }
}


texts: Is it ok to have NaN while comparing fields in JavaScript?

texts:
I am comparing two integer values, but there is chance of parseInt giving NaN. I would like to know if I need to do any additional checks.

var txtFromCustomerId = document.getElementById(FROMCUSTOMERID_FIELDNAME);
var txtToCustomerId = document.getElementById(TOCUSTOMERID_FIELDNAME);

if (txtFromCustomerId  != null && txtToCustomerId != null) {
    var fromCustomerId = parseInt(txtFromCustomerId.value);
    var toCustomerId = parseInt(txtToCustomerId.value);

    if (fromCustomerId > toCustomerId) { <---There is chance of parseInt giving Nan
        //some other stuff
    }
}


texts: Credit card verification: string conversion most optimal?

texts:
Below is some code which verifies a credit card number using the checksum as well as check if number of digits are appropriate as well if digits start with right numbers. I am not sure if converting the double into a string was the best bet. I wasn't going to at first but had trouble figuring out the modulo math to get every second digit without knowing the length of the double (# of digits).

Also, in my use of strtok(), what should I be doing with the balance of the string after the delimiter? Is that hanging out in memory somewhere?

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

int main(void)
{
    double cardnumber;
    printf("Give me a number: \n");
    scanf("%lf", &cardnumber);

    if(cardnumber < 1000000000000 || cardnumber > 10000000000000000)
    {
        printf("INVALID\n");
        return 0;
    }
    if(cardnumber < 100000000000000 && cardnumber > 9999999999999)
    {
        printf("INVALID\n");
        return 0;
    }

    char creditcard[17];
    sprintf(creditcard, "%f", cardnumber);
    char* ptr_cc;
    ptr_cc = strtok(creditcard,".");
    int card_size = strlen(ptr_cc);
    int sum = 0;
    for(int i = 1; i < card_size; i+=2)
    {
        int x = creditcard[card_size-1-i] - '0';
        int prod = 2 * x;
        if(prod>=10)
        {
            prod = prod%10 + prod/prod%10;
        }
        sum += prod;
    }
    for(int i = 0; i < card_size; i+=2)
    {
        int x = creditcard[card_size-1-i] - '0';
        sum += x;
    }
    if(sum%10 != 0)
    {
        printf("INVALID\n");
        return 0;
    }
    else if(creditcard[0] == '4')
    {
        printf("VISA\n");
        return 0;
    }
    else if(creditcard[0] == '3' && (creditcard[1] == '7' || creditcard[1] =='4'))
    {
        printf("AMEX\n");
        return 0;
    }
    else if(creditcard[0] == '5' && (creditcard[1] >='1' && creditcard[1] <='5'))
    {
        printf("MASTERCARD\n");
        return 0;
    }
    else
    {
        printf("INVALID\n");
        return 0;
    }
}


texts:
I think we all know the game of Scrabble and how popular it is as a simple programming challenge. Here's my attempt at computing a Scrabble score for a given word done in Go.

I must admit, I'm fairly new to Go (been learning it for a week or so). Having said that, I'd greatly appreciate all sorts of tips for improving not only the solution itself but also the style to be more Go-ish.

I've used golint and gofmt on this, but with gofmt I'm not sure I use it correctly, as it simply prints out the code to stdout.

There's a simple test suit that comes along with the solution.

// Package scrabble deals with proper word score counting
package scrabble

import "strings"

// countScore returns a score map per given word
func countScore() map[rune]int {
    var scoreMap = map[string]int{
    "aeioulnrst": 1,
    "dg":         2,
    "bcmp":       3,
    "fhvwy":      4,
    "k":          5,
    "jx":         8,
    "qz":         10,
    }
    var actualScore = make(map[rune]int)
    for letters, score := range scoreMap {
        for _, letter := range letters {
            actualScore[letter] = score
        }
    }
    return actualScore
}

// Score count Scrabble score
func Score(word string) (score int) {
    for _, char := range strings.ToLower(word) {
        score += countScore()[char]
    }
    return
}

As for the solution, I've noticed it's kinda slow. What's more, it takes  over 600 allocs/op. That's a lot for such a simple task. Why is that?

package scrabble

import "testing"

func TestScore(t *testing.T) {
    for _, test := range scrabbleScoreTests {
        if actual := Score(test.input); actual != test.expected {
            t.Errorf("Score(%q) expected %d, Actual %d", test.input, test.expected, actual)
        }
    }
}

func BenchmarkScore(b *testing.B) {
    for i := 0; i < b.N; i++ {
        for _, test := range scrabbleScoreTests {
            Score(test.input)
        }
    }
}

Test cases:

package scrabble

type scrabbleTest struct {
    input    string
    expected int
}

var scrabbleScoreTests = []scrabbleTest{
    {"a", 1},                           // lowercase letter
    {"A", 1},                           // uppercase letter
    {"f", 4},                           // valuable letter
    {"at", 2},                          // short word
    {"zoo", 12},                        // short, valuable word
    {"street", 6},                      // medium word
    {"quirky", 22},                     // medium, valuable word
    {"OxyphenButazone", 41},            // long, mixed-case word
    {"pinata", 8},                      // english-like word
    {"", 0},                            // empty input
    {"abcdefghijklmnopqrstuvwxyz", 87}, // entire alphabet available
}


texts: Implementation similar to boost::optional for modelling function failure

texts:
The idea being you can have a simple type called maybe that wraps another type, which provides the ability to possibly not return a value from a function.  I'm sure it's not perfect yet, but it's got the broad strokes I'm looking for.  I'm mostly looking for corner cases I've missed and anything else I've overlooked.

#ifndef MAYBE_H_
#define MAYBE_H_

#include <exception>

namespace {
    // implementation enabled for non-reference types
    template <class T>
    struct maybe {
        maybe()             : valid(false) {}       // default constructor

        maybe(const T& val) : valid(true)  {        // contructor from wrapped value
            new ((void*)storage) T(val);
        }

        maybe(const maybe &other) {                 // copy constructor
            valid = other.valid;
            if (valid) {
                new ((void*)storage) T(other.get_ref());
            }
        }

        maybe(maybe &&other) : maybe() {            // move constructor
            std::swap(valid,   other.valid);
            std::swap(storage, other.storage);
        }

        ~maybe() {                                  // destructor
            if (valid) {
                get_ref().~T();
            }
        }

        // assignment operator, uses copy-and-swap trick
        maybe& operator =(maybe other) {
            swap(*this, other);
            return *this;
        }

        // type-coercion operator to get back to wrapped value
        // calling without checking validity causes bad_exception
        operator T&() {
            if (!valid) {
                throw std::bad_exception();
            }
            return get_ref();
        }

        // for checking validity of container
        explicit operator bool() { return valid; }
    private:
        bool valid;
        alignas(T) char storage[sizeof(T)];

        T& get_ref() const { return *static_cast<T*>((void*)storage); }
    };

    // implementation enabled for reference types
    template <class T>
    struct maybe<T&> {
        maybe()                   : valid(false)        value(nullptr)     {}
        maybe(T& val)             : valid(true),        value(&val)        {}
        maybe(const maybe &other) : valid(other.valid), value(other.value) {}

        operator T&() {
            if (!valid) {
                throw std::bad_exception();
            }
            return *value;
        }

        explicit operator bool() { return valid; }
    private:
        bool valid;
        T*   value;
    };
} // namespace {

#endif//MAYBE_H_


texts: Refactor multiple if-else conditions when condition is a minor change

texts:
I'm new programmer and I'm working on Xamarin MVVM app and I have a pin view like

So, basically  I have numbers from 0-9 if you pick one number its visible then if you pick a second one first one changed to * and I store all numbers into string called PinCode
ViewModel Code:
  public string PinCode { get; set; } = string.Empty;

        private async Task<bool> SelectedButton(Button button)
        {
            //If button is a number then
            if (button.Text != null)
            {
                if (PinCode.Length < 4)
                {
                    PinCode = PinCode + button.Text;

                    //Assign every number field text depending of PinCode length
                    if (PinCode.Length == 1)
                    {
                        PinNumberOne = button.Text;
                    }
                    else if (PinCode.Length == 2)
                    {
                        PinNumberTwo = button.Text;
                        PinNumberOne = "*";
                    }
                    else if (PinCode.Length == 3)
                    {
                        PinNumberThree = button.Text;
                        PinNumberOne = "*";
                        PinNumberTwo = "*";
                    }
                    else if (PinCode.Length == 4)
                    {
                        PinNumberFour = button.Text;
                        PinNumberOne = "*";
                        PinNumberTwo = "*";
                        PinNumberThree = "*";
                    }
                }
            }
            // if it's backspace button then
            else
            {
                PinCode = PinCode.Remove(PinCode.Length - 1);

                if (PinCode.Length == 3)
                {
                    PinNumberFour = "_";
                }
                else if (PinCode.Length == 2)
                {
                    PinNumberFour = "_";
                    PinNumberThree = "_";
                }
                else if (PinCode.Length == 1)
                {
                    PinNumberFour = "_";
                    PinNumberThree = "_";
                    PinNumberTwo = "_";
                }
                else if (PinCode.Length == 0)
                {
                    PinNumberFour = "_";
                    PinNumberThree = "_";
                    PinNumberTwo = "_";
                    PinNumberOne = "_";
                }
            }
            return true;
        }

As you can see, I have a lot of repeated code and I know it's possible to improve this method much better, but I can not find the way. If you guys have an idea of a recursion or how can I refactor this code to do something much clear and clean I really appreciate it. Regards


texts:
My problem is this: Given two strings, append them together and return the result. However, if the strings are different lengths, omit chars from the longer String so it is the same length as the shorter String. So "Hello" and "Hi" yield "loHi". The strings may be any length.
Is there a way to do it without using of StringBuilder like me:

public String equalConcatenation(String a, String b) {
  if(a.length() > b.length()){
    StringBuilder sb = new StringBuilder(a);
    sb.delete(0, (a.length() - b.length()));
    return sb.toString() + b;
  }
  StringBuilder sb = new StringBuilder(b);
  sb.delete(0, (b.length() - a.length()));
  return a + sb.toString();
}


texts: Javascript. Reverse order of words in string, but not special characters

texts:
Hello I am hoping someone can provide me feedback on my solution to this prob. If there are additional edge cases I should consider etc. Thank you!
The question: "Given a sentence with a set of delimiters, reverse the order of the words in the sentence and keep the delimiters in place."
let isAlpha = (char) => {
  let pat = /[a-zA-z]/igm;     // match any alphabetic character
  if(char.match(pat)){
      return true
  } else {
      return false
  }
}

function reverse(s){

  let specialArr = []

  for(ltr of s){
    if(!isAlpha(ltr)){                        // pull out all special characters in order
      specialArr.push(ltr)
    }
  }

  let regCharArr = s.split(/[^a-z]/ig).reverse()     // use split to pull out all words separated by non alpha characters. then reverse

  let result = []                                    // init result array

  if(isAlpha(s[0])){
    result = regCharArr.flatMap((val, idx) => [val, specialArr[idx]])   //use flatmap to combine the two arrays...if origin array starts with letter, combine special array into reg array
  }

  if(!isAlpha(s[0])){
    result = specialArr.flatMap((val, idx) => [val, regCharArr[idx]])    // vice versa
  }

  for(let i = 0; i < result.length; i++){         // remove any undefineds
    if(result[i] === undefined){
      result.splice(i, 1)
    }
  }
  return result.join('')
}

// let sentence = "one|twotwo/three:four"  // four|three/twotwo:one
let sentence = "|brian/steve:chris|jon"     // |jon/chris:steve|brian

console.log(reverse(sentence))

```


texts:
Problem

Implement a base N to base 10 (decimal) converter, where N is between 2 and 36 inclusive.

Implementation

Am I over-complicating things in calculateDecimalCharacterValue?

public class BaseToDecimalConverter {

  public static int convertToDecimal(int base, String input) {
    if (base < 2) {
      throw new IllegalArgumentException();
    }

    if (base > 36) {
      throw new IllegalArgumentException();
    }

    if (input == null) {
      throw new IllegalArgumentException();
    }

    int length = input.length();
    int sum = 0;
    for (int i = 0; i < length; i++) {
      int digitValue = calculateDecimalCharacterValue(input.charAt(i), base);
      sum += digitValue * Math.pow(base, length - 1 - i);
    }

    return sum;
  }

  public static int calculateDecimalCharacterValue(char c, int base) {
    if (base < 2) {
      throw new IllegalArgumentException();
    }

    if (base > 36) {
      throw new IllegalArgumentException();
    }

    if (Character.isDigit(c)) {
      int numericValue = Character.getNumericValue(c);
      if (numericValue < 0) {
        throw new IllegalArgumentException();
      }
      return numericValue;
    }

    if (Character.isAlphabetic(c) && base > 10) {
      int alphabetValue = Character.toUpperCase(c) - 'A' + 10;
      if (alphabetValue > base) {
        throw new IllegalArgumentException();
      }
      return alphabetValue;
    }

    throw new IllegalArgumentException();
  }
}


texts:
So this isn't EXACTLY my code but it is close enough to show what I have. Also the naming is only for this site so if its not really clear forgive me. Its much clearer in the actual code.

class Member(models.Model):
    team = models.IntegerField(default=0)
    match = models.ForeignKey(Match, null=True, blank=True)

    def engage(self, match_instance, team_number):
        self.match = match_instance
        self.team = team_number
        self.save()

class NPCGeneric(models.Model):
    speed = models.IntegerField(default=1)
    difficulty = models.IntegerField(default=0)

class NPCInstance(Member):
    generic = models.ForiegnKey(NPCGeneric);
    status = models.CharField(max_length=50)

    def engage(self, match_instance, team_number):
        new_instance = NPCInstance(generic=self)
        new_instance.save()
        return new_instance.engage(match_instance, team_number)

class Player(Member):
    name = models.CharField(max_length=100)

class Match(models.Model):
    event_members = []

    def __init__(self, *args, **kwargs):
        retval = super(Match, self).__init__(*args, **kwargs)
        if(args[0] and hasattr(args[0], '__iter__')):
            teams = args[0]
            args = args[1:]
            self.__init_new__(teams)
        elif(self.id):
            self.__init_existing__()
        return retval

    def __init_new__(self, teams):
        new_teams = []
        for team in teams:
            new_team = []
            new_teams.append(new_team)
            team_number = new_teams.index(new_team)
            for event_member in team:
                team_member = event_member .engage(self, team_number)
                team_member .save()
                new_team.append(team_member)
        self.event_members = new_teams

    def __init_existing__(self):
        new_teams = []
        def add_list(list, member, team):
            while(list.__len__() < (team + 1)):
                list.append([])
            list[team].append(member)

        for event_member in self.member_set.all():
            try:
                member = event_member.npcinstance
            except:
                member = event_member.player
            add_list(new_teams, member, member.team)
        self.event_members= new_teams

So this is where I start thinking that there has to be a better cleaner way. Unfortunately my brain just keeps getting stuck on what I already have.

I'd love to know if anyone can suggest a cleaner/Pythonic way for holding the Members in the Match class. specifically:

The initialising just seems very odd and clumsy. I'm afraid I will introduce errors this way.
a better way of representing teams other than a list of lists event_members


texts: Request for help to speed up batch program for 17,000 TXT files

texts:
I have over 17,000 pages that have been scanned (for a local history archive) which I have OCRed using Tesseract to individual TXT files. I want to be able to search/locate every page containing a search word of more than 3, lower case letters. So for each TXT file I need to:

Delete all rubbish from the OCR text i.e. non-alphanumeric characters:
jrepl "[^a-zA-Z0-9\s]" "" /x /f %%G /O -

Remove 1, 2 and 3 letter words: jrepl "\b\w{1,3}\b" "" /x /f %%G /O -

Change all characters to lower case: jrepl "(\w)" "$1.toLowerCase()" /i /j /x /f %%G /O -

To be able to sort the remaining words they need to be on separate new lines: jrepl "\s" "\n" /x /f %%G /O -

Finally sort all unique words into alphabetic order and create the modified TXT file: sort /UNIQUE %%G /O %%G

I have a batch file that does the above using JREPL but it is very slow. It has been running for over 100 HOURS and I'm not even half way. Any suggestions so as to speed up the processing? I am running Windows 10.
This is the Batch file I am running:
Setlocal EnableDelayedExpansion
for %%G in (*.txt) do (
set old=%%G
echo !old!
@echo on

rem remove non-alphanumeric
call jrepl "[^a-zA-Z0-9\s]" "" /x /f %%G /O -

rem remove 1, 2 and 3 letter words
call jrepl "\b\w{1,3}\b" "" /x /f %%G /O -

rem all to lowercase
call jrepl "(\w)" "$1.toLowerCase()" /i /j /x /f %%G /O -

rem replace spaces with new lines
call jrepl "\s" "\n" /x /f %%G /O -

rem reduce to unique words
sort /UNIQUE %%G /O %%G

)
pause


texts:
I'm currently learning some javascript and I've been getting up to scratch with ES6. I have learned the basics and continued to build things that I've wanted to build in Javascript for a long time.

I am looking for someone to review the code, and to hopefully aid me in becoming a better developer in learning from mistakes.

So the image slider is working from an array which is a div with 4 hidden img elements. The is an img element which is being created within the div #image-display id. The JS then swaps the src attribute based off the number within the counter and the key from the array.

The working copy is on codepen: https://codepen.io/syncoed/pen/WmpEQJ

HTML

        &#10096;
        &#10097;

CSS

 #image-display{
 width:500px;
 height: 100%;
 border: 3px solid orange;
 z-index: -1;
 padding:3;
 margin:0;
}

#img-size{
 height:100%;
 width:100%;
 z-index: -1;
 margin:0;
 position: relative;
}

/* left arrow */
#left{
 z-index: 0;
 position: fixed;
 left:21.5%;
 top:10%;
 cursor: pointer;
 color:#ffffff;
 padding:0;
}

/* right arrow */
 #right{
 z-index: 0;
 position: fixed;
 right:53.5%;
 top: 10%;
 cursor: pointer;
 color:#ffffff;
 padding:0;
}

/*Desktop Media Queries*/

@media(min-width: 1573px) {

#right{
    right:35%;
    top: 12%;
}

#left{
    left:35.5%;
    top:12%;
 }
}

@media(min-width: 1613px) {

#right{
    right:35.5%;
    top: 11%;
}

#left{
    left:35.5%;
    top:11%;
 }
}

@media(min-width: 1140px) {

#right{
    right:37.5%;
    top: 11%;
}

#left{
    left:37.5%;
    top:11%;
 }
}

Javascript

 const imgDisplay = document.querySelector('#image-display');
 const allImages = document.querySelector('#img-container');

 //gets all images
 let all = allImages.querySelectorAll('img');

var imageContainer = document.querySelector('.selector');
let counter = 0;
var newImg = document.createElement('img');
newImg.setAttribute('id', 'img-size');

newImg.setAttribute('src', all[0].src);
imgDisplay.appendChild(newImg);

let imageSelected = all[counter];

imgDisplay.addEventListener('click', (e) => {

  if (counter == all.length - 1 && e.target.id == "right") {

    newImg.setAttribute('src', all[0].src);
    counter = 0;

 } else if (counter == 0 && e.target.id == 'left') {

    counter = all.length - 1;
    newImg.setAttribute('src', all[counter].src);

 } else {

    if (e.target.tagName == 'SPAN' && e.target.id == 'right') {
        counter++;

        newImg.setAttribute('src', all[counter].src);
    }

    if (e.target.tagName == 'SPAN' && e.target.id == 'left') {

        counter--;
        newImg.setAttribute('src', all[counter].src);

    }
 }

});


texts:
I am building a MySQL to Realmdb converter app.

I use Entity Framework to deal with MySQL, so below is the code of one of my model classes. I don't want to have multiple classes representing the same object, so instead of creating separate models for EF and Realm, I am using same model for both ORM's.

The question is, is there any way to improve it, make cleaner and neat, because I don't like putting [Key] for EF and then [PrimaryKey] for Realm and the same with [Index] and [Indexed]. Also does it affect the performance of reading/writing (having support for both ORM's in one model)

using Google.Protobuf.WellKnownTypes;
using MySql.Data.EntityFrameworkCore.DataAnnotations;
using Realms;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Text;

namespace Shared.Models
{
    [Table("phrase")]
    public class Phrase : RealmObject
    {
        [Key]
        [PrimaryKey]
        [Column("phrase_id")]
        public int Id { get; set; }

        [Column("entry_id")]
        public int EntryId { get; set; }

        [Index]
        [Indexed]
        [Column("content")]
        public string Content { get; set; }

        [Index]
        [Indexed]
        [Column("notes")]
        public string Notes { get; set; }

        [Column("created_at")]
        public string CreatedAt { get; set; }

        [Column("updated_at")]
        public string UpdatedAt { get; set; }
    }
}


texts:
I wrote this code to delete an item from a linked list. I checked it and it works, but I want to know if the logic could be written simpler or clearer.

typedef struct linked_list{
  int value;
  struct linked_list * next;
}linked;

int deleteSpecificItem(linked ** head, int val)
{
 if(!head || !(*head)) return -1;
 linked * tmp = *head;
 int ret;
 linked * listToDel;
 if(tmp->value == val)
 {
    *head = (*head)->next;
    ret = tmp->value;
    free(tmp);
    return ret;
 }
 while(tmp->next != NULL)
 {
    if(tmp->next->value == val)
    {
        listToDel = tmp->next;
        tmp->next = tmp->next->next;
        ret = listToDel->value;
        free(listToDel);
        return ret;
    }
    tmp = tmp->next;
 }
 return -1;
}

When checking if a pointer is NULL, I can use either !head or head != NULL. What is preferred in companies?


texts:
Usage:

// Usage: dndgenerate /e [emhd] [0-9+]
//          dndgenerate /e d 4 4 5 4
// /e   Generate Encounter. Parameter can be one of
//          e - Easy
//          m - Medium
//          h - Hard
//          d - Deadly
//      As well as a list of heroes by their levels
//
// Example:  dndgenerate /e m 4 4 5 4
//      Generate a medium encounter for three level 4 and one level 5 adventurers.

The code to make it happen:

type DifficultyOption = Easy | Medium | Hard | Deadly

type EncounterOptions = {
    difficulty: DifficultyOption option
    heroes: int list
}

let (|Level|_|) (str: string) =
    let mutable intValue = 0

    if System.Int32.TryParse(str, &intValue)
        then match intValue with
             | x when x < 0 -> None
             | x when x > 20 -> None
             | x -> Some x
        else None

let (|Difficulty|_|) (str: string) =
    match str with
    | "e" | "E" -> Some(Easy)
    | "m" | "M" -> Some(Medium)
    | "h" | "H" -> Some(Hard)
    | "d" | "D" -> Some(Deadly)
    | x -> None

let isComplete (options:EncounterOptions) =
    not <| options.heroes.IsEmpty && options.difficulty.IsSome

type VerboseOption = VerboseOutput | TerseOutput

type MiscOptions = {
    verbose: VerboseOption
}

type GeneratorType =
    | E of EncounterOptions
    | Unknown

type ParseMode = TopLevel | Encounter | Plot | Dungeon | Settlement | Error

type CommandLineOptions = {
    misc: MiscOptions
    parseMode: ParseMode
    generatorType: GeneratorType
}

let parseTopLevel arg miscSoFar =
    match arg with
    | "/v" ->
        let newMiscSoFar = { miscSoFar with verbose = VerboseOutput }
        { misc = newMiscSoFar; parseMode = TopLevel; generatorType = Unknown }

    | "/e" ->
        { misc = miscSoFar; parseMode = Encounter; generatorType = E { difficulty = None; heroes = [] } }

    | x ->
        { misc = miscSoFar; parseMode = Error; generatorType = Unknown }

let parseEncounter arg miscSoFar encounterGenerator =
    match arg with
    | Level x ->
        let builder' = { encounterGenerator with heroes = x :: encounterGenerator.heroes }
        { misc = miscSoFar; parseMode = Encounter; generatorType = E builder' }

    | Difficulty x ->
        let builder' = { encounterGenerator with difficulty = Some x }
        { misc = miscSoFar; parseMode = Encounter; generatorType = E builder' }

    | _ ->
        { misc = miscSoFar; parseMode = Error; generatorType = E encounterGenerator }

let foldFunction state element =
    match state with
    | { misc = m; parseMode = TopLevel } ->
        parseTopLevel element m

    | { misc = m; parseMode = Encounter; generatorType = E(g) } ->
        parseEncounter element m g

    | { parseMode = Error } ->
        state

    | { misc = m; parseMode = p; generatorType = g } ->
        printfn "Unexpected constellation of %A %A %A" m p g
        state

let disableIfIncomplete commandLineOptions =
    match commandLineOptions.parseMode with
    | Error ->
        commandLineOptions

    | _ ->
        match commandLineOptions.generatorType with
        | E(encounter) when isComplete encounter ->
            commandLineOptions

        | Unknown -> commandLineOptions

        | _ -> { commandLineOptions with parseMode = Error }

let parseCommandLine args =
    let defaultOptions = {
        verbose = TerseOutput
    }

    let initialFoldState =
        { misc = defaultOptions; parseMode = TopLevel; generatorType = Unknown }

    let finalFoldState = args |> List.fold foldFunction initialFoldState

    disableIfIncomplete finalFoldState

Based on code from Scott Wlaschin's Parsing command line arguments but extended to include argument groups and error handling. Purposefully avoided FParsec because I'm new to F# and wanted to solve it vanilla-style first.


texts:
I made this simple addition calculator in Java and I'm wondering how I can improve it.

package com.craftxbox.main;

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        int inInt1;
        int inInt2;
        int outInt;
        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        inInt1 = in.nextInt();
        inInt2 = in.nextInt();
        outInt = inInt1 + inInt2;
        System.out.println(outInt);

    }
}


texts:
I've made a small thread pool that i'll be using to communicate with a Redis server:

#include "redox.hpp"

redox::Redox rdx;

void my_cool_function()
{
    // do stuff with rdx
}

int main()
{
    rdx.connect("localhost");
    int max_threads = std::thread::hardware_concurrency();
    std::vector<std::thread> pool;

    for (int i = 0; i < max_threads; i++) {
        pool.push_back(std::thread(my_cool_function));
    }

    for (std::thread &thread : pool) {
        thread.join();
    }

    pool.empty();
    rdx.disconnect();

    return 0;
}

Do I need to call delete rdx on the end of my main function? What about the pool var?


texts: Dynamic association generation in ActiveRecord

texts:
I'm developing a Rails-based web interface/API for a large, vendor-supplied, legacy Oracle database. One of the constraints is that I can't change the schema other than adding views, because it still has to support the vendor's application.

The table for customer data has a limited number of columns, and extended attributes are stored in customer_def_field_value. These attributes are defined in customer_def_field_def.

so I end up with the classes:

class FieldDef < ActiveRecord::Base

  set_table_name 'customer_def_field_def'
  set_primary_key :customer_def_field_def_id
  set_sequence_name 's_customer_def_field_def'

  alias_attribute :field_def_id, :customer_def_field_def_id

  has_many :field_values

  def symbol
    self.title.parameterize('_').to_sym
  end
end

class FieldValue < ActiveRecord::Base

  set_table_name 'customer_def_field_value'
  set_primary_keys :cust_id, :customer_def_field_def_id
  set_sequence_name :autogenerated

  alias_attribute :field_def_id, :customer_def_field_def_id

  belongs_to :customer, :foreign_key => :cust_id
  belongs_to :field_def, :foreign_key => :customer_def_field_def_id
end

In order to get associations on Customer for each of the 'custom fields', I have this code in the Customer class:

FieldDef.find_each do |field|
  has_one field.symbol, :class_name => 'FieldValue', :foreign_key => :cust_id, :conditions => proc{ "customer_def_field_def_id = #{field.id}"}
  accepts_nested_attributes_for field.symbol
  delegate :field_value, :to => field.symbol, :prefix => true
  delegate :field_value=, :to => field.symbol, :prefix => true
  attr_accessor ('set_' + field.symbol.to_s).to_sym
end

This works like a charm, but it queries the DB every time a Customer is instantiated in order to generate the method definitions.

It hasn't been a performance issue... yet.

New custom field types aren't added very often, so I think I might be able to do this in an initializer rather than in my model, and just restart the application if new fields have to be added... but I wanted to get some feedback. Thanks!


texts: Handling pagination on a particular page

texts: I have a Java script that handles pagination on a particular page by using a jQuery pagination plugin. Is there any way to improve the code?