texts:
I know heaps are commonly implemented by an array. But, I wanted to share my pointer implementation and have your feedback(s) :)

General idea:

I convert the index to its binary value and then trace the heap (0 = leftChild & 1 = rightChild)] Note: The first 1 is for entering the root.
I do the push at the same time.

Example: for the 12th element, 12 = 1100. The first 1 is for entering the root. Now I trace the heap by following 100.

    struct Node{
         Node *leftChild;
         Node *rightChild;
        int data;
    };

    bool insertHeap(Node **heap, int data, short index){
        Node *newNode, *temp, *parent;
        int tempData;
        short mask = 0x80;

    try{
        newNode = new Node;
    }
    catch (bad_alloc& e) {
        cerr << "Memory allocation error: " << e.what() << endl;
        return false;
    }

    while (!(index & mask)) index <<= 1;

    index <<= 1;
    parent = NULL;
    temp = *heap;

    while (temp){
        if (data > temp->data){
            tempData = temp->data;
            temp->data = data;
            data = tempData;
        }
        parent = temp;

        if (!(index & mask)) temp = temp->leftChild;
        else temp = temp->rightChild;

        if (temp) index <<= 1;
    }

    newNode->leftChild = NULL;
    newNode->rightChild = NULL;
    newNode->data = data;

    if(!parent){
        *heap = newNode;
        return true;
    }

    if (!(index & mask)) parent->leftChild = newNode;
    else parent->rightChild = newNode;

    return true;
}

This is my main():

#include <iostream>
using namespace std;

int main (){
    Node *heap = NULL;
    int arr[13] = {3,6,8,1,5,9,4,2,0,7,11,14,13};

    for (int i=0; i<13; i++) insertHeap(&heap, arr[i], i+1);
    return 0;
}


texts:
I am writing a C++AMP library, and as one of my utility methods I am implementing a parallel reduction algorithm based on the cascade method documented on this blog post with slight improvements by utilizing asynchronous CPU execution.
Does anyone have any performance/correctness/language improvements to offer?
template <typename T, std::size_t TileSize = DEFAULT_TILE_SIZE, std::size_t NumTiles = DEFAULT_NUM_TILES>
auto ParallelAccumulate( const concurrency::array_view<const T, 1>& avData ) -> decltype(std::declval<T>() + std::declval<T>())
{
    static_assert(IsPowerOfTwo( TileSize ), "Tile Size must be a power of two");
    static_assert(is_amp_compatible<T>::value, "The internal type of the array_view must be amp comptible");
    static_assert(NumTiles > 0, "There must be a non-zero number of tiles");

    std::size_t sArrayLength = avData.extent.size();
    const std::size_t sStrideLength = TileSize * NumTiles * 2U;

    // Accumulate tail (if necessary):
    const std::size_t sTailLength = sArrayLength % sStrideLength;
    std::future<decltype(std::declval<T>() + std::declval<T>())> futTailSum;
    if( sTailLength != 0 )
    {
        std::vector<T> vecTail( sTailLength );
        concurrency::copy( avData.section( concurrency::index<1>( sArrayLength - sTailLength ) ), vecTail.begin() );
        futTailSum = std::async( std::launch::async, [&vecTail]{ return concurrency::parallel_reduce( vecTail.begin(), vecTail.end(), static_cast<T>(0) ); } );

        if( (sArrayLength -= sTailLength) == 0 )
        {
            return futTailSum.get();
        }
    }

    concurrency::array<decltype(std::declval<T>() + std::declval<T>()), 1> arrPartialResult( NumTiles );
    concurrency::parallel_for_each( concurrency::extent<1>( TileSize * NumTiles ).tile<TileSize>(), [=, &arrPartialResult]( concurrency::tiled_index<1> tIndex ) restrict( amp ) {
        tile_static decltype(std::declval<T>() + std::declval<T>()) tTileData[TileSize];
        std::size_t sLocalIndex = tIndex.local[0];

        std::size_t sInputIndex = (tIndex.tile[0] * 2U * TileSize) + sLocalIndex;
        tTileData[sLocalIndex] = static_cast<decltype(std::declval<T>() + std::declval<T>())>(0);

        do {
            tTileData[sLocalIndex] += avData[sInputIndex] + avData[sInputIndex + TileSize];
            sInputIndex += sStrideLength;
        } while( sInputIndex < sArrayLength );

        tIndex.barrier.wait();

        for( std::size_t sStride = TileSize / 2U; sStride > 0; sStride /= 2U )
        {
            if( sLocalIndex < sStride )
            {
                tTileData[sLocalIndex] += tTileData[sLocalIndex + sStride];
            }

            tIndex.barrier.wait();
        }

        if( sLocalIndex == 0 )
        {
            arrPartialResult[tIndex.tile[0]] = tTileData[0];
        }
    } );

    std::vector<decltype(std::declval<T>() + std::declval<T>())> vecPartialResult( NumTiles );
    concurrency::copy( arrPartialResult, vecPartialResult );
    return concurrency::parallel_reduce( vecPartialResult.begin(), vecPartialResult.end(), static_cast<T>(0) ) + futTailSum.get();
}


texts: Get tuple data in an array containing only one element from another tuple

texts:
Example: I want to select tuple in an array(t_bet), which contains just one element from judge_tpl = (5,12,24). For example, (3, 4, 5, 16, 30) is ok while (3, 12, 24, 29, 30) is not because it contains two elements.

t_bet = [(3, 12, 24, 29, 30),
 (3, 13, 18, 19, 22),
 (1, 11, 16, 17, 22),
 (3, 4, 5, 16, 30),
 (1, 11, 15, 20, 24)]

lst = []
for i in t_bet:
    if (5 in i) and (12 not in i) and (24 not in i ) :
        lst.append(i)
    elif (5 not in i) and (12 in i) and (24 not in i ):
        lst.append(i)
    elif (5 not in i) and (12 not in i) and (24 in i ):
        lst.append(i)

lst: [(3, 4, 5, 16, 30), (1, 11, 15, 20, 24)]

I have to list all combinations using if..elif,which is inconvenient especially when there are so many elements in judge_tpl.

Notice: The tuples in t_bet have same lengths while there are more than 10 elements in  judge_tpl.


texts:
My task:

  Body Mass Index (BMI) is a measure of health based on height and weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters.

  Write a java code to let the user enter weight, feet, and inches and interpret the users BMI.

My code:

//import scanner
import java.util.Scanner;

//import Math class
import java.lang.Math;

public class ComputeBMI {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //create scanner
        Scanner input = new Scanner(System.in);

        //declare variables
        double weight;
        int feet;
        int inches;

        //prompt user
        System.out.print("Enter weight in pounds: ");
        weight = input.nextFloat();

        System.out.print("Enter feet: ");
        feet = input.nextInt();

        System.out.print("Enter inches: ");
        inches = input.nextInt();

        //convert measurements
        double weightInKilos = weight * 0.453592;
        double heightInMeters = (((feet * 12) + inches) * .0254);
        double bmi = weightInKilos / Math.pow(heightInMeters, 2.0);
//      double bmi = weightInKilos / (heightInMeters * heightInMeters);

        //display output
        System.out.println("Your BMI is: " + bmi);

        //interpret BMI
        if (bmi < 18.5 ) {
            System.out.print("Underweight");
        }

        else if (bmi >= 18.5 && bmi < 25) {
            System.out.print("Normal");
        }

        else if (bmi >= 25 && bmi < 30) {
            System.out.print("Overweight");
        }

        else if (bmi >= 30) {
            System.out.print("Obese");
        }

//      Do I need this last else if there?
//      else {
//          System.out.print("");
//      }

        input.close();

    }

}

I used only the material we've been taught thus far to complete my code. My POC is clarity/fluidity of my code and my variable data types. In my mind, feet and inches should be integers and weight should be a double. Valid hypothesis?

Thanks, y'all.


texts:
I'm trying to estimate a weighted logistic regression as part of a bigger project. I have an implementation in Matlab2015b, but I wanted to give Julia a try to see if I could speed up the estimation and learn Julia better. The estimation time is on the project level already running into hours as this function is repeatedly called. I'm suspecting that due to my Matlab background, I'm missing out on some optimizations available in Julia.

function logit(y,x,w)
b = x\y;  # use ols values as start
maxit = 100;
tol = 0.000001;

#initialize breaks
crit = 1.0;
iter = 1;

  # loop
  while (iter < maxit) && (crit > tol)
          # Gradient & Hessian for logit
          (g,H) = LogitGradientAndHessian(y,x,b,w);

          # proposed change in coefficients
          db = -H\g

          # stepsize determination. Try steps of 1 or smaller
          s = 1.0
          L1 = LogitLogLikelihood(b+s*db,y,x,w)
          while s>tol
              s = s/2
              L2 = LogitLogLikelihood(b+s*db,y,x,w)
              if (L2-L1)<0 # log likelihood increases by less than 0/tol, abort
                  s = 2*s # take previous step size, with step size the likelihood is declining
                  break
              end
              L1 = L2; # reduce step-size, this is the new log likelihood
            end

      # take step
      b = b + s*db; # update coefficients
      crit = maximum(abs.(db)); # maximum absolute change in coefficient values (without step size like in original code...)
      iter = iter + 1;
end # end of while

return b,iter
end

function sigmoid(z::Float64)
z = 1.0/(1.0+exp(-z))
if z<0.0000001
  z = 0.0000001
elseif z>0.99999999
  z = 0.99999999
end
return z
end

function LogitLogLikelihood(b,y,x,w)
xb = x*b
L = sum(w .* (y.*xb-log.(1+exp.(xb))))
return L
end

function LogitGradientAndHessian(y,x,b,w)
# gradient
delta = sigmoid.(x*b)
g = x'*(w.*(y.-delta))

# pre-allocate Hessian
k = size(x,2)
H = zeros(eltype(g), (k,k))

# compute Hessian (could also do only upper-right and copy to bottom-left)
for n=1:size(x,1)
tmp = w[n]*delta[n]*(1.0-delta[n])
for kk1=1:k
    for kk2=1:k
          H[kk1,kk2] = H[kk1,kk2]-tmp*x[n,kk1]*x[n,kk2]
      end
    end
end

return g,H
end

The code to benchmark this (of course first do the warm up as per the instructions)

N = Int(1e6);
y = Int.(randn(N,1).>0)
x = [ones(N,1) randn(N,1)]
w = ones(N,1)
w = w./sum(w)

@time logit(y,x,w)

I find that at the moment the Julia code is about as fast as the Matlab code which follows a very similar style. Can this code be (substantially) improved?


texts:
The following code is for this problem.

  Input

  The input consists of a single line with three integers n
  , s
  , and k
   (1 ≤ n ≤ 10,000, 1≤ k ≤ s ≤ 500
  ). n
   is the number of throws, k
   the number of different numbers that are needed to win and s
   is the number of sides the die has.

  Output

  Output one line with the probability that a player throws at least k
   different numbers within n
   throws with an s
  -sided die. Your answer should be within absolute or relative error at most 10−7
  .

  Sample Input 1

  3 3 2

  Sample Output 1

  0.888888889

  Sample Input 2

  3 3 3

  Sample Output 2

  0.222222222

This program used 0.89s to pass all test cases. But I find other people use Java can achieve ~0.20s. How can I improve my code?

The idea is to establish a table for the recursive call to look up previously calculated the value.

import java.util.*;

public class Dice
{
  static double table[][];

  public static double game(int s, int r, int d)
  {
    if(table[r][d] != -1) return table[r][d];
    double a = (1 - (double)d/(double)s) * game(s, r - 1, d + 1);
    double b = ((double)d/(double)s) * game(s, r - 1, d);
    double sum = a + b;
    table[r][d] = sum;
    return sum;
  }

  public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int s = in.nextInt();
    int k = in.nextInt();
    table = new double[n+1][n+1];

    for(int i = 0; i < n+1; i++)
     for(int j = 0; j < n+1; j++)
       table[i][j] = (double)-1;

    for(int i = 0; i < n+1; i++)
     for(int j = 0; j < n+1; j++)
      if(i + j < k)
        table[i][j] = (double)0;

    for(int j = 0; j < n+1; j++)
     for(int i = k; i < n+1; i++)
       table[j][i] = (double)1;

    System.out.println(game(s, n, 0));
   }
 }


texts: A tiny command-line program that prints a sum of numbers

texts:
Here's my first Rust program that I could actually use for something:

use std::io;
use std::process;

fn main() {
    let mut sum = 0;
    loop {
        let mut number_str = String::new();
        match io::stdin().read_line(&mut number_str) {
            Ok(n) => { if n == 0 {break} },
            Err(e) => { println!("ERROR: got '{}' when reading a line", e) }
        }
        match number_str.trim().parse::<i32>() {
            Ok(n) => { sum += n }
            Err(n) => {
                println!("ERROR: Entered something that is not a number: '{}'",
                    number_str.trim_right());
                process::exit(1)
            },
        }
    }
    println!("{}", sum);
}

Did I violate any style rules? Is there anything else I should add/change/improve?


texts:
This ASP.NET MVC website is for my professor to track my progress on my Checkers app.  This is the first time I have build an ASP.NET website entirely on my own, and I would like a review to make sure I am doing everything in the best way possible.

First, my HomeController:

public class HomeController : Controller
{
    private T Deserialize<T>(string filePath)
    {
        var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        var data = System.IO.File.ReadAllText(filePath);
        return jss.Deserialize<T>(data);
    }

    public ActionResult Index()
    {
        var announcements = Deserialize<ListOfItems<Announcement>>(Server.MapPath("~/App_Data/Announcements.json"));
        var latestAnnouncement = announcements.Items.Last();
        if (DateTime.Now.Date.Subtract(TimeSpan.FromDays(7)) > latestAnnouncement.AnnouncementDate)
        {
            latestAnnouncement = null;
        }

        return View(latestAnnouncement);
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

    public ActionResult Reports()
    {
        var reports = Deserialize<ListOfItems<BiweeklyReport>>(Server.MapPath("~/App_Data/Reports.json"));

        return View(reports.Items);
    }

    public ActionResult Resources()
    {
        var resources = Deserialize<ListOfItems<Resource>>(Server.MapPath("~/App_Data/Resources.json"));

        return View(resources.Items);
    }

    public ActionResult Announcements()
    {
        var announcements = Deserialize<ListOfItems<Announcement>>(Server.MapPath("~/App_Data/Announcements.json"));

        return View(announcements.Items);
    }
}

My models are as follows:

First, a generic class for easy serialization of a list of items:

[Serializable]
public class ListOfItems<T>
{
    public List<T> Items { get; set; }
}

And a set of items to serialize.  To keep this post slim, I will only post one:

[Serializable]
public class Announcement
{
    public string Title { get; set; }
    public DateTime AnnouncementDate { get; set; }
    public string Content { get; set; }
}

My views are all either static information or a simple iteration over a list of data; here is my view for the above model class:

@model List<Announcement>
@using ITM3804Website.Models

@{
    ViewBag.Title = "Announcements";
}

@ViewBag.Title

@{
    var orderedAnnouncements = Model.OrderByDescending(x => x.AnnouncementDate);
    foreach (var announcement in orderedAnnouncements)
    {

             @announcement.Title

             @announcement.AnnouncementDate.ToString("MMMM d, yyyy")

             @announcement.Content

        if (announcement != orderedAnnouncements.Last())
        {

         }
     }
}


texts:
typedef struct Stack {
   char v;
   int x;
   int y;
   struct Stack* next;
  } Stack;

Above is my stack struct.

Stack* helper (char val, int x, int y)
  {
    Stack* node = (Stack*)malloc(sizeof(Stack));
    node->v = val;
    node->x = x;
    node->y = y;
    return node;
  }
  void push (Stack** top,char val,int x,int y)
  {
    Stack* node = helper(val,x,y);
    node->next = *top;
    *top = node;
    printf("%c pushed to stack\n",val);
  }
  void pop (Stack** top,char *val,int *w,int *h)
  {
    if (checkempty(*top))
      return;
    Stack* temp = *top;
    *top = (*top)->next;
    *val = temp->v;
    *w = temp->x;
    *h = temp->y;
    free(temp);
  }
  int checkempty(Stack* top)
  {
    return !top;
  }

Above are my push and pop functions.
I was wondering if there are better ways to do this ? Or is what I am doing the standard way ?


texts:
I am going on with refactoring my code base while migrating from Python 2 to Python 3. I am using generators to make reusable components this time as I am more comfortable with them this time then last time. But there are times when I am stuck at their use. Like below example. These two are essentially same with one infinitely generating and other with a limit.

Is there a way to make these as one function? Normally an extra optional parameter as limit will do the trick but with generators I am not sure how to use them. Is there some way to do that?

def fibonacci_inf(a, b):
    """Lazily generates Fibonacci numbers Infinitely"""
    while True:
        yield b
        a, b = b, a + b

def fibonacci(a, b, num):
    """Lazily generates Fibonacci numbers"""
    while b < num:
        yield b
        a, b = b, a + b


texts: Bit Array in Ruby using integer as a storage

texts:
Ruby's Fixnum and Bignum can hold very large integers and automatically handle overflow. I decided to implement BitArray using an integer as storage. Please let me know what you think about code and functionality of a BitArray.

class BitArray
  include Enumerable

  def initialize size
    @size = size
    @field = 2**size
  end

  def set positions
    bits = positions.kind_of?(Integer) ? [positions] : positions
    bits.each {  |position| @field |= 1 << (@size - position) }
    self
  end

  def clear positions
    bits = positions.kind_of?(Integer) ? [positions] : positions
    bits.each {  |position| @field ^= 1 << (@size - position) }
    self
  end

  def get position
    (@field >> (@size - position) ).to_s(2)[-1].to_i
  end

  def each(&block)
    @field.to_s(2)[1..-1].split("").each { |bit_string| yield(bit_string.to_i) }
  end

  def to_s
    @field.to_s(2)[1..-1]
  end

  def count
    @field.to_s(2)[1..-1].split("").inject(0) {|sum,bit| sum + bit.to_i}
  end

end

And the Test

require 'minitest/autorun'
require_relative 'bit_array'

class BitArrayTest < MiniTest::Unit::TestCase

  def test_equal
    assert_equal "00000", BitArray.new(5).to_s
  end

  def test_set
    assert_equal "00100", BitArray.new(5).set(3).to_s
    assert_equal "00010", BitArray.new(5).set(4).to_s
    assert_equal "11100", BitArray.new(5).set([1,2,3]).to_s
    assert_equal "100000000101", BitArray.new(12).set([1,10,12]).to_s
  end

  def test_clear
    assert_equal "01000", BitArray.new(5).set([1,2]).clear(1).to_s
  end

  def test_get
    assert_equal 0, BitArray.new(5).set([1,2]).get(3)
    assert_equal 0, BitArray.new(12).set([12]).get(11)
    assert_equal 0, BitArray.new(12).set([12]).get(1)
  end

  def test_count
    assert_equal 2, BitArray.new(5).set([1,2]).count
  end

  def test_iterate
    assert_equal ["0", "0", "0", "0", "0"],  BitArray.new(5).each {|n| puts n }
  end

end


texts:
I decided it would be fun to implement Conway's Game of Life (CGOL) in Emacs Lisp as my first elisp script.

My goals for the implementation were pretty simple

Transform current buffer into the next generation of CGOL
Just use max height/width of the current buffer (don't worry about overflowing the space, keep it bounded)
Be able to specify which character means "alive", assume all others are dead

To implement this, I came up with the following

(defun conway-current-buffer (alive-char)
  (interactive "cAlive-charater: ")

  (defun key (x y)
    (concat (number-to-string x) "-" (number-to-string y)))

  (defun pair-to-key (p)
    (concat (number-to-string (car p)) "-" (number-to-string (cadr p))))

  (defun neighbors (x y)
    (list
     (list (+ x 1) (+ y 1))
     (list (+ x 1) (- y 1))
     (list (- x 1) (- y 1))
     (list (- x 1) (+ y 1))

     (list (+ x 1) y)
     (list (- x 1) y)
     (list x       (- y 1))
     (list x       (+ y 1))))

  (defun alive-neighbor-count (x y state)
    (progn
      (setq alive-neighbors 0)
      (dolist (neighbor (neighbors x y))
        (if (gethash (pair-to-key neighbor) state)
            (setq alive-neighbors (+ 1 alive-neighbors))))
      alive-neighbors))

  (defun lives-on (x y state)
    (let ((alive-ns (alive-neighbor-count x y state))
          (alive (gethash (key x y) state nil)))
      (or (eq alive-ns 3) (and alive (eq alive-ns 2)))))

  (defun clear-buffer ()
    (kill-region (point-min) (point-max)))

  (defun render (height width state)
    (progn
      (clear-buffer)
      (setq y 0)
      (while (< y height)
        (progn
          (setq x 1)
          (while (<= x width)
            (if (gethash (key x y) state)
                (insert (char-to-string alive-char))
              (insert " "))
            (setq x (+ 1 x)))
          (setq y (+ 1 y))
          (if (< y height) (insert "\n"))))))

  (defun next-state (height width state)
    (progn
      (setq next (make-hash-table :test #'equal))
      (setq y 0)
      (while (< y height)
        (progn
          (setq x 0)
          (while (< x width)
            (if (lives-on x y state) (puthash (key x y) t next))
            (setq x (+ 1 x)))
          (setq y (+ 1 y))))
      next))

  (let ((text (buffer-string))
        (state (make-hash-table :test #'equal)))
    (progn
      (setq lines (split-string text "\n"))
      (setq width 0)
      (setq height (length lines))
      (setq y 0)
      (dolist (line lines)
        (progn
          (setq width (max width (length line)))
          (setq x 0)
          (dolist (c (split-string line ""))
            (progn
              (if (eq alive-char (string-to-char c)) (puthash (key x y) t state))
              (setq x (+ 1 x))))
          (setq y (+ 1 y)))
        )
      (render height width (next-state height width state)))))

What I'm Looking For in a Review

Please point out any beginner mistakes
Am I scoping correctly (esp. with setqs and nested defuns)?
Non-idiomatic code, easier functions to use
Performance concerns - though I didn't necessarily strive for optimized, any tips are appreciated
General suggestions

"Bonus Points"

I know CR SE's not a Q&A site as much, so feel free to skip these, but

Is this "good enough" to distribute as a package (i.e. is interactive all it takes?)
Given I'm using spacemacs, where would I included this to be able to use it?
How would one define a hash :test that uses (x . y) pairs instead of strings (e.g. "x-y")?


texts: Finding a path from one wikipedia page to another using semantic similarity of links (Spacy)

texts:
I've just picked coding back up for the first time in a long time, so I understand if your eyes bleed looking at this code. It all works, but I'd be grateful for any tips (how to improve the python code, how to use Spacy's semantic similarity vector feature better, how to make it work faster, etc).
The main product of the code is the list_of_matches list, which shows how I got from one page to another. Clearly this example goes from "frog" to "crystal", but theoretically those could be anything.
import spacy
import wikipedia
import en_core_web_lg
nlp = en_core_web_lg.load()

word_1 = 'frog'
word_2 = 'crystal'
count = 0
closest_match = word_1
list_of_matches = []

link_list_1 = [nlp(word) for word in(wikipedia.page("Frog", auto_suggest=False).links)]

for item in link_list_1:
    print(item)

while float(item.similarity(nlp(word_2))) != 1.0 and count != 20:
    if closest_match.lower() == word_2:
        list_of_matches.append(word_2)
        break

    list_of_matches.append(closest_match)
    try:
        link_list = [nlp(word) for word in wikipedia.page(closest_match, auto_suggest=False).links]
    except wikipedia.exceptions.DisambiguationError:
        pass
    count += 1
    highest_match = 0
    for item in link_list:
        if(item.vector_norm):
            if float(item.similarity(nlp(word_2))) != 0.0:
                similarity = (item.text, word_2, item.similarity(nlp(word_2)))
                #print(similarity)
                link, word_2, vector = similarity
                if vector > highest_match and link not in list_of_matches:
                    highest_match = vector
                    closest_match = link
                    print(closest_match, highest_match)

print(list_of_matches)


texts: Generating .xml files based on .csv files

texts:
This reads in data from a .csv file and generates an .xml file with respect to the .csv data. Can you spot any parts where re-factoring can make this code more efficient?

import csv
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.etree.ElementTree import ElementTree
import xml.etree.ElementTree as etree

def main():
    reader = read_csv()
    generate_xml(reader)

def read_csv():
    with open ('1250_12.csv', 'r') as data:
        return list(csv.reader(data))

def generate_xml(reader):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')
    current_group = None
    i = 0
    for row in reader:
        if i > 0:
            x1,y1,z1,x2,y2,z2,cost = row
            if current_group is None or i != current_group.text:
                current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
                toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
                cost = SubElement(current_group, 'cost',{'':cost})
        i+=1

    def indent(elem, level=0):
        i = "\n" + level*"  "
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "  "
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                indent(elem, level+1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i
    indent(root)
    tree.write(open('holes1.xml','w'))


texts: Collecting company data from accident reports

texts:
name = company_location
for i, j in enumerate (list):
    if j == 'Last 10 Accidents':
        last = i
        try:
            date1 = list[last+28]
            employee1 = list[last+31]
            days_lost1 = list[last+49]
            days_paid1 = list[last+43]
            with open("report.csv","a+") as report:
                report.write(str(name)+", "+str(date1)+", "+str(employee1)+", "+str(days_lost1)+", "+str(days_paid1))
            report.close()
        except (ValueError, TypeError, IndexError):
            with open("report.csv","a+") as report:
                report.write(str(name)+"\n")
            report.close()

        try:
            date2 = list[last+50]
            employee2 = list[last+53]
            days_lost2 = list[last+71]
            days_paid2 = list[last+65]
            with open("report.csv","a+") as report:
                report.write(", "+str(date2)+", "+str(employee2)+",     "+str(days_lost2)+", "+str(days_paid2))
            report.close()
        except (ValueError, TypeError, IndexError):
            with open("report.csv","a+") as report:
                report.write("\n")
            report.close()

        try:
            date3 = list[last+72]
            employee3 = list[last+75]
            days_lost3 = list[last+93]
            days_paid3 = list[last+87]
            with open("report.csv","a+") as report:
                report.write(", "+str(date3)+", "+str(employee3)+", "+str(days_lost3)+", "+str(days_paid3))
            report.close()
        except (ValueError, TypeError, IndexError):
            with open("report.csv","a+") as report:
                report.write("\n")
            report.close()


texts: Javascript assignment as expression in fat-arrow one-liner

texts:
I have a promise where I'm taking the eventual result from the callback and storing it in a value that's scoped outside of the current block in a before hook, all in one line, like this.

describe('mongo stuff', () => {
  let project;

  before(() => {
    return mongo.findFirst('projects').then(data => project = data);
  });

  it('should have the correct company name', () => {
      expect(project.projectName).to.equal('Company1');
  });

});

Note: Mocha, the test runner I'm using, understands promises. That means, placing a return statement before a promise in a before hook, or in an it test, will halt the execution of the next task in the mocha test runner until the promise has been resolved. In other words, data => project = data will always completely execute before any tests that evaluate the contents of project are run.

I use data as a temp variable just so I can assign it to the higher-scoped project variable. This lets me use it in some later test like in the example above.

I was told in a code review that using an assignment as an expression isn't as clear as writing it out.

return mongo.findFirst('projects').then(data => {
    project = data;
});

Which do you think is better? Do you have any solid justification for avoiding the one-liner?


texts:
In my project I am using 10-15 SQL queries, for that I have a common class for database connectivity and using that I have executed the queries by passing the connection, command and dataReader.

With some reference in SO, I learned that my code is not properly structured.  I would like to learn and write high performance code.

DBConnectivity.cs:

class DBConnectivity
    {
        public SqlConnection connection = null;
        public SqlCommand command = null;
        public SqlDataReader dataReader = null;
        public string connectionString = null;
        public List<MasterTableAttributes> masterTableList;
        public DBConnectivity()
        {
            connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
            connection = new SqlConnection(connectionString.ToString());

            //-----Master table results
            connection.Open();
            string masterSelectQuery = "SELECT * FROM MASTER_TABLE";
            command = new SqlCommand(masterSelectQuery, connection);
            dataReader = command.ExecuteReader();
            masterTableList = new List<MasterTableAttributes>();

            while (dataReader.Read())
            {
                MasterTableAttributes masterTableAttribute = new MasterTableAttributes()
                {
                    fileId = Convert.ToInt32(dataReader["Id"]),
                    fileName = Convert.ToString(dataReader["FileName"]),
                    frequency = Convert.ToString(dataReader["Frequency"]),
                    scheduledTime = Convert.ToString(dataReader["Scheduled_Time"])
                };
                masterTableList.Add(masterTableAttribute);
            }
            dataReader.Close();
            connection.Close();
        }
    }

Program.cs:

class Program
    {
        static void Main(string[] args)
            {
                DBConnectivity dbConnectivity = new DBConnectivity();
                Transaction txnObj = new Transaction(dbConnectivity); //Query1
                Sales saleObj = new Sales (dbConnectivity);//Query2
           }
    }

Transaction.cs:

class Transaction
    {
        public Transaction(DBConnectivity dbConnectivity)
        {
            dbConnectivity.connection.Open();
            string txnQuery = "SELECT ...";

            dbConnectivity.command = new SqlCommand(txnQuery, dbConnectivity.connection);

            dbConnectivity.dataReader = dbConnectivity.command.ExecuteReader();

            while (dbConnectivity.dataReader.Read())
            {
                ...
            }
            dbConnectivity.dataReder.close();
            dbConnectivity.connection.Close();
        }
    }

Sales.cs:

class Sales
    {
        public Sales(DBConnectivity dbConnectivity)
        {
            dbConnectivity.connection.Open();
            string salesQuery = "SELECT ...";

            dbConnectivity.command = new SqlCommand(salesQuery, dbConnectivity.connection);

            dbConnectivity.dataReader = dbConnectivity.command.ExecuteReader();

            while (dbConnectivity.dataReader.Read())
            {
                ...
            }
            dbConnectivity.dataReder.close();
            dbConnectivity.connection.Close();
        }
    }


texts: How can I make this code safer against XSS attacks?

texts:
I'm not sure what I'm doing wrong, but I run the code using a Web Vulnerability software and I get a lot of XSS attacks against the code. Is there something I could do better?

// connect to database
include("dbconnect.php");

$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$category = $_POST['category'];

$add = $db->prepare("INSERT INTO contacts SET firstName=(?), lastName=(?), email=(?), phone=(?), category=(?)");
$add->bind_param('sssss', $firstName, $lastName, $email, $phone, $category);

$firstName = $db->real_escape_string($firstName);
$lastName = $db->real_escape_string($lastName);
$email = $db->real_escape_string($email);
$phone = $db->real_escape_string($phone);
$category = $db->real_escape_string($category);

$add->execute();
$add->close();
header("Location:http://localhost/address-book/contact.php");
exit;

?>

Everything works great, but I'm wonder if there's a safer way to go about it.

I wrote it as prepared statements and ran each variable through mysqli_real_escape_string hoping to strip most of the nasty things. But, no lucky.

I'm new to PHP, so this is all a bit alien to me.


texts:
This code is for a NodeJS logging module. I created it because I wanted to find a way to log different type of things but not show them all at the same time. I also wanted to format the logs in a custom manner.

Is there anything I could do to improve this code, such as making it shorter? Are there still any bugs?

// original way of adding config
//var config  = require('config');
var config  = {
     debug: true,
     debugArray:['info','warn']//add remove log types to show
     //'info','warn','error','log','system','socketio','sql'
};

var dateFormat = require('dateformat');
var chalk = require('chalk');
var path = require('path');
var Logger = Object.create({});
var define = Object.defineProperty.bind(undefined, Logger);

function doLog(msg, type, search, stack){
  if(config.debug && ( config.debugArray.indexOf(search) > -1)){
      var fdate = dateFormat(new Date(), 'yyyy-mm-dd hh:MM:ss.l');
      var fFilename = stack.getFileName().substr(path.dirname(require.main.filename).length + 1);
      var lineNumber = stack.getLineNumber();
      var preMsg =  fdate + ' ' +  type + ' [' + chalk.yellow(fFilename + ':' + lineNumber) + '] ';
      console.log(preMsg + msg);
  }
}
Logger.log = function (txt){
  doLog(txt,'LOG', 'log', this.stack[1]);
};

Logger.system = function (txt){
  doLog(chalk.gray(txt), chalk.gray('SYSTEM'), 'system', this.stack[1]);
};

Logger.socketio = function (txt){
  doLog(chalk.cyan(txt), chalk.cyan('SOCKET'), 'socketio', this.stack[1]);
};

Logger.sql = function (txt){
  doLog(txt, chalk.cyan('SQL'), 'sql', this.stack[1]);
};

Logger.info = function (txt){
  doLog(chalk.cyan(txt), chalk.cyan('INFO'), 'info', this.stack[1]);
};

Logger.warn = function (txt){
  doLog(chalk.yellow(txt), chalk.yellow('WARN'), 'warn', this.stack[1]);
};

Logger.error = function (txt){
  doLog(chalk.red(txt), chalk.red('ERROR'), 'error', this.stack[1]);
};

define('stack', {
  get: function(){
    var originalStack = Error.prepareStackTrace;
    Error.prepareStackTrace = function(_, stack){ return stack; };
    var err = new Error();
    Error.captureStackTrace(err, arguments.callee);
    var stack = err.stack;
    Error.prepareStackTrace = originalStack;
    return stack;
  }
});

module.exports = Logger;


texts:
The following is my wordsearch solving algorithm. I'd greatly appreciate tips on how to improve it (e.g. improve efficiency, better approach, etc.):

public boolean traverse(Grid grid) {
    for (int r = 0; r < grid.getRows(); r++) {
        for (int c = 0; c < grid.getCols(); c++) {
            for (Direction direction : Direction.values()) {
                currentPoint.y = r;
                currentPoint.x = c;
                this.direction = direction;

                if (find(grid, currentPoint, 0)) {
                    for (Point point : consideredPoints) {
                        grid.markLetterAt(point);
                    }

                   return true;
                }
            }
        }
    }

    return false;
}

Direction is an enum with all the cardinal directions (N, NE, S, NW, etc...). It has a method (updatePoint()) which changes a Point to the direction (e.g. NE does point.y -= 1, point.x += 1)

Here is find:

private boolean find(Grid grid, Point point, int count) {
    if (!grid.isValidLetter(point)) { // Checks if the point is valid (e.g not < 0)
        consideredPoints.clear();
        return false;
    }

    if (grid.getLetterAt(point).equals(word.substring(count, count + 1))) {
        consideredPoints.add(new Point(point));

        if (count == word.length() - 1) {
            return true;
        }

        direction.updatePoint(point);
        return find(grid, point, count + 1);
    }

    consideredPoints.clear();
    return false;
}


texts: Stack implementation using linked list in C++

texts:
I'd like some feedback for the code I wrote. I haven't programmed in C++ for two years.

#include <string>

#pragma once
template <class T>
class StackLinkedList
{
public:
    StackLinkedList() : m_List(nullptr), m_Size(0) {}
    ~StackLinkedList();
    void push(const T& val);
    void pop();
    T& top();
    const T& top() const;
    size_t size() const;
    bool empty() const;
private:
    struct Node;
    Node *m_List;
    size_t m_Size;
};

template <class T>
struct StackLinkedList<T>::Node
{
    T m_Val;
    Node* m_Next;
    Node(const T& val, Node* nextPtr) : m_Val(val), m_Next(nextPtr) {}
};

template<class T>
StackLinkedList<T>::~StackLinkedList()
{
    typename Node* nextNodePtr;
    for (typename Node* curNodePtr = m_List; curNodePtr != nullptr; )
    {
        nextNodePtr = curNodePtr->m_Next;
        delete curNodePtr;
        curNodePtr = nextNodePtr;
    }
}

template<class T>
void StackLinkedList<T>::push(const T& val)
{
    typename Node* newNode = new Node(val, m_List);
    m_List = newNode;
    m_Size++;
}

template<class T>
void StackLinkedList<T>::pop()
{
    if (m_List != nullptr)
    {
        typename Node* curNodePtr = m_List;
        m_List = m_List->m_Next;
        delete curNodePtr;
        m_Size--;
    }
}

template<class T>
T& StackLinkedList<T>::top()
{
    if (empty())
    {
        throw new std::string("Stack is empty");
    }
    return m_List->m_Val;
}

template<class T>
const T& StackLinkedList<T>::top() const
{
    if (empty())
    {
        throw new std::string("Stack is empty")
    }
    return m_List->m_Val;
}

template<class T>
size_t StackLinkedList<T>::size() const
{
    return m_Size;
}

template<class T>
bool StackLinkedList<T>::empty() const
{
    return m_Size == 0;
}


texts: Check if n-th root of product of numbers is a whole number C++

texts:
I've got an assignment which sounds like this:

  Given a number \$m\$ and \$n\$ other numbers, say if the \$m\$-th root of the product of those numbers is a whole number (print 1) or not (print 0). If yes, also print, in sorted order, the result of the \$m\$-th root, decomposed in prime factors.

This is how the expression would look:

$$\sqrt[m]{x_1 x_2 x_3 \dots x_n}$$

My idea was this: for the result to be a whole number, if we were to decompose all of the numbers, then make the product of all of them, every power of every base has to be divisible with \$m\$.

This is what I came up with:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

using Prime_factorization = vector < pair<int, int> >;

void add_base_and_power(Prime_factorization& prime_factorization, int    base, int power)
{
    // Check if we've already got the base we're trying to add
    auto it = find_if(prime_factorization.begin(), prime_factorization.end(), [&](pair <int, int> p) { return p.first == base; } );

    if (it != prime_factorization.end()) // If yes, add the power to the existing base
        it->second += power;
    else
        prime_factorization.push_back(make_pair(base, power)); // Else, create a new base
}

void check_if_is_factor(Prime_factorization& prime_factorization, int &number, int divisor)
{
    if (number % divisor == 0) { // If the divisor is a base, we divide until it no longer can

        int power { 0 };
        while (number % divisor == 0) {
            number /= divisor;
            ++power;
        }

        // Add base and power to factorization
        add_base_and_power(prime_factorization, divisor, power);
    }
}

void decompose(Prime_factorization& prime_factorization, int number)
{
    check_if_is_factor(prime_factorization, number, 2); // Check if it divides by 2 so after that we can only check for uneven bases

    for (int div { 3 }; div * div <= number && number > 1; div += 2)
        check_if_is_factor(prime_factorization, number, div);

    // If number is bigger than 1 it means we got out of the previous for loop with the first condition, so the number must be prime
    if (number > 1)
        add_base_and_power(prime_factorization, number, 1);
}

int main() {

    // Get m-th root
    int m;
    cin >> m;

    // Get number of terms
    int n;
    cin >> n;

    // Take n numbers and decompose each of them
    Prime_factorization prime_factorization;
    for (int i { 1 }; i <= n; ++i) {

        int x;
        cin >> x;

        decompose(prime_factorization, x);
    }

    // After decomposing all of the numbers, we check to see if each power can be divided by m(the root)
    bool okay { true };
    for (auto& i : prime_factorization)
        if (i.second % m != 0) {
            okay = false;
            break;
        }

    // We must print the base-power combinations in sorted order
    sort(prime_factorization.begin(), prime_factorization.end(), [](pair<int, int> p1, pair<int, int> p2) { return p1.first < p2.first; });

    if (okay) {
        cout << 1 << '\n';

        for (auto& i : prime_factorization)
            cout << i.first << ' ' << (i.second / m) << '\n';
    } else
        cout << 0;
}

How could I improve my code? Is there any better algorithm you might've thought of?


texts:
I would like my program to be reviewed. I had to write a simple program that calculates the number of molecules in a hydrocarbon.

1 carbon atom has 12 AMU.
1 hydrogen atom has 1 AMU.

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter mass of hydrocarbon (in grams)\n"
            "followed by the number of carbon atoms\n"
            "followed by the number of hydrogen atoms\n"
            "(e.g. 10.5 2 6): " << flush;

    float mass;
    float carbonAtoms;
    int hydrogenAtoms;
    cin >> mass >> carbonAtoms >> hydrogenAtoms;

    long formulaWght = (carbonAtoms * 12) + (hydrogenAtoms * 1);

    double molecules = (mass / formulaWght) * 6.02e23;

    cout << mass << " grams of hydrocarbon\nwith "
            << carbonAtoms << " carbon atom(s) and "
               << hydrogenAtoms << " hydrogen atom(s)\ncontains "
                  << molecules << " molecules" << endl;

    return 0;
}


texts:
I am new to C++ and would like to know the most efficient way of forcing a user to enter an integer. Here is my function that I have created. Please show me the best way and explain why it's better than this.

int getInt(){
    int x;
    while (true){
        cout << "Enter an int." << endl;
        cin.clear();
        while(cin.get() != '\n');
        cin >> x;
        if (!cin.fail()){
            return x;
        }
    }
}


texts: Given N*N matrix, rotate it by 90 degree to left and right without extra memory

texts:
I'm looking for a code review, clever optimizations, and good coding practices. Unit testing has been a visual inspection and concluded expectations match. Also, is the space complexity of the extra variable used to swap \$O(1)\$? Typically, is \$O(1)\$ an acceptable space to use when code requires no extra memory?

public final class RotateNinetyInPlace {

    private RotateNinetyInPlace() {}

    private static void transpose(int[][] m) {

        for (int i = 0; i < m.length; i++) {
            for (int j = i; j < m[0].length; j++) {
                int x = m[i][j];
                m[i][j] = m[j][i];
                m[j][i] = x;
            }
        }
    }

    public static void rotateByNinetyToLeft(int[][] m) {
        // transpose
        transpose(m);

        //  swap rows
        for (int  i = 0; i < m.length/2; i++) {
            for (int j = 0; j < m[0].length; j++) {
                int x = m[i][j];
                m[i][j] = m[m.length -1 -i][j];
                m[m.length -1 -i][j] = x;
            }
        }
    }

    public static void rotateByNinetyToRight(int[][] m) {
        // transpose
        transpose(m);

        // swap columns
        for (int  j = 0; j < m[0].length/2; j++) {
            for (int i = 0; i < m.length; i++) {
                int x = m[i][j];
                m[i][j] = m[i][m[0].length -1 -j];
                m[i][m[0].length -1 -j] = x;
            }
        }
    }

    public static void main(String[] args) {
        int[][] mEven = {{1, 3},
                        {2, 4}};

        rotateByNinetyToLeft(mEven);

        for (int i = 0; i < mEven.length; i++) {
            for (int j = 0; j < mEven[0].length; j++) {
                System.out.print(mEven[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("---------------------------------");

        rotateByNinetyToRight(mEven);

        for (int i = 0; i < mEven.length; i++) {
            for (int j = 0; j < mEven[0].length; j++) {
                System.out.print(mEven[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("---------------------------------");

        int[][] mOdd = {{1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9}};

        rotateByNinetyToLeft(mOdd);

        for (int i = 0; i < mOdd.length; i++) {
            for (int j = 0; j < mOdd[0].length; j++) {
                System.out.print(mOdd[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("---------------------------------");

        rotateByNinetyToRight(mOdd);

        for (int i = 0; i < mOdd.length; i++) {
            for (int j = 0; j < mOdd[0].length; j++) {
                System.out.print(mOdd[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("---------------------------------");

    }
}


texts:
I have it set up so I place my mouse in the center of where I want the spiral to be, then I press enter to start the program, then define the radius initially and how much it grows each time it goes around.

I use \$\sin(\theta)\$ = opposite / hypotenuse and \$\cos(\theta)\$ = adjacent / hypotenuse to find how much my coordinates change based on the degree and the radius of my circle that itself is gradually increasing to create a spiral. There is also some printing at the end that I had just to help with debugging. As simple as I think something is going to be there are always problems.

Converting to int is because NumPy data can't be operated on.

from numpy import sin, cos, pi
import pyautogui as cc
import time
# (x-h)^2 + (y-k)^2 = r^2
# knowling radius and degree, r*sin(deg*pi/180) = rise || cos = run

input('Enter to Begin\n-->')
radius = int(input('What do you want your beginning radius to be?\n-->'))
rate = int(input('How much do you want it to increase by each cycle?\n-->'))
h, k = cc.position()
degree = 0
x = h+radius*(int(cos(degree*pi/180)*10**5)/10**5)
y = k+radius*(int(sin(degree*pi/180)*10**5)/10**5)
cc.moveTo(x, y)
cc.mouseDown()
while True:
    degree += 1
    radius += rate / 360
    x = h+radius*(int(cos(degree*pi/180)*10**5)/10**5)
    y = k+radius*(int(sin(degree*pi/180)*10**5)/10**5)
    cc.moveTo(x, y)
    print('Cords: '+str(x)+'||'+str(y))
    print('radius: '+str(radius))
    print('degree: '+str(degree))
    print()

All feedback is appreciated, but I'm really wondering how I could make this faster in Python.


texts: New features for Processing game/desk accessory

texts:
I have written a simple desk accessory in Proccessing called Trip, you can see it below. It is working, but it is very simple, and needs more features.

import processing.pdf.*;

PImage tardis;
int flash = 0;

void setup() {
  size(256, 256);
  frame.setResizable(true);
  tardis = loadImage("TARDIS1.jpg");
  beginRecord(PDF, "trip.pdf");
  background(random(100), random(100), random(100));
  randomSeed(299792458);
}
void draw() {
  stroke(random(100), random(100), random(100));
  line(random(width), random(height), mouseX, mouseY);
  if (flash == 1) {
    background(random(100), random(100), random(100));
  }
}
void keyPressed() {
  if (key == 's') {
    endRecord();
    exit();
  }
  else if (key == 'q') {
    exit();
  }
  else if (key == 'b') {
    background(random(100), random(100), random(100));
  }
  else if (key == 't') {
    image(tardis ,0 ,0, width, height);
  }
  else if (key == 'f') {
    if (flash == 0) {
      flash = 1;
    }
    else if (flash == 1) {
      flash = 0;
    }
  }
}

I would appreciate any new ideas for features, particularly Easter egg-style secret features.


texts: Printing a number from memory in assembly

texts:
I'm trying to work up to being able to print the hailstone sequence in assembly. To do that though, I first needed to learn how to actually print a number out using the write system call.
After a few design iterations, I ended up using division to get each digit one at a time by using the remainder. Each remainder gets pushed onto the stack, then the address of the stack is given to the system call to print out.
What I'd like advice on:

In a couple places, I have math split out over multiple lines, like:
 sub edx, esp  ; Calculate how many were pushed
 dec edx

It doesn't seem like it's possible to combine that into something like sub edx, esp - 0, but if there is a neater way, I'd like to know.

This is my first time using div. Is there anything wrong with how I'm using it? Also, is there a sane way of not using div altogether? Apparently it's stupid slow and should be avoided if possible.

Anything else notable. I'm a super-beginner, and this code is quite verbose.

I'm using n to represent the number that I want to print out. In theory though, that number could come from anywhere. It's just a placeholder for the exercise.
global _start

section .data
    n: dd 123456

section .text
    _start:
        mov ebp, esp  ; So we can tell how many were pushed

        mov ecx, [n]

        .loop:
            mov edx, 0  ; Zeroing out edx for div
            mov eax, ecx  ; Num to be divided
            mov ebx, 10  ; Divide by 10
            div ebx
            mov ecx, eax  ; Quotient

            add edx, '0'
            push edx  ; Remainder

            cmp ecx, 0
            jne .loop

        mov eax, 4  ; Write system call
        mov ebx, 1  ; STDOUT
        mov ecx, esp  ; The string on the stack
        mov edx, ebp
        sub edx, esp  ; Calculate how many were pushed
        dec edx
        int 0x80

        mov eax, 1
        mov ebx, 0
        int 0x80

Assembled and linked using:
nasm numprint2.asm -g -f elf32 -Wall -o numprint2.o
ld numprint2.o -m elf_i386 -o numprint2


texts: Refactoring a loop with many boolean conditions

texts:
I usually spent more time on refactoring than in developing itself. But this little piece of code is really hard to refactor. I'd like to keep it as short as possible, but it's quite undarstandable:

foreach($all_headers as $uid => $h) // Intera gli headers
{

    // Is the header valid?
    $isInbox   = $h->to == $mailbox->address;
    $hasPin    = ($pin = substr($h->subject, 0, 5)) !== false && is_numeric($pin);
    $hasTitle  = strlen($title = trim(substr($h->subject, 5))) > 0;
    $isAllowed = $hasPin && call_user_func($pincall, $mailbox->address, $h->from, $pin);

    $log->info("messaggio $uid: in:$isInbox pin:$hasPin alw:$isAllowed");

    // Skip this header if not vlaid
    if (!$isInbox || !$hasPin || !$isAllowed) continue;

    // Add some properties to current header
    $h->title = $hasTitle ? $title : null;
    $h->pin   = $pin;
    $valid_headers[$uid] = $h;

}

Since i'm filtering $all_headers array, one cool idea would be using array_filter with some kind of mechanism to add/remove conditions "on the fly".

Thank you people, as always.


texts:
I wrote a simulator that simulates chess games. The game uses probability to determine the player that is most likely to win. though they might be upsets(a low rated player winning the game). I would love insights and suggestions on how to improve on the algorithm, general review is also welcomed.
NOTE: The names and rating were gotten from chess.com application and the code were written in jupyter-notebook
"""Chess Game simulator"""

import random
import time

NAMES = ['Jimmy', 'Samie', 'Elani', 'Aron', 'Emir', 'Sven', 'Nelson',
         'Antonio', 'Isabel', 'Wally', 'Li', 'Noam', 'Francis', 'Danya',
         'Danny', 'Engine']

RATINGS = [600, 900, 400, 700, 1000, 1100,
           1300, 1500, 1600, 1800, 2000,
           2200, 2300, 2650, 2500, 1000]

class Player:
    """This class holds the player information"""

    def __init__(self, name, rating):
        self.name = name
        self.rating = rating
        self.opponent = None

    def __repr__(self):
        return 'Player({}, {})'.format(self.name, self.rating)

class ChessGame():

    def __init__(self, players):
        self.players = players
        self.tournament_rounds = {1: 'Round 1', 2: 'Round 2', 3: 'Semi-final', 4: 'Final'}
        self.game_round = 0

    def next_round(self):
        """Go the next round of the tournament"""

        self.game_round += 1

        try:
            print(self.tournament_rounds[self.game_round])
        except KeyError:
            return

    def make_pair(self):
        """Combine two players randomly to play a chess game"""

        players = self.players[:]
        new_players = []

        while players:
            player1 = random.choice(players)
            players.remove(player1)
            player2 = random.choice(players)
            players.remove(player2)

            player1.opponent = player2
            player2.opponent = player1
            new_players.append(player1)

        self.players = new_players

    def game(self):
        """run the simulation"""

        if len(self.players) < 2:
            print('Exception: Not enough players to play a game')
            return

        self.next_round()
        print('--------------------------------------------')
        self.make_pair()
        for player in self.players:
            print(f'{player.name}({player.rating}) vs {player.opponent.name}({player.opponent.rating})')
        time.sleep(3)
        print('--------------------------------------------')
        self.players = self.score_game()

    def score_game(self):
        """Score the game using probabilities"""

        winners = []
        for player in self.players:
            total_rating = player.rating + player.opponent.rating
            player_chance = player.rating / total_rating

            maximum_range = 1000
            player_range = [i for i in range(0, int(player_chance * maximum_range))]
            choice = random.randint(0, maximum_range)
            if choice in player_range:
                print(f'{player.name} wins this round by checkmate')
                player.rating += self.game_round * 200
                winners.append(player)
            else:
                print(f'{player.opponent.name} wins this round by checkmate')
                player.opponent.rating += self.game_round * 200
                winners.append(player.opponent)

        return winners

CHESS_PLAYERS = [Player(name, rating) for name, rating in zip(NAMES, RATINGS)]

CHESS_SIM = ChessGame(CHESS_PLAYERS)
CHESS_SIM.game()
print()
CHESS_SIM.game()
print()
CHESS_SIM.game()
print()
CHESS_SIM.game()


texts: To-do app, as one monster function and as several smaller functions

texts:
I am learning to code by making a todo app in pure javascript. My first attempt can be seen here.

It's all cosmetic, meaning it stores no information, generates no objects or arrays, though it was sure fun to learn how to manipulate DOM elements in pure JavaScript and building my first "program"!

I am rebuilding it in a more OOP manner. In this first jsfiddle:

when(toDo, "keypress", function(event){
  if (event.key == "Enter" || event.keyCode == 13) {
    pushArray();
    toDo.value = "";
  }
});

function pushArray(){
  var nt = new Task(toDo.value, "No note yet");
  fruits.push(nt);
  var task = document.createElement("div");
  task.setAttribute("class", "taskitem");
  task.innerHTML = nt.Name;
  var t = document.createElement("input");
  t.setAttribute("class", "tasknote");
  task.appendChild(t);
  when(t, "keypress", function(event){
  if (event.key == "Enter" || event.keyCode == 13) {
    nt.Note = t.value;
    this.parentNode.innerHTML = nt.Name + " " + nt.Note;
    t.value = "";
  }
});

  result.appendChild(task);
  console.log(fruits);
}

Hitting enter fires a function that does everything. creates a new task object, pushes it to the array, displays the task and appends a note that can be updated anytime, for example -  task:get milk note:almond milk. However I eventually want to rebuild this app again using local storage, and again with ajax and JSON. I'm thinking I'm going to have a hard time injecting that functionality into this single function without breaking it. So I did it again and broke the steps down into several smaller functions that 'plug' into each other:  https://jsfiddle.net/8wm0r345/

  function Task(name, note) {
  this.Note = note;
  this.Name = name;
  this.completed = false;
}

function pushArray() {
  var nt = new Task(toDo.value, "No note yet");
  taskArray.push(nt);
  displayArray(result, nt.Name);
  appendNote(result, nt);
}

function displayArray(x, obj) {
  var task = make("div", "class", "taskitem", obj);
  x.appendChild(task);
}

function appendNote(el, obj) {
  var t = make("input", "class", "tasknote");
  el.appendChild(t);
  when(t, "keypress", submitNote.bind(null, obj, t));
}

function submitNote(newTask, theInput) {
  if (event.key == "Enter" || event.keyCode == 13) {
    newTask.Note = theInput.value;
    var n = make("div", "class", "hasNote", newTask.Note);
    var t = theInput;
    t.parentNode.insertBefore(n, t.nextSibling);
    t.parentNode.removeChild(t);
    when(n, "dblclick", function() {
      n.parentNode.insertBefore(t, n.nextSibling);
      n.parentNode.removeChild(n);
    });
  }
}

My question is: What is the recommended approach to building a small program like this? And are there any alarming issues in either code presented here?


texts:
As a fairly new C# programmer I am a unsure about when and how to best make use of LINQ (and also when to choose the expression method syntax vs. the query syntax). This question often comes up for me at work, because I heavily lean toward making full use of new language features and a functional style, while my colleagues seem to prefer a more conservative style. This means I have to think a lot about when using LINQ is actually worth it.

Now here is where the review part comes in. This is an anonymized piece of code that this question came up for, once coded in a LINQ style and once in imperative style. Which version do you believe is preferable from a readability / maintainability viewpoint?

void updateItems()
{
    Items.Clear();
    Items.AddRange(Widget.GetDetectedWidgets()
        .Intersect(GetRelevantWidgets())
        .Select(widget => readSerialNr(widget))
        .Where(serial => serial != null)
        .DefaultIfEmpty("No relevant widgets found.")
        .ToArray());
}

void updateItems()
{
    Items.Clear();
    List<string> relevantWidgets = GetRelevantWidgets().ToList();
    foreach(string widget in Widget.GetDetectedWidgets())
    {
        if(relevantWidgets.Contains(widget))
        {
            string serial = readSerialNr(widget);
            if(serial != null)
                Items.Add(serial);
        }
    }
    if(Items.Count == 0)
        Items.Add("No relevant widgets found.");
}


texts:
Is this a good Singleton implementation? Is there anything I should be aware of? If so, how can it be improved?

template <class T>
class Singleton
{
public:
    static T& getInstance()
    {
        static T instance;
        return instance;
    }

protected:
    Singleton() {}
    ~Singleton() {}

private:
    Singleton(Singleton const&);
    void operator=(Singleton const&);
};

Usage example:

#include <stdio.h>

class A : public Singleton<A> {
public:
    A() {
        a = 100;
    }

    int get_a() { return a; }
    void set_a(int v) { a = v;  }
private:
    int a;
};

A& s = A::getInstance();

void free1() {
    printf("%d\n", s.get_a());
}

void free2() {
    s.set_a(200);
}

void free3() {
    printf("--> %d", s.get_a());
}

void main() {
    free1();
    free2();
    free3();
}

Let's consider an alternative to avoid the usage of Singletons, instead having:

class A : public Singleton<A>

let's say it becomes:

class A

and let's say we define a global variable:

A g_s = A();

and then this global variable will be accessed by other files using external, would that bring some sort of benefit?

external A g_s;


texts: Platform for creating data-oriented web apps

texts:
In my web development company, we have many designers who have the following development knowledge:

Client-side web languages (HTML, CSS, JavaScript)
Basic database design (how to create tables, relationships, etc), and
Basic SQL

So we thought about giving them a simple platform to create data-oriented web apps.

What do you think of the following coding style for ASP.NET MVC?
How can we improve it?
Any ideas for a better SQL injection solution than the params array? Remember that the code should look clean and simple.

/apps/pages/index.html

@(DB.Select(table: "pages",
            where: "id = ? and date > ?",
            params: new[] { Request.QueryString["ID"], Request.QueryString["Date"] }))

    @foreach (var row in Model) {

@row.Name

    }

/apps/pages/create.html

@(DB.InsertOnPost(table: "pages",
                  fields: "name, description, date",
                  values: "?, ?, Now",
                  params: new[] { Request.Form["Name"], Request.Form["Description"] }))

@RedirectOnPost("/pages")

<form action="/pages/create" method=”post”>

        Name
        <input type="text" name="name" />

        Description
        <textarea name="description"></textarea>

</form>

/apps/pages/edit.html

@(DB.UpdateOnPost(table: "pages",
                  set: "name = ?, description = ?",
                  where: "id = ?",
                  params: new[] { Request.Form["Name"], Request.Form["Description"],
                                  Request.QueryString["ID"] }))

@RedirectOnPost("/pages")

@(DB.Select(table: "pages",
            where: "id = ?",
            params: new[] { Request.QueryString["ID"] })

<form action="/pages/edit" method="post">

        Name
        <input type="text" name="name" value="@Model.Name" />

        Description
        <textarea name="description">@Model.Description</textarea>

</form>


texts:
I have this userform that looks up into a sheet. The problem is that when there are a lot of rows to look up it takes too long to execute (for example 100 thousand rows). Is it possible to reduce the time?

Here is the userform's textbox code where I put what I am looking for, and the data is shown on a listbox ("LSTART")

Private Sub TXTBUSCAART_Change()
    Dim rowCount As Long, itemCount As Long, counter As Long, n As Long
    Dim dataSheet As Worksheet
    Dim dataIn, dataOut()

    LSTART.Clear
    LSTART.ColumnCount = 9

    Set dataSheet = Sheets("CONCAT")
    With dataSheet

        rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
        itemCount = Application.WorksheetFunction.CountIf(.Range("A2:A" & rowCount), "*" & TXTBUSCAART.Text & "*")

        If itemCount > 0 Then
            ReDim dataOut(1 To itemCount, 1 To 9)
            dataIn = .Range("A2:I" & rowCount).Value
            counter = 1

            For n = 1 To UBound(dataIn)
                M = InStr(1, dataIn(n, 1), UCase(TXTBUSCAART.Text))
                If M > 0 Then
                    dataOut(counter, 1) = dataIn(n, 1)
                    dataOut(counter, 2) = dataIn(n, 3)
                    dataOut(counter, 3) = dataIn(n, 2)
                    dataOut(counter, 4) = dataIn(n, 4)
                    dataOut(counter, 5) = dataIn(n, 6)
                    dataOut(counter, 6) = dataIn(n, 5)
                    dataOut(counter, 7) = dataIn(n, 8)
                    dataOut(counter, 8) = dataIn(n, 9)
                    dataOut(counter, 9) = dataIn(n, 7)
                    counter = counter + 1
                End If
            Next

        LSTART.List = dataOut

        End If
    End With

End Sub


texts: Google Scripts (Add, Remove & Moving Record) stop timeout

texts:
What is it?

The google sheet that the macros are on acts as a sort of "back-end" for the records of a behaviour system at a school. I build multiple google sheets that link to this one that pull the data. Each week the behaviour records are put in this main sheet and then formulas total up the rest. The macros are for when a pupil is added, removed or a new one starts to make sure the data stays in line with the pupil.

The Problem

When it is full of data it take too long to perform the operations and can timeout the google sheet (especially on school computers).
execution log of move pupil code

Solution?

From the research I have done I could try batching code (don't know how to do them in scripts) but would like to know any ways to change/ rework my code to make it way more efficient.
google sheet with scripts as macros

Code

Add Pupil Code

function insertRow() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var row = SpreadsheetApp.getActiveRange().getRow();
for (var i = 0; i < sheets.length; i++) {
    sheets[i].insertRowBefore(row);

  }
}

Remove Pupil Code

function deleteRow() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var row = SpreadsheetApp.getActiveRange().getRow();
for (var i = 0; i < sheets.length; i++) {
    sheets[i].deleteRow(row);
  }
}

Move Pupil Code

function moveRow() {
var ui = SpreadsheetApp.getUi();
var formResponse = ui.prompt('Move Pupil Row', 'Enter the pupils new form', ui.ButtonSet.OK_CANCEL);
var currentResponse = ui.prompt('Move Pupil Row', 'Enter the current row number for this pupil', ui.ButtonSet.OK_CANCEL);
var newResponse = ui.prompt('Move Pupil Row', 'Enter the new row number for this pupil', ui.ButtonSet.OK_CANCEL);

if (newResponse.getSelectedButton() == ui.Button.OK) {
Logger.log('Collected New Form', formResponse.getResponseText());

Logger.log('Collected Current Row', currentResponse.getResponseText());

Logger.log('Collected New Row', newResponse.getResponseText());

var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var row = currentResponse.getResponseText()

var newForm = formResponse.getResponseText()
var pupilData = SpreadsheetApp.getActive().getSheetByName('PupilData');
var formCell = pupilData.getRange("A"+row);
formCell.setValue(newForm);

var newRow = newResponse.getResponseText()
var newRowRange = "A"+newRow+":AP"+newRow

if (row < newRow) {
  var rowRange = "A"+row+":AP"+row
} else {
  row = +row
  row = row + 1
  var rowRange = "A"+row+":AP"+row
}

for (var i = 0; i < sheets.length; i++) {
  sheets[i].insertRowBefore(newRow);
}

for (var i = 0; i < sheets.length; i++) {
  sheets[i].getRange(rowRange).moveTo(sheets[i].getRange(newRowRange));
  sheets[i].deleteRow(row);
}

var halfTerm1 = SpreadsheetApp.getActive().getSheetByName('HT1');
var halfTerm2 = SpreadsheetApp.getActive().getSheetByName('HT2');
var halfTerm3 = SpreadsheetApp.getActive().getSheetByName('HT3');
var halfTerm4 = SpreadsheetApp.getActive().getSheetByName('HT4');
var halfTerm5 = SpreadsheetApp.getActive().getSheetByName('HT5');
var halfTerm6 = SpreadsheetApp.getActive().getSheetByName('HT6');
var year = SpreadsheetApp.getActive().getSheetByName('Year');
halfTerm1.getRange('C5:AP').clearContent();
halfTerm2.getRange('C5:AP').clearContent();
halfTerm3.getRange('C5:AP').clearContent();
halfTerm4.getRange('C5:AP').clearContent();
halfTerm5.getRange('C5:AP').clearContent();
halfTerm6.getRange('C5:AP').clearContent();
year.getRange('C5:AP').clearContent();

} else if (newResponse.getSelectedButton() == ui.Button.CANCEL) {
Logger.log('The user canceled the dialog.');

} else {
    Logger.log('The user closed the dialog.');

}
}


texts: Shortening Oracle SQL containing several unions

texts:
I believe the provided code can be rewritten shorter. Now one block is basically copy-pasted. In reality I have 6 such blocks.
This would be the data:
WITH
x(id, yr, more_info) AS
    (SELECT 1, 2020, 'info1' FROM DUAL UNION
     SELECT 2, 2021, 'info2' FROM DUAL UNION
     SELECT 3, 2021, 'info3' FROM DUAL UNION
     SELECT 4, 2020, 'info4' FROM DUAL )
,
n(n_id, n_id2, n_year) AS
    (SELECT 1, 3, 2021 FROM DUAL UNION
     SELECT 2, 4, 2021 FROM DUAL )

Desired result - complemented table x with up-to-date column yr values and info taken from previous year:

Current code:
WITH
x(id, yr, more_info) AS
    (SELECT 1, 2020, 'info1' FROM DUAL UNION
     SELECT 2, 2021, 'info2' FROM DUAL UNION
     SELECT 3, 2021, 'info3' FROM DUAL UNION
     SELECT 4, 2020, 'info4' FROM DUAL )
,
n(n_id, n_id2, n_year) AS
    (SELECT 1, 3, 2021 FROM DUAL UNION
     SELECT 2, 4, 2021 FROM DUAL )

SELECT * FROM x

-- ========>  BLOCK_1 for column n_id  <=========
UNION
SELECT n_id, n_year, more_info
FROM (SELECT *
      FROM x
      WHERE (id, yr) IN (SELECT id, MAX(yr)
                         FROM x
                         GROUP BY id) ) t1,
     (SELECT n_id, n_year
      FROM n
      WHERE (n_id, n_year) NOT IN (SELECT id, yr
                                   FROM x) ) t2
WHERE t1.id = t2.n_id

-- ========>  BLOCK_2 for column n_id2  <========
UNION
SELECT n_id2, n_year, more_info
FROM (SELECT *
      FROM x
      WHERE (id, yr) IN (SELECT id, MAX(yr)
                         FROM x
                         GROUP BY id) ) t1,
     (SELECT n_id2, n_year
      FROM n
      WHERE (n_id2, n_year) NOT IN (SELECT id, yr
                                   FROM x) ) t2
WHERE t1.id = t2.n_id2


texts: Sorting elements in array with a certain condition

texts:
This is what I have:

function get_create returns a link with new filtered/sorted properties:

Code on screenshot

function get_create ($new_query = array(), $script = null, $ext = true, $amp = true) {
   $pr_url = $GLOBALS['pref_url'].$GLOBALS['host_name'];
   $arr_query = array();

if (!empty($new_query)):

   $new_query = array_filter($new_query, function($element) {
        return !empty($element);}); //delete empty elements

 if ($ext) {
   $cur_url = str_replace("&amp;", "&",$GLOBALS['cur_url'])
   $str_query = parse_url($cur_url, PHP_URL_QUERY); // get string of queries
   parse_str($str_query,$arr_query); // create an array with queries

   $arr_query = array_replace_recursive($arr_query,$new_query)
   $arr_query = get_sort_by_key($arr_query);
 }
 else {
   $arr_query = $new_query; // if $new_query empty
 }

 //make a new link with new parameters
  $fn_query = (!empty($arr_query) ? '?'.http_build_query($arr_query,'',($amp ? '&amp;' : '')) : null);
  $fn_script = (!empty($script) ? $script : $GLOBALS['script_name']);

 return $pr_url.$fn_script.$fn_query; // return the link
else :
 return $GLOBALS['home_url'];
endif;

} // end func

In parameters we have:

$new_query (which contains the new properties for $_get part)
$script (contain a new way to script, where data)
$ext (boolean given parameter which make the logic different)
$amp (if true then formats and again)

function get_sort_by_key helps with sorting array (the keys in array must be in this order: lng-topic-page-sort-search).

Code 2 on screenshot

function get_sort_by_key($array = array()) {
$new_array = array();
 foreach ($array as $key => $value) {
    $key = strtolower(trim($key));
    switch ($key) {
        case $key == 'lng': $order = 0;
            break;
        case $key == 'topic': $order = 1;
            break;
        case $key == 'page': $order = 2;
            break;
        case $key == 'sort': $order = 3;
            break;
        case $key == 'search': $order = 4;
            break;
        default: $order = 5; break;
    }
    $new_array[$order][$key] = $value;
 }

ksort($new_array);
   return $fn_array = call_user_func_array('array_merge',$new_array);
}

I need to create the function which gets an array full of new parameters and adds or replaces the current $_GET by them in a specific order.

An example:

I had the URL like this: http://localhost/test.php. After initialization func: get_create(array('sort' => 1, 'topic' => 2) I get  http://localhost/test.php?topic=2&sort=1, where the order is important (not http://localhost/test.php?sort=1&topic=2).

How can I make the function look better? My code works, at least now. But I know that I'm wrong. Maybe some elegant solution exists in my case.


texts: Creating a non-binary tree by weights of the node and then traversing it

texts:
I wrote this code which adds children to nodes according to the weight of the heading of a non-binary tree. I am a novice programmer, so I would love to know how this code can be improved.

import java.util.LinkedList;

public class Sample {

    public static void main(String... args) {
        Sample buildTree = new Sample();
        LinkedList<Heading> headings = new LinkedList<>();

        headings.add(new Heading(1, "a"));
        headings.add(new Heading(2, "b"));
        headings.add(new Heading(2, "c"));
        headings.add(new Heading(3, "d"));
        headings.add(new Heading(3, "e"));
        headings.add(new Heading(3, "f"));
        headings.add(new Heading(4, "g"));
        headings.add(new Heading(5, "h"));
        headings.add(new Heading(2, "i"));
        headings.add(new Heading(1, "j"));
        headings.add(new Heading(1, "k"));
        headings.add(new Heading(2, "l"));

        Node structuredHeadings = buildTree.outline(headings);
        System.out.print(buildTree.print(structuredHeadings));
    }

    /* @param  input  A linked list which contains headings with weights and its text
    *  @return A non binary  tree which contains headings sorted by their weights
    *
    */

    Node outline(LinkedList<Heading> input) {

        Node mainNode = new Node(new Heading(0, ""));

        Node currentNode = mainNode;
        Node parentNode = null;

        for (Heading head : input) {

            if (head == null) {
                return null;
            }

            if(head.weight < 0){
                throw new IllegalArgumentException("Weight can not be negative");
            }

            if (currentNode.head.weight == head.weight) {
                currentNode = parentNode;
                currentNode.children.add(new Node(head));
                currentNode = currentNode.children.getLast();

            }

            if (currentNode.head.weight < head.weight) {
                parentNode = currentNode;
                currentNode.children.add(new Node(head));
                currentNode = currentNode.children.getLast();

            }

            if (currentNode.head.weight > head.weight) {

                currentNode = mainNode;
                while (true) {
                    int weight = currentNode.children.getLast().head.weight;
                    if (weight == head.weight) {

                        parentNode = currentNode;
                        currentNode.children.add(new Node(head));
                        currentNode = currentNode.children.getLast();
                        break;
                    }
                    currentNode = currentNode.children.getLast();
                }
            }

        }

        return mainNode;

    }

    String print(Node node) {

        String build  = " Node(Heading(" + node.head.weight + ", '" + node.head.text + "')" + ", List( ";
        for (Node child : node.children) {

            build +=   print(child);

        }
        build += ") ";
        return build;

    }

    static class Heading {
        int weight;
        String text;

        Heading(int weight, String text) {
            this.weight = weight;
            this.text = text;
        }

    }

    static class Node {
        Heading head;
        LinkedList<Node> children;

        Node(Heading head) {
            this.head = head;
            children = new LinkedList<>();
        }

    }
}


texts:
I needed a variadic function to pack and unpack bits into integer types. This is my first attempt:

template<typename T>
constexpr T pack(bool b)
{
    return b;
}

template<typename T, typename... Types>
constexpr T pack(bool b, Types... args)
{
    return (b << sizeof...(Types)) | pack<T>(args...);
}

template<typename T, typename... Types>
void unpack(T packed, bool& b1)
{
    b1 = packed & 1;
}

template<typename T, typename... Types>
void unpack(T packed, bool& b1, Types&... args)
{
    b1 = packed & (1 << sizeof...(Types));
    unpack(packed, args...);
}

Usage example:

int main(void)
{
    std::cout << pack<int>(1, 0, 0, 1, 0, 1, 1, 0) << std::endl; // 150
    std::cout << pack<int>(1, 0, 1) << std::endl; // 5
    int val = pack<int>(1, 0, 1);
    bool b1, b2, b3;
    unpack(val, b1, b2, b3);
    std::cout << b1 << " " << b2 << " " << b3 << std::endl; // 1 0 1
}

Does this code contain any bugs, can it be improved, and are variadic templates used appropriately here (I still don't master their syntax)?


texts: Getting all possible letter combinations of a word

texts:
I wrote a simple algorithm for finding all possible letter combinations of a single word. I want to know if my code can be improved in any way, although I'm mostly interested in efficiency.
You can ignore my notes if you wish, they are mostly for myself and the questions in them are not the ones I ask answers for here^^

The code:

#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <unordered_set>

/**
    1. Used std::vector to store words, then sorted it and removed duplicates.
        >4s for 10 letters.
    2. Moved to std::unordered_set. Time improved to >2s.

    Notes:
        I used [i] instead of at(i) for efficiency in some cases (at(i) does bound checking
        (right?), and I do that myself, so it's unnecessary
        (or is the performance hit too small to matter?)).
**/

const char* outFile = "wordCombos.txt";

// Only this function should be used in main()
// Gets all possible letter combinations from a single word, prints them to a file
// Does not modify the original string
void unscramble(std::string str);

int main()
{
    // Opening the file to clear it
    std::ofstream out(outFile, std::ios::trunc);
    out.close();

    // Test values
    unscramble("aaa");
    unscramble("     Amazing \t\t\t\n  \n");
    unscramble("   \t\t\n  \n   \n \t\t");
    // This last one already takes 4 seconds. 10 letters
    // More than 3.5 million words
    unscramble("lakdjflakk");
    // 11 letters - 27 seconds
    //unscramble("lakdjlakkpp");
}

// Remove tabs, newlines, spaces
void trimSpaces(std::string& a)
{
    if(a.find_first_not_of(" \n\t") == std::string::npos){
        a = "";
        return;
    }
    int begin = a.find_first_not_of(" \n\t");
    int length = a.find_last_not_of(" \n\t") - begin + 1;
    a = a.substr(begin, length);
}

// Process a string, add all possible letter combos to word
// Assumes that a valid letters vector is given (size > 0)
// Uses recursion
void getLetterCombos(std::unordered_set<std::string>& words,
                     const std::vector<char>& letters,
                     std::string curWord)
{
    if(letters.size() == 1){
        words.insert(curWord + letters[0]);
        return;
    }

    for(int i = 0; i < letters.size(); ++i){
        std::vector<char> temp = letters;
        std::string tWord = curWord + temp[i];
        temp.erase(temp.begin() + i);
        getLetterCombos(words, temp, tWord);
    }
}

void unscramble(std::string str)
{
    trimSpaces(str);

    if(str == "" || str.find_first_of(" \t\n") != std::string::npos){
        std::cout << "Error: Invalid input: no word or more than a single word given.\n";
        return;
    }

    // All combos should be in uppercase
    std::transform(str.begin(), str.end(), str.begin(), toupper);

    std::unordered_set<std::string> words;
    std::vector<char> letters;
    letters.reserve(str.size());
    for(int i = 0; i < str.size(); ++i){
        letters.push_back(str[i]);
    }
    getLetterCombos(words, letters, "");

    std::ofstream out(outFile, std::ios::app);
    out << "Initial word: " << str << ",\nAll possible letter combinations: \n";
    for(std::unordered_set<std::string>::iterator it = words.begin(); it != words.end(); ++it){
        out << *it << "\n";
    }
    out << "\n";
}


texts: Luhn Algoritm for social security numbers

texts:
I just got some negative feedback on some code I wrote and I was not able to know exactly what was wrong with it (I tried). It is a program that verifies to see if a social security number is valid or not. The program is working fine.So I would really appreciate it if somebody could take a look and tell me if this can be optimized in some way.

Here is the code:

public class Logic
{
    public static bool ValidityChecker(string socialSecurityNumber)
    {
        FileInfo f = new FileInfo("C:\\Log\\log.txt"); //Checks to see if folder path exists. Otherwise creates a C:\Log\ folder.
        if (!f.Directory.Exists)
        {
            Directory.CreateDirectory(f.DirectoryName);
        }

        if (ValidityCheckIsNotNull(socialSecurityNumber) == true && ValidityCheckIsSSN(socialSecurityNumber) == true) //If the string is not null/empty and if the Social Security Number is valid, then return true.
            return true;
        else //If the string is null/empty or the social security number is invalid. Then log the invalid data and return false.
            using (StreamWriter w = new StreamWriter("C:\\Log\\log.txt", true))
            {
                w.WriteLine(DateTime.Now + " Kandidatdata: " + socialSecurityNumber.ToString());
                w.Close();
            }
        return false;
    }

    public static bool ValidityCheckIsNotNull(string socialSecurityNumber) //If string is null or empty return false. Otherwise return true.
    {
        if (string.IsNullOrEmpty(socialSecurityNumber))
            return false;
        else return true;
    }

    public static bool ValidityCheckIsSSN(string socialSecurityNumber) //Uses the algoritm (from the task documentation) to see if a Social Security number is valid or not.
    {
        int totalSSN = socialSecurityNumber.Where((e) => e >= '0' && e <= '9').Reverse().Select((e, i) => (e - 48) * (i % 2 == 0 ? 1 : 2)).Sum((e) => e / 10 + e % 10);
        return totalSSN % 10 == 0;
    }
}


texts: Cut specific rows and paste to new workbook faster

texts:
I'm quite new to trying to write my own macros and I've been able to piece this one together, but it takes quite some time to run. Here is the macro for one value (I have to create workbooks for ~20 different values). Are there any ways I can improve its speed?

Also, I am assuming I can just replicate my For/Next loop with new values and workbooks and not have to run this macro every time with a new value. So if not, please tell me I'm being naive.

Sub MakeRecruitCommLog()

    Application.ScreenUpdating = False

    old_workbook = ActiveWorkbook.Name
    old_sheet = ActiveSheet.Name
    Workbooks.Add
    new_workbook1 = ActiveWorkbook.Name

    Workbooks(old_workbook).Activate
    Rows("1:1").Select

    Selection.Copy

    Workbooks(new_workbook1).Activate
    Range("A1").Select
    ActiveSheet.Paste

    Dim transfer_row As Long
    new_transfer = 2

    Workbooks(old_workbook).Activate

    For transfer_row = 2 To 514000
        Do While Range("L" & transfer_row) = "value1"

            Workbooks(old_workbook).Worksheets(old_sheet).Range(transfer_row & ":" & transfer_row).Cut _
                Workbooks(new_workbook1).Worksheets("Sheet1").Range("A" & new_transfer)

            new_transfer = new_transfer + 1

            Workbooks(old_workbook).Worksheets(old_sheet).Activate
            Rows(transfer_row & ":" & transfer_row).Delete Shift:=x1Up

        Loop
        Next transfer_row

    Workbooks(new_workbook1).Activate

End Sub


texts:
I decided to create simple blog app by using Ember.js which should has the following interface

For this purpose I created blog route which contain the following code:

import Ember from 'ember';

export default Ember.Route.extend({
  setupController: function (controller, model) {
    controller.set('currentPost', 0);
    controller.set('model', model.objectAt(controller.get('currentPost')));
  },

  model: function () {
    return this.store.find('blog-post');
  },

  actions: {
    nextPost: function () {
      var controller = this.controller;
      controller.incrementProperty('currentPost');
      this.store.find('blog-post').then(function (value) {
        controller.set('model', value.objectAt(controller.get('currentPost')));
      });
    }
  }
});

In blog.hbs I have blog-post component. This component receive data from model, which is filtered inside setupController method, in order to load only one post, but not the whole array of posts. But when user clicks Next button, I need update data in component, and it's done in nextPost method. It works good, but it's look weird and ugly, because we access to store and retrieve the model data, however it has already done in model hook.

nextPost: function () {
          var controller = this.controller;
          controller.incrementProperty('currentPost');
          this.store.find('blog-post').then(function (value) {
            controller.set('model', value.objectAt(controller.get('currentPost')));
          });
        }

What app design changes I need to do or to refactor the code, in order to make it clear and concise?


texts: best way to write series of objects to a .ser file using ObjectOutputStream and read them back

texts:
I create series of objects out of Student Class and store them in a vector. I write each object in to a .ser file once it created. Then I read them back. My code is working perfectly. What I want to know is, I do this in a correct optimized way or are there any easy and optimized ways to get this done?? And also how to replace or delete specific object in a .ser file without re-witting whole the file again.

Student Class

public class Student implements Comparable<Student>, Serializable{

    private String firstName = "";
    private int registrationNumber;
    private int coursework1;
    private int coursework2;
    private int finalExam;
    private double moduleMark;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public int getRegistrationNumber() {
        return registrationNumber;
    }
    public void setRegistrationNumber(int registrationNumber) {
        this.registrationNumber = registrationNumber;
    }
    public int getCoursework1() {
        return coursework1;
    }
    public void setCoursework1(int coursework1) {
        this.coursework1 = coursework1;
    }
    public int getCoursework2() {
        return coursework2;
    }
    public void setCoursework2(int coursework2) {
        this.coursework2 = coursework2;
    }
    public int getFinalExam() {
        return finalExam;
    }
    public void setFinalExam(int finalExam) {
        this.finalExam = finalExam;
    }
    public double getModuleMark() {
        return moduleMark;
    }
    public void setModuleMark(double moduleMark) {
        this.moduleMark = moduleMark;
    }
    public int compareTo(Student s){
        if (this.moduleMark > s.moduleMark)
            return 1;
        else if (this.moduleMark == s.moduleMark)
            return 0;
        else
            return -1;
    }
}

File writing part

public static void Write(Student mm){
        try
          {
            FileOutputStream fileOut = new FileOutputStream("info.ser",true);
            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));

            out.writeObject(mm);
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved in info.ser");
          }catch(IOException i)
          {
              //i.printStackTrace();
          }

    }

Reading part

public static int Read() {
        int count=0;
        try{
            vector = new Vector<Student>();
            FileInputStream saveFile = new FileInputStream("info.ser");
            ObjectInputStream save;
            try{
                for(;;){
                    save = new ObjectInputStream(saveFile);
                    student = (Student) save.readObject();
                    vector.add(student);
                    count++;
                }
            }catch(EOFException e){
                //e.printStackTrace();
            }
            saveFile.close();

        }catch(Exception exc){
            exc.printStackTrace();
        }
        return count;
    }


texts: Roslyn analyzer, converted from C# to F#

texts:
I'm learning F# and for an exercise, I took a roslyn analyzer in C# and ported it to F#.

In the excerpt below the GetParameterInfo function:

takes in ArgumentSyntax which describes an argument passed to a
C# method at an invocation site.
And finds the corresponding IParameterSymbol which describes the method's parameter at the point in code where the method is defined.

Here it is:

module UseNamedArgs.ParameterInfo

open System
open System.Collections.Immutable
open Microsoft.CodeAnalysis
open Microsoft.CodeAnalysis.CSharp.Syntax
open UseNamedArgs.CSharpAdapters
open UseNamedArgs.MaybeBuilder

type ParameterInfo = {
    MethodOrProperty : ISymbol;
    Parameter : IParameterSymbol }

type ISymbol with
    member symbol.GetParameters() =
        match symbol with
        | :? IMethodSymbol as s   -> s.Parameters
        | :? IPropertySymbol as s -> s.Parameters
        | _                       -> ImmutableArray<IParameterSymbol>.Empty
        |> Seq.toList

/// <summary>
/// To be able to convert positional arguments to named we need to find
/// corresponding <see cref="IParameterSymbol" /> for each argument.
/// </summary>
type SemanticModel with
    member sema.GetParameterInfo (argument: ArgumentSyntax) =
        maybe {
            let argList = argument.Parent :?> ArgumentListSyntax
            let exprSyntax = argList.Parent  :?> ExpressionSyntax
            let methodOrProperty = sema.GetSymbolInfo(exprSyntax).Symbol
            let! parameters = methodOrProperty.GetParameters() |> Option.ofList
            if isNull argument.NameColon then
                // A positional argument.
                match argList.Arguments.IndexOf(argument) with
                | index when index >= 0 && index < parameters.Length ->
                    return { MethodOrProperty = methodOrProperty;
                             Parameter = parameters.[index] }
                | index when index >= parameters.Length
                             && parameters.[parameters.Length - 1].IsParams ->
                    return { MethodOrProperty = methodOrProperty;
                             Parameter = parameters.[parameters.Length - 1] }
                | _ -> return! None
            else
                // Potentially, this is a named argument.
                let! name = argument.NameColon.Name |> Option.ofObj
                let! nameText = name.Identifier.ValueText |> Option.ofObj
                // Yes, it's a named argument.
                let! parameter = parameters |> Seq.tryFind (fun param ->
                    String.Equals(param.Name,
                                  nameText,
                                  StringComparison.Ordinal))

                return { MethodOrProperty = methodOrProperty;
                         Parameter = parameter }
}

The original C# code of this snippet was adapted from
CSharpEssentials
The maybe computational expression is defined in
MaybeBuilder
— but it's likely pretty much what you'd expect a maybe to be.

How can I change the code so it'll be more idiomatic F#?
And is it even anywhere in the ballpark of idiomatic F#?


texts: Checking to see if array can be sorted using only one operation

texts:
I'm doing this HackerRank problem, which asks whether an array of up to 100000 integers can be sorted in ascending order by exactly one of the following:

swapping two elements
reversing a subarray
doing nothing (i.e. it is already sorted)

I've written this code and it passes all the tests, but it seems very convoluted. Is there any way I can streamline this code to make it more Pythonic?

n = int(raw_input())
ar = map(int, raw_input().strip().split())
ar.insert(0, -1)
ar.append(1000001)

ups = 0
downs = 0

for i in xrange(1, n+1):
    if ar[i] < ar[i-1] and ar[i] < ar[i+1]:
        downs += 1
        later_index = i
    elif ar[i] > ar[i-1] and ar[i] > ar[i+1]:
        ups += 1
        first_index = i

for i in xrange(n, 0, -1):
    if ar[i] > ar[i-1] and ar[i] > ar[i+1]:
        swap_i = i

if downs == ups == 2:
    ar[swap_i], ar[later_index] = ar[later_index], ar[swap_i]
    if all(ar[i] < ar[i+1] for i in xrange(1, n)):
        print 'yes'
        print 'swap %d %d' % (swap_i, later_index)
    else:
        print 'no'
elif downs == ups == 1:
    if first_index == 1 or later_index == n:
        ar[swap_i], ar[later_index] = ar[later_index], ar[swap_i]
        if all(ar[i] < ar[i+1] for i in xrange(1, n)):
            print 'yes'
            print 'swap %d %d' % (swap_i, later_index)
        else:
            print 'no'
    else:
        if first_index - later_index == -1:
            ar[first_index], ar[later_index] = ar[later_index], ar[first_index]
            if all(ar[i] < ar[i+1] for i in xrange(1, n)):
                print 'yes'
                print 'swap %d %d' % (first_index, later_index)
            else:
                print 'no'
        else:
            ar = ar[:first_index:] + ar[later_index:first_index-1:-1] + ar[later_index+1::]
            if all(ar[i] < ar[i+1] for i in xrange(1, n)):
                print 'yes'
                print 'reverse %d %d' % (first_index, later_index)
            else:
                print 'no'
elif ups ==1 and downs == 0:
    print 'yes'
    print 'reverse %d %d' % (first_index, later_index)
else:
    print 'no'

I feel there are far too many if-else blocks ruining the program structure.


texts:
I am trying to learn Meteor, so I tried to write a basic location autocomplete.

Currently, given a string, it will request suggestions from https://photon.komoot.de/ (amazing free location autocomplete btw) and display them in an ul-li. What is not done yet is keyboard navigation.

autocomplete.html

<template name="autocomplete">
    <input id="{{name}}" class="autocomplete-input {{className}}"
        placeholder="{{placeholder}}" autocomplete="off"/>

</template>

autocomplete.js

(function() {
    var inputEl, suggestionsEl, timeout, displayedSuggestions, selectedSuggestion;
    var search = function(inputString) {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function() {
            HTTP.get("https://photon.komoot.de/api/?q=" + inputString + "&lang=" + globalConfig.language, {},
                function(error, response) {
                    if (error) {

                    } else {
                        displayedSuggestions = response.data.features;
                        display(displayedSuggestions);
                    }
                });
        }, 300);
    };

    var suggestionString = function (suggestion) {
        return suggestion.properties.name + ' (' + suggestion.properties.country + ')';
    };

    var selectSuggestion = function(elt) {
        inputEl.value = elt.innerHTML;
        selectedSuggestion = displayedSuggestions[elt['data-index']];
        suggestionsEl.style.display = 'none';
    };

    var display = function(data) {
        suggestionsEl.innerHTML = '';
        suggestionsEl.style.display = 'block';
        for (var i = 0; i < data.length; i++) {
            var suggestion = data[i];
            var li = document.createElement('li');
            li.className = "suggestion";
            li.onclick = function() {selectSuggestion(this);};
            li['data-index'] = i;
            li.innerHTML = suggestionString(suggestion);
            suggestionsEl.appendChild(li);
        }

    };

    Template.autocomplete.onRendered( function(){
        inputEl = this.find('.autocomplete-input');
        suggestionsEl = this.find('.suggestions');
    });

    Template.autocomplete.events({
        "keyup .autocomplete-input": function (event) {
            search(event.target.value);
        }
    });
})();

Two things does not seem very "meteor"-like. First, I have a lot of local functions, and local variables. Are they supposed to be put somewhere else?

Also, I am worried about performance. The keyup event is based on the class of the input. If it is looking through the DOM at each keystroke, it might get slow. I tried using inputEl instead, but this does not seem possible (or is it?).


texts: Get count of positive numbers and sum of negative numbers

texts:
Write a function called manipulate_data which will act as follows:

  When given a list of integers, return a list, where the first element is the count of positives numbers and the second element is the sum of negative numbers.

Sample code

def manipulate_data(data):
    if isinstance(data, (list, tuple, set)):
        #didn't know where 0 stood so I excluded it
        return [len([n for n in data if isinstance(n, int) and n > 0]), sum(n for n in data if isinstance(n, int) and n < 0)]