texts: Maximum possibility of banknotes to keep into the given integer value

texts:
Banknotes are given specifically 100, 50, 20, 10, 5, 2, 1. Required to check and find out: What is the maximum possibility to keep these individually into the given integer value.
For example:
input: 576
output: 576
        5 nota(s) de R$ 100,00
        1 nota(s) de R$ 50,00
        1 nota(s) de R$ 20,00
        0 nota(s) de R$ 10,00
        1 nota(s) de R$ 5,00
        0 nota(s) de R$ 2,00
        1 nota(s) de R$ 1,00

I have solved this problem by following this strategy->
#include <stdio.h>
int main(){

    int number, count = 0, occupied = 0, number_update, i;
    int a = 100;
    scanf("%d",&number);
    number_update = number;
    printf("%d\n",number);

    //Getting the number that can be stored maximum in the given integer.
    for (i = 0; i < 7; i++){
        count = 0;

        while (a <= number_update){
        count++;
        occupied = occupied + a;
        number_update = number_update - a;
        }
        printf("%d nota(s) de R$ %d,00\n",count,a);
        number_update = number - occupied;

        if (i == 0){
         a = a-50;

        }

        else if (i == 1){
            a = a-30;
        }

        else if (i == 2){
            a = a-10;
        }

        else if (i == 3){
            a = a-5;
        }

        else if (i == 4){
            a = a-3;
        }

        else {
            a = a-1;
        }

       }
        return 0;
}

I am here for:
Would you propose any simplification from my existing solution?
Will I face any problem with some conditions?
The way I followed to solve this problem. Is it ok or not?


texts:
I just went through a very easy online example creating a Rock-Paper-Scissors game, but it seemed like it was not a great use of computing power.

It seemed like I was writing out results for every possible outcome instead of declaring properties or attributes for variables that will dictate the results depending on the situation.

Could an index or something be used to set up the variables?

var rock = ["rock", "paper", "scissors"];
var paper = ["paper", "scissors", "rock"];
var scissors = ["scissors", "rock", "paper"];
    index           0         1        2

Player 1 could select a variable, then player 2 could select a string in the index, and the position of the selection in the index would determine the winner (0 = tie, 1 = p1Loss, 2 = p1Win). Is this possible?

I think the code in the example below would start to get messy and bloated if you were to expand on the choices/options. i.e. Instead of 3 options you have 9, any one of which will beat 4 options and loose to the other 4.

I guess I'm just wondering if there is a better way to do this that would scale better with larger numbers.

I've included the code from the example below:

var user1Choice = prompt("Do you choose rock, paper or scissors?");
var user2Choice = prompt("Do you choose rock, paper or scissors?");

var compare = function(choice1, choice2) {
    if (choice1 === choice2) {
        return "its a tie";
    }

    else if (choice1 === "rock") {

        if (choice2 === "scissors") {
            return "rock wins";
        }
        else {
            return "paper wins";
        }
    }

    else if (choice1 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors wins";
        }
    }

    else if (choice1 === "scissors") {
        if (choice2 === "paper") {
            return "scissors wins";
        }
        else {
            return "paper wins";
        }
    }

}

compare(user1Choice, user2Choice)


texts:
I am learning Haskell, and what is better than advent of code to do so? The day 1 problem is about adding together the digits that are followed by the same digit from a "circular" string (the next of the last is the first). My solution is the following:

import Data.List
import Data.Char

result :: [Char] -> Int
result s = sum . map (digitToInt . fst)
               . filter (uncurry (==))
               . zip s
               $ (drop 1 . cycle $ s)

My question is not only about the algorithm (I think that it is ok, and the problem is not that difficult) but also about the "haskellish" style.

Because I am used to Rust/Ocaml/Elm etc., at first I wrote:

import Data.List
import Data.Char
import Data.Function

result :: [Char] -> Int
result str = str & zip (drop 1 . cycle $ str)
                 & filter (uncurry (==))
                 & map (digitToInt . fst)
                 & sum

then I read that Haskell people prefer to compose functions and then pass the parameter, not doing the forward thing. What do you think about that?

Also, I searched over the Internet, and I found some divided code, more like that:

import Data.List
import Data.Char

transformCharPairsToInts :: [(Char, Char)] -> [Int]
transformCharPairsToInts = map $ digitToInt . fst

keepPairsWithSameChars :: [(Char, Char)] -> [(Char, Char)]
keepPairsWithSameChars = filter $ uncurry (==)

result :: [Char] -> Int
result str = sum . transformCharPairsToInts . keepPairsWithSameChars $ zip str shiftedStr
  where
    shiftedStr = drop 1 . cycle $ str

What is the most idiomatic thing? The style that Haskell people prefer?

The main:

-- exemple cases
main = mapM_ (print . result) $ ["1122", "1111", "1234", "91212129"]

Thank you for your remarks.


texts: Calculate all possible combinations of given characters

texts:
I was asked in my textbook Lectures on Discrete Mathematics for Computer Science to construct a program that would take an alphabet ({a,b,c} or any combination of characters {1,4,s,a}) as well as a length value and calculate all possible combinations of this alphabet.

For example:

char[] alphabet = new char[] {'a','b'};
possibleStrings(3, alphabet,"");

This will output:

aaa
aab
aba
abb
baa
bab
bba
bbb

That is all combinations of the alphabet {a,b,c} with the string length set to 3.

The code I have written is functional, however I'd like to read what things I am doing wrong or could be doing better. The book didn't give an example program, so I only hope this is what it was looking for, but maybe there's a much better way to do it or way to improve how I'm doing it. Maybe this is fine, but I just need someone to look at it and tell me in that case.

public class Program {

    public static void main(String[] args) {

        // Create an alphabet to work with
        char[] alphabet = new char[] {'a','b'};
        // Find all possible combinations of this alphabet in the string size of 3
        StringExcersise.possibleStrings(3, alphabet,"");
    }

} class StringExcersise {

    public static void possibleStrings(int maxLength, char[] alphabet, String curr) {

        // If the current string has reached it's maximum length
        if(curr.length() == maxLength) {
            System.out.println(curr);

        // Else add each letter from the alphabet to new strings and process these new strings again
        } else {
            for(int i = 0; i < alphabet.length; i++) {
                String oldCurr = curr;
                curr += alphabet[i];
                possibleStrings(maxLength,alphabet,curr);
                curr = oldCurr;
            }
        }
    }
}


texts:
I was implementing a rolling median solution and was not sure why my Python implementation was around 40 times slower than my C++ implementation.

Here are the complete implementations:

C++

#include <iostream>
#include <vector>
#include <string.h>
using namespace std;

int tree[17][65536];

void insert(int x) { for (int i=0; i<17; i++) { tree[i][x]++; x/=2; } }
void erase(int x) { for (int i=0; i<17; i++) { tree[i][x]--; x/=2; } }
int kThElement(int k) {
    int a=0, b=16;
    while (b--) { a*=2; if (tree[b][a]<k) k-=tree[b][a++]; }
    return a;
}

long long sumOfMedians(int seed, int mul, int add, int N, int K) {
    long long result = 0;
    memset(tree, 0, sizeof(tree));
    vector<long long> temperatures;
    temperatures.push_back( seed );
    for (int i=1; i<N; i++)
      temperatures.push_back( ( temperatures.back()*mul+add ) % 65536 );
    for (int i=0; i<N; i++) {
      insert(temperatures[i]);
      if (i>=K) erase(temperatures[i-K]);
      if (i>=K-1) result += kThElement( (K+1)/2 );
    }
    return result;
}

// default input
// 47 5621 1 125000 1700
// output
// 4040137193

int main()
{
  int seed,mul,add,N,K;
  cin >> seed >> mul >> add >> N >> K;
  cout << sumOfMedians(seed,mul,add,N,K)  << endl;
  return 0;
}

Python

def insert(tree,levels,n):
        for i in xrange(levels):
                tree[i][n] += 1
                n /= 2
def delete(tree,levels,n):
        for i in xrange(levels):
                tree[i][n] -= 1
                n /= 2

def kthElem(tree,levels,k):
        a = 0
        for b in reversed(xrange(levels)):
                a *= 2
                if tree[b][a] < k:
                        k -= tree[b][a]
                        a += 1
        return a

def main():
        seed,mul,add,N,K = map(int,raw_input().split())
        levels = 17
        tree = [[0] * 65536 for _ in xrange(levels)]
        temps = [0] * N
        temps[0] = seed
        for i in xrange(1,N):
                temps[i] = (temps[i-1]*mul + add) % 65536
        result = 0
        for i in xrange(N):
                insert(tree,levels,temps[i])
                if (i >= K):
                        delete(tree,levels,temps[i-K])
                if (i >= K-1):
                        result += kthElem(tree,levels,((K+1)/2))

        print result

# default input
# 47 5621 1 125000 1700
# output
# 4040137193
main()

On the above mentioned input (in the comments of the code), the C++ code took around 0.06 seconds while Python took around 2.3 seconds.

Can some one suggest the possible problems with my Python code and how to improve to less than 10x performance hit?

I don't expect it to be anywhere near C++ implementation but to the order of 5-10x. I know I can optimize this by using libraries like NumPy (and/or SciPy). I am asking this question from the point of view of using Python for solving programming challenges. These libraries are usually not allowed in these challenges. I am just asking if it is even possible to beat the time limit for this algorithm in Python.

In case somebody is interested, the C++ code is borrowed from floating median problem here.


texts: Getting a value with timeout using Kotlin coroutines

texts:
So, here's a task. A background thread may or may not call all of it's listeners some time after sendRequest() was called (in other words sendRequest() schedules a possible event). The required function must:

Subscribe to those events
Call sendRequest() periodically until the function returns anything
Return the first suitable result (filtering is done in the listener and is omitted in this snippet) or null after a timeout
Unsubscribe from those events regardless of the result

suspend fun findServer(): Server? {
    var listener: ((Server) -> Unit)? = null
    return try {
        withTimeoutOrNull(10000) {
            suspendCancellableCoroutine<Server> { continuation ->
                listener = { server: Server ->
                    continuation.resume(server)
                }.also { discoveryService.addListener(it) }

                launch {
                    while (continuation.isActive) {
                        discoveryService.sendRequest()
                        delay(1000)
                    }
                }
            }
        }
    } finally {
        listener?.let { discoveryService.removeListener(it) }
    }
}

The current implementation seems to work fine, but the nullable listener variable feels kind of clunky and requires using also to keep the listener reference, which in turn breaks type inference and makes me specify listener's parameter type (no big deal, but...). I could use a lateinit var here, but it probably can lead to exceptions when withTimeoutOrNull() stops before the listener was initialized.

Any recommendations on improving this snippet? Or am I, in fact, doing everything totally wrong here?


texts: Initialize C array at definition depending on runtime input

texts:
Best way to initialize rr and cc depending on cycle number to pre-defined values in r and c.

int func(int cycle, int index, int i) {
  char *rr;
  char *cc;

  if (cycle % 2 == 0) {
      char r[4] = { 0, -1, 0, 1 };
      char c[4] = { 1, 0, -1, 0 };
      rr = r;
      cc = c;
  }
  else {
      char r[4] = { -1, -1, 1, 1 };
      char c[4] = { 1, -1, -1, 1 };
      rr = r;
      cc = c;
  }

  return(index + rr[i] + cc[i]);
}


texts: Temperature and speed unit converter class in JS

texts:
This is what I came up with, but I'm not sure if:

putting it in Class is the best approach
multiple repeats (this.val etc.) are acceptable
there is a better approach (maybe with constructor)

class UnitChange {
  temperature(val, to) {
    this.val = val;
    this.to = to;
    if (this.to === "toF") {
      return this.val * 1.8 + 32;
    } else {
      return (this.val - 32) / 1.8;
    }
  }
  speed(currentUnit, val, to) {
    this.currentUnit = currentUnit;
    this.val = val;
    this.to = to;
    if (this.to === "tomph") {
       if (this.currentUnit === "kph") {
       return this.val * 0.62;
      } else {
       return this.val * 2.23;
      }
    } else if (this.to === "tokph") {
      if (this.currentUnit === "mph") {
        return this.val * 1.60;
      } else {
        return this.val * 3.6;
      }
    } else if (this.to === "toms") {
    if (this.currentUnit === "kph") {
      return this.val * 0.27;
    } else {
      return this.val * 0.44;
    }
  }
 }
};

let change = new UnitChange();
console.log(change.temperature(8, "toF"));
console.log(change.speed("kph", 100, "tomph"));


texts: Multiple games with same rpg-classes base

texts:
Please, if you find a better title, tell me because I really didn't know what to put in here!

I like to guess how I could implement a game, and to be sure that my perception is working, I plan to develop small games. For instance, I plan to build a FFTA-like game, a FTL-like game, a tower-defense game, and so on. As a base, I created a bunch of rpg-classes (Warrior, Wizard, ...), and I want to use all of them in each of my futur game.

The only sure thing I know about what should be in common for every game is the stat system:

  Strength
  Constitution
  Agility
  Accuracy
  Intelligence
  Charisma
  Luck

I will continue with what I plan to do, but I am not really sure about my choices:

namespace General
{
    public interface IStatsOwner
    {
        int Strength { get; }
        int Constitution { get; }
        int Agility { get; }
        int Accuracy { get; }
        int Intelligence { get; }
        int Charisma { get; }
        int Luck { get; }
    }

    public abstract class WarriorBase : IStatsOwner
    {
        public int Strength { get { return 5; } }
        public int Constitution { get { return 4; } }
        public int Agility { get { return 3; } }
        public int Accuracy { get { return 3; } }
        public int Intelligence { get { return 2; } }
        public int Charisma { get { return 3; } }
        public int Luck { get { return 1; } }
    }

    public abstract class WizardBase : IStatsOwner
    {
        public int Strength { get { return 2; } }
        public int Constitution { get { return 3; } }
        public int Agility { get { return 3; } }
        public int Accuracy { get { return 3; } }
        public int Intelligence { get { return 5; } }
        public int Charisma { get { return 4; } }
        public int Luck { get { return 1; } }
    }

    public interface IGame
    {
        Type WarriorType { get; }
        Type WizardType { get; }
    }
}

namespace FFTALike
{
    public interface IDamageable
    {
        void TakeDamages();
    }

    public class Warrior : General.WarriorBase, IDamageable
    {
        public void TakeDamages() { Console.WriteLine($"Taking damages with CON={Constitution}"); }
    }

    public class Wizard : General.WizardBase, IDamageable
    {
        public void TakeDamages() { Console.WriteLine($"Taking damages with CON={Constitution}"); }
    }

    public Game : IGame
    {
        public Type WarriorType { get { return typeof(Warrior); } }
        public Type WizardType { get { return typeof(Wizard); } }
    }
}

namespace TowerDefense
{
    public interface ILocatable
    {
        Location Location { get; set; } // Location(int X, int Y)
    }

    public interface IShooter
    {
        void Shoot();
    }

    public class Warrior : WarriorBase, ILocatable, IShooter
    {
        public Location Location { get; set; }
        public void Shoot() { Console.WriteLine($"Shooting with STR={Strength}"); }
    }

    public class Wizard : WizardBase, ILocatable, IShooter
    {
        public Location Location { get; set; }
        public void Shoot() { Console.WriteLine($"Shooting with STR={Strength}"); }
    }

    public Game : IGame
    {
        public Type WarriorType { get { return typeof(Warrior); } }
        public Type WizardType { get { return typeof(Wizard); } }
    }
}

What I feel uncomfortable with is:

  I don't enforce the fact that IGame.WarriorType inherits WarriorBase
  I duplicate TakeDamages(), Location { get; set; } and Shoot() (I actually have 20 rpg-classes, so I isocuplate these implementations)

Please note that I want the final implementation to fit with SOLID principles, because I want these projects to be training projects.


texts: Telegram Bot that retrieves book information from GoodReads

texts:
The project below is about a Telegram bot that implements both inline and offline modes. The idea is to get a brief info about a book, searched by title(it's author, rating, short description). I decided to retrieve the info from GoodReads. Besides the parse implementation, I have trouble in correctly accessing the Telegram API. Every recommendation and criticism is welcomed!

The GoodReads access to retrieve data

import goodreads
from goodreads import client
import random

class GoodreadsBook():

  def __init__(self):
    self.client_key = "[data]"
    self.client_secret = "[data]"

  def authenticate(self):
    self.auth_client = client.GoodreadsClient(self.client_key, self.client_secret)

  def parse_book(self, book):
    return {
        'title': book_data.title,
        'author': book_data.authors[0],
        'rating': book_data.rating,
        'review': book_data.review,
        'cover': book_data.image_url,
        'link': book_data.link
    }

  def book(self):
    """ Get info about a random book """
    max_book_num = 10 000 000
    index = random.randint(1, max_book_num)
    book = self.auth_client.book(index)

    return parse_book(book)

  def book_search(self, q, page=1, search_field='all'):
    """ Get the most popular books for the given query. This will search all
        books in the title/author/ISBN fields and show matches, sorted by
        popularity on Goodreads.
        :param q: query text
        :param page: which page to return (default 1)
        :param search_fields: field to search, one of 'title', 'author' or
        'genre' (default is 'all')
    """
    books = self.auth_client.search_books(str(q), page, search_field)

    return map(parse_book, books)

Main implementation of the bot

import telebot
from telebot import types
import gd

token = '[data]'
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])  # greeting
def send_welcome(message):
    bot.reply_to(message.chat.id, "Hi! How are you?")

@bot.message_handler(commands=['help'])  # command list
def send_welcome(message):
    bot.reply_to(message.chat.id, "This bot can do: ")

@bot.message_handler(commands=['random']) # /random
def random(message):
    book = random_book()
    text = "Some text"
    bot.send_message(message.chat.id, text, disable_web_page_preview=False)

@bot.inline_handler(lambda query: query.query == 'text')  # inline session
def query_text(query):
    raise Http404("Poll does not exist")
    book_req = book_info(query)
    try:
        result = []
        i = 0
        for book in book_req:
            result.append(types.InlineQueryResultArticle(id=i,
                title=book[i]['title'],
                url=book[i]['link'],
                hide_url=True,
                description=book[i]['review'],
                thumb_url=book[i]['cover'], thumb_width=48, thumb_height=48
                ))
            i += 1
        bot.answer_inline_query(query.id, result)
    except Exception as e:
        print("{!s}\n{!s}".format(type(e), str(e)))

def main_loop():
    bot.polling(True)
    while 1:
        time.sleep(3)

if __name__ == '__main__':
    try:
        main_loop()
    except KeyboardInterrupt:
        print >> sys.stderr, '\nExiting by user request.\n'
        sys.exit(0)


texts: Merge/Insertion sort program taking longer than an hour to finish - C++

texts:
My program uses merge and insertion sort to sort a set of numbers.
It works perfectly fine for small inputs, less than 2 seconds for 1,000 ints. But I need to sort 1,000,000 ints. When I try with 1 million, it takes over 2 hours to sort. Can someone please help me optimize this program so it works faster?
FYI: I have several versions of this program because I have been trying to make it faster. Originally, my program would read 1 million ints from a text file, sort, then output the sorted numbers to a text file. But I assumed that was taking a large portion of the running time so I took that out completely.
Instead, I initialized the vector with 1,000,000 ints in the main program, like so:
vector<int> vec {7000, 8090, 189, 19, 0, 29032, ... ,90};

Again, my program works great with small input sizes. Any advice? Thank you!
#include<iostream>
#include<vector>
#include <time.h>
#include <stdio.h>
#include<fstream>

using namespace std;

void merge(vector<int> &vec, int left, int center, int right, int originalsize)
{
   int leftVsize, rightVsize; //left and right vector sizes
   vector<int> vec1;

   leftVsize = center-left+1;            //calculating left and right temporary vector sizes
   rightVsize = right - center;

   vector<int> tempLeft(leftVsize);     //initializing temp left and right vectors
   vector<int> tempRight(rightVsize);

   for(int i = 0; i < tempLeft.size(); ++i)
   {
     tempLeft.at(i) = vec.at(left+i);      //initializing left vector
   }

   for(int i = 0; i < tempRight.size(); ++i)
   {
      tempRight.at(i) = vec.at(i+center+1);   //initializing right vector
   }

   int i = left, j = 0, k = 0;

   while((j < tempLeft.size()) && (k < tempRight.size()))      //while left and right vector have elements
   {
      if(tempLeft.at(j) <= tempRight.at(k))     //if left element is smaller
      {
        vec.at(i) = tempLeft.at(j);   //add value to original vector
        j++;
      }
      else      //else
      {
        vec.at(i) = tempRight.at(k);      //add value to original vector
        k++;
      }
     i++;
   }

 while(j < tempLeft.size())      //while left vector has elements
 {
    vec.at(i++) = tempLeft.at(j++);
 }

 while(k < tempRight.size())     //while right vector has elements
 {
    vec.at(i++) = tempRight.at(k++);
 }

}

void insertionSort(vector<int> &vec, int originalsize)
{
   for(int i = 1; i < originalsize; ++i)     //starting from 1 for original vector size
  {
    int tempval = vec[i];      //set tempval to vector value at 1
    int j = i;                    //j now equals i

    for(j = i; ((j > 0)&&(tempval < vec[j-1])); --j)    //for j=i while j is greater than 0 and tempval is less than the number before it
    {
      vec[j] = vec[j-1];    //set vector[j] to vector[j-1]
 }
      vec[j] = tempval;   //tempval now holds vec[j]
}
}

void sort(vector<int> &vec, int left, int right, int originalsize)
{
  int insertion = right - left;
  if(insertion <= 8)    //if righ-left is less than or equal to 8
  {
     insertionSort(vec, originalsize);       // call insertion sort
  }
  if(left < right)
  {
    int center = (left+right)/2;    //calculating center of vector
    sort(vec, left, center, originalsize);    //calling sort for temp vector
    sort(vec, center+1, right, originalsize);   //calling sort for temp vector
    merge(vec, left, center, right, originalsize);    //calling merge to merge two vectors together
  }
 }

int main()
{
  vector<int> vec { 1 million ints };
  int temp;
  clock_t q, q1, q2,t;

  int orgsize = vec.size();

  q=clock();

  sort(vec, 0, (vec.size()-1), orgsize);    //calling sort function

  q=clock()-q;

  cout << "Total Time: "<< ((float)q)/CLOCKS_PER_SEC <<"\n";
 return 0;
}


texts: Computing sum on column + sum on row + sum on each diagonal

texts:
I have the following problem:
I read from a file the dimension(n) of the matrix(which is n * n) and the matrix.
For each element in the matrix I have to compute sum of row + sum of column + sum of the diagonal which the element is on and is parallel to main diagonal + sum of the diagonal which the element is on and is parallel to antidiagonal, and find the element with max corresponding sum and coordinates(row and column) on which the element is found. Element itself should be taken into count just once.

I have a working program, but I need it to be faster. How could I solve this problem faster? Can my algorithm be improved or I have to write another one? 2 ≤ n ≤ 300, -10000 ≤ m[i][j] ≤ 10000

Input file:

3
 1  -8  3
-2   4  5
 6  -9  7

Output file:

18
0 2

Code:

#include <set>
#include <iostream>
#include <fstream>
#include <limits>

using namespace std;
int sumOnRow(int row, int n, int **m)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; i++)
        sum += m[row][i];
    return sum;
}

int sumOnColumn(int column, int n, int **m)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; i++)
    {
        sum += m[i][column];
    }
    return sum;
}

int sumOnAD(int i, int j, int n, int **m)
{
    int a = i - 1;
    int b = j + 1;
    int sum = 0;
    while ((a >= 0) && (b < n))
    {
        sum += m[a--][b++];
    }
    a = i + 1;
    b = j - 1;
    while ((a < n) && (b >= 0))
    {
        sum += m[a++][b--];
    }
    return sum;
}

int sumOnMD(int i, int j, int n, int **m)
{
    int a = i + 1;
    int b = j + 1;
    int sum = 0;
    while ((b < n) && (a < n))
    {
        sum += m[a++][b++];
    }
    a = i - 1;
    b = j - 1;
    while ((a >= 0) && (b >= 0))
    {
        sum += m[a--][b--];
    }
    return sum;
}

int main()
{
    fstream in;
    in.open ("inputFile.in");
    if (!in)
    {
        cerr << "Can't open input file\n";
    }
    fstream out;
    out.open ("outputFile.out", ios::out);
    if (!out)
    {
        cerr << "Can't open output file\n";
    }

    short n;
    in >> n;

    int i;
    int **m = new int *[n];
    for (i = 0; i < n; i++)
        m[i] = new int [n];

    int j;
    //read the matrix
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            in >> m[i][j];
        }
    }

    int elementSum = 0;
    int maxSum = INT_MIN;
    int savedI = 0;
    int savedJ = 0;

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            elementSum += sumOnRow(i, n, m);
            elementSum += sumOnColumn(j, n, m);
            elementSum += sumOnMD(i, j, n, m);
            elementSum += sumOnAD(i, j, n, m);
            //element was taken into count both in the sum on row and the sum on column
            elementSum -= m[i][j];
            if (elementSum > maxSum)
            {
                maxSum = elementSum;
                savedI = i;
                savedJ = j;
            }
            elementSum = 0;
        }
    }
    out << maxSum << "\n" << savedI << " " << savedJ;
    return 0;
    }


texts:
Here I have implemented a queue. Is this a correct, efficient queue implementation? what issues are there if any and what can be done to make it better?

import java.util.*;

public class Queue2{
    private int amountInQueue;
    private int[] queue;
    private int rearIndex;
    private int frontIndex;

    public Queue2(){
        amountInQueue = 0;
        queue = new int[10];
        rearIndex = 0;
        frontIndex = 0;
    }

    public Queue2(int queueCapacity){
        amountInQueue = 0;
        queue = new int[queueCapacity];
        rearIndex = 0;
        frontIndex = 0;
    }

    public void enqueue(int valueToAdd){
        if(amountInQueue == queue.length){
            throw new FullQueueException();
        }
        else if(rearIndex == queue.length -1){
            rearIndex = 0;
            queue[rearIndex] = valueToAdd;
            amountInQueue++;
        }
        else if(amountInQueue == 0){
            queue[rearIndex] = valueToAdd;
            amountInQueue++;
        }
        else{
            rearIndex++;
            queue[rearIndex] = valueToAdd;
            amountInQueue++;
        }
    }

    public int dequeue(){
        int frontValue = frontIndex;
        if(amountInQueue == 0){
            throw new EmptyQueueException();
        }
        if(frontIndex == queue.length -1){
            frontValue = queue[frontIndex];
            frontIndex = 0;
            amountInQueue--;
        }
        else{
            frontValue = queue[frontIndex];
            frontIndex++;
            amountInQueue--;
        }
        return frontValue;
    }

    public boolean isEmpty(){
        return amountInQueue == 0;
    }

    public int valueAtRear(){
        return queue[rearIndex];
    }

    public int valueAtFront(){
        return queue[frontIndex];
    }

    public int currentSize(){
      return amountInQueue;
    }

  class FullQueueException extends RuntimeException{
      public FullQueueException(){
          super("You cannot add values to a queue that is full");
      }
  }

  class EmptyQueueException extends RuntimeException{
      public EmptyQueueException(){
          super("You cannot remove values from a queue that is empty");
      }
  }
}


texts:
I've written a simple program in Python which does the following:

Input: an integer \$n\$

Output: a \$2^n x 2^n\$ matrix containing small \$L\$s which fill the entire matrix except one single square. Each L has its unique number, and consists of three squares.

It's a fairly simple program, and you can see clearly what it does by typing in a few different \$n\$s.

What I'd like to do: Keep the actual algorithm as it is now (the rec() function), but improve my C-like code to make full use of Python's features.

#!/usr/bin/env python

import sys, math

ur = [[1,0],
      [1,1]]

ul = [[0,1],
      [1,1]]

lr = [[1,1],
      [1,0]]

ll = [[1,1],
      [0,1]]

shapeCounter = 1

matrix = []

def printMatrix():
    for row in matrix:
        for element in row:
            if(element >= 10):
                print("%d" % element),
            else:
                print(" %d" % element),
        print
    print

def square(n):
    global matrix
    matrix = [[0]*(2**n) for x in xrange(2**n)]
    matrix[0][len(matrix) - 1] = -1
    rec(0, 0, len(matrix) - 1, len(matrix) - 1)
    matrix[0][len(matrix) - 1] = 0
    printMatrix()

def writeRect(rect, x, y):
    global shapeCounter
    matrix[y][x] += rect[0][0] * shapeCounter
    matrix[y+1][x] += rect[1][0] * shapeCounter
    matrix[y][x+1] += rect[0][1] * shapeCounter
    matrix[y+1][x+1] += rect[1][1] * shapeCounter
    shapeCounter += 1

def rec(sx, sy,
        ex, ey):
    if(ex - sx < 1 or ey - sy < 1):
        return
    #print("(%d,%d) (%d,%d)" %(sx,sy,ex,ey))

    if(matrix[sy][sx] != 0):
        rect = ul
    elif(matrix[ey][sx] != 0):
        rect = ll
    elif(matrix[sy][ex] != 0):
        rect = ur
    elif(matrix[ey][ex] != 0):
        rect = lr

    hx = sx + (ex - sx) / 2
    hy = sy + (ey - sy) / 2

    writeRect(rect, hx, hy)

    rec(sx, sy, hx, hy)
    rec(hx + 1, sy, ex, hy)
    rec(sx, hy + 1, hx, ey)
    rec(hx + 1, hy + 1, ex, ey)

if __name__=='__main__':
    square(int(sys.argv[1]))


texts: Handling selections for a vending machine

texts:
To summarise, the code is based of a vending machine and allows the user to choose an item once chosen, it will add 1 to the item to display how many total items the user has.

However, it is incredibly long and more or less it essentially repeats the same code again which is inefficient. How can I compress this code into smaller sections?

if selection == 1:
    item = "Chocolate"
    print ("1 for Diary Milk 2 for Maltesars 3 for Kit Kat:")
    selection = int(input("Please enter your option:"))
    if selection == 1:
        item = "Diary Milk"
        itemValue = itemValue + 1
    elif selection == 2:
        item = "Maltesars"
        itemValue = itemValue + 1

    elif selection == 3:
        item = "Kit kat"
        itemValue = itemValue + 1

elif selection ==2:
    item = "Gum"
    print ("1 for Airwaves 2 for Extra Pepermint 3 for Wriggley's Summer fruit:")
    selection = int(input("Please enter your option:"))
    if selection == 1:
        item = "Airwaves"
        itemValue = itemValue+1
    elif selection == 2:
        item = "Extra Pepermint"
        itemValue = itemValue+1

    elif selection == 3:
        item = "Wriggley's Summer fruit"

elif selection ==3:
    item = "Fizzy Drink"
    print ("1 for Coke 2 for Tango Cherry 3 for Dr Pepper:")
    selection = int(input("Please enter your option:"))
    if selection == 1:
        item = "Coke"
        itemValue = itemValue+1
    elif selection == 2:
        item = "Tango Cherry"
        itemValue = itemValue+1
    elif selection == 3:
        item = "Dr Pepper"
        itemValue = itemValue+1


texts: PHP Sort Associative Array first by relativity of value then by other value desc

texts:
I am trying to sort an associative array by following this scheme:

Sort by 'qt': positives first, non-positives after.  Magnitude does not matter, only sign.
In positive part: sort by sa DESC
In negative part: sort by sa DESC

I managed to have the desired result but by tinkering :
$array = [
    [
        "id" => 1,
        "qt" => 1000,
        "sa" => 50
    ],
    [
        "id" => 2,
        "qt" => 0,
        "sa" => 50
    ],
    [
        "id" => 3,
        "qt" => 0,
        "sa" => 350
    ],
    [
        "id" => 4,
        "qt" => 5000,
        "sa" => 250
    ],
    [
        "id" => 5,
        "qt" => 10,
        "sa" => 9000
    ]
];

$p_qty = array();
$n_qty = array();
foreach ($array as $e) {
    if($e['qt'] <= 0){ array_push($n_qty, $e); }
    else             { array_push($p_qty, $e); }
}
usort($p_qty, function($a, $b){
    return
        $a['sa'] == $b['sa'] ? (
            $a['sa'] == $b['sa'] ? 0 : (
                $a['qt'] < $b['qt'] ? 1 : -1
            )
        ) : (
            $a['sa'] < $b['sa'] ? 1 : -1
        );
});
usort($n_qty, function($a, $b){
    return
        $a['sa'] == $b['sa'] ? (
            $a['sa'] == $b['sa'] ? 0 : (
                $a['qt'] < $b['qt'] ? 1 : -1
            )
        ) : (
            $a['sa'] < $b['sa'] ? 1 : -1
        );
});

I get the wanted result: ID [5, 4, 1, 3, 2]
Is there a simple to do the wanted result in a unique usort function ?


texts:
I'm using Swift 2.1 and ReactiveCocoa 4.0.4 alpha 1. I'm combining multiple signals to enable a button based on if they have valid inputs. The following code works correctly, but I'm wondering if there is a more elegant and efficient way of accomplishing this with the ReactiveCocoa APIs, as well as if this is the proper way to be using the API in Swift.

    let sig0 = firstTextField.rac_textSignal()
        .max(self.firstTextField, max: maxLength)
        .map{ next in
            if let str = next as? String {
                return str.characters.count > 0
            } else {
                return false
            }
    }

    let sig1 = secondTextField.rac_textSignal()
        .max(self.secondTextField, max: maxLength)
        .map{ next in
            if let str = next as? String {
                return str.characters.count > 0
            } else {
                return false
            }
    }

    let combined = RACSignal.combineLatest([sig0, sig1])
    combined.subscribeNext { (obj: AnyObject!) -> Void in
        let tup = obj as! RACTuple
        let valid = (tup.first as! Bool) && (tup.second as! Bool)
        self.button.enabled = valid
    }


texts:
I am learning Java and this is my solution for a program that will read in a name from the command line and write it out 100 times furthermore words are never split up assuming that the console is 80 characters wide.
Could someone please help me improve its quality?

/**
* Program to print command line argument 100 times
* Words are never split up. Assuming that the console is 80 characters wide.
*
**/
class Hundred {
    private static final int LINE_WIDTH = 80;

    public static void main(String[] args) {
        if(args.length == 0) {
            System.out.println("Argument missing");
        } else {
            String name = args[0];

            int wordsOnOneLine = LINE_WIDTH / (name.length() + 1);
            int i = 0;
            while(i < 100) {
                for(int j = 0; j < wordsOnOneLine && i < 100; j++) {
                    i++;
                    System.out.print(name);
                    System.out.print(" ");
                }
                System.out.println();
            }
        }
    }
}


texts:
I am just learning how to do some multiprocessing with Python, and I would like to create a non-blocking chat application that can add/retrieve messages to/from a database. This is my somewhat primitive attempt (note: It is simplified for the purposes of this post); however, I would like to know how close/far off off the mark I am. Any comments, revisions, suggestions, etc. are greatly appreciated.

Thank you!

import multiprocessing
import Queue
import time

# Get all past messages
def batch_messages():
    # The messages list here will be attained via a db query
    messages = [">> This is a message.", ">> Hello, how are you doing today?", ">> Really good!"]
    for m in messages:
        print m

# Add messages to the DB
def add_messages(q):

    # Retrieve from the queue
    message_to_add = q.get()

    # For testing purposes only; perfrom another DB query to add the message to the DB
    print "(Add to DB)"

# Recieve new, inputted messages.
def receive_new_message(q, new_message):

    # Add the new message to the queue:
    q.put(new_message)

    # Print the message to the screen
    print ">>", new_message

if __name__ == "__main__":

    # Set up the queue
    q = multiprocessing.Queue()

    # Print the past messages
    batch_messages()

    while True:
        # Enter a new message
        input_message = raw_input("Type a message: ")

        # Set up the processes
        p_add = multiprocessing.Process(target=add_messages, args=(q,))
        p_rec = multiprocessing.Process(target=receive_new_message, args=(q, input_message,))

        # Start the processes
        p_rec.start()
        p_add.start()

        # Let the processes catch up before printing "Type a message: " again. (Shell purposes only)
        time.sleep(1)


texts: Calculate True Positive, False Positive, True Negative and False negative and colourize output

texts:
Objective : Calculate True Positive, False Positive, True Negative and False negative and colourize the image accordignly, based on ground-truth and prediction from my classifier model.

Problem : Very Slow

Description:

The prediction is a gray-level image that comes from my classifier.

The truth_image is also a gray-level image, but its the correct image that prediction should try to approximate.

The mask_image segmentates the ROI ( region of interest), when its pixel value is 1, means its inside the region of interest, if its 0, then we should ignore and move on to the next pixel.

The output is the array where I want to keep the colourized image.

def coloured_prediction_truth(prediction, truth_image, mask_image,output_image):
    prediction = prediction.astype(np.uint8)
    truth_image = truth_image.astype(np.uint8)
    #output_image = np.empty(shape=(submission_image.shape[0], submission_image.shape[1], 4), dtype=np.uint8)

    #binarize values , values > 127 becomes 1. Else -> 0
    for i in xrange(0, prediction.shape[0]):
        for j in xrange(0, prediction.shape[1]):
            if prediction[i, j] > 127:
                prediction[i, j] = 1
            else:
                prediction[i, j] = 0

    for i in xrange(0, truth_image.shape[0]):
        for j in xrange(0, truth_image.shape[1]):
            if truth_image[i, j] > 127:
                truth_image[i, j] = 1
            else:
                truth_image[i, j] = 0

    for i in xrange(0, mask_image.shape[0]):
        for j in xrange(0, mask_image.shape[1]):
            if mask_image[i, j] > 127:
                mask_image[i, j] = 1
            else:
                mask_image[i, j] = 0

    # B-G-R-A
    blue = [255, 0, 0, 255]
    green = [0, 255, 0, 255]
    red = [0, 0, 255, 255]
    orange = [0, 128, 255, 255]
    black = [0, 0, 0, 255]

    TruePositive = 0.00
    TrueNegative = 0.00
    FalsePositive = 0.00
    FalseNegative = 0.00

    #Count pixel by pixel
    for i in xrange(0, output_image.shape[0]):
        for j in xrange(0, output_image.shape[1]):

            pred = prediction[i, j]
            truth = truth_image[i, j]
            mask = mask_image[i, j]

            if mask == 1:

                if pred == 1 and truth == 1:
                    output_image[i, j] = blue
                    TruePositive = TruePositive + 1
                else:
                    if pred == 0 and truth == 0:
                        output_image[i, j] = green
                        TrueNegative = TrueNegative + 1
                    else:
                        if pred == 0 and truth == 1:
                            output_image[i, j] = red
                            FalseNegative = FalseNegative + 1
                        else:
                            if pred == 1 and truth == 0:
                                output_image[i, j] = orange
                                FalsePositive = FalsePositive + 1
                            else:
                                output_image[i, j] = black
            else:
                output_image[i, j] = black

    accuracy = float((TruePositive + TrueNegative)) / float((TruePositive + FalsePositive + FalseNegative + TrueNegative))
    sensitivity = float((TruePositive)) / float((TruePositive + FalseNegative))
    specificity = float((TrueNegative)) / float((TrueNegative + FalsePositive))
    try:
        positivePredictiveValue = float((TruePositive)) / float((TruePositive + FalsePositive))
    except Exception:
        positivePredictiveValue = 0

    return output_image, TruePositive, TrueNegative, FalsePositive, FalseNegative, accuracy, sensitivity, specificity, positivePredictiveValue

Example :

From these 3 images, the coloured image, would be:


texts:
I completed the following exercise on HackerRank. My program is fed a list of commands, such as:

12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

Where the first line of the input is the number of commands, the rest of the lines commands and parameters.

Here is my code, nothing too fancy; any and all comments welcome!

def commdr(lst, instruct):
    if instruct[0] == 'insert':
        lst.insert(int(instruct[1]), int(instruct[2]))
    elif instruct[0] == 'print':
        print(lst)
    elif instruct[0] == 'remove':
        lst.remove(int(instruct[1]))
    elif instruct[0] == 'append':
        lst.append(int(instruct[1]))
    elif instruct[0] == 'sort':
        lst.sort()
    elif instruct[0] == 'reverse':
        lst.reverse()
    elif instruct[0] == 'pop':
        lst.pop()
    else:
        print("Command not recognized!")

n = int(input())
lst = []
for command in range(0,n):
    temp = [str(i) for i in input().strip().split()]
    commdr(lst, temp)


texts:
I know the following code are horrible, so I'd like a review. Criticism are welcome. I want to know what went wrong, and how I can avoid the same mistake in the future.

Version 1
const unsigned int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
for (int i = 1; i < argc; ++i) {
  unsigned long tmp;
  try { tmp = std::stoul(argv[i], nullptr, 10); }
  catch (std::invalid_argument) { std::cerr << "Invalid base! Conversion failed.\n"; return -2; }
  catch (std::out_of_range) { std::cerr << "Invalid base! Too large.\n"; return -2; }
  if (tmp > std::numeric_limits<unsigned int>::max()) { std::cerr << "Invalid base! Too large.\n"; return -2; }
  if (tmp < 2) { std::cerr << "Invalid base! Must at least be 2.\n"; return -2; }
  if (tmp > set_max) { std::cerr << "Invalid base! Must be within " << set_max << ".\n"; return -2; }
  base.push_back(static_cast<unsigned int>(tmp));
}

Version 2
const int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
try { for (int i = 1; i < argc; ++i) {
  unsigned long tmp; try { tmp = std::stoul(argv[i], nullptr, 0); }
  catch (std::invalid_argument                         ) { throw std::string("Conversion failed"                        ); }
  catch (std::out_of_range                             ) { throw std::string("Too large"                                ); }
  if    (tmp > std::numeric_limits<unsigned int>::max()) { throw std::string("Too large"                                ); }
  if    (tmp < 2                                       ) { throw std::string("Must at least be 2"                       ); }
  if    (tmp > set_max                                 ) { throw std::string("Must be within " + std::to_string(set_max)); }
  base.push_back(static_cast<unsigned int>(tmp));
} } catch (std::string &err_msg) { std::cerr << "Invalid base! " << err_msg << ".\n"; return -2; }

Version 3
const int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
for (int i = 1; i < argc; ++i) {
  unsigned long tmp;
  try {
    try {
      tmp = std::stoul(argv[i], nullptr, 0);
    }
    catch (std::invalid_argument) {
      throw std::string("Conversion failed");
    }
    catch (std::out_of_range) {
      throw std::string("Too large");
    }
    if (tmp > std::numeric_limits<unsigned int>::max()) {
      throw std::string("Too large");
    }
    if (tmp < 2) {
      throw std::string("Must at least be 2");
    }
    if (tmp > set_max) {
      throw std::string("Must be within " + std::to_string(set_max));
    }
  }
  catch (std::string &err_msg) {
    std::cerr << "Invalid base! " << err_msg << ".\n";
    return -2;
  }
  base.push_back(static_cast<unsigned int>(tmp));
}


texts:
In my game there are AI characters that try to either steal your gold or destroy the walls of your castle.  Previously I simply updated them all every second, but with a large number of characters on the map there were some noticeable frame skips.  This code spreads out the updating of the AIs so they are no longer done all at once.

I believe there are better ways to do this so I am looking for clues as to a better structure.

One nice thing about this approach is that it dynamically adapts to the number of AIs and will increase the speed of updates depending on how many are in game. It's also possible to change the number of AIs that will be updated each tick by changing a single variable.

public void updatePersons(float delta) {
    this.personAccumulator += delta;
    if (this.personAccumulator > this.timeBetweenPersonMoves) {
        this.personAccumulator = 0;

        this.personsToDestroy.clear();

        int numPersons = this.persons.size();
        int currentPerson = this.currentTick * this.numPersonsPerTick;
        int targetPerson = Math.min(numPersons, currentPerson + this.numPersonsPerTick);

        for (int i = currentPerson; i < targetPerson; i++) {
            PersonRoot person = this.persons.get(i);
            person.update(this.buildings);
            if (person.checkForFire(this.gameScreen.fireImages)) {
                person.shouldDestroy = true;

                this.gameScreen.personDied(person);
            }
            if (person.shouldDestroy) {
                this.personsToDestroy.add(person);
            }
        }

        for (PersonRoot person : this.personsToDestroy) {
            person.destroy();
            this.persons.remove(person);
        }

        //this now needs its own update because it will happen faster
        //when there are more persons as a side effect of this new approach
        this.spawnNewPersons();

        numPersons = this.persons.size();
        this.numTicksRequired = (int)Math.floor(numPersons / this.numPersonsPerTick);
        if (this.currentTick < this.numTicksRequired) {
            this.currentTick++;
        } else {
            this.currentTick = 0;
        }
        //adjust speed of ticks depending on how many persons there are
        if (this.numTicksRequired > 0) {
            this.timeBetweenPersonMoves = this.idealTimeBetweenPersonMoves / this.numTicksRequired;
        } else {
            this.timeBetweenPersonMoves = this.idealTimeBetweenPersonMoves;
        }
    }
}

They are not the greatest screenshots in the world, but I have some before and after screenshots from the profiling.

Before:

After:

Between the two screenshots I also changed a heavily used HashMap into a libGDX ObjectMap, so that has some effect on the numbers as well. Also, the idea behind the code above was not to necessarily increase overall performance, but rather to improve the user experience and reduce stuttering by spreading the work out over time.


texts: Show a ProgressDialog and send an SMS in the background

texts:
I have written a procedure that

shows a ProgressDialog
sends an SMS
updates the View from another thread
hides the ProgressDialog

But it seems to me that this is not the best way to do this. I would like to hear advice and my mistakes. It seems to me that it is possible to optimize the code for quick work procedures.

public boolean sendCommand(commandXDev command, final String uniValue) {
    SharedPreferences prefs = this.getSharedPreferences("serjaru.bsh.xdev2", Context.MODE_PRIVATE);
    final String phoneNumber = prefs.getString("phonenumber", "");
    int gateway = prefs.getInt("gateway", 0);

    if (gateway == 0) {

        if (command == commandXDev.Get) {
            final ProgressDialog progress = ProgressDialog.show(Relays.this, "Please wait", "Sending SMS...", true);
            progress.setCancelable(true);

            final Handler handler = new Handler();
            Runnable runnable = new Runnable() {

                public void run() {
                    if (myPhone.sendSMSMessage("+" + phoneNumber, ImeiPhone + "#get")) {
                        handler.post(new Runnable() {
                            public void run() {
                                statusLabel.setText("SMS sended!");
                            }
                        });
                    } else {
                        handler.post(new Runnable() {
                            public void run() {
                                statusLabel.setText("Error. SMS not sended.");
                            }
                        });
                    }
                    progress.dismiss();
                }
            };
            new Thread(runnable).start();
        }
    }
}


texts: Generating pattern similar to QR code using strings

texts:
I wrote this class to generate a random "image," similar to a QR code, using strings. How can I make it better (I am a beginner in programming)?

import random

""" N is the length of squared field to be generated"""
class genImg():
  def __init__(self, N):
    self.N = N
    self.field = []

  def genField(self):
    for i in range(self.N):
      row = []
      for j in range(self.N):
        row.append("|-|")
      self.field.append(row[:])

  def getField(self):
    return self.field

  def fillField(self):
    field = self.getField()
    result = ""
    for i in field:
      row = ""
      for j in i:
        randNum = random.randint(1,100)
        if randNum % 2 == 0 or randNum % 3 == 0:
          j = '|0|'
        row += str(j) + " "
      result += row[:-1] + "\n"
    print(result)


texts:
I've recently (an hour ago) started a project for making a wrapper for Imgur's API using the REST client Retrofit.

I've only implemented a single endpoint so far as I'm questioning my design. While I've been programming in Java for some time now, I'm only now taking my first class in high school, so I've been kinda winging designs in the past and trying to get better at them now.

I'm specifically questioning the contents of the response package.

I just pushed the project on Github, the project is currently less than 150 lines of code so it should be pretty easy to look through.

https://github.com/Rabrg/imgur-api

Response:

package me.rabrg.imgur.response;

import me.rabrg.imgur.response.model.Model;

public class Response<M extends Model> {

    public M data;

    public boolean success;
    public int status;
}

Model:

package me.rabrg.imgur.response.model;

public abstract class Model {
}

Image:

package me.rabrg.imgur.response.model;

public class Image extends Model {

    public String id;
    public String title;
    public String description;
    public long datetime;
    public String type;
    public boolean animated;
    public int width;
    public int height;
    public long size;
    public int views;
    public long bandwidth;
    public String deletehash;
    public String name;
    public String section;
    public String link;
    public String gifv;
    public String mp4;
    public String webm;
    public boolean looping;
    public boolean favorite;
    public boolean nsfw;
    public String vote;
    public String account_url;
    public String account_id;
}


texts: Transforming class names to method names

texts:
I have a lot of filter classes which are named after the method names they filter by.

For example:

OrderByBestValueFilter corresponds to #best_value
OrderByPriceFilter corresponds to #price

and so on...

Since I'm doing a lot of these transformations, and the point of this set us is to make filters easy to add or remove, I have a base class where most of the work is done.  To extract the method name from the calling class, I have this method:

def criteria
  class_name = self.class.name.split('::').last
  class_name.sub!(/Order/, '')
  class_name.sub!(/By/, '')
  class_name.sub!(/Filter/, '')
  class_name.scan(/[A-Z][^A-Z]*/)
  class_name.map(&:downcase).join('_')
end

which I pared down to the following:

def criteria
  class_name = self.class.name.split('::').last
  name = class_name.scan(/[A-Z][^A-Z]*/) - %w[Order By Filter]
  name.map(&:downcase).join('_')
end

but this is still gross.  Any suggestions?


texts:
In my code, there is a chain of functions call where the deepest function may throw an exception. I catch and handle it according to the business logic. The problem is that all other functions in the call chain are dependent on this function, thus, if the deepest function returns null all others function will throw the NullPointerException.

My question is, from the code style/maintainability/best practices point of view, can I care about the exception only at the deepest call chain level and in all higher function in the chain use something like catch (NullPointerException ignored) {}?

Is it a good idea at all to use ignored in a try-catch expression or should I really address to all catches even if they are just the consequences of the execution of another function, where I do the proper exception handling?

The code fragment:

public static JSONObject jsonBuilder(String xmlDataSource) {

    JSONObject xmlJSONObj = null;

    try {
        xmlJSONObj = XML.toJSONObject(xmlDataSource);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return xmlJSONObj;
}

public static void fetchPushData(DBDriver drv, MongoCollection<Document> dbColl, TrackedEpisode episode) {

    String xmlFeed = JsonHandler.xmlDataLoader(episode.getUrlRSS());

    try {
        JSONObject xmlJSONObj = JsonHandler.jsonBuilder(xmlFeed);

        JsonHandler.docBuilderEvent(xmlJSONObj, episode.getEpisodeID());

        JSONArray itemsArr = JsonHandler.getItemsArr(xmlJSONObj);

        episode.setEpisodeLastUpdate(getLatestPubDate(itemsArr));

        drv.insertToDB(dbColl, itemsArr);

    } catch (NullPointerException ignored) {}
}

Here we can see that in case of failure jsonBuilder() throws exception, which I handle and returns null. Now, the docBuilderEvent() will also throw NullPointerException due to null in xmlJSONObj. Should I care about this NullPointerException or it's enough to handle it only in the jsonBuilder()?


texts:
This is the first PHP script I have written. It downloads and installs a plugin called "anti-spam" by using the WordPress API. It also provides an option to either delete all comments or delete the comments, which are unapproved or marked as SPAM.

        <title>SPAM tool</title>

Simple SPAM Managing tool

<form action="" method="post">
<input type="radio" name="radio" value="all">Delete ALL comments

<input type="radio" name="radio" value="un">Delete UNapproved comments

<input type="submit" name="submit" value="Kill spam" />
</form>

            <?php

include "wp-config.php"; #adds Wordpress configuration, so we can use DB config
include "wp-load.php";
include "wp-admin/includes/plugin.php";
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); #connect to DB
    if (!$connect) {
    echo 'Database connect failed';
    } else {
    echo 'Connection to database OK!';
    }
        echo "
";
$select = mysql_select_db(DB_NAME);
$tablename = $table_prefix . "comments";
$query  = ("SELECT COUNT(comment_approved) FROM $tablename WHERE comment_approved = 0");
$execute = mysql_query($query, $connect);
    if ($execute) {
            echo ("Comments UNapproved (comment_approved = 0): "), mysql_result($execute, 0);}
    else {echo "Comment count failed";}

        echo ('
');
$query  = ("SELECT COUNT(comment_approved) FROM $tablename");
$execute = mysql_query($query, $connect);
    if ($execute) {
            echo ("Comments total: "), mysql_result($execute, 0);}
        else {echo "Comment count failed";}

        echo ('
');
    $args = (object) array( 'slug' => 'Anti-spam' );

    $request = array( 'action' => 'plugin_information', 'timeout' => 15, 'request' => serialize( $args) );

    $url = 'http://api.wordpress.org/plugins/info/1.0/';

    $response = wp_remote_post( $url, array( 'body' => $request ) );

    $plugin_info = unserialize( $response['body'] );

    $durl = $plugin_info->download_link;

    echo "$durl";
$download = file_put_contents("antispam.zip", file_get_contents("$durl")); #downloads the Anti-spam plugin
if ($download) {
echo "Download OK!";}
else {
echo "Download FAIL!";} #check if download is OK
echo "
";
$path = getcwd();
$zip = new ZipArchive; #extracts the .zip
if ($zip->open('antispam.zip') === TRUE) {
    $zip->extractTo("$path/wp-content/plugins/");
    $zip->close();
    echo 'Plugin extracted';
} else {
    echo 'Extract Failed';
    }
echo "
";
$activate = activate_plugin( "$path/wp-content/plugins/anti-spam/anti-spam.php" ); #Activate the plugin
if ( is_wp_error( $activate ) ) {

} else {
echo 'AntiSPAM plug-in activated!';}

echo ('
');
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
{
if ($_POST['radio']=="all") { $select = mysql_select_db(DB_NAME);
$tablename = $table_prefix . "comments";
$query  = ("TRUNCATE $tablename"); #TRUNCATE comments
mysql_query($query, $connect);
echo "DELETED!";
}
elseif ($_POST['radio']=="un") { $select = mysql_select_db(DB_NAME);
$tablename = $table_prefix . "comments";
$tablename2 = $table_prefix . "commentmeta"
$query  = ("DELETE FROM $tablename WHERE comment_approved = 0 or comment_approved = 'spam'");
mysql_query($query, $connect);
$query2  = ("DELETE FROM $tablename2 WHERE comment_id NOT IN (SELECT comment_id FROM $tablename)");
mysql_query($query2, $connect);
echo "DELETED!";
    } }}
else{ echo "Please choose any radio button.";}
mysql_close($connect);
exit;
?>

You can also check the project's repository at GitHub.


texts:
I'm also doing the fun little Advent of Code challenges in order to learn Rust. Until now things went quite smoothly, but while I'm proceeding with the tasks I'd love to learn where I can actually improve my Rust coding (and not only getting the correct results).

I'm specifically looking for feedback where I'm violating Rust idioms or suggestions e.g. for simplifications as my knowledge of the Rust STD library features is still quite limited. On the other hand in context of those coding challenges I don't really care too much about stuff like input validation/stability/error handling or even performance (as you would in actual production code).

As requested, a small summary of what the program does, as the linked description is admittedly a little exhaustive:

The program basically simulates very basic machine code. A set of instructions represented as a list of integers values is given by a text file (comma delimited values).

Instructions start with an "opcode", describing the operations. In our case this may either be an addition (1), multiplication (2) or program end (99). All other values are deemed invalid as an opcode. The 3 integers following the opcodes are the parameters, giving the addresses of the operands (offset 1 and 2), as well as the target address to store the result (offset 3).

The result of the program is defined to be stored at address 0. In the 2nd part of the task one is given a program result (target_value 19690720) and is supposed to figure out which values need to reside at the memory addresses at 1 and 2 before starting the program (which are in this context called "noun" and "verb") in order to get this result.

Here's my implementation part 2 of day 2:

use std::fs;

fn add_values (value_a: i32, value_b: i32, target: &mut i32) {
    *target = value_a + value_b
}

fn multiply_values (value_a: i32, value_b: i32, target: &mut i32) {
    *target = value_a * value_b
}

fn run_program(memory: &mut Vec<i32>) -> i32 {
    let command_stride = 4;
    let mut current_pos = 0;
    while current_pos < memory.len() {
        let current_instruction = memory[current_pos];
        let address_a = memory[current_pos + 1] as usize;
        let address_b = memory[current_pos + 2] as usize;
        let address_target = memory[current_pos + 3] as usize;
        match current_instruction {
            1 => add_values(memory[address_a], memory[address_b], &mut memory[address_target]),
            2 => multiply_values(memory[address_a], memory[address_b], &mut memory[address_target]),
            99 => break,
            _ => panic!("Invalid command value!")
        }
        current_pos += command_stride;
    }
    //return result of the program stored at address 0
    memory[0]
}

fn main() {
    let contents = fs::read_to_string("input.txt")
        .expect("Something went wrong reading the file");

    let split_codes = contents.split_terminator(',');
    let codes : Vec<i32> = split_codes.filter_map(|v| v.parse::<i32>().ok()).collect();

    let target_value = 19690720;

    for noun in 0..100 {
        for verb in 0..100 {
            let mut current_memory = codes.clone();
            //init noun and verb
            current_memory[1] = noun;
            current_memory[2] = verb;

            let current_result = run_program(&mut current_memory);

            if current_result == target_value {
                 println!("Target value reached, noun: {}, verb {}", noun, verb);
                 println!("Result = {}", 100*noun + verb);
                 break;
            }
        }
    }
}


texts:
So I get a user input of a lot of numbers in a single line like this

100 100 200 300 300 300 400 500 500 700.

I want to store the distinct ones in a list.
A simple approach is to do this:

nums = input().split(' ')
myList = list(set([(int(i) for i in nums]))

My question is, is this a faster/better way:

nums = input().split(' ')
setList = set()
myList = []
for i in nums:
    if int(i) not in setList:
        myList.append(int(i))
        setList.add(int(i))


texts:
In my code I have three requests to a MySQL database:

@app.route('/private', methods=['POST'])
def private():
    login = request.form['login']
    if login is None or not login:
        return jsonify(data='Incorrect URL')

    try:
        c, conn = cursor_connection()
        c = conn.cursor()
        c.execute("SELECT accounts_info_uid "
                  "FROM auth_info WHERE login='{}' ".format(login))

        id = c.fetchall()
        if not id:
            return jsonify(data='Incorrect login')

        c.execute("SELECT * FROM boxes_id AS tb1 LEFT JOIN"
                  " accounts_info AS tb2 ON tb2.boxes_ids=tb1.uid "
                  # "LEFT JOIN electricity_info as tb3 ON tb3.boxes_id_uid=tb1.uid"
                  " WHERE tb2.uid={} ".format(id[0][0]))

        uid, mc_address, working_status, activation_status, _,\
        first_name, second_name, registration_date, phone, email, boxes_id = c.fetchall()[0]
        c.execute(" SELECT consumed_electricity "
                  "FROM electricity_info "
                  "WHERE boxes_id_uid={} ".format(boxes_id))
        consumed_electricity = [float(val[0]) for val in c.fetchall()]
        c.close()
        conn.close()

    except Exception as e:
        logger.error(msg='Cannot execute /private {}'.format(e))
        return str(e)

I fetched a list from electricity info by primary key in boxes_id (so in electricity_info it is called boxes_id_uid).

Structure of pk in my tables:

auth_info --------> pk is accounts_info_uid

boxes_id ----------> pk is uid

accounts_info ------> pk is uid and it is connected to table boxes_id by field boxes_id

electricity_info ------> pk is boxes_id_uid

I think it can be optimized in one SQL request. If so, can you tell me how to achieve that?


texts: PySpark Dataframes program to process huge amounts of server data from a parquet file

texts:
I'm new to spark and dataframes and I'm looking for feedback on what bad or inefficient processes might be in my code so I can improve and learn.  My program reads in a parquet file that contains server log data about requests made to our website.  I think it is pretty self-explanatory, the only parts that might not be is that we add some etl fields for tracking, and we cast the accessing device to one of a set of choices to make reporting easier (accomplished through the switch sql expression).

Here is my code:

from functools import reduce
from time import time

from boto3 import client
import psycopg2 as ppg2
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import col, current_date, date_format, lit, when

EMR_CLIENT = client('emr')
conf = SparkConf().setAppName('Canvas Requests Logs')
sc = SparkContext(conf=conf)
sql_context = SQLContext(sc)
# for dependencies
# sc.addPyFile()

if __name__ == '__main__':
    start = time()
    df = sql_context.read.parquet(
        r'/Users/mharris/PycharmProjects/etl3/pyspark/Datasets/'
        r'usage_data.gz.parquet')

    course_data = df.filter(df['context_type'] == 'Course')
    request_data = df.select(
        df['user_id'],
        df['context_id'].alias('course_id'),
        date_format(df['request_timestamp'], 'MM').alias('request_month'),
        df['user_agent']
    )

    sesh_id_data = df.groupBy('user_id').count()
    sesh_id_data = sesh_id_data.withColumnRenamed('count', 'num_sessions')

    joined_data = request_data.join(
        sesh_id_data,
        on=request_data['user_id'] == sesh_id_data['user_id']
    ).drop(sesh_id_data['user_id'])

    etl_fields = [c.alias(a) for (a, c) in [
        ('etl_process_status', lit('DEV')),
        ('etl_datetime_local', current_date()),
        ('etl_transformation_name', lit('agg_canvas_logs_user_agent_types')),
        ('etl_pdi_version', lit(r'Apache Spark')),
        ('etl_pdi_build_version', lit(r'1.6.1')),
        ('etl_pdi_hostname', lit(r'N/A')),
        ('etl_pdi_ipaddress', lit(r'N/A')),
        ('etl_checksum_md5', lit(r'N/A'))
    ]]

    case_stmt = r'''
    CASE
        WHEN user_agent LIKE '%CanvasAPI%' THEN 'api'
        WHEN user_agent LIKE '%candroid%' THEN 'mobile_app_android'
        WHEN user_agent LIKE '%iCanvas%' THEN 'mobile_app_ios'
        WHEN user_agent LIKE '%CanvasKit%' THEN 'mobile_app_ios'
        WHEN user_agent LIKE '%Windows NT%' THEN 'desktop'
        WHEN user_agent LIKE '%MacBook%' THEN 'desktop'
        WHEN user_agent LIKE '%iPhone%' THEN 'mobile'
        WHEN user_agent LIKE '%iPod Touch%' THEN 'mobile'
        WHEN user_agent LIKE '%iPad%' THEN 'mobile'
        WHEN user_agent LIKE '%iOS%' THEN 'mobile'
        WHEN user_agent LIKE '%CrOS%' THEN 'desktop'
        WHEN user_agent LIKE '%Android%' THEN 'mobile'
        WHEN user_agent LIKE '%Linux%' THEN 'desktop'
        WHEN user_agent LIKE '%Mac OS%' THEN 'desktop'
        WHEN user_agent LIKE '%Macintosh%' THEN 'desktop'
        ELSE 'other_unknown'
    END AS user_agent_type
    '''
    all_fields = joined_data.select('*', *etl_fields)
    final_data = all_fields.selectExpr(
        '*', case_stmt
    ).drop(all_fields['user_agent'])
    # TODO Study the below code for understanding
    # c = col("user_agent")
    # vs = [('Android', 'mobile'), ('Linux', 'desktop')]
    # expr = reduce(
    #     lambda acc, kv: when(c.like(kv[0]), kv[1]).otherwise(acc),
    #     vs,
    #     'other_unknown'
    # ).alias('user_agent_type')
    final_data = final_data.select(
        'user_id',
        'course_id',
        'request_month',
        'user_agent_type',
        'num_sessions',
        'etl_process_status',
        'etl_datetime_local',
        'etl_transformation_name',
        'etl_pdi_version',
        'etl_pdi_build_version',
        'etl_pdi_hostname',
        'etl_pdi_ipaddress',
        'etl_checksum_md5'
    )
    final_data.write.parquet('outfile')
    end = time()
    print('Total run time was {time}'.format(time=end - start))


texts: ListView MultiSelect, MVVM and RoutedCommands

texts:
As far as I know (and I don't claim to know much about this!), direct binding to ListView.SelectedItems isn't possible in WPF. I've seen work-arounds involving code-behind which I'm not too crazy about, especially since I'm having a hard time with getting a DelegateCommand to work, and decided to use RoutedCommands. For the following XAML command binding...

<UserControl.CommandBindings>
    <CommandBinding Command="{x:Static my:ClientSearchSection.AddSelectionCommand}"
                    CanExecute="CanExecuteAddSelectionCommand"
                    Executed="ExecuteAddSelectionCommand"/>
</UserControl.CommandBindings>

...I have the following code-behind:

public static readonly RoutedCommand AddSelectionCommand = new RoutedCommand();

private void CanExecuteAddSelectionCommand(object sender, CanExecuteRoutedEventArgs e)
{
    if (Commands != null)
    {
        Commands.SelectedClients = SearchResultsList.SelectedItems.Cast<ClientViewModel>().ToList();
        e.CanExecute = Commands.CanExecuteAddSelectionCommand();
    }
    e.Handled = true;
}

private void ExecuteAddSelectionCommand(object sender, ExecutedRoutedEventArgs e)
{
    Commands.SelectedClients = SearchResultsList.SelectedItems.Cast<ClientViewModel>().ToList();
    Commands.OnExecuteAddSelectionCommand();
    e.Handled = true;
}

Where Commands is a get-only private property that returns an interface implemented by the ViewModel, which defines all the CanExecuteXXXX and ExecuteXXXX methods.

Here's how I have it:

private IViewModel _viewModel;
private IClientsSearchSectionCommands Commands { get { return _viewModel as IClientsSearchSectionCommands; } }

public ClientSearchSection()
{
    InitializeComponent();
    DataContextChanged += ClientsSearchSection_DataContextChanged;
}

void ClientSearchSection_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    _viewModel = e.NewValue as IViewModel;
}

This allows me to implement the command code in the ViewModel, for example:

public bool CanExecuteAddSelectionCommand()
{
    return SelectedClients.Count > 0;
}

public void OnExecuteAddSelectionCommand()
{
    // whatever needs to happen here, I can access my model as needed
}

The trick that allows the SelectedItems to work is with this property, exposed by the IClientsSearchSectionCommands interface implemented by the ViewModel:

public IList<ClientViewModel> SelectedClients { get; set; }

...and the fact that I'm setting them in the commands' CanExecute and Executed handlers.

This works beautifully... but is it weird in any way? [How] could it be done better?

I don't want to dive into behaviors at this point, firstly because I have no clue about them, second, because I'm dragging a more junior developper into WPF & MVVM, coming from WinForms and inline-SQL-in-the-form's-code-behind, so I'd like to know if this code is easy enough to follow...


texts: Get the Nth Term in the Fibonacci Sequence

texts:
I'm trying out a new editor (CLion) and I decided to try an old well known programming problem. I also decided to try out C99 rather than C89.

This program calculates the nth term of the Fibonacci Sequence where the value of the current term is the sum of the 2 previous terms. The first 4 terms are 0, 1, 1, 2. The upper limit applied in the program is the 91st term, on my computer using long long the term value goes negative at 93rd term.

All Comments and observations are appreciated. I'm especially interested in performance, function and variable names and suggestions about how I can increase the range of terms using integers. I know I can use doubles but that may incur floating point errors at some point. As far as performance goes, the program has a nice small memory signature (0.5% of the system memory) speed is where I would be worried.

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

static const int MinimumTerm = 0;
static const int MaximumTerm = 91;
static const int MaxTries = 3;
static const int inputFailure = -1;

static int getTermCount()
{
    char *fmtstr = "Please enter an integer value between %d and %d\n";
    printf(fmtstr, MinimumTerm, MaximumTerm);

    int term = 0;
    int count = 0;
    do
    {
        scanf("%d", &term);
        if (count < MaxTries)
        {
            if (term < MinimumTerm || term > MaximumTerm)
            {
                fprintf(stderr, fmtstr, MinimumTerm, MaximumTerm);
            }
        }
        else
        {
            return inputFailure;
        }
        count++;
    } while (term < MinimumTerm || term > MaximumTerm);

    return term;
}

static long long getNthFibonacciTerm(int term)
{
    int termCount = 2;
    long long prevValue = 0;
    long long nthValue = 1;

    switch  (term)
    {
        case 0: return 0;
        case 1: return 1;
    }

    while  (termCount < term)
    {
        long long newValue = prevValue + nthValue;
        prevValue = nthValue;
        nthValue = newValue;
        termCount++;
    }

    return  nthValue;
}

int main()
{
    int term = getTermCount();
    if (term < MinimumTerm)
    {
        fprintf(stderr, "Invalid Input\n");
        return EXIT_FAILURE;
    }

    printf("The %d term of the Fibonacci Sequence is %lld\n", term, getNthFibonacciTerm(term));

    return EXIT_SUCCESS;
}


texts:
The following C# methods take n bits and operates on them all in one pass.

// Sets n bits to zero at index i.
uint zerobits(uint x, int n, int i) {
    return x & ~((uint.MaxValue >> (sizeof(uint) * 8 - n)) << i);
}

// Sets n bits to one at index i.
uint setbits(uint x, int n, int i) {
    return x | ((uint.MaxValue >> (sizeof(uint) * 8 - n)) << i);
}

// Toggles n bits at index i.
uint togglebits(uint x, int n, int i) {
    return x ^ ((uint.MaxValue >> (sizeof(uint) * 8 - n)) << i);
}

Is there any way to optimize these? Or do they not need to be optimized at all?


texts: ListView + ArrayAdapter: Setting OnClickListener to items

texts:
I've recently written a Java program that displays a list of Word objects using a ListView and a custom ArrayAdapter.
I also want to set an OnClickListener on the items that plays an audio file (specified in the Word class).
This is the code I've written for it:
WordAdapter.java:

/* Set OnClickListener on item */
    // Create MediaPlayer for the audio file
    final MediaPlayer audio = MediaPlayer.create(getContext(), currentWord.getAudioResourceId());
    // Set OnClickListener
    listItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!audio.isPlaying()) {
                audio.start();
            }
        }
    });

Is there a more efficient way to accomplish this behaviour?


texts: Getting B+ matrix (Warshall algorithm) in Matlab

texts:
Pseudocode:

// B = nxn binary matrix
// Bm = resulting matrix
for (i=1; i<=n; i++)
{
  for (j=1; j<=n; j++)
  {
    if (B[i,j] == 1)
    {
      for (k=1; k<=n; k++)
      {
        Bm[i,j] = B[i,j] | B[k,j];
      }
    }
  }
}

This is the Warshall algorithm written (in my way):

B = [1 1 0 0 0; 0 0 0 1 0; 0 0 0 0 1; 0 1 0 0 0; 0 0 0 0 0];

n = 5;

Bm = zeros(n);

for i = 1:n
    for j = 1:n
        if B(i,j) == 1
            for k = 1:n
                Bm(i,k) = B(i,k) | B(k,j);
            end
        end
    end
end

It works but, how can I improve the matrix loops?


texts:
So I've made custom binary streams which work like this:

/// \brief Reads a variable from the stream.
/// \tparam T Type of the variable.
/// \param[out] var Variable to read.
/// \return Reference to this stream.
/// \throw TODO
/// \note No endianness conversion will be performed if a byte is not 8 bit
/// wide.
template <typename T>
BinaryInputStream& operator>>(T& var)
{
    static_assert(std::is_pod<T>::value, "BinaryInputStream::operator>>: "
        "Binary stream can only read POD types.");
    static_assert(!std::is_enum<T>::value, "BinaryInputStream::operator>>: "
        "Directly reading enums is unsafe. Implement a custom overload and "
        "check the value inside it.");
    char* buffer = reinterpret_cast<char*>(&var);
    std::size_t buffersize = sizeof(var);
    this->Read(buffer, buffersize);
#if CHAR_BIT == 8
    Endianness systemendianness = General::GetEndianness();
    if (systemendianness == Endianness::Unknown)
    {
        return *this;
    }
    if (systemendianness != this->GetEndianness())
    {
        SwapBytes(var);
    }
#endif
    return *this;
}

/// \brief Writes a variable to the stream.
/// \tparam T Type of the variable.
/// \param[in] var Variable to write.
/// \return Reference to this stream.
/// \throw TODO
/// \note No endianness conversion will be performed if a byte is not 8 bit
/// wide.
template <typename T>
BinaryOutputStream& operator<<(T var)
{
    static_assert(std::is_pod<T>::value,
        "Binary stream can only write POD types.");
#if CHAR_BIT == 8
    Endianness systemendianness = General::GetEndianness();
    if ((systemendianness != Endianness::Unknown) &&
        (systemendianness != this->GetEndianness()))
    {
        SwapBytes(var);
    }
#endif
    char* buffer = reinterpret_cast<char*>(&var);
    std::size_t buffersize = sizeof(var);
    this->Write(buffer, buffersize);
    return *this;
}

/// \brief Swaps bytes of a given variable.
/// \tparam T type of the variable.
/// \param[in,out] var Input variable.
template <typename T>
void SwapBytes(T &var)
{
    char* buffer = reinterpret_cast<char*>(&var);
    for (std::size_t i = 0, j = sizeof(var) - 1; i < j; ++i, --j)
    {
        std::swap(buffer[i], buffer[j]);
    }
}

Is this correct? Have I triggered undefined behavior? Are static_asserts correct? Maybe they are overly restrictive or not strict enough? Please quote the standard if possible.


texts: Creating a list from combinations of the original data

texts:
I am trying to create a list based on some data, but the code I am using is very slow when I run it on large data. So I suspect I am not using all of the Python power for this task. Is there a more efficient and faster way of doing this in Python?

Here an explanantion of the code:

  You can think of this problem as a list of games (list_type) each with a list of participating teams and the scores for each team in the game (list_xx).For each of the pairs in the current game it first calculate the sum of the differences in score from the previous competitions (win_comp_past_difs); including only the pairs in the current game.  Then it update each pair in the current game with the difference in scores. Using a defaultdict keeps track of the scores for each pair in each game and update this score as each game is played.

In the example below, based on some data, there are for-loops used to create a new variable list_zz.

The data and the for-loop code:

import pandas as pd
import numpy as np
from collections import defaultdict
from itertools import permutations

list_type = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'], ['C', 'A', 'B'], ['A'], ['B', 'C']]

list_xx = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0], [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]

list_zz= []
#for-loop
wd = defaultdict(float)
for i, x in zip(list_type, list_xx):
    # staff 1
    if len(i) == 1:
        #print('NaN')
        list_zz.append(np.nan)
        continue
    # Pairs and difference generator for current game (i)
    pairs = list(permutations(i, 2))
    dgen = (value[0] - value[1] for value in permutations(x, 2))
    # Sum of differences from previous games incluiding only pair of teams in the current game
    for team, result in zip(i, x):
        win_comp_past_difs = sum(wd[key] for key in pairs if key[0] == team)
        #print(win_comp_past_difs)
        list_zz.append(win_comp_past_difs)
    # Update pair differences for current game
    for pair, diff in zip(pairs, dgen):
        wd[pair] += diff
print(list_zz)

Which looks like this:

[0.0,
 0.0,
 nan,
 -4.0,
 4.0,
 0.0,
 0.0,
 0.0,
 nan,
 -10.0,
 13.0,
 -3.0,
 nan,
 3.0,
 -3.0,
 -6.0,
 6.0,
 -10.0,
 -10.0,
 20.0,
 nan,
 14.0,
 -14.0]

If you could elaborate on the code to make it more efficient and execute faster, I would really appreciate it.


texts: Validating email addresses through temporary mail message

texts:
I was given this project and have changed a lot of code on it, now I am going over the code to make sure that I know what everything does and can maintain it efficiently, and to make sure I want my name on it.

Here is the method they have been using to validate e-mail addresses from a textbox input.

private string ValidateEmailAddresses(string addressesIn)
{
    MailMessage msg = new MailMessage();

    if (!String.IsNullOrWhiteSpace(addressesIn))
    {
        string[] allAddresses = addressesIn.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        foreach (string addy in allAddresses)
        {
            try
            {
                msg.To.Add(addy);
            }
            catch (FormatException)
            { }
        }
    }
    return msg.To.ToString();
}

Is there a better way to accomplish this task?


texts: Generate subsets of k elements from a set of strings

texts:
This is the task:

Write a recursive program, which prints all subsets of a given set of N words.
Example input:
words = {'test', 'rock', 'fun'}

Example output:
(), (test), (rock), (fun), (test rock), (test fun),

(rock fun), (test rock fun)

In fact I need to generate all subsets from 0 to words.Length. In Pascal (if anybody knows) there is a function (not sure that it's "function") that looks like that:
var a:set of example

I need the same in C#. This is what I tried (the program works, but it's a lot of code):
class Program
{
    static int abc;
    static string[] extractedwords;
    static int k;
    static int margin;
    static string[] words = { "coffee", "ice-cream", "chocolate", "red" };
    static void Main(string[] args)
    {
        abc = 0;
        k = 1;
        Console.WriteLine("The margin of words: ");
        margin = int.Parse(Console.ReadLine());
        extractedwords = new string[margin];
        GenerateWords(0);
    }
    static void GenerateWords(int n)
    {
        if (n == k)
        {
            if (n != 0)
            {
                for (int s = n - 1; s >= 0; s--)
                {
                    for (int a = 0; a < s; a++)
                    {
                        if (extractedwords[s] == extractedwords[a])
                        {
                            return;
                        }
                    }
                }
            }
            PrintWords(extractedwords);
            return;
        }
        for (int a = 0; a < words.Length; a++)
        {
            extractedwords[n] = words[a];
            GenerateWords(n + 1);
        }
        if (k >= margin)
        {
            return;
        }
        if (n == 0)
        {
            k++;
            GenerateWords(n);
        }
    }
    static void PrintWords(string[] words)
    {
        for (int n = 0; n < words.Length; n++)
        {
            Console.Write("{0} ", words[n]);
        }
        Console.WriteLine();
    }
}


texts: Java app for getting metadata of millions of files in a directory

texts:
I am writing a Java app that gets the metadata of files in a directory and exports it to a .csv file. The app works fine if the number of files is fewer than a million. But if I feed in a path that has about 3200000 files in all of directories and sub-directories, it takes forever. Is there a way I can speed up things here?

    private void extractDetailsCSV(File libSourcePath, String extractFile) throws ScraperException {

    log.info("Inside extract details csv");

    try{
        FileMetadataUtil fileUtil = new FileMetadataUtil();

        File[] listOfFiles = libSourcePath.listFiles();

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

            if(listOfFiles[i].isDirectory()) {
                extractDetailsCSV(listOfFiles[i],extractFile);
            }

            if(listOfFiles[i].isFile()){

                ScraperOutputVO so = new ScraperOutputVO();

                Path path = Paths.get(listOfFiles[i].getAbsolutePath());

                so.setFilePath(listOfFiles[i].getParent());
                so.setFileName(listOfFiles[i].getName());

                so.setFileType(getFileType(listOfFiles[i].getAbsolutePath()));

                BasicFileAttributes basicAttribs = fileUtil.getBasicFileAttributes(path);
                if(basicAttribs != null) {
                    so.setDateCreated(basicAttribs.creationTime().toString().substring(0, 10) + " " + basicAttribs.creationTime().toString().substring(11, 16));
                    so.setDateLastModified(basicAttribs.lastModifiedTime().toString().substring(0, 10) + " " + basicAttribs.lastModifiedTime().toString().substring(11, 16));
                    so.setDateLastAccessed(basicAttribs.lastAccessTime().toString().substring(0, 10) + " " + basicAttribs.lastAccessTime().toString().substring(11, 16));
                }

                so.setFileSize(String.valueOf(listOfFiles[i].length()));
                so.setAuthors(fileUtil.getOwner(path));

                so.setFolderLink(listOfFiles[i].getAbsolutePath());
                writeCsvFileDtl(extractFile, so);

                so.setFileName(listOfFiles[i].getName());
                noOfFiles ++;
            }
        }
    } catch (Exception e) {
        log.error("IOException while setting up columns" + e.fillInStackTrace());
        throw new ScraperException("IOException while setting up columns" , e.fillInStackTrace());
    }

    log.info("Done extracting details to csv file");
}

public void writeCsvFileDtl(String extractFile, ScraperOutputVO scraperOutputVO) throws ScraperException {
    try {
        FileWriter writer = new FileWriter(extractFile, true);
        writer.append(scraperOutputVO.getFilePath());
        writer.append(',');
        writer.append(scraperOutputVO.getFileName());
        writer.append(',');
        writer.append(scraperOutputVO.getFileType());
        writer.append(',');
        writer.append(scraperOutputVO.getDateCreated());
        writer.append(',');
        writer.append(scraperOutputVO.getDateLastModified());
        writer.append(',');
        writer.append(scraperOutputVO.getDateLastAccessed());
        writer.append(',');
        writer.append(scraperOutputVO.getFileSize());
        writer.append(',');
        writer.append(scraperOutputVO.getAuthors());
        writer.append(',');
        writer.append(scraperOutputVO.getFolderLink());
        writer.append('\n');
        writer.flush();
        writer.close();
    } catch (IOException e) {
        log.info("IOException while writing to csv file" + e.fillInStackTrace());
        throw new ScraperException("IOException while writing to csv file" , e.fillInStackTrace());

    }
}
}


texts:
First attempt at dynamic programming. I want to make this run faster and better.

fibonacci.cpp

#include "fibonacci.h"

std::map<int, unsigned long long int> initializeMap() {
    std::map<int, unsigned long long int> m;
    m[0] = 0;
    m[1] = 1;
    return m;
}

std::map<int, unsigned long long int> __fib_result_map = initializeMap();

unsigned long long int fibonacci(int seq) {
    using namespace std;
    map<int, unsigned long long int>& m = __fib_result_map;
    if(m[seq] == 0 && seq != 0) {
        m[seq] = fibonacci(seq - 2) + fibonacci(seq - 1);
    }
    return m[seq];
}

fibonacci.h

#ifndef __fibonacci
#define __fibonacci

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>

unsigned long long int fibonacci(int seq);

#endif

fib_cpp.cpp

#include "fibonacci.h"
#include <cstdlib>
using namespace std;

int main(int argc, char* argv[]) {

    if(argc <= 1) {
        cerr << "No arguments specified. Usage: " << argv[0] << " <values>\n";
        return 1;
    }
    for(int i = 1; i < argc; i++) {
        cout << fibonacci(atoi(argv[i])) << endl;
    }
    return 0;
}

Here is the repository on Github.


texts:
From SICP's 1.24: (Exponentiation)

(you may need to click through and read ~1 page to understand)

  Exercise 1.16.  Design a procedure
  that evolves an iterative
  exponentiation process that uses
  successive squaring and uses a
  logarithmic number of steps, as does
  fast-expt. (Hint: Using the
  observation that (bn/2)2 = (b2)n/2,
  keep, along with the exponent n and
  the base b, an additional state
  variable a, and define the state
  transformation in such a way that the
  product a bn is unchanged from state
  to state. At the beginning of the
  process a is taken to be 1, and the
  answer is given by the value of a at
  the end of the process. In general,
  the technique of defining an invariant
  quantity that remains unchanged from
  state to state is a powerful way to
  think about the design of iterative
  algorithms.)

I wrote the following solution:

(define (even n) (= (remainder n 2) 0))

(define (fast-expt b n)
  (fast-expt-iter b b n))

(define (fast-expt-iter a b n)
  (cond ((= n 1) a)
    ((even n) (fast-expt-iter (* a b) b (/ n 2)))
    (else (fast-expt-iter (* a b) b (- n 1)))))

Do you think my solution is correct?  Moreover, what do you think about my code?


texts:
I'm trying to generate a vigenere square using expl3. My aim is to provide an easy interface for different alphabets and different scaling. Therefore I chose a tabular-based approach which seemed very easy to customize.

Points I would especially appreciate feedback to:

Is using tabular a good idea or might it be very bad (e.g. when the user customizes array stretches)?
Am I abusing expl3 at any point (local vs. global)?
the user interface in general (key-value approach)

Code:

\documentclass{article}
\usepackage[landscape]{geometry}
\usepackage{xparse}

\ExplSyntaxOn
\keys_define:nn { vigenere }
    {
        font        .code:n    = { \cs_set_eq:NN \__vigenere_font: #1 },
        font   .default:n = { \small },
        font   .initial:n = { \small },
        tabcolsep .dim_set:N = \l__vigenere_tabcolsep_dim,
        tabcolsep .initial:n = { 3pt },
        alphabet  .tl_set:N  = \l__vigenere_alphabet_tl,
        alphabet  .initial:n = { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z }
    }
\NewDocumentCommand { \printvigeneretabular } { O{} }
    {
        \group_begin:
        \keys_set:nn { vigenere } { #1 }
        \clist_set:NV  \l_tmpa_clist \l__vigenere_alphabet_tl
        \clist_clear:N \l_tmpb_clist
        \tl_clear:N    \l_tmpa_tl
        \int_step_inline:nnnn { 1 } { 1 } { \clist_count:N \l_tmpa_clist }
            {
                \tl_put_right:Nx \l_tmpa_tl { c| }
            }
        \__vigenere_font:
        \dim_set_eq:NN \tabcolsep \l__vigenere_tabcolsep_dim
        \expandafter\tabular\expandafter{\expandafter|\l_tmpa_tl}
            \hline
            \bool_while_do:nn { \int_compare_p:n { \clist_count:N \l_tmpa_clist > 0 } }
                {
                    \clist_use:Nnnn \l_tmpa_clist { & } { & } { & }
                    \clist_if_empty:NF \l_tmpb_clist
                        { & \clist_use:Nnnn \l_tmpb_clist { & } { & } { & } }
                    \clist_gpop:NN \l_tmpa_clist \l_tmpa_tl
                    \clist_gput_right:NV \l_tmpb_clist \l_tmpa_tl
                    \\\hline
                }
        \endtabular
        \group_end:
    }
\ExplSyntaxOff

\begin{document}
 \printvigeneretabular\par
 \printvigeneretabular[font=\tiny,alphabet={1,2,3,4,5,6,7,8,9,10},tabcolsep=1pt]
\end{document}


texts: Recursive Web Scraping with Python Beautiful Soup

texts:
I wrote a short program which should allow a user to specify a starting page in Discogs Wiki Style Guide, scrape the other styles listed on the page, and then output a graph (represented here as a dictionary of sets) of the relationship between subgenres.

I'm looking for guidance/critique on: (1) How to clean up the request_page function, I think there is a more elegant way both getting href attrs and filtering to only those with "/style/". (2) The general structure of the program. Self-taught and relative beginner so it's highly appreciated if anyone could point out general irregularities.

import re
import requests
from bs4 import BeautifulSoup

def get_related_styles(start):

    def request_page(start):

        response = requests.get('{0}{1}'.format(base_style_url, start))
        soup = BeautifulSoup(response.content,'lxml')

        ## these lines feel inelegant. considered solutions with
        ## soup.findAll('a', attrs = {'href': pattern.match})

        urls = [anchor.get('href') for anchor in soup.findAll('a')]
        pattern = re.compile('/style/[a-zA-Z0-9\-]*[^/]') # can use lookback regex w/ escape chars?
        style_urls = {pattern.match(url).group().replace('/style/','') for url in urls if pattern.match(url)}

        return style_urls

    def connect_styles(start , style_2):

        ## Nodes should not connect to self
        ## Note that styles are directed - e.g. (A ==> B) =/=> (B ==> A)

        if start != style_2:
            if start not in all_styles.keys():
                all_styles[start] = {style_2}

            else:
                all_styles[start].add(style_2)

        if style_2 not in do_not_visit:
            do_not_visit.add(style_2)
            get_related_styles(style_2)

    style_urls = request_page(start)

    for new_style in style_urls:
        connect_styles(start,new_style)

Example Use:

start = 'Avant-garde-Jazz'
base_style_url = 'https://reference.discogslabs.com/style/'

all_styles = {}
do_not_visit = {start}

get_related_styles(start)

print(all_styles)
{'Free-Jazz': {'Free-Improvisation', 'Free-Funk'}, 'Free-Improvisation': {'Free-Jazz', 'Avant-garde-Jazz'}, 'Avant-garde-Jazz': {'Free-Jazz'}, 'Free-Funk': {'Free-Jazz'}}


texts: Vanilla ES6 Todo/Task List with LocalStorage

texts:
I'm making a simple todo list app with ES6. I'm looking for some feedback on the code, I feel like there is some improvement possible. Maybe there is a better way to attach eventListeners to input and button, but to keep in mind they have to be set not just when a new element is added but on window load when the items from localStorage are retrieved. I tried to keep it short as best I could.

import TaskItem from './TaskItem'; //constructor for id, title, and completed boolean
import * as helpers from './Helpers'; //two extra methods

export default class TaskList {

    constructor()
    {
        this.inputField= document.getElementById('task-input');
        this.addButton = document.getElementById('add-task');
        this.tasksElem = document.getElementById('tasks');
        this.tasks = JSON.parse(localStorage.getItem('userTasks')) || [];

        this.displayTasks()
        this.initializeEventListeners()

    }

    initializeEventListeners()
    {
        this.tasksElem.addEventListener('click', (event) => {
            const taskId = event.target.parentNode.getAttribute('data-id');

            switch (event.target.localName) {
                case 'button':
                    this.removeTask(taskId);
                    break;
                case 'input':
                    this.toggleCompleted(taskId);
                    break;
                default:
            }
        })

        this.addButton.addEventListener('click', this.addNewTask.bind(this))

    }

    addNewTask()
    {
        const newTaskTitle = this.inputField.value.trim();

        if (newTaskTitle)
        {
            let newTaskID = helpers.getRandomId().toString(); //still need to check if id exists
            const newTask = new TaskItem(newTaskID, helpers.htmlEscape(newTaskTitle))
            this.tasks.push(newTask)
            this.inputField.value = '';
            this.saveTasks()
            this.displayTasks()
        }

    }

    removeTask(idToRemove)
    {
        this.tasks = this.tasks.filter((task) => {
            return task.id !== idToRemove
        });

        this.saveTasks()
        this.displayTasks()
    }
    toggleCompleted(idToToggle)
    {
        this.tasks.forEach((task)=>{
            if (task.id === idToToggle) {
                task.completed = !task.completed;
            }
        })

        this.saveTasks()
        this.displayTasks()
    }

    saveTasks()
    {
              localStorage.setItem('userTasks',JSON.stringify(this.tasks));
    }

    displayTasks()
    {
        this.tasksElem.innerHTML = this.tasks.reduce((acc, task) => {
            return acc + this.returnTaskTemplate(task)
        },'');

    }

    returnTaskTemplate(task)
    {
        return `

                   <input class="toggle" type="checkbox" ${task.completed ? 'checked' : ''}>
                   ${task.title}
                   <button>Remove</button>

`;
    }
}

Any feedback is appreciated.