texts:
This program takes in an image, and saves an "arrowed" version of that image to /tmp/image.png. Example input and output is below the code.

from PIL import Image, ImageDraw
import operator
from pprint import pprint
import sys

base_width = 10
arrow_base_height = 15
arrow_point_height = 15
margin = (20,20)
do_outline = True
outline = (0, 0, 0) # black
background_color  = (255, 255, 255) # white

arrow_width = base_width / 2
total_arrow_height = arrow_base_height + arrow_point_height
total_arrow_width = 2 * base_width

def drawArrow(coords, color):
    if do_outline:
        draw.polygon(coords, fill=color, outline=outline)
    else:
        draw.polygon(coords, fill=color)

def to_real_coordinates(coords):
    # translates the coords to pixels on the picture
    return translate(coords, margin)

def translate(coords, vector):
    # Translates a list of coordinate tuples over a vector tuple
    t_coords = []
    for cord in coords:
        t_coords.append(tuple(map(operator.add, cord, vector)))
    return t_coords

def mirror(coords):
    # Takes a list of coordinate tuples and mirrors it across the first element of
    #    the first tuple
    # Formula: 2 * base - original
    m_coords = []
    base = coords[0]
    double_base = tuple(map(operator.mul, base, len(base)* (2,) ))
    for cord in coords:
        m_coords.append(tuple(map(operator.sub, double_base, cord)))
    return m_coords

def get_arrow_coords():
    coords = [
        (0, 0),
        (arrow_base_height, 0),
        (arrow_base_height, arrow_width),
        (arrow_base_height + arrow_point_height, - arrow_width),
        (arrow_base_height, -3 * arrow_width),
        (arrow_base_height, - base_width),
        (0, - base_width)
    ]
    return coords

if __name__ == "__main__":
    orig = Image.open(sys.argv[1]).transpose(Image.ROTATE_90)
    pix = orig.load()
    new_size = (1024,1024)
    actual_size = (new_size[0] + 2 * margin[0], new_size[1] + 2*margin[1])
    im = Image.new("RGB", actual_size, background_color)
    draw = ImageDraw.Draw(im)
    arrow = get_arrow_coords()
    m_arrow = mirror(arrow)
    for i in range(new_size[0] / total_arrow_height):
        for j in range((new_size[1] / total_arrow_width)):
            color = pix[
                i * total_arrow_height * orig.size[0] / new_size[0],
                j * total_arrow_width * orig.size[1] / new_size[1]
            ]
            # calculate and draw arrow
            coords = translate(arrow, (i * total_arrow_height, j * total_arrow_width))
            real_coords = to_real_coordinates(coords)
            drawArrow(real_coords, color)
            # calculate and draw mirrored arrow
            coords = translate(m_arrow, (arrow_base_height + i * total_arrow_height, j * total_arrow_width))
            real_coords = to_real_coordinates(coords)
            drawArrow(real_coords, color)

    im = im.transpose(Image.ROTATE_270)
    im.show()
    im.save("/tmp/image.png")


texts: Lexicographically largest string from allowed swaps

texts:
Problem: Given a string str and array of pairs that indicates which
  indices in the string can be swapped, return the lexicographically
  largest string that results from doing the allowed swaps. You can swap
  indices any number of times.

  Example

  For str = "abdc" and pairs = [[1, 4], [3, 4]], the output should be
  swapLexOrder(str, pairs) = "dbca".

  By swapping the given indices, you get the strings: "cbda", "cbad",
  "dbac", "dbca". The lexicographically largest string in this list is
  "dbca".

My comments: My program passed all the tests on the CodeSignal website, but since I am relatively new to algorithms, there's probably a more efficient way to solve it. In addition, I'm looking for general code review: does my code have signs that I look like a beginner? thank you.

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

std::string swapLexOrder(std::string str, std::vector<std::vector<int>> pairs)
{
    if(pairs.size() == 0) return str;
    std::vector<std::set<int>> pairpool; //pairpool : contains sets of interchangeable indices
    std::vector<std::vector<std::string>> stringpool; //stringpool : contains vectors of interchangeable characters

    //creates pairpool structure
    for(std::size_t i = 0; i < pairs.size(); i++)
    {
        bool alrExists = false;
        std::set<int> newSet;
        for(auto& p : pairpool)
        {
            for(auto ele : p)
            {
                if((pairs[i][0] == ele) || (pairs[i][1] == ele))
                {
                    if(!alrExists)
                    {
                        alrExists = true;
                        p.insert(pairs[i][0]);
                        p.insert(pairs[i][1]);
                        newSet = p;
                    }
                    else
                    {
                        if(p == newSet) break;
                        p.insert(newSet.begin(), newSet.end());
                        pairpool.erase(std::remove(pairpool.begin(), pairpool.end(), newSet), pairpool.end());
                        break;  //  needed this break statement really badly
                    }
                }
            }
        }
        if(!alrExists)
        {
            newSet.insert(pairs[i][0]);
            newSet.insert(pairs[i][1]);
            pairpool.push_back(newSet);
        }
    }

    //creates sorted stringpool structure
    for(auto p : pairpool)
    {
        std::vector<std::string> newset;
        for(auto ele : p)
        {
            newset.push_back(str.substr(ele - 1, 1));
        }
        std::sort(newset.begin(), newset.end());
        stringpool.push_back(newset);
    }

    //uses stringpool and pairpool to modify string only one time through
    int counter = 0;
    for(auto p : pairpool)
    {
        for(auto ele : p)
        {
            str.replace(ele - 1, 1, stringpool[counter].back());
            stringpool[counter].pop_back();
        }
        counter++;
    }

    return str;
}

int main()
{
    std::cout << swapLexOrder("acxrabdz", {{1, 3}, {6, 8}, {3, 8}, {2, 7}}) << "\n";
    std::string STR = "lvvyfrbhgiyexoirhunnuejzhesylojwbyatfkrv";
    std::vector<std::vector<int>> PAIR =
    {
        {13, 23},
        {13, 28},
        {15, 20},
        {24, 29},
        {6, 7},
        {3, 4},
        {21, 30},
        {2, 13},
        {12, 15},
        {19, 23},
        {10, 19},
        {13, 14},
        {6, 16},
        {17, 25},
        {6, 21},
        {17, 26},
        {5, 6},
        {12, 24}
    };
    std::cout << swapLexOrder(STR, PAIR) << "\n";
    return 0;
}


texts:
I would like to turn the following:

this is a $test

into

this is a
$test

currently I have

var regexp = new RegExp('$([^\\s]*)','g'),
    html = '
this is a $test
',
    matched = html.match(regexp)[0]

if (matched){
   html = html.replace(match, '
' + match + '
')
}

which works, but is there a more concise way of doing this?


texts:
I took the code from internet and tried to simplify it. So, what can I do?

How can I simplify my code more to make it easily understandable?

public class NaiveBayesAlgorithm
{
    private static List<Training> trainingDataSet = new List<Training>();
    private static Dictionary<string, HeightWeightSize> gaussianDataSet = new Dictionary<string, HeightWeightSize>();
    private static Dictionary<string, Gaussian> gaussianList = new Dictionary<string, Gaussian>();

    //takes a table
    public static void Train(List<Training> trainingData)
    {
        //adding the training data to the dataset
        trainingDataSet = trainingData;

        foreach(Training t in trainingDataSet)
        {
            if (!gaussianDataSet.ContainsKey(t.Class))
            {
                gaussianDataSet.Add(t.Class, new HeightWeightSize());
            }

            gaussianDataSet[t.Class].Height.Add(t.Height);
            gaussianDataSet[t.Class].Weight.Add(t.Weight);
            gaussianDataSet[t.Class].FootSize.Add(t.FootSize);
        }

        foreach(string key in gaussianDataSet.Keys)
        {
            Gaussian gaussian = new Gaussian();
            gaussian.Sex = key;
            gaussian.Count = gaussianDataSet[key].Height.Count;

            gaussian.HeightMean = Statistics.Mean(gaussianDataSet[key].Height);
            gaussian.WeightMean = Statistics.Mean(gaussianDataSet[key].Weight);
            gaussian.FootSizeMean = Statistics.Mean(gaussianDataSet[key].FootSize);

            gaussian.HeightVariance = Statistics.Variance(gaussianDataSet[key].Height);
            gaussian.WeightVariance = Statistics.Variance(gaussianDataSet[key].Weight);
            gaussian.FootSizeVariance = Statistics.Variance(gaussianDataSet[key].FootSize);

            gaussianList.Add(key, gaussian);
        }

        string str2 = string.Empty;
    }

    public static string Classify(double[] obj)
    {
        double maxScore = 0;
        string className = string.Empty;

        foreach( string key in gaussianList.Keys)
        {
            gaussianList[key].HeightNormalDist = Statistics.NormalDist(obj[0], gaussianList[key].HeightMean, gaussianList[key].HeightVariance);
            gaussianList[key].WeightNormalDist = Statistics.NormalDist(obj[1], gaussianList[key].WeightMean, gaussianList[key].WeightVariance);
            gaussianList[key].FootSizeNormalDist = Statistics.NormalDist(obj[2], gaussianList[key].FootSizeMean, gaussianList[key].FootSizeVariance);

            gaussianList[key].CombinedNormalDist = gaussianList[key].HeightNormalDist * gaussianList[key].WeightNormalDist * gaussianList[key].FootSizeNormalDist;
            gaussianList[key].UltimateScore = gaussianList[key].CombinedNormalDist * 0.5;

            if(maxScore < gaussianList[key].UltimateScore)
            {
                maxScore = gaussianList[key].UltimateScore;
                className = key;
            }
        }

        return className;
    }
}


texts: Generate another random path through a complete graph

texts:
What this does is generate a random path of cities to later calculate the length of the newly generated tour of cities, the TSP.

I am trying to figure out if there is a more efficient way to write this algorithm. I have tried using the std::shuffle and std::random_shuffle but did not notice any improvement in the run time. Any other resources I should try taking a look at?

std::vector<City> GetRandomPath(std::vector<City> oldPath)
{
    std::vector<City> newPath;

    newPath = oldPath;

    int randPoint = rand() % (oldPath.size()-1);
    int randPoint2 = rand() % (oldPath.size()-1 - randPoint) + randPoint;

    int k=1;
    for(int i =0; i < randPoint; i++)
    {
        newPath.push_back(oldPath.at(i));
    }
    for(int i=randPoint; i < randPoint2; i++)
    {

        newPath.push_back(oldPath.at(randPoint2-k));
        k++;
    }
    for(int i=randPoint2; i < oldPath.size(); i++)
    {
        newPath.push_back(oldPath.at(i));
    }

    return newPath;
}


texts:
I am very new to Java and although my code works, I know that it must be possible to write this using fewer lines of code. I am serializing multiple objects, eventually I will look into serializing to multiple files, for now, I am using just one file, so it constantly gets over-written. How can I nest or reduce the number of if statements I am using. In my code snippet, I am using an if statement for each individual object, and duplicating my try/catch block. This is horrible code, but I am stumped as to how I can write this more efficiently.

In very simple terms, please give me an example of how to nest or reduce code duplication. I shouldn't need to re-do my try/catch block constantly!

public class Serializer
{
   public void Serialize()
   {

    MainMenu pass_choice = new MainMenu();
    int passed_choice = pass_choice.chooseTeam();

    if(passed_choice==1){
    ClubInfo club = new ClubInfo();
     club.teamName = "Arsenal";
     club.stadium = "Emirates";
     club.division = "Premier League";
      club.SSN = 11122333;
      club.stadiumCapacity = 60000;

    try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/home/cg/root/club.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);

         out.writeObject(club);

         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in C:/tmp/club.ser");
         System.out.println("Choice is :" + passed_choice);
      }catch(IOException i)
      {
          i.printStackTrace();
      }
} // end if 1
   else
    if(passed_choice==2){
    ClubInfo club1 = new ClubInfo();
    club1.teamName = "Aston Villa";
    club1.stadium = "Villa Park";
    club1.division = "Premier League";
    club1.SSN = 111223334;
    club1.stadiumCapacity = 40000;

    try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/home/cg/root/club.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);

         out.writeObject(club1);

         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in C:/tmp/club.ser");
         System.out.println("Choice is :" + passed_choice);
      }catch(IOException i)
      {
          i.printStackTrace();
      }
} // end if 2
   }
}


texts: Handling click events to open and close menus depending on the click target

texts:
I'm building a navigation that has a breadcrumb with drop down menus. I want the menus to open up when I click the open link, then there are many instances when the menu should close:

The link is clicked a second time, with the intention of closing the menu
When another menu is open, the first menu should close
When a menu is open, and anywhere outside the menu is clicked
When a menu item is clicked

I'm anticipating that I'll have many click events to handle, and many different types of menus, pop-ups and drop downs through the entire site, so I'm trying to handle that efficiently, thus the switch statement.

$().ready(function () {
    //Click event mayhem!
    $('html').click(function (event) {
        event.stopPropagation();
        var target = $(event.target);
        switch (target.attr('class')) {
            case 'expandDropDown':
                handleBreadCrumbDropDownClick(target);
                break;
            case 'headlineTitle':
                event.preventDefault();
                handleAccordionItemClick(target);
                break;
            default:
                //Always close dropdown menus, unless they're specifically being opened
                toggleDropDown('.BC-DropDown-Open');
        }
    });
});

function handleBreadCrumbDropDownClick(target) {
    //Get the drop down list being targeted
    var dropDownList = '#' + target.attr('itemprop');
    //Offset of the expander link
    var offset = target.offset();
    if ($(dropDownList).hasClass('BC-DropDown-Open')) {
        //Dropdown is being closed with the expandDropDown link
        $(dropDownList)
                        .hide()
                        .toggleClass('BC-DropDown-Open');
    }
    else {
        //Dropdown is being opened with the expandDropDown link

        if ($('.BC-DropDown-Open').length > 0) {
            //Close existing drop down lists if any
            toggleDropDown('.BC-DropDown-Open');
        }
        //Open selected dropdown
        toggleDropDown(dropDownList, offset);
    }
}


texts:
Here's my solution for Euler Problem 3:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

I'm using the Euler problems to learn some basics of C++. Are there any C++ "conventions" I'm missing, or any languages features I could use to get a better understanding of C++?
#include <iostream>
#include <vector>
#include <algorithm>

#include "fibonacci.h"
#include <limits>

int get_prime_above(int i);

bool is_prime(int number);

bool has_decimals(float number);

int main() {

    // What number are we getting the prime factors for?
    long target_number = 600851475143;

    // Holds the prime factors.
    std::vector<int> primes;

    // No point dividing by 1, it's a useless factor in this context.
    int current_prime = get_prime_above(1);
    while (target_number > 1) {
        // Does the target divide by the prime evenly?
        long result = target_number % (long) current_prime;
        if (result != 0) {
            // If not, move on to the next prime.
            current_prime = get_prime_above(current_prime);
            continue;
        }

        // If it does, push the prime
        primes.push_back(current_prime);
        // Change the target number to what ever is left to work out
        target_number = (long) target_number / (long) current_prime;
        // And reset the prime.
        current_prime = get_prime_above(1);
    }

    // Sort and reverse the primes,
    // so the highest will be at index 0
    std::sort(primes.begin(), primes.end());
    std::reverse(primes.begin(), primes.end());

    std::cout << "Largest prime: " + std::to_string(primes[0]) << std::endl;
}

/**
 * Get the next prime number above i.
 * @param i
 * @return
 */
int get_prime_above(int i = 1) {
    // Current number we're checking.
    int current_number = 0;
    while (current_number < std::numeric_limits<int>::max()) {

        // If it's lower than what the user wants, just keep incrementing.
        if (current_number <= i) {
            current_number++;
            continue;
        }

        // If it's prime, return it.
        if (is_prime(current_number)) {
            return current_number;
        }

        current_number++;
    }
    throw std::runtime_error("Couldn't find a prime within the int maximum value");
}

/**
 * Is the given number a prime?
 * @param number
 * @return bool
 */
bool is_prime(int number) {
    // Loop all the numbers between (not inclusive of) 1 and number
    // as we know that 1 and number will always have no decimal.
    // If number is 7, it would loop 2..6
    for (int tmp = number - 1; tmp > 1; tmp--) {
        // Divide the number
        float result = ((float) number / (float) tmp);

        // If the result has decimals, it doesn't divide equally
        // so return false.
        if (!has_decimals(result)) {
            return false;
        }
    }

    // All the in between numbers had decimals, so it's a prime.
    return true;
}

/**
 * Is this number a decimal?
 * If converting the float to an int and back again changes the value,
 * then the int conversion removed some decimals.
 * @param number
 * @return bool
 */
bool has_decimals(float number) {
    return number != (float) (int) number;
}


texts: Look through a string and return the most frequent character (Ruby)

texts:
I want to determine which separator is used in a csv file. CSV.foreach will return something like this:

["something1;something2;something3"]

The code beneath does the trick, but something better must exist. I find it annoying to have the need for sep_count. Do you know of a method that returns the most frequent of the characters from SEPERATORS?

SEPERATORS = [";", ","]

CSV.foreach(@file, @config) do |header|
  sep_count = 0
  SEPERATORS.each do |seperator|
    if header.first.scan(/#{seperator}/).count > sep_count
      @config[:col_sep] = seperator
      sep_count = header.first.scan(/#{seperator}/).count
    end
  end
  break
end

EDIT:

Based on your awesome answers I got the 1-liner that I asked for:

@config[:col_sep] = %w(; ,).sort_by { |separator| File.open(@file).first(1).join.count(separator) }.last

I have also come up with this piece of code that determines both col_sep and row_sep:

first_line = ""
File.open(@file) do |file|
  file.each_char do |char|
    first_line << char
    if "\r\n".include?(char)
      @config[:row_sep] = first_line.scan(/\n$|\r$/).first
      break
    end
  end
end
@config[:col_sep] = %w(; ,).sort_by { |separator| first_line.count(separator) }.last

By using the full code we ensure that it is always the first line that gets used, and we also set the row_sep. Feel free to comment if you think anything could be improved further.


texts: Counting adjacent swaps to sort an array with 3 different values

texts:
This is the Kindergarten Excursion problem from kattis.com:

  The kindergarten teachers had finally managed to get all the kids in a line for the walk to the bus station and the weekly excursion. What they hadn’t thought of was the fact that today different kids were supposed to go to different excursions. They should walk as one line to the bus station, but to avoid total chaos when they arrive there, all the kids going to the zoo should be in the beginning of the line, the ones going to the lake should be in the middle and the rest, going to the science museum, should be in the end.

  Since it takes a lot of time to get all the kids to stand in a line no kid may step out of the line. To get the line organized after excursion group, kids standing next to each other can swap places. Now the kindergarten teachers wonder, if they will have time to do this and still catch their bus.

  Task

  You will be given a sequence of numbers 0, 1, and 2, denoting the excursion destinations of each kid from first to last in the line. Pairs of adjacent kids can swap positions, and the line should be organized after destination number starting with 0 and ending with 2. What is the minimum number of swaps required to organize the line?

  Input

  The only line of input contains a string consisting of characters 0, 1 or 2, denoting the destinations of kids. The length of the string will be at most 1,000,000 characters.

  Output

  Output one line with one integer – the minimum number of swaps needed to get the kids in order.

  Sample Input 1

10210

  Sample Output 1

5

This is my code. My solution is too slow and I need help with optimization or a different approach for this problem.

def excursion(str):
    digits = [0, 0, 0]
    x = 0
    for i in range(len(str)):
        for j in range((int(str[i])) + 1, 3):
            x += digits[j]
        digits[int(str[i])] += 1
    return x

print(excursion(input()))


texts:
In my app I need to query location and scan wifi periodically. To conserve power I need to change the rate dynamically, depending on the distance to the target. Also I want to wait for both asynchronous calls to complete. Coroutines seemed the obvious choice, but since this is my first take at coroutines I want to have a second opinion.

I came up with the following solution:

@SuppressLint("MissingPermission")
suspend fun getCurrentLocation(context: Context): Location? = suspendCoroutine { cont ->
    val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context)
    val locationRequest = LocationRequest()
    locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    locationRequest.numUpdates = 1
    val listener = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult?) {
            cont.resume(locationResult?.lastLocation)
        }
    }
    val task = fusedLocationProviderClient.requestLocationUpdates(locationRequest,
                                                                  listener,
                                                                  null)
    task.addOnFailureListener { cont.resumeWithException(it) }
}

also

class WifiScanner(val context: ContextWrapper) {
    val wifiManager: WifiManager

    init {
        wifiManager = context.baseContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    }

    suspend fun getCurrentScanResult(): List<ScanResult> =
        suspendCoroutine { cont ->
            val wifiScanReceiver = object : BroadcastReceiver() {
                override fun onReceive(c: Context, intent: Intent) {
                    if (intent.action?.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) == true) {
                        val scanResults = wifiManager.scanResults
                        //sort so that strongest signal is on top
                        scanResults.sortByDescending { it.level }
                        Log.i("received wifi", scanResults.toString())
                        context.unregisterReceiver(this)
                        cont.resume(scanResults)
                    }
                }
            }
            context.registerReceiver(wifiScanReceiver,
                                     IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
            wifiManager.startScan()
        }
}

Both are executed concurrently like this:

val location = async { getCurrentLocation() }
val wifi = async { wifiScanner.getCurrentScanResult() }
val currentLocation = location.await()
val currentWifiInfo = wifi.await()

In a quick test it works fine, but it feels like abusing the system. Can I use this like that without breaking the common conventions?


texts: Find the center of n squares which together build a rectangle

texts:
I have a rectangle with size w and height h. Now I want to split this rectangle into n new rectangles that are as similar as possible to a square. Afterwards I'd like to calculated the center of each square.

public static List<Point> getCenters(int number, double width, double height)
    {
        List<Point> points = new List<Point>();
        int originalNumberOfSquares = number;
        int numberOfSquares = number;
        if (numberOfSquares % 2 == 1)
        {
            numberOfSquares++;
        }
        int rectangleWidth = Convert.ToInt32(width);
        int rectangleHeight = Convert.ToInt32(height);

        double minDistance = Double.MaxValue;
        int nSquaresInRow = -1;
        int nSquaresInColumn = -1;

        for (int i = 0; i <= numberOfSquares; i++)
        {
            for (int j = 0; j <= numberOfSquares; j++)
            {
                if (i * j == numberOfSquares)
                {
                    if (Math.Abs(i - j) < minDistance)
                    {
                        minDistance = Math.Abs(i - j);
                        nSquaresInRow = i;
                        nSquaresInColumn = j;
                    }
                }
            }
        }

        int squareWidth = rectangleWidth / nSquaresInColumn;
        int squareHeight = rectangleHeight / nSquaresInRow;

        for (int r = 0; r < originalNumberOfSquares; r++)
        {
            int xSquareCenter = (((r + 1) * 2) - 1) * (squareWidth / 2);
            while (xSquareCenter > rectangleWidth)
            {
                xSquareCenter = xSquareCenter - rectangleWidth;
            }

            int row = (r / nSquaresInColumn) + 1;
            int ySquareCenter = ((2 * row) - 1) * (squareHeight / 2);

            points.Add(new Point(Convert.ToDouble(xSquareCenter), Convert.ToDouble(ySquareCenter)));
        }

        return points;
    }

Now the code works, but I think it's a little bit ugly. Any hints on how I can improve it?


texts:
This is a program to find solutions to Goldbach's weak conjecture. I've tried to optimise the solution function by never looking at primes that are larger than the remaining sum, but it feels clunky. Any ideas?

extern crate primal;

use std::env;

fn get_input() -> usize {
    env::args()
        .nth(1)
        .expect("Single positive integer expected as argument")
        .parse::<usize>()
        .expect("Single positive integer expected as argument")
}

fn list_primes_until(input: &usize) -> Vec<usize> {
    let sieve = primal::Sieve::new(input.clone());
    return sieve.primes_from(0).take_while(|x| x <= input).collect();
}

fn get_goldbach_solution(input: &usize) -> Option<[usize; 3]> {
    let first_primes = list_primes_until(&input);

    for first_prime in first_primes {
        if input - first_prime < 1 {
            continue;
        }

        let second_primes = list_primes_until(&(input - first_prime));
        for second_prime in second_primes {
            if input - first_prime - second_prime < 1 {
                continue;
            }

            let third_primes = list_primes_until(&(input - first_prime - second_prime));
            for third_prime in third_primes {
                if &(first_prime + second_prime + third_prime) == input {
                    return Some([first_prime, second_prime, third_prime]);
                }
            }
        }
    }

    return None;
}

fn main() {
    let input = get_input();

    let solution = get_goldbach_solution(&input).expect("No solution found for input");
    println!(
        "{} = {} + {} + {}",
        input,
        solution[0],
        solution[1],
        solution[2]
    );
}


texts:
A while back this question proposed a constexpr compile-time Sieve of Eratosthenes. It also linked to another SO question about compile-time computation of CRCs. I've found a place where I'd like to precompute the hash of a few C-strings, so I used those previous questions as a base.

I'm implementing the one-at-a-time hash algorithm for C-style strings. I'm stuck to using C++11, so the function has to be recursive and without any local state:

namespace ct
{

constexpr std::uint32_t stringLength(const char * cstr)
{
    return (*cstr != '\0') ? (stringLength(cstr + 1) + 1) : 0;
}

constexpr std::uint32_t sumSHL(std::uint32_t h, std::uint32_t shift) { return h + (h << shift); }
constexpr std::uint32_t sumSHR(std::uint32_t h, std::uint32_t shift) { return h + (h >> shift); }
constexpr std::uint32_t xorSHR(std::uint32_t h, std::uint32_t shift) { return h ^ (h >> shift); }

constexpr std::uint32_t hashFinishImpl(std::uint32_t h)
{
    // h += (h <<  3)
    // h ^= (h >> 11)
    // h += (h << 15)
    return sumSHL(xorSHR(sumSHL(h, 3), 11), 15);
}

constexpr std::uint32_t hashStepImpl(std::uint32_t h, std::uint32_t c)
{
    // h += c
    // h += (h << 10)
    // h ^= (h >>  6)
    return xorSHR(sumSHL(h + c, 10), 6);
}

constexpr std::uint32_t hashImpl(const char * cstr, std::uint32_t length, std::uint32_t h)
{
    return (length != 0) ? hashImpl(cstr + 1, length - 1, hashStepImpl(h, *cstr)) : hashFinishImpl(h);
}

constexpr std::uint32_t hashCString(const char * cstr)
{
    return hashImpl(cstr, stringLength(cstr), 0);
}

} // namespace ct {}

I'm thinking it looks a bit convoluted, but couldn't think of a better way of handling it... Any suggestions are appreciated.


texts: A S.I.N checker, using Luhn's Algorithm, and created in swing.

texts:
I have created a program to validate a Canadian S.I.N. using Luhn's Algorithm, and was wondering if there was any way to make it more efficient. From what i can tell, it is already extremely efficient, but any tips or advice will be greatly appreciated.

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

class SinChecker extends JFrame
{ //naming variables
JTextField t1;
private JLabel j, j1, j2, j3;
ButtonListener bl1;
ButtonListener2 bl2;

public SinChecker ()
{ //Get the container
Container c = getContentPane ();

//Set absolute layout
c.setLayout (null);

//Set Background Color
c.setBackground (Color.WHITE);

//Creating label Guess my number text
JLabel j = new JLabel ("S.I.N. Validation Checker");
j.setForeground (Color.BLUE);
j.setFont (new Font ("tunga", Font.BOLD, 24));
j.setSize (270, 20);
j.setLocation (30, 35);

//Creating label Enter a number.....
j1 = new JLabel ("Enter your S.I.N. below.");
j1.setFont (new Font ("tunga", Font.PLAIN, 17));
j1.setSize (270, 20);
j1.setLocation (66, 60);

//Creating a label Instuctions
JLabel j2 = new JLabel ("Enter a 9-digit Social Insurance Number");
j2.setFont (new Font ("tunga", Font.PLAIN, 17));
j2.setSize (270, 20);
j2.setLocation (10, 165);

//Creating a label Instuctions
JLabel j3 = new JLabel ("with no spaces between the digits please.");
j3.setFont (new Font ("tunga", Font.PLAIN, 17));
j3.setSize (270, 20);
j3.setLocation (10, 180);

//Creating TextField for x input guess
t1 = new JTextField (10);
t1.setSize (70, 30);
t1.setLocation (100, 80);

//creating 2 buttons
JButton b1 = new JButton ("Proceed");
b1.setSize (120, 30);
b1.setLocation (70, 200);
bl1 = new ButtonListener ();
b1.addActionListener (bl1);

JButton b2 = new JButton ("Re-enter");
b2.setSize (120, 30);
b2.setLocation (70, 250);
bl2 = new ButtonListener2 ();
b2.addActionListener (bl2);

//Place the components in the pane
c.add (j);
c.add (j1);
c.add (j2);
c.add (j3);

c.add (t1);
c.add (b1);
c.add (b2);

//Set the title of the window
setTitle ("Social Insurance Number Checker");

//Set the size of the window and display it
setSize (300, 350);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}

//implement  first action listener
private class ButtonListener implements ActionListener
{

public void actionPerformed (ActionEvent e)
{
    int a = Integer.parseInt (t1.getText ());
    boolean evenDigit = false;   //alternates between true and false
    int sum = 0; //accumulates the sum of the digits (as modified)

    while (a > 0)
    {
        int nextDigit = a % 10; //grab the last digit
        a = a / 10; //discard that digit
        if (evenDigit)
        {
            //double it, then add the two digits of the result
            nextDigit = 2 * nextDigit;
            nextDigit = (nextDigit / 10) + (nextDigit % 10);
        } // if(evenDigit)
        sum = sum + nextDigit;
        evenDigit = !evenDigit; //toggle the flag each time
    } // end while

    if (0 == sum % 10)
    {
        j1.setText ("That is a valid S.I.N.");
    }
    else
    {
        j1.setText ("That is not a valid S.I.N.");

    }
    t1.requestFocus ();
    t1.selectAll ();
}
   }

 private class ButtonListener2 implements ActionListener
 {
   public void actionPerformed (ActionEvent e)
   {
    //reset the label messages
    t1.setText ("");
    j1.setText ("Enter your S.I.N. below.");

    t1.requestFocus ();
    t1.selectAll ();

}
}

public static void main (String[] args)
{
  new SinChecker ();
 } }


texts:
In the following code I'm trying to calculate Net Wage of employees and classes Earning, Deduction and WageBalance has a composition relationship with WageInfo. And there is a class called WageManager which is having a association with WageInfo, handling all operations like BalanceWage(). DataService class encapsulates all db logic.  Please review my code and let me know of any flaws.

Is the way I've implemented the relationships correct?  Would you have a method to calculate BalanceWage in a more elegant way?

    class WageManager
    {
        WageInfo _WageInfo;
        DataService _DataService;

        public WageManager(WageInfo wageInfo, DataService dataService )
        {
            _WageInfo = wageInfo;
            _DataService = dataService;
        }

        public List<WageBalance> BalanceWages()
        {

            var earningList = _DataService.GetEarningsList(); //DataService returns a List<Earning> list
            var deductionList = _DataService.GetDeductionList(); //DataService returns a List<Deduction>
            int i = 0;

            foreach (Earning e in earningList)
            {

    // Sum all earnings...

            var totalEarnings = earningList[i].AmountForEPF + earningList[i].OverTimeAmount + earningList[i].IncentiveAllowance + earningList[i].SpecialAllowance + earningList[i].OtherAllowance + earningList[i].ExtraShiftAmount + earningList[i].BroughtForwardAmount;

    // Sum all deductions...

            var totalDeductions = deductionList[i].AdvanceAmount + deductionList[i].CarriedForwardAmount + deductionList[i].DeathDonationAmount + deductionList[i].EPFAmount + deductionList[i].FineAmount + deductionList[i].InsuranceInstalmentAmount + deductionList[i].LoanInstalmentAmount + deductionList[i].MealsAmount + deductionList[i].OtherDeductionAmount + deductionList[i].UniformInstalmentAmount + deductionList[i].WelfareAmount;
            var employeeID = earningList[i].EmployeeID;
            var netEarning = totalEarnings - totalDeductions;

            WageInfo wageInfo = new WageInfo();

            wageInfo.WageBalance.EmployeeID = employeeID;
            wageInfo.WageBalance.NetWage = decimal.Truncate(netEarning / 100) * 100;
            wageInfo.WageBalance.CarriedForwardAmount = netEarning - wageInfo.WageBalance.NetWage;

            _WageInfo.WageBalanceList.Add(wageInfo.WageBalance);
            i += 1;
        }

        _DataService.BalanceWages(_WageInfo.WageBalanceList);

        return _WageInfo.WageBalanceList;
    }
}

class WageInfo
{
    public DateTime WagePeriodStartDate { get; set; }
    public DateTime WagePeriodEndDate { get; set; }
    public string Reference { get; set; }
    public Deduction Deduction = new Deduction();
    public Earning Earning = new Earning();
    public WageBalance WageBalance = new WageBalance();
    public List<WageBalance> WageBalanceList = new List<WageBalance>();

    public WageInfo()
    {
    }

}

public class WageBalance
{
    public int EmployeeID {get;set;}
    public string EmployeeName { get; set; }
    public decimal NetWage { get; set; }
    public decimal CarriedForwardAmount { get; set; }
}


texts:
Aim:

Use C++0x features to make function interposition safer. The problem is that it's easy to make a typo when wrapping and interposing on functions.

Prototype Implementation:

#define MAKE_WRAPPER(x) static const wrapper<decltype(::x), ::x> x(#x)

namespace {
  template<typename Sig, Sig& S>
  struct wrapper;

  template<typename Ret, typename... Args, Ret(&P)(Args...)>
  struct wrapper<Ret(Args...), P> {
         typedef Ret(*real_func)(Args...);
         real_func f;
         wrapper(const std::string& sym) : f(NULL) {
                dlerror();
                void *ptr = dlsym(RTLD_NEXT, sym.c_str());
                f = (real_func)ptr;
                if (NULL == f) {
                  std::cerr << "dlsym(): " << dlerror() << std::endl;
                }
                std::cout << "constructing wrapper: " << this << " for: " << sym << "(at " << ptr << ")" << std::endl;
         }

         Ret operator()(const Args&... args) const {
                return f(args...);
         }
  };
}

Example usage:

extern "C" {
  void glXSwapBuffers(Display *dpy, GLXDrawable drawable) {
         MAKE_WRAPPER(glXSwapBuffers);
         // Do stuff here before making the call to the wrapper
         glXSwapBuffers(dpy, drawable);
  }
}

Questions:

Is it worth the effort?
How can it be improved?


texts:
I want to search through an array of n numbers and find the numbers that are repeated. So far I have this code, which does the job, but I find it to be a rather cumbersome method, but I can't seem to find another method of doing it.

class Checknumber{
    int [] numbers = new int [5];
    Scanner inn = new Scanner(System.in);
    boolean b = true;
    int temp = -1;

    void sjekk(){
        System.out.println("Write five numbers");
        for(int i = 0; i < numbers.length; i++){
        numbers [i] = inn.nextInt();
    }

    //sjekker om det er like tall i arrayen
    System.out.print("\nNumbers that are repeated: ");
    for(int i = 0; i < numbers.length; i++){

        if(!b){
            System.out.print(temp + " ");
        }

        b = true;
        temp = numbers[i];
        for(int j = 0; j < numbers.length; j++){
            if(i != j && temp == numbers[j] && numbers[j] != -2){
                b = false;
                numbers[j] = -2;
            }
        }
    }

}


texts: Random iteration over an array using divide and conquer

texts:
I have created a utility class which allows random iteration over an array.
The idea is pretty much a divide and conquer approach.

public class RandomIterator<T> implements Iterator<T> {

    //recursion stack
    private final LinkedList<int[]> offsets = new LinkedList<>();
    private final ThreadLocalRandom random = ThreadLocalRandom.current();
    private final T[] words;

    public RandomIterator(T[] words) {

        this.words = words;

        //add default lower and upper bound
        offsets.addLast(new int[]{0, words.length});
    }

    @Override
    public boolean hasNext() {
        return !offsets.isEmpty();
    }

    @Override
    public T next() {

        final int[] offset = offsets.removeFirst();

        final int upperBound = offset[1];
        final int lowerBound = offset[0];

        final T toReturn;

        if (lowerBound + 1 == upperBound) {

            //range contains only 1 index
            toReturn = words[lowerBound];
        } else {

            final int randomIndex = random.nextInt(lowerBound, upperBound);
            toReturn = words[randomIndex];

            if (randomIndex + 1 < upperBound)
                offsets.addLast(new int[]{randomIndex + 1, upperBound});
            if (randomIndex > lowerBound)
                offsets.addLast(new int[]{lowerBound, randomIndex});
        }

        return toReturn;
    }
}

You can see this in action here. It works fine, but I feel its not truly random. The original array used in the link above is a lexicographically sorted array of 2000 latin words. As we can see in the output there are multiple groups of words which appear to be in order. For e.g.. a range like this occurred in one run.

aberam
abeas
abditi
abdidimusque
abdideris
abdiderim
abdideras
abdideramus
abalienato

Suggestions will be much appreciated :)

EDIT

It seems I did not express my thoughts properly.
I do not want repetitions during the random iteration. The idea is basically to cover all the array indices once, but do it randomly. The example linked above does this. It uses the same lexicographically sorted array of latin words on each run, and randomly iterates it and writes out each word to the outputstream.
Randomness in the output can be defined as probability of occurrence of words with very small "distance" from each other.
For eg. the words "quote" and "quoted" have very small distance. My requirement is that word with very small distance should not occur close to each other in the output (random).

When I say the output is not truly random, I mean that I can observe groups of contiguous words in the output which have very small distance from each other. Hence the output gives the expression of not being truly random.


texts: Getting angle between all points in array

texts:
I have got some code that calculates the angle between all of the points in an array. It works, but it is quite slow. This is because it has complexity O(n^2). It has to loop through the array and apply the angle function to every combination of points.

import math
import random
def angle(pos1,pos2):
    dx=pos2[0]-pos1[0]
    dy=pos2[1]-pos1[1]
    rads=math.atan2(dy,dx)
    rads%=2*math.pi
    degs=math.degrees(rads)
    return degs
class Point(object):
    def __init__(self):
        self.pos=[random.randint(0,500) for _ in range(2)]#random x,y
        self.angles=[]
points=[Point() for _ in range(100)]
for point in points:
    point.angles=[] #so that each frame, they will be recalculated
    for otherC in points:
        if otherC is point:continue #don't check own angle
        ang=angle(point.pos,otherC.pos)
        point.angles.append(ang)

I feel like it could be greatly sped up by using numPy or some other method. I did some searching (here), but all I could find was functions to get angle between planes, or complex numbers. I just need simple arrays. How can this code be optimized for more speed?


texts: Better way to use a Condition (CancellationToken)

texts:
Is there a better way to write this, as I am using the condition of the Cancellation Token to tell if it should use a byte[] from another thread or not.

        SharpDX.Windows.RenderLoop.Run(form, () =>
        {
            if (CTS.IsCancellationRequested)
                form.Dispose();

            if (Queue.TryTake(out TextureData, 300))
            {
                Stoptimer = new Stopwatch();
                Stoptimer.Start();

                device.BeginScene();
                sprite.Begin(SpriteFlags.None);
                try
                {
                    using (var surface = texture.GetSurfaceLevel(0))
                    {
                        if (!CTS.IsCancellationRequested)
                            Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0);
                    }
                    sprite.Draw(texture, new ColorBGRA(0xffffffff));
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Rendering: Texture");
                }

                sprite.End();
                device.EndScene();
                device.Present();
                Stoptimer.Stop();
                Console.WriteLine(Stoptimer.ElapsedTicks);
            }
        });

The important place is here:

        if (!CTS.IsCancellationRequested)
            Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0);

As I need to recheck this, as the Cancellation can happen After it has taken the data from the Queue.

But I wonder, is there a better way to write it?

As you can see, I use the CTS condition 2 times, and it would be nice if I could only use it once to control the flow or something.


texts: JavaScript and callback: apply an action on each element of a callback input

texts:
I'm quite new to js. I even don't know how to call this problem: apply an action on each element of a callback input, but the elements are actually an output..

I crash a lot on this situation: I have a nested callback where first I load a json array and then I perform an action on each element of this array.

$.getJSON(DATA_URL+'/groups', function( groups ) {
    groups.forEach( function(g){
        appendDropdownItem(g);
    } );
});

I want to do it in one line. Not because I think one line is cool but because I think that this nested callback only gets the code dirty and affect readability.

In a pythonic approach I imagine somethings like a comprehension:

[appendDropDownItem(g) for g in loadAjax(DATA_URL+'/groups')]

So.. how to make it one liner/more readable?


texts: Exercise to fetch data from JSON files using ES6 promises

texts:
I did an exercise (self-imposed) promise fetching some data from placeholder JSON files on https://jsonplaceholder.typicode.com/. The exercise in my opinion is finished, but I can't shake the feeling that the code is as dirty as code can be. Please check it out and point me into the right direction and tell me what I did wrong.

The exercise can be found here: http://codepen.io/kresimircoko/pen/vggPmJ

'use strict';
const root = 'https://jsonplaceholder.typicode.com/';
const postList = document.querySelector('#post-list');
console.clear();

const commentsPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'comments');
    xhr.send();
});

const usersPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'users');
    xhr.send();
});

const postsPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'posts');
    xhr.send();
});

// Posts
postsPromise
    .then(data => {
        const posts = JSON.parse(data); // Contains our posts

        usersPromise
            .then(data => {
                const users = JSON.parse(data); // Contains our users
                commentsPromise
                    .then(data => {
                        const comments = JSON.parse(data);
                        displayPosts(posts, users, comments);
                    });
            });
    }).catch(error => { console.log(error); });

// Users

function displayPosts(posts ,users, comments) {
    let output = '';
    posts.map(post => {
        output += `

 ${displayUserName(users, post)}

 ${post.title}

 ${post.body}

 ${displayCommentAmount(comments, post)} comments

        `;
    });
    postList.innerHTML = output;
}

function displayUserName(users, post) {
    return users.map(user => {
        if (user.id === post.userId) {
            return user.name;
        }
    }).join('');
};

function displayCommentAmount(comments, post) {
     const commentArray = comments.filter(comment => {
        return comment.postId === post.id;
    });
    return commentArray.length;
}


texts:
I wrote a bash script for backing up my LAMP server. To be honest that's my first experience in bash so I want to ask you for help in its improvement.

#!/bin/bash

date=`(date +%Y%m%d%H%M)`

declare -A users=(
    ["user1"]="password1"
    ["user2"]="password2"
)

for user in ${!users[@]}
do
    directory=$user

    directories=`find /var/www/$directory -maxdepth 1 -mindepth 1 -type d`

    for directory in $directories
    do
        cd $directory

        if [ ! -d backups ]
        then
            mkdir backups
        fi

        tar --exclude ./backups -czf backups/$date.tar.gz .

        password=${users[$user]}

        databases=`mysql -u $user -p$password -Bse "SHOW DATABASES;"`

        for database in $databases
        do
            if [ $database = ${directory##*/} ]
            then
                mysqldump -u $user -p$password $database | gzip > backups/$date.sql.gz
            fi
        done

        chmod 770 backups -R
        chown $user:$user backups -R
    done
done


texts: Does this I/O operation caused a memory leak

texts:
My colleague did some code Optimise work.

Code below is from a public method of a public class (NOT STATIC CLASS OR METHOD)

code before:

                Bitmap btMap = new Bitmap(Convert.ToInt32(WebConfig.StatsOpenEmailImageWidth), Convert.ToInt32(WebConfig.StatsOpenEmailImageHeight), PixelFormat.Format32bppArgb);
                MemoryStream memStrm = new MemoryStream();

                btMap.Save(memStrm, ImageFormat.Png);
                memStrm.WriteTo(context.Response.OutputStream);

Code after:

                using (Bitmap btMap = new Bitmap(Convert.ToInt32(WebConfig.StatsOpenEmailImageWidth), Convert.ToInt32(WebConfig.StatsOpenEmailImageHeight), PixelFormat.Format32bppArgb))
                {
                    using (MemoryStream memStrm = new MemoryStream())
                    {
                        btMap.Save(memStrm, ImageFormat.Png);
                        memStrm.WriteTo(context.Response.OutputStream);
                    }
                }

Is it a necessary optimisation againt memory leak?


texts: Interface for server requests and responses

texts:
I have an MVC framework I've written. I'm trying to abstract out ASP.NET specific bits as well as make it more testable. Previously, I relied on HttpContext.Current in many places, which proves to be very unfriendly to unit testing. So, I started designing my own minimalistic interface for everything I'd need from there. However, it seems to keep on growing.

/// <summary>
/// This is a very simplified context for server requests and responses
/// It should not cover "everything", but should instead have only what BarelyMVC needs to function
/// As a result, it will usually only have the most commonly used things in it
/// All "get" methods should normally return null if a given name/key doesn't exist
/// </summary>
public interface IServerContext
{
    /// <summary>
    /// Gets a cookie from the current request
    /// </summary>
    HttpCookie GetCookie(string name);
    /// <summary>
    /// Sets a cookie to send with the current response
    /// </summary>
    void SetCookie(HttpCookie cookie);
    /// <summary>
    /// Kills the current request. Kills it with fire! This function should never return(for security purposes)
    /// </summary>
    void KillIt();
    /// <summary>
    /// Gets the user agent sent by the current request
    /// </summary>
    string UserAgent{get;}
    /// <summary>
    /// Maps a relative URL path to an absolute path on the host (is this needed?)
    /// </summary>
    string MapPath(string path);
    /// <summary>
    /// Gets the client's IP address
    /// </summary>
    string UserIP{get;}
    /// <summary>
    /// Gets an HTTP header by name from the current request
    /// </summary>
    string GetHeader(string name);
    /// <summary>
    /// Sets an HTTP header to be sent back in the response to the current request
    /// </summary>
    void SetHeader(string name, string value);
    /// <summary>
    /// Performs a server-side transfer to another URL to service the current request (is this needed?)
    /// Should perform a KillIt() afterwards and never return
    /// </summary>
    void Transfer(string url);
    /// <summary>
    /// Send a 302 redirect back to the client for the given URL and use KillIt() to end the request
    /// </summary>
    void Redirect(string url);
    /// <summary>
    /// Gets a generic item from a key/value store associated with the current request only
    /// </summary>
    object GetItem(string name);
    /// <summary>
    /// Sets a generic item to a key/value store associated with the current request only
    /// </summary>
    object SetItem(string name, object value);
    /// <summary>
    /// Gets or sets the HTTP status code
    /// </summary>
    string HttpStatus{get;set;}
    /// <summary>
    /// Gets a TextWriter which can be used to send content back as the response
    /// </summary>
    TextWriter Writer{get;}
    /// <summary>
    /// Gets a parameter dictionary corresponding to the FORM values passed in by a POST request
    /// </summary>
    ParameterDictionary Form{get;}
    /// <summary>
    /// Gets the URL of the current request
    /// </summary>
    Uri RequestUrl{get;}
}

Is this interface already too big? I know I could abstract out the Request and Response parts, but I tend to think it make it a bit harder to use, especially because of my limits on "get" and "set" being stuck to request and response respectively.

What do you think? Refactoring into Request/Response interfaces, or is it OK how it is?


texts:
I find this piece of Java code really ugly and cumbersome. How can I refactor it to be more clean and easier to read?

ByteArrayOutputStream out = null;
try {
    out = new ByteArrayOutputStream();
    workbook.write(out);
    return out.toByteArray();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

return null;


texts:
I'm building a website where all data interactions are done over ajax other than the initial page load. Now I discovered the need for CSRF tokens.

I elected to deliver the token in a meta tag like so:

<meta name="csrf" content="JI8qMif9gHuD06m/HByCzg==" />

The function that generates the token is as so:

public function csrf()
{
    return str_replace('+','',base64_encode(openssl_random_pseudo_bytes(16)));
}

All controllers for ajax extend a parent controller called JsonController. The JSON controller handles the check of the CSRF token in its constructor (I'll explain why later):

function __construct()
{
    $app = \StarterKit\App::getInstance();

    //ensure request is ajax
    if(!$app->slim->request->isXhr()){
        $app->halt(403,'Access Denied to Ajax Resource');
    }
    //validate csrf token, then update.
    if($app->slim->request->isPost()){
        $fail = false;
        if(!isset($app->post['csrf'])){
            $fail = true;
        }else{
            if($app->post['csrf'] !== $app->session['csrf']){
                $fail = true;
            }
        }
        if($fail !== false){
            $app->halt(403,'Access Denied');
        }
    }

    if($app->slim->request->isGet()){
        $fail = false;
        if(!isset($app->get['csrf'])){
            $fail = true;
        }else{
            if($app->get['csrf'] !== $app->session['csrf']){
                $fail = true;
            }
        }
        if($fail !== false){
            $app->halt(403,'Access Denied');
        }
    }
    $this->app = $app;
}

Now, for the part where I am still unsure of. How should I return the new CSRF token to the client securely? Json controller has a method called __try() this method's responsibility is to invoke the particular Ajax route (method), capture its response (or an exception) and return a JSON encoded response. It is here in this function that the CSRF token is updated. I assume it is safe to return the CSRF token to the user in the JSON response here?

public function __try($method)
{
    try{
        if(!method_exists($this,$method)){
            throw new \exception('method not found');
        }
        $msg = call_user_func([$this,$method]);
    }
    catch(\exception $e){
        if($this->app->debug === true){
            $err = $e->getMessage().'|'.$e->getFile().'|'.$e->getLine();
        }else{
            $err = $e->getMessage();
        }
        $msg = ['error'=>1,'message'=>$err];
    }
    $msg['csrf'] = $this->app->session['csrf'] = $this->app->csrf();
    echo json_encode($msg, JSON_HEX_QUOT | JSON_HEX_TAG);
}

The JavaScript component of the equation here is insignificant. It basically gets/sets the CSRF token and injects it into the request body of any Ajax request (I've built an API wrapper around $.ajax so this is an automated process).

I've tested it and it works, but I'm dying to know: is this even secure? It seems like it is to me because I tried copying the session ID into Firefox and using it to access the session with no success. I'm curious to know your thoughts.


texts:
I would like to know if this code follows recommended practices and standards for AJAX/PHP calls. Can this AJAX + PHP code be improved in terms of security, performance, etc.?

ajax.js:

function getTableData() {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            document.querySelector('#test-table tbody').innerHTML = this.responseText;
        }
    }
    xmlhttp.open('GET', 'ajax.php', true);
    xmlhttp.send();
}

$(document).ready(function () {
    getTableData();
});

ajax.php:

<?php
$data = prepareDataForTable();
$data_length = count($data);
$columns = 4;

for ($row = 0; $row < $data_length; $row += $columns) {
    echo '
';
        for ($col = 0; $col < $columns && ($col + $row) < $data_length; $col++) {
            echo '' . $data[$col + $row] . '	';
        }
    echo '
';
}
?>

ajax.html:

I specifically want to know if this is a good way to send information back to the client - by running loops and echoing output.


texts:
I'm brushing up on Python, working my way through Python Workout. One of the exercises is to emulate the Python zip() function, assuming each iterable passed to the function is of the same length. Here's what I've come up with:
def myzip(*args):
    result = [[] for _ in range(len(args[0]))]
    for i, v in enumerate(args):
        for j, w in enumerate(v):
            result[j].append(w)

    for i, v in enumerate(result):
        result[i] = tuple(v)

    return result

While my function works, I have a hunch there must be a more succinct way of achieving the same thing (forgoing the nested loops). Is there? I'm running Python 3.9.


texts: Finding prime divisors with wheel factorization

texts:
I am just starting to learn C++, and I wrote was the following implementation of the trial division algorithm to find the prime factors of a positive integer. I'm hoping the community here can suggest changes to both the algorithm and to the implementation. I barely know any language-specific features of C++, so I'm sure there is a lot of room for improvement.

In particular, I would like to be able to the following things:

Work with larger integers than what int allows.
Catch errors arising from command-line arguments that cannot be parsed as ints.
Remove the hard-coding of the wheel and the cases of the first primes 2, 3, and 5.
Improve general style/use more features of C++.

#include <iostream>

/*
 * Print out p as many times as it divides n.
 * Return the quotient of n by the highest power of p dividing n.
 */
int checkdivisor(int n, int p) {
  while (n % p == 0) {
    std::cout << p << std::endl;
    n /= p;
  }
  return n;
}

// Wheel for eliminating more composite numbers.
const int PERIOD = 7;
const int WHEEL235[PERIOD] = {4, 2, 4, 2, 4, 6, 2};

/*
 * Print the prime divisors of n.
 * The algorithm is trial division with 2-3-5 wheel factorization.
 */
void primedivisors(int n) {
  if (n > 1) {
    // Check 2, 3, and 5 individually
    n = checkdivisor(n, 2);
    n = checkdivisor(n, 3);
    n = checkdivisor(n, 5);
    // Start at the next potential prime divisor, 7.
    int p = 7;
    int i = 0;
    while (n > 1) {
      // If p^2 > n, then n is the last remaining prime divisor.
      if (p * p > n) {
        std::cout << n << std::endl;
        return;
      }
      // Check if p is a prime divisor.
      n = checkdivisor(n, p);
      // Increment p based on the wheel.
      p += WHEEL235[i++ % PERIOD];
    }
  }
}

/*
 * Parse command-line arguments as ints (if possible), and print their prime
 * factors.
 */
int main(int argc, char* argv[]) {
  for (int i = 1; i < argc; i++) {
    primedivisors(std::stoi(argv[i]));
  }
}


texts: Iterate comparison - How can I write this better?

texts:
I would like to write the following piece of code cleaner and more efficient, any comments will be greatly appreciated:

Dim dt As DataTable = SomeDataTable
    For Each dr As DataRow In dt.Rows
        Dim myColumn As String = dr("column").Trim().ToUpper()
        For Each group As String In collection
            If (group.Trim().ToUpper() = myColumn) Then
               'Add some logic here
            End If
        Next`


texts: Extending SeqLike - move an element to the front of the sequence

texts:
I wrote a method called bringToFront, which moves an element a to the first position of a sequence seq if it exists; otherwise, seq is returned.
If a appears in the sequence more than once, only the first occurrence is moved.

Sample input/output:

List(1, 2, 3, 4, 3).bringToFront(1)     // List(1, 2, 3, 4, 3)
List(1, 2, 3, 4, 3).bringToFront(2)     // List(2, 1, 3, 4, 3)
List(1, 2, 3, 4, 3).bringToFront(3)     // List(3, 1, 2, 4, 3)
List(1, 2, 3, 4, 3).bringToFront(4)     // List(4, 1, 2, 3, 3)
List(1, 2, 3, 4, 3).bringToFront(5)     // List(1, 2, 3, 4, 3)

I could have easily defined these as extensions on List[A] or Seq[A], but I wanted to try and define them for the most abstract type possible, SeqLike[A, Repr]. For this, a CanBuildFrom is needed (I think).

Code:

implicit class SeqLikeOps[A, Repr <: SeqLike[A, Repr]](seq: SeqLike[A, Repr]) {
  def bringToFront(a: A)(implicit cbf: CanBuildFrom[Repr, A, Repr]): Repr = {
    seq.find(_ == a) match {
      case Some(_) => a +: seq.removeFirst(a)
      case _ => seq.repr
    }
  }

  def removeFirst(a: A)(implicit cbf: CanBuildFrom[Repr, A, Repr]): Repr = {
    val b = cbf()

    @tailrec
    def go(xs: SeqLike[A, Repr]): Unit = xs match {
      case h +: t if h == a => b ++= t
      case h +: t => b += h; go(t)
      case _ => ()
    }

    go(seq)
    b.result()
  }
}

My concerns:

Is this the correct way of extending types like SeqLike or TraversableLike in general?
In SeqLike[A, Repr], A and Repr are covariant. In SeqLikeOps[A, Repr], they're not, because they appear in a contravariant position in the signatures of bringToFront and remoteFirst. Is there any downside to this? Could they, somehow, be made covariant?
Do I need the upper bound <: SeqLike[A, Repr]?
Are the names I chose for these methods good? Suggestions are welcome.
Is there a more efficient (in regards to memory and/or time complexity) and/or idiomatic way of implementing this?

Feel free to point out anything else I might have done wrong.


texts:
I have a method that calls a "bridge" for TraderMarketInfo. When info is received, it checks if info IsSet and raises an event. I want to make this method async. C# .NET4.0 VS2012.

Original method:

public void RequestMarketInfo()
{
    TraderMarketInfo marketInfo = bridge.GetMarketInfoAll(Data.Symbol);
    if (marketInfo.IsSet)
        OnMarketInfoUpdated(new MarketInfoUpdateEventArgs(Data.ConnectionId, marketInfo));
}

My attempt to make it async:

public void RequestMarketInfo()
{
    var task = Task<TraderMarketInfo>.Factory.StartNew(() => bridge.GetMarketInfoAll(Data.Symbol));
    task.ContinueWith(t =>
    {
        if (t.Result.IsSet)
            OnMarketInfoUpdated(new MarketInfoUpdateEventArgs(Data.ConnectionId, t.Result));
    });
}

Is it done right?


texts:
I'm yrying to practice some OO PHP and I'm just wondering if what I'm doing is okay or not. Please tell me if there are any alarms in my method so that I can stop doing it and learn a better way.

In my conditional statement, I was following the rule of no else keyword, based on this article by William Durand, which talks about Object Calisthenics.

I also don't know if I'm using the abstract properly, being that I learned it just a few minutes ago - but it works, so I suppose it's being used correctly.

<?php

        abstract class Homework
        {
            protected $coursesTaken = 0;
            protected $minimumCourses = 10;

            abstract function completedOrNot();
        }

        class HistoryHomework extends Homework
        {
            public function __construct($coursesTaken)
            {
                $this->coursesTaken = $coursesTaken;
            }

            public function completedOrNot()
            {
                if ($this->coursesTaken >= $this->minimumCourses)
                {
                    return "You completed the course in " . $this->coursesTaken
                    . " classes, but you only needed " . $this->minimumCourses
                    . " classes to complete the course! \n\n";
                }

                return "Sorry, you did not complete this course. You only took "
                . $this->coursesTaken . " classes, and you need a minimum of "
                . $this->minimumCourses . " to pass. \n\n";
            }
        }

        $student1 = new HistoryHomework(11);
        echo $student1->completedOrNot(); // You have completed the course in 11 classes, but you only needed 10 classes to complete the course!

        $student2 = new HistoryHomework(7);
        echo $student2->completedOrNot(); // Sorry, you did not complete this course. You only took 7 classes, and you need a minimum of 10 to pass.


texts:
A related question got me thinking about a compact Braille dictionary.
It certainly would be easier with Int16 or string but was going for most compact.
I don't think there is a case insensitive char so went with dual entries.

Dictionary<char, byte> braile = new Dictionary<char, byte>()
                        { { 'a', 0x20 }, { 'b', 0x30 }, { 'c', 0x24 }, { 'd', 0x26 }, { 'e', 0x22 }, { 'f', 0x34 }
                        , { 'g', 0x36 }, { 'h', 0x32 }, { 'i', 0x14 }, { 'j', 0x16 }, { 'k', 0x28 }, { 'l', 0x38 }
                        , { 'm', 0x2c }, { 'n', 0x2e }, { 'o', 0x2a }, { 'p', 0x3c }, { 'q', 0x3e }, { 'r', 0x3a }
                        , { 's', 0x1c }, { 't', 0x1e }, { 'u', 0x29 }, { 'v', 0x39 }, { 'w', 0x17 }, { 'x', 0x2d }
                        , { 'y', 0x2f }, { 'z', 0x2b }
                        , { 'A', 0x20 }, { 'B', 0x30 }, { 'C', 0x24 }, { 'D', 0x26 }, { 'E', 0x22 }, { 'F', 0x34 }
                        , { 'G', 0x36 }, { 'H', 0x32 }, { 'I', 0x14 }, { 'J', 0x16 }, { 'K', 0x28 }, { 'L', 0x38 }
                        , { 'M', 0x2c }, { 'N', 0x2e }, { 'O', 0x2a }, { 'P', 0x3c }, { 'Q', 0x3e }, { 'R', 0x3a }
                        , { 'S', 0x1c }, { 'T', 0x1e }, { 'U', 0x29 }, { 'V', 0x39 }, { 'W', 0x17 }, { 'X', 0x2d }
                        , { 'Y', 0x2f }, { 'Z', 0x2b }};
foreach (KeyValuePair<char, byte> c in braile)
{
    Debug.WriteLine("{0} {1}", c.Key, c.Value.ToBraile());
}
Debug.WriteLine("{0} {1}", 'w', braile['w'].ToBraile());
Debug.WriteLine("{0} {1}", 'B', braile['B'].ToBraile());

public static class MyExtensions
{
    public static string ToBraile(this byte b)
    {
        return Convert.ToString(b, 2).PadLeft(6, '0');
    }
}


texts: Counting valleys traversed below sea level, given elevation changes

texts:
Problem Statement:

  Gary is an avid hiker. He tracks his hikes meticulously, paying close
  attention to small details like topography. During his last hike he
  took exactly steps. For every step he took, he noted if it was an
  uphill, or a downhill,  step. Gary's hikes start and end at sea
  level and each step up or down represents a  unit change in altitude.
  We define the following terms:

  A mountain is a sequence of consecutive steps above sea level,
  starting with a step up from sea level and ending with a step down to
  sea level. A valley is a sequence of consecutive steps below sea
  level, starting with a step down from sea level and ending with a step
  up to sea level. Given Gary's sequence of up and down steps during his
  last hike, find and print the number of valleys he walked through.

  For example, if Gary's path is, he first enters a valley units deep.
  Then he climbs out an up onto a mountain units high. Finally, he
  returns to sea level and ends his hike.

  Function Description

  Complete the countingValleys function in the editor below. It must
  return an integer that denotes the number of valleys Gary traversed.

  countingValleys has the following parameter(s):

  n: the number of steps Gary takes
  s: a string describing his path

  Input Format

  The first line contains an integer, the number of steps in Gary's
  hike.  The second line contains a single string, of characters that
  describe his path.

  Output Format

  Print a single integer that denotes the number of
  valleys Gary walked through during his hike.

My solution goes like this :

def countingValleys(n: Int, s: String): Int = {
  def rec(path: List[Char], counter: Int, valleys: Int): Int = {
    path match  {
      case Nil => valleys
      case x::xs if (x == 'U') && ((counter + 1) == 0) =>
        rec(xs, counter+1, valleys+1 )
      case x::xs if x == 'U' => rec(xs, counter +1, valleys)
      case x::xs if x == 'D' => rec(xs, counter -1, valleys)
    }
  }
  rec(s.toList, 0, 0)
}

Sample Input:

8
UDDDUDUU

Sample Output:

1

I wonder if there is a more idiomatic solution in functional programming style.


texts:
I have built a real estate management system with Django. I want to know if my design database was wrong. Please let me know how to improve it.

Should I make the models use more than two tables (classes)?

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='profiles', default='logo.png')
    phone = models.CharField(max_length=11, default='')
    bio = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=20, default='erbil')
    location = models.CharField(max_length=40, default='')
    date = models.DateTimeField(default=datetime.now)
    active = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.user}'

class Listing(models.Model):
    objects = ListingManager()

    company = models.ForeignKey(User, on_delete=models.CASCADE )
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True, default='', blank=True)
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=100, choices=city_choices, default='lodon')
    estate_type = models.CharField(max_length=20, choices=estate_choices, default=house)
    description = models.TextField(blank=True)
    rent_sale = models.CharField(max_length=20, choices=rent_sale_choice, default=sale)
    price = models.IntegerField()
    bedrooms = models.IntegerField(default=0)
    bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
    garage = models.IntegerField(default=0)
    sqft = models.IntegerField()
    sold =  models.BooleanField(default=False)
    sold_time = models.DateTimeField(default=datetime.now,blank=True)
    photo_main = models.ImageField(upload_to='listings_main')
    photo_1 = models.ImageField(upload_to='listings_1', blank=True)
    photo_2 = models.ImageField(upload_to='listings_1', blank=True)
    photo_3 = models.ImageField(upload_to='listings_1', blank=True)
    photo_4 = models.ImageField(upload_to='listings_1', blank=True)
    photo_5 = models.ImageField(upload_to='listings_1', blank=True)
    photo_6 = models.ImageField(upload_to='listings_1', blank=True)
    is_published = models.BooleanField(default=True)
    list_date = models.DateTimeField(default=datetime.now, blank=True)
    unless = models.CharField(default='', max_length=20)


texts:
I am trying to build a very basic JS framework for my own uses, ultimately collating a lot of pieces of JavaScript I have created over the years. But I would not call myself a JavaScript expert.

What I have written below works well enough but I really would like to know if I am making any fundamental errors in the way this is set up, rather than re-writing a lot of code further down the line.

This basic start point is mirroring the way jQuery can be written to select an element and chain an event to that object, but using all the querySelectorAll instead of the older methods.

If anyone can find basic or advanced flaws in what I've done that would be most useful.


texts: Compute binary XOR of all integers in a range, mod 2

texts:
here I am taking 3 inputs. 1st input will take test cases and the other two input will take starting and ending range. the program is running fine as expected but the limit of this question for compilation is 1 sec, and my code is taking 5.01 sec.

How can I make it more efficient so that I can submit the code?

  The challenge was to take number of test cases.

  Each test cases show take 2 input (starting and ending range) Eg: 1  4
  (i.e 1,2,3,4)

  Do the bitwise XOR operation for all of them (i.e  1^2^3^4)

  Which when
  you perform will be equal to 4

  Now just check if it is even or odd and print the same.

Here's my code:

from sys import stdin, stdout
t = stdin.readline()
for i in range(int(t)):
    p = 0
    a, b = map(int,stdin.readline().split())
    for x in range(a,b+1):
        p ^= int(x)
    if p % 2 == 0:
        stdout.write(str("Even\n"))
    else:
        stdout.write(str("Odd\n"))

compiling in python 3.6

INPUT:
    4
    1 4
    2 6
    3 3
    2 3

OUTPUT:
    Even
    Even
    Odd
    Odd

Working perfectly with no issue in code.


texts:
This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.

The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.

It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.

I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.

import os

# Declare Functions
def jsonStart():
    return "{\n"

def jsonEnd(indent):
    return "\n" + jsonIndent(indent) + "}"

def jsonIndent(amount):
    amount = amount * 4
    return " " * amount

def jsonKeyValue(key, value, indent = 0):
    return jsonIndent(indent) + jsonKey(key) + jsonValue(value)

def jsonKey(key, indent = 0):
    return jsonIndent(indent) + "\"" + key + "\"" + ": "

def jsonValue(value):
    return "\"" + value + "\""

def deleteCreatedFiles():
    print("\nSomething went wrong")
    for file in createdFiles:
        print("Deleting: " + file)
        os.remove(file)
    print("\n")

def createFile(filename, data):
    try:
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        with open(filename, "w+")as newFile:
            newFile.write(data)
    except:
        deleteCreatedFiles()
        raise
    else:
        createdFiles.append(os.path.relpath(newFile.name))
        print("Created" + os.path.relpath(newFile.name))

def blockStatesFile():
    data = jsonStart()
    data += jsonKey("variants", 1) + jsonStart()
    data += jsonKey("normal", 2) + "{ " + jsonKeyValue("model", modid + ":" + blockName) + "}"
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

def modelsItemFile():
    data = jsonStart()
    data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",\n"
    data += jsonKey("textures", 1) + jsonStart()
    data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2)
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

def modelsBlockFile():
    data = jsonStart()
    data += jsonKeyValue("parent", "block/cube_all", 1) + ",\n"
    data += jsonKey("textures", 1) + jsonStart()
    data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2)
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

# Run Script
createdFiles = []
blockName = input("block name: ")
modid = input("modid: ")
createFile("blockstates/" + blockName + ".json", blockStatesFile())
createFile("models/item/" + blockName + ".json", modelsItemFile())
createFile("models/block/" + blockName + ".json", modelsBlockFile())


texts: iterating over the values of a list of ordered dictionaries

texts:
I am facing the following problem: I have a special data structure that is a dictionary whose keys are integers (dimensions). The values are also dictionaries whose keys are strings (geometric types) and whose values are numpy arrays (connectivities). Something like this:

custom = {1: {'a': np.zeros(10), 'b': np.zeros(100)}, 2:{'c': np.zeros(20), 'd': np.zeros(200)}}

I use this data structure quite a lot in the code, and every time I need to iterate over all rows in the numpy arrays of this data structure (all values of the dictionaries), I have to type:

for d, delem in custom.items():
    for k, v in delem.items():
        for row in v:
            print(row)

And this is way too verbose. So to make things easier to other developers, I am trying to encapsulate this behavior in a custom class so that I can type:

for row in custom:
    print(row)

Also, an important requirement is that all rows have to be traversed "in order".
And so I came up with a Test class that derives from list. The class is initialized by passing a dictionary (maybe I can improve this later by just adding the elements directly to it). I have overridden the __iter__ and __next__ methods to provide the iteration type I want. By default, iteration is done through the highest dimension present. But the user can do iteration over lower-dimensional dictionaries and for that I overrode the __call__ method.
The technique works, I an iterate as many times as I want over this data structure, and I accomplished the simplicity I wanted. But I'm a bit concerned about performance, as I don't think that calling self[self.d][self.etype][self.idx-1] is very efficient. Maybe there are other improvements to be made as well that I don't see.

import sys
import numpy as np
from collections import OrderedDict

custom = {0: {'n1': np.array([[3]])}, 1: {'l2': np.array([[ 0,  4],
       [ 4,  5],
       [40, 41],
       [41, 42],       [57,  3],
       [57,  3]])}, 2: {'t3x': np.array([[188, 401, 400],
       [188, 187, 401],
       [187, 205, 401],
       [324, 306, 417],
       [306, 305, 417],
       [305, 416, 417]]), 'q3': np.array([[188, 401, 400, 0],
       [188, 187, 401, 0],
       [187, 205, 401, 0],
       [323, 324, 417, 0],
       [324, 306, 417, 0],
       [306, 305, 417, 0],
       [305, 416, 417, 0]])}}

class Test(list):

    def __init__(self, *args, **kwargs):

        super(Test, self).__init__(*args, **kwargs)

        for k,v in args[0].items():
            self[k] = OrderedDict(v)

        self.d = -1
        self.setup()

    def setup(self):
        self.iterator = iter(self[self.d].keys())
        self.etype = next(self.iterator)
        self.idx = 0

    def __iter__(self):
        self.setup()
        return self

    def __next__(self):

        try:
            self.idx += 1
            return self[self.d][self.etype][self.idx-1]

        except IndexError:

            self.etype = next(self.iterator)
            self.idx = 0
            return self[self.d][self.etype][self.idx-1]

    def __call__(self, d):
        self.d = d-1
        return self

def main(argv=()):

    tst = Test(custom)
    print(tst)

    # iterate over the container
    for el in tst:
        print(el)

    # iterate again over the container
    for el in tst:
        print(el)

    # iterate over lower dimension
    for el in tst(-1):
        print(el)

    return 0

if __name__ == "__main__":
    sys.exit(main())


texts: Solve membership binary mask problem in Scala

texts:
Imagine you have two string sequences:

val s1 = Seq("c", "a", "b", "z", "a", "b")
val s2 = Seq("a", "b")

You need to come up with an algorithm that generates a binary membership mask of s2 in s1, e.g.:

algorithm(s1, s2) => 011000

Here are some other examples:

val s1 = Seq("a", "b", "z", "c", "a")
val s2 = Seq("a", "b", "z")
11100

val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a", "b")
00011

val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a")
00100

val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a", "a")
00110

Notice that we only count first sequence match and discard the rest sequence matches.

Basically, in case of s2 = Seq("z", "b", "a", "a", "b") and s1 = Seq("a", "b") we are trying to solve the following task:

"z"  "b"  "a"  "a"  "b"
 |    |    |    |    |
" "  " "  " "  "a"  "b"
 |    |    |    |    |
 0    0    0    1    1

Why? Imagine you have a sequence of auto-generated strings like "This is Google Inc ." but you only need to extract "Google" from it cutting everything else. It is easy when you know what you are searching for but once it is "This is ? Inc ." you have no way but to rely on binary masks that you collected from a big corpus. In order to generate such masks, you first need the algorithm described above.

I have come up with a simple while loop. This looks pretty ugly, so there should be another more Scala-like solution. How would you solve it?

def binmask(a: Seq[String], b: Seq[String]): String = {
  val x = a.sliding(b.length, 1)
  var continue = true
  var mask = ""
  while (continue && x.hasNext) {
    val g = x.next()
    if (g == b) {
      mask += "1"*b.length + "0"*x.length
      continue = false
    } else mask += "0"
  }
  if (continue) mask += "0"
  mask
}


texts: Principal Component Analysis in Tensorflow

texts:
To learn the low-level API of Tensorflow I am trying to implement some traditional machine learning algorithms. The following Python script implements Principal Component Analysis using gradient descent. It finds component weights that maximize the variance of each component. The weights are constrained to be orthonormal, as required by the PCA definition.

The results are consistent with Scikit-Learn's PCA implementation, so I assume the code works correctly.

Since these are my first baby steps with Tensorflow, I doubt that I used the API in an idiomatic way. How can my use of Tensorflow be improved?

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

x_data = np.random.randn(100, 3) @ [[0, 0, 1], [1, -2, 0], [0, 1, 0]]  # data set
n_components = 3  # number of desired components

def proj(v, u):
    '''project vector v on vector u'''
    return u * (tf.reduce_sum(u * v) / tf.reduce_sum(u**2))

def orthonormalize(w):
    '''orthonormalize vectors basis w'''
    n = w.shape[1]
    ortho_vecs = []
    for i in range(n):
        next_vector = w[:, i]
        for vec in ortho_vecs:
            next_vector -= proj(w[:, i], vec)
        ortho_vecs.append(next_vector)
    u = tf.stack(ortho_vecs, axis=-1)
    return u / tf.reduce_sum(u**2, axis=-2)**0.5  # normalize basis vectors

# reset tensorflow (because I run this in a persisting Jupyter kernel)
tf.reset_default_graph()

# placeholder tensor for input data
x = tf.placeholder(tf.float32, shape=[None, x_data.shape[-1]])

# PCA is one densely connected layer with no biases and linear activation function.
# Each unit corresponds to one component, and components are constrained to be
# orthonormal.
y = tf.layers.dense(x, units=n_components, use_bias=False,
                    kernel_constraint=orthonormalize)

# mean and variance of the resulting components
mean_y = tf.reduce_mean(y, axis=-2)
var_y = tf.reduce_mean((y - mean_y)**2, axis=-2)

# minimize the sum of component variances
# This seems not only to converge to the correct components, but even sorts
# the components from largest to smallest. I don't know why... possibly has to
# do with the orthogonalization where the first component is unconstrained and
# each successive component is more and more constrained...
optimizer = tf.train.GradientDescentOptimizer(0.001)
train = optimizer.minimize(-tf.reduce_sum(var_y))

with tf.Session() as sess:
    # initialize weights
    init = tf.global_variables_initializer()
    sess.run(init)

    # iterate training
    train_var = []
    train_weights = []
    for _ in range(1000):
        # stochastic gradient descent (need at least two samples for computing
        # the variance... call it micro-batch?)
        x_batch = x_data[np.random.randint(x_data.shape[0], size=2)]
        #x_batch = x_data  # full data set

        _, v, w = sess.run([train, var_y] + tf.trainable_variables(),
                           feed_dict={x: x_batch})

        train_weights.append(w.ravel())

        train_var.append(np.var(x_data @ w, axis=0))

    # plot convergence of weights and variances
    plt.subplot(2, 1, 1)
    plt.plot(train_var)
    plt.subplot(2, 1, 2)
    plt.plot(train_weights)

    writer = tf.summary.FileWriter("test", sess.graph)

    # print final component weights
    print(sess.run(tf.trainable_variables()))


texts:
It's a user alert script. It worked in every browser I tested. But the function itself looks very messy/repetitive. Is there any way to make this cleaner?

function message(text) {
    var alert = document.createElement('div');
    var alertText = document.createTextNode(text);
    var alertCloseButton = document.createElement('i');
    var buttonText = document.createTextNode('close');
    var shadow = document.createElement('div');

    alert.className = 'alert-text';
    alertCloseButton.className = 'material-icons';
    alertCloseButton.id = 'close-alert';
    alertCloseButton.setAttribute('onclick', 'function() { var a = this.parentNode; var s = a.parentNode; s.parentNode.removeChild(s)}');
    alertCloseButton.onclick = function() { var a = this.parentNode; var s = a.parentNode; s.parentNode.removeChild(s) };
    alertCloseButton.appendChild(buttonText);
    alert.appendChild(alertCloseButton);
    alert.appendChild(alertText);
    shadow.className = 'shadow';
    shadow.appendChild(alert);

    document.body.appendChild(shadow);
}
var button = document.querySelector('button');
button.addEventListener('click', function(){
    message('Button clicked');
});

Here's the code working: https://jsfiddle.net/3aouyfz7/


texts: Beginner python solution to CSES "Permutations"

texts:
I'm working through the CSES problem set as I learn to program, and this solution was accepted, but I'm not quite happy with it. I just know there's a faster way to check whether or not a solution's valid instead of looping through every element, and I'm sure there're plenty more improvements that could be made. Any feedback is appreciated!
Problem: A permutation of integers 1,2,…,n is called beautiful if there are no adjacent elements whose difference is 1.
Given n, construct a beautiful permutation if such a permutation exists.
If there are several solutions, you may print any of them. If there are no solutions, print "NO SOLUTION".
def check_solution(sol):
    last = sol[0]
    for num in sol:
        if num - last == 1 or num - last == -1:
            return False
        last = num
    return True

a = [int(x) for x in range(1, int(input())+1)]
b = []
even = a[1::2]
odd = a[::2]

b.extend(even)
b.extend(odd)

if check_solution(b):
    print(*b)
else:
    print("NO SOLUTION")


texts: How to append ajax return data to a table

texts:
I am trying to append data to a table based on the ajax returned data.

My codes work but it seems ugly. I was wondering if anyone here can help me
to simplfy it. Thanks a lot!

    ajax.callback=function(data){
          for (var i=0; i<dataObj[0].data.length; i++){
              var td=document.createElement('td');
              td.innerHTML=dataObj[0].data[i].ID;
              var td2=document.createElement('td');
              td2.innerHTML=dataObj[0].data[i].test;
              var td3=document.createElement('td');
              td3.innerHTML=dataObj[0].data[i].year;
              var td4=document.createElement('td');
              td4.innerHTML=dataObj[0].data[i].code;
              var td5=document.createElement('td');
              td5.innerHTML=dataObj[0].data[i].Label;
              var td6=document.createElement('td');
              td6.innerHTML=dataObj[0].data[i].contents;
              var td7=document.createElement('td');
              td7.innerHTML=dataObj[0].data[i].test;

              var tr=document.createElement('tr');
              tr.appendChild(td);
              tr.appendChild(td2);
              tr.appendChild(td3);
              tr.appendChild(td4);
              tr.appendChild(td5);
              tr.appendChild(td6);
              tr.appendChild(td7);

              $('#Table').append(tr);

           }
    }


texts: Compiler warning on unused exception...need to improve structure?

texts:
Consider the below:

public int DoSomethingComplicated(ComplicatedObject input)
{
    try {
        return input.Analyse();
    }
    catch(CustomExceptionOne ex1)
    {
         throw;
    }
    catch(CustomExceptionTwo ex2)
    {
         Log(ex2.Message);
         return -1;
    }
}

Obviously I have abstracted quite a bit for the example, but the idea is that the try block performs a task which can cause one of two types of runtime exception.

In the event that the exception type is CustomExceptionOne, I want to simply throw the exception. For CustomExceptionTwo on the other hand, I want to log the issue but return -1.

I do not have access to the input.Analyse() method in order to change it.

This all looks fine to me, and works fine, but I get a compiler warning because ex1 is technically never used. I don't really want to throw the entire ex1 exception, so I am wondering how I can get this warning to go away.

I can think of a couple of hacky ways like Console.WriteLine(ex1.Message) or something but that isn't a route I particularly want to go down.


texts: Challenge: solution for this deep-iteration JavaScript function dilemma?

texts:
Trying to implement a deep-iteration function with some constraints, I've noticed the faster solution is iterating it twice! Any attempt to avoid this resulted in slower code. So, the challenge: can you redesign the function below removing the code duplicate and doubled iteration, without making it slower?

Constraints:

It must deeply iterate through a tree, providing, for a callback function, the node value and it's path.
It must work for arrays and objects.
Arrays must be iterated by ascending numerical keys first and non-numerical keys last.
It must allow for early interruption by using "return", and must return that value.

Code:

function iter(obj,fn,iter_pos){
    var ret, iter_pos = iter_pos || [];
    for (var i=0; i<obj.length; ++i)
        if (ret = typeof(obj[i]) == "object" ? iter(obj[i],fn,iter_pos.concat(i)) : fn(iter_pos.concat(i),obj[i]))
            return ret;
    for (var key in obj)
        if (isNaN(Number(key)))
            if (ret = typeof(obj[key]) == "object" ? iter(obj[key],fn,iter_pos.concat(key)) : fn(iter_pos.concat(key),obj[key]))
                return ret;
};

Test:

var tree = [1,2,[3,3,3],4];
tree.x = 5;
tree.y = {x:6,y:7,z:8};
tree.z = 9;
console.log(
    iter(tree,function(path,val){
        console.log("Value ",val," at path: ",path);
        if (val==7)
            return "Returned early!";
    })
);

Output:

Value  1  at path:  [ 0 ]
Value  2  at path:  [ 1 ]
Value  3  at path:  [ 2, 0 ]
Value  3  at path:  [ 2, 1 ]
Value  3  at path:  [ 2, 2 ]
Value  4  at path:  [ 3 ]
Value  5  at path:  [ 'x' ]
Value  6  at path:  [ 'y', 'x' ]
Value  7  at path:  [ 'y', 'y' ]
Returned early!


texts: Accessing parent isolated scope in directive

texts:
I was looking for a way to markup parts of my app as restricted to only certain roles, on an element basis.

This works quite well, using an attribute directive, where I specify the allowed roles and disable/hide the corresponding element; e.g.

<input require-role="admin" />

In order to make the app more maintainable I thought about inheriting the the required role attribute, e.g.

<form>

        <input required-role/>
        <input required-role/>
        <input required-role/>
        <input required-role/>
        <input />

            <input required-role/>

        <input required-role/>
        <input required-role/>
        <input required-role/>
        <input required-role="Admin"/>

    <button required-role="Admin">Save</button>
    <button required-role="User">Send to review</button>
</form>

What I came up with is the following directive, that recursively searches in the isolatedScope of the parent element until it eventually finds the requiredRole property:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope){
  $scope.name = 'World';
});
app.directive('requireRole', function(){
  var getRequiredRoleFromParent = function(element){
    var par = element.parent();
    if (!par) return;
    var is = par.isolateScope();
    if (is && is.requireRole) return is.requireRole;
    return getRequiredRoleFromParent(par);
  };
  return {
    restrict: 'A',
    scope   : {
      requireRole: '@'
    },
    link    : function(scope, element){
      var labelClass = "label-success";
      if (!scope.requireRole) {
        scope.requireRole = getRequiredRoleFromParent(element);
        labelClass = "label-info";
      }
      element.prepend('' + scope.requireRole + '');
    }
  }
});

I am happy with the solution I came up with, yet my experience developing directives is limited; maybe there are better ways to achieve the same behavior?

Plunkr can be found here


texts:
These functions are more or less the same. They are doing the sign in process for a flask application. A user is retrieved from a database (identified through email address) and the password is checked for validity (bcrypt). If either of those failed, an error should be displayed for the user in the template (signin.html).

What is considered to be more readable or elegant. Are there other, nicer solutions?

@app.route('/signin', methods=['POST'])
@public
def do_signin():
    user = get_user_by_email([request.form.get('email')])
    invalid = user is None or not bcrypt.checkpw(
        request.form.get('password').encode('utf-8'),
        user['password'].encode('utf-8'),
    )

    if invalid:
        error = 'Invalid Email or Password'
    else:
        session[SESSION_TOKEN] = add_token(user['id'])
        return redirect(url_for('index'))
    return render_template('signin.html', error=error or None)

or

@app.route('/signin', methods=['POST'])
@public
def do_signin():
    user = get_user_by_email([request.form.get('email')])
    error = 'Invalid Email or Password' if user is None or not bcrypt.checkpw(
        request.form.get('password').encode('utf-8'),
        user['password'].encode('utf-8'),
    ) else None

    if error is None:
        session[SESSION_TOKEN] = add_token(user['id'])
        return redirect(url_for('index'))
    return render_template('signin.html', error=error or None)

or

@app.route('/signin', methods=['POST'])
@public
def do_signin():
    user = get_user_by_email([request.form.get('email')])

    if user is None:
        error = 'Invalid Email or Password'
    elif not bcrypt.checkpw(
        request.form.get('password').encode('utf-8'),
        user['password'].encode('utf-8')
    ):
        error = 'Invalid Email or Password'
    else:
        session[SESSION_TOKEN] = add_token(user['id'])
        return redirect(url_for('index'))
    return render_template('signin.html', error=error or None)


texts:
The goal is to convert a hex string to a byte array with the following requirements:

\$O(1)\$ additional space apart from input and output.
\$O(n)\$ runtime

This mostly just prohibits creating a new string with a 0 prepended to avoid having to deal with odd strings.

private static byte[] ConvertHexToBytes(string input) {
    var result = new byte[(input.Length + 1) / 2];
    var offset = 0;
    if (input.Length % 2 == 1) {
        // If length of input is odd, the first character has an implicit 0 prepended.
        result[0] = (byte)Convert.ToUInt32(input[0] + "", 16);
        offset = 1;
    }
    for (int i = 0; i < input.Length / 2; i++) {
        result[i + offset] = (byte)Convert.ToUInt32(input.Substring(i * 2 + offset, 2), 16);
    }
    return result;
}

Can we write this nicer, possibly using Linq (and some chained iterables) in C#?

Test code that covers I think all requirements:

private static void TestConversions() {
    var inputs = new[] { "",
                    "0",
                     "10",
                     "f",
                     "0f",
                     "010",
                     "0ff",
                     "f2ab"
                 };
    var i = 0;
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] {  }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0 }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0x10 }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0xf }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0xf }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0x0, 0x10 }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0x0, 0xff }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0xf2, 0xab }));
    Debug.Assert(i == inputs.Length);
}