texts: Python Tkinter Custom Widget (Frame) with Mousewheel Scroll Event

texts:
I try to write a GUI for practicing with one Window, containing two frames in a ttk.Notebook. Each of these Custom Widget Frames should have a scrollbar and the MouseWheel bound to a yscroll for the canvas which is placed in this frame.

My questions are:
- Is this a common/recommended way to do that?
- If I do it like this the MouseWheel works only on one of the Frames of my window. Why?
- I am a beginner, so if you see any other mistakes/uncommon things, please let me know!

Here is an extraction of my code:

from tkinter import *
import tkinter.ttk as ttk

class MyFirstGUI(object):
    def __init__(self, master):
        self.master = master

        self.gui_control = ttk.Notebook(master)

        self.main_gui = ttk.Frame(self.gui_control, borderwidth=0)
        self.systems_gui = ttk.Frame(self.gui_control, borderwidth=0)

        self.gui_control.add(self.main_gui, text='Main')
        self.gui_control.add(self.systems_gui, text='Systems')

        self.gui_control.grid(column=1,row=1, columnspan=9, rowspan=50,sticky=N+E+S+W)

        self.test_1 = Main.MainFrame(self.main_gui)
        self.test_1.grid(row=0, column=0, sticky="NESW")

        self.test_2 = Systems.SystemFrame(self.systems_gui)
        self.test_2.grid(row=0, column=0, sticky="NESW")

        #[...]

master.mainloop()

MainGUI:

class MainFrame(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self.main_canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0)
        self.main_canvas.grid(row=0,column=0, sticky="NESW")

        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.main_canvas.yview)
        self.vsb.grid(row=0,column=1, sticky="NS")

        self.main_canvas.bind_all("<MouseWheel>", self._on_mousewheel)

    def _on_mousewheel(self, event):
        self.main_canvas.yview_scroll(int(-1*(event.delta/120)), "units")

    #[...]

Systems GUI (basically the same):

class SystemFrame(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self.system_canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0)
        self.system_canvas.grid(row=0,column=0, sticky="NESW")

        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.system_canvas.yview)
        self.vsb.grid(row=0,column=1, sticky="NS")

        self.system_canvas.bind_all("<MouseWheel>", self._on_mousewheel)

    def _on_mousewheel(self, event):
        self.system_canvas.yview_scroll(int(-1*(event.delta/120)), "units")

    #[...]


texts: Text interface for employee management in Rust

texts:
I'm in the process of reading The Rust Programming Language, and decided to do the 3rd task at the end of the 8th chapter.
The description is as follows:

  Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

Please tell me if my code is any good.

use std::collections::HashMap;
use std::io;
use std::io::Write;

use regex::Regex;

fn main() {
    let add_regex = Regex::new(r"^(?i)Add\s(\w(?:\w|\s)*\w?)\sto\s(\w+)$").unwrap();
    let list_regex = Regex::new(r"^(?i)List\s(\w+)$").unwrap();
    let all_regex = Regex::new(r"^(?i)Show all$").unwrap();
    let mut departments: HashMap<String, Vec<String>> = HashMap::new();

    loop {
        let mut input = String::new();

        print!("Enter command: ");
        io::stdout().flush();
        io::stdin().read_line(&mut input);

        input = String::from(input.trim());

        let add_match = add_regex.captures(&input);
        let list_match = list_regex.captures(&input);
        let all_match = all_regex.captures(&input);

        if add_match.is_some() {
            let unwrapped_match = add_match.unwrap();
            let employee = &unwrapped_match[1];
            let dpt = &unwrapped_match[2];

            match departments.get_mut(dpt) {
                Some(v) => {
                    v.push(String::from(employee));
                    v.sort();
                },
                None => {
                    let emp_list = vec![String::from(employee)];
                    departments.insert(String::from(dpt), emp_list);
                }
            }
        } else if list_match.is_some() {
            let unwrapped_match = list_match.unwrap();
            let employees = departments.get(&unwrapped_match[1]);

            if !employees.is_some() {
                println!("No such department");
                continue;
            }

            println!("Department employees: {}", employees.unwrap().join(", "));
            io::stdout().flush();
        } else if all_match.is_some() {
            for (dpt, employees) in &departments {
                println!("{}: {}", dpt, employees.join(", "));
            }
        } else {
            println!("Please enter a valid command");
        }
    }
}

Sample output:

Enter command: add f to ff
Enter command: add b to ff
Enter command: list ff
Department employees: b, f
Enter command: add Darth Vader to ff
Enter command: list ff
Department employees: Darth Vader, b, f
Enter command: add d to zz
Enter command: add 1 to zz
Enter command: show all
ff: Darth Vader, b, f
zz: 1, d


texts: Setting receive_payment_on flag for employment applicants

texts:
I would like to refactor this block, it looks clunky:

# refactor me
receive_payment_on = false
config[:sections].each do |section|
  if section[:applicants]
    section[:applicants][:sections].each do |app_sec|
      if app_sec[:employment] && app_sec[:employment][:receive_payment_on]
        receive_payment_on = true
      end
    end
  end
end


texts: Java merge sort implementation efficiency

texts:
The problem was to implement merge sort algorithm in Java, where I recursively split and merge the array until I have the sorted array. Even though the code is working properly, I feel it is verbose and can still be improved.

  private static int[] Split_merge(int[] a) {

    int splitindex = a.length/2;
    int[] lhs=Arrays.copyOfRange(a, 0, splitindex);
    int[] rhs= Arrays.copyOfRange(a, splitindex, a.length);
    if(lhs.length==1 || rhs.length==1){
      return a= merge(lhs, rhs);

    }else {
       lhs= Split_merge(lhs);
      rhs=  Split_merge(rhs);
        return a=merge(lhs, rhs);

    }

}

private static int[] merge(int[] lhs, int[] rhs) {
    int[] result = new int[lhs.length+rhs.length];
    int reslutindex=0;
    int lhsindex=0;
    int rhsinsex=0;
            while(reslutindex<=result.length-1){

                    if(rhsinsex>=rhs.length ||lhsindex<=lhs.length-1 && lhs[lhsindex]<=rhs[rhsinsex]){
                        result[reslutindex] = lhs[lhsindex];
                    lhsindex++;
                    reslutindex++;
                    }else {
                    if(rhsinsex<=rhs.length-1){
                          result[reslutindex] = rhs[rhsinsex];
                    rhsinsex++;
                    reslutindex++;
                    }

                }

                }

    return result;

}


texts: Show image when in viewpoint of browser window

texts:
I am working on a web project and am trying to create a way to detect when an image is in viewpoint of the browser window then load/show the image. Since there are some rather large image that are being resize to use a thumbnails, I am trying to take into consideration those that might view it one a mobile device and reduce page loading time. I notice that many site with galleries are doing the same thing.

I create a little script using JavaScript to detect when an  tag is in view and then take its data attribute value (the URL of the image) and set it's  attribute to it.

Is this is an efficient way of doing it or should I just use PHP the create thumbnails?

I have included snippets of the HTML and JavaScript I am using.

HTML of the image

JavaScript with jQuery

//Show images when in viewpoint
$(window).on('scroll load',function(){
    //Window width & height
    var viewpointWidth = $(window).width(),
    viewpointHeight = $(window).height(),
    //Document Top pos & Left pos
    documentScrollTop = $(document).scrollTop(),
    documentScrollLeft = $(document).scrollLeft(),
    //Document Positions
    minTop = documentScrollTop,
    maxTop = documentScrollTop + viewpointHeight,
    minLeft = documentScrollLeft,
    maxLeft = documentScrollLeft + viewpointWidth;
    //Loop for each image
    $('.page-content img').each(function(){
        $eleImage = $(this),
        elementOffset = $eleImage.offset();
        if((elementOffset.top > minTop && elementOffset.top < maxTop) && (elementOffset.left > minLeft &&elementOffset.left < maxLeft)) {
            $(this).attr('src',$(this).data('image-src'));
        }
    });
});


texts:
I made a very simple generic function to foreach over an array in C using a callback function:

#include <stddef.h>
void foreach_array(void* array, size_t size, size_t bytes_per_element, void (*callback)(void*)) {
    char* iter;
    for(iter = array; iter < (char*)array + (int)size; iter += (int)bytes_per_element) {
        callback((void*)iter);
    }
}

It can be used like:

#include <stdio.h>
void print_double(void* doubleToPrint) {
    printf("%f\n", *((double*)doubleToPrint));
}

int main() {
    double myArray[] = {3.0, 6.0, 9.0};
    foreach_array(myArray, sizeof(myArray), sizeof(*myArray), print_double);
}

Comments:

I had to use char* instead of void* for the iteration variable, Because the standard doesn't define pointer arithmetic on void*.
I typecasted the size and bytes_per_element arguments to an int because I wasn't sure if it was defined behavior to use pointer arithmetic using a size_t value.

I thought this foreach function was interesting, So I wanted to put it here for a code review.


texts: Parse the phone balance from the operator site

texts:
How can I write this code better?

$cookieUrl = 'https://-------------/ps/scc/login.php';
$sessionUrl = 'https://-------------/ps/scc/php/check.php';
$balanceUrl = 'https://-------------/SCWWW/ACCOUNT_INFO';
$vars = "LOGIN={$this->login}&PASSWORD={$this->password}";
$response = $this->_sendPostRequest($cookieUrl, '', null, 1);
preg_match_all("/PHPSESSID.*;/isU",
            $response, $matches, PREG_PATTERN_ORDER);
$phpsessid = $matches[0][0];
$response = $this->_sendPostRequest($sessionUrl, $vars, $phpsessid);
preg_match_all("/<SESSION_ID>.*<\/SESSION_ID>/isU",
        $response, $matches, PREG_PATTERN_ORDER);
$sessionId = strip_tags($matches[0][0]);
$vars = "SESSION_ID={$sessionId}";
$response = $this->_sendPostRequest($balanceUrl, $vars);
preg_match_all("/
.*<\/div>/isU",
        $response, $matches, PREG_PATTERN_ORDER);
if (count($matches[0]) == 0) {
    preg_match_all("/
.*<\/div>/isU",
            $response, $matches, PREG_PATTERN_ORDER);
}
$this->balance = strip_tags($matches[0][0]);
$this->updated = date(Settings_Constants::DATETIME_DATABASE_FORMAT);
$this->save();
$this->balance;


texts:
I would like to know what you think:

<?php
 $nav_normal = array("1. Home","2. Read Me","3. License Agreement","4. General Information","5. Database Installer","6. Create an Account","7. Create Config","8. Successfully installed"
    );

$last_normal = array_pop(array_keys($nav_normal));

foreach($nav_normal as $name){

    if($Nav_ID == $name){
            $Nav_Type = "Selected";
    }else{
            $Nav_Type = "Unselected";
    }

    ?><li class="<?php echo($Nav_Type); ?>"><?php echo($name); ?>
<?php
            //this part is only for the (google chrome) view-source:\\
            //this will not be shown into the normal layout/output\\
            if($name != $last_normal){
                    echo("\n                                        ");
            }else{
                    echo("\n");
            }

}

On each page I write at the place of the navigation bar:

<?php
 $Nav_ID = "1. Home"; //etc. etc.\\
 include_once("navigation.php");
?>

I hope you can give me a review on what you think is either good or bad.  Just give your opinion.


texts: Cor.test inside for loop is very slow for large matrix processing

texts:
I have a matrix of  36,000 genes measurements for 60 samples. For calculating most correlated genes of the first gene in the matrix, my following program gives the result. However processing time is extremely slow.

dat <- as.matrix(read.table("/path/gene_matrix.txt", header = TRUE, fill = TRUE))
corr_list <- data.frame(top=numeric(), correlated=numeric(), cor=numeric(), p.value=numeric())

for (i in 2:nrow(dat)) {
r <- cor.test(dat[1,], dat[i,])
corr_list[i-1,] <- c(rownames(dat)[1], rownames(dat)[i], r$estimate, r$p.value)
}

corr_list <- corr_list[order(corr_list$cor, decreasing = TRUE), ]

write.table(corr_list, "/path/most_related.txt", quote = FALSE, row.names = FALSE, sep="\t")

Anyone could suggest an efficient method for the above problem.


texts:
Recently, I have been trying my hands on LINQ.  So I've implemented the diagonal difference using Linq in Hackerrank.  I know a similar question has been asked in python Diagonal Difference
Here is an excerpt of the problem Hackerrank -Diagonal Difference

Given a square matrix of size N X N , calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, N . The next  lines denote the matrix's rows, with each line containing space-separated integers describing the columns.
Output Format
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.

Sample Input
3
11 2 4
4 5 6
10 8 -12

Sample Output
15
Explanation
The primary diagonal is:
11
      5
            -12

Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
            4
      5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
My Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        int[][] a = new int[n][];
        for(int a_i = 0; a_i < n; a_i++){
            string[] a_temp = Console.ReadLine().Split(' ');
            a[a_i] = Array.ConvertAll(a_temp,Int32.Parse);
        }
        int value = -1;

        IEnumerable<int> leftDiagonal=  a.Select((x) => x.ElementAt(value +1));
        int total1 = 0, total2=0;
        foreach (var b in leftDiagonal)
        {
            total1 += b;
            value++;
        }

        int value2 = a.Length;
        IEnumerable<int> ans2 = a.Select((x) => x.ElementAt(value2 - 1));
        foreach (var b1 in ans2)
        {
            total2 += b1;
            value2--;
        }
        Console.WriteLine(Math.Abs(total1 - total2));
    }
}

Final Statement

I'm looking for improvements in terms of syntax, style, alternatives, and performance . I'm aware of the naming convention but some of these were the pre-defined structure in Hackerrank
Using Linq this way is it an overkill for the small data?


texts: How to simplify these delegate functions?

texts:
I'm looking for a way to simplify this code, because I could develop more overloads for TryThis  I made the string and int both of class Nullable so that in each overloaded function, the catch block could return the same value.

The problem is I need, if possible, no overloads of TryThis.  The function overloads are both identical, except for the type of delegate they are passed.  Is there some kind of variable that would encompass any delegate that can be executed?

class Program
{
    delegate int MyIntReturn();
    delegate string MyStringReturn();
    static private MyIntReturn ReadInt = () => {return int.Parse(Console.ReadLine()); };
    static private MyStringReturn ReadString = () => { return Console.ReadLine(); };

    static private Nullable<int> TryThis(MyIntReturn MyAction)
    {
        try
        {
            return MyAction();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return null;
        }
    }
    private static Nullable<string> TryThis(MyStringReturn MyAction)
    {
        try
        {
            return MyAction();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return null;
        }
    }

}


texts: Improving my code of Margrabe Formula in Python

texts:
I am new to Python and I want to see how can I improve my code to make it faster and cleaner. Below you can see the code of Margrabe's Formula for pricing Exchange Options.

I think the part where I check if the argument is None and if not take predetermined values, can be improved but i don't know how to do it. Is using scipy.stats.norm for calculating the pdf and cdf of the normal distribution faster than manually coding it myself?

    from __future__ import division
    from math import log, sqrt, pi
    from scipy.stats import norm

    s1 = 10
    s2 = 20
    sigma1 = 1.25
    sigma2 = 1.45
    t = 0.5
    rho = 0.85

    def sigma(sigma1, sigma2, rho):
        return sqrt(sigma1**2 + sigma2**2 - 2*rho*sigma1*sigma2)

    def d1(s1, s2, t, sigma1, sigma2, rho):
        return (log(s1/s2)+ 1/2 * sigma(sigma1, sigma2, rho)**2 * t)/(sigma(sigma1, sigma2, rho) * sqrt(t))

    def d2(s1, s2, t, sigma1, sigma2, rho):
        return d1(s1,s2,t, sigma1, sigma2, rho) - sigma(sigma1, sigma2, rho) * sqrt(t)

    def Margrabe(stock1=None, stock2=None, sig1=None, sig2=None, time=None, corr=None):

        if stock1 == None:
            stock1 = s1
        if stock2 == None:
            stock2 = s2
        if time == None:
            time = t
        if sig1 == None:
            sig1 = sigma1
        if sig2 == None:
            sig2 = sigma2
        if corr==None:
            corr = rho

        dd1 = d1(stock1, stock2, time, sig1, sig2, corr)
        dd2 = d2(stock1, stock2, time, sig1, sig2, corr)
        return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)

    print "Margrabe = " + str(Margrabe())


texts: Ensure that a Sinatra hash always has a valid value

texts:
I'm trying to ensure that a Sinatra hash always has a valid value.

Is there a more-concise way to write this?

params[:v] = if [:icons,:list].include? (params[:v] ||= :list).downcase.to_sym then (params[:v] ||= :list).downcase.to_sym else :list end


texts: Node.JS module to retrieve configuration from environment variables

texts:
I don't like the idea of sprinkling process.env all over the place and wanted to abstract it out a bit. I'm new to Node and know there must be a better way to do a few things.

Not repeat the name 4 times (twice as a string and twice as a field)
Any cleaner way to create properties and centralize existence checks than how I've done it? Mind you, I am trying to keep this Node 4.3.2 compatible sans Babel transpilers to keep it simple and working in AWS Lambda's NodeJs environment.

// module

module.exports = {

}

var configError = function (keyName) {
  console.error("ExternalVars error! Could not load a value for: "+keyName);
  process.exit(1);
}

// TODO: extract repeated function?
Object.defineProperty(module.exports, 'SAMPLE_SECRET', {
    get: function() {
        if (!process.env.SAMPLE_SECRET)
            configError('SAMPLE_SECRET');
        else
            return process.env.SAMPLE_SECRET;
    }
});

Object.defineProperty(module.exports, 'SAMPLE_SECRET_MORE', {
    get: function() {
        if (!process.env.SAMPLE_SECRET_MORE)
            configError('SAMPLE_SECRET_MORE');
        else
            return process.env.SAMPLE_SECRET_MORE;
    }
});

// usage example

var externalvars = require('./config/externalvars.js');

var sampleSecret = externalvars.SAMPLE_SECRET;
var sampleSecretMore = externalvars.SAMPLE_SECRET_MORE;


texts: Finding cells in a 3D grid with free neighbors

texts:
I have a program, where the get_free function below has the most major computational cost by far, and I was wondering if there was a faster way to do it. Perhaps an all-numpy solution would be faster.

The task is to find the indices of the third dimension in a three-dimensional boolean array where the cell (as specified by the two first dimensions) and its neighbors (as given by the neighbors2 function) are 0. That's what get_free does.

Don't worry too much about understanding the neighbors2 function, it doesn't do much heavy lifting. The indices can be returned in two formats, as specified by the docstring, which can be helpful for some numpy-functions.

Any feedback, regarding code quality in general or for optimizing performance is appreciated.

import numpy as np
import timeit

rows, cols = 7, 7
depth = 70
state = np.random.choice([0, 1], size=(rows, cols, depth)).astype(bool)

def neighbors2(row, col, separate=False):
    """
    If 'separate' is True, return ([r1, r2, ...], [c1, c2, ...])
    if not, return [(r1, c1), (r2, c2), ...]

    Returns a list of indices of neighbors (in an hexogonal grid)
    within a radius of 2, not including self.
    """
    if separate:
        rs = []
        cs = []
    else:
        idxs = []

    r_low = max(0, row-2)
    r_hi = min(rows-1, row+2)
    c_low = max(0, col-2)
    c_hi = min(cols-1, col+2)
    if col % 2 == 0:
        cross1 = row-2
        cross2 = row+2
    else:
        cross1 = row+2
        cross2 = row-2
    for r in range(r_low, r_hi+1):
        for c in range(c_low, c_hi+1):
            if not ((r, c) == (row, col) or
                    (r, c) == (cross1, col-2) or
                    (r, c) == (cross1, col-1) or
                    (r, c) == (cross1, col+1) or
                    (r, c) == (cross1, col+2) or
                    (r, c) == (cross2, col-2) or
                    (r, c) == (cross2, col+2)):
                if separate:
                    rs.append(r)
                    cs.append(c)
                else:
                    idxs.append((r, c))
    if separate:
        return (rs, cs)
    else:
        return idxs

def get_free(cell):
    """
    Return the indices of a a cell that are 0 and
    where all its neighbors are 0 for the same depth
    """
    candidates = np.where(state[cell] == 0)[0]
    neighs = neighbors2(*cell, False)
    free = []
    # Exclude elements that have non-zero value in neighboring cells
    for candidate in candidates:
        non_zero = False
        for neigh in neighs:
            if state[neigh][candidate]:
                non_zero = True
                break
        if not non_zero:
            free.append(candidate)

print(timeit.timeit("get_free((4, 4))", number=100000,
      setup="from __main__ import get_free"))


texts: Number of possible numbers in roman number string

texts:
I just started learning programming a few months ago, and I'm intrigued by Haskell. To learn a bit I tried to adapt some code I have in Java so I can see what are equivalent solutions in Haskell.

The problem I had was to see how many different numbers can be “represented” by a string of roman numbers (0, .., 9, where X is equivalent to zero).

For example "I" means just one possible number (1), but "II" could be two possibilities: 11 (two "I") or 2 (one "II"). This is from some competitive programming website. Similar "XX" should give 1, since it represents 00 only. A bit bigger example: "IVII" should give 6, because there are 6 possibilities:

"I" + "V" + "I" + "I" = 1511
"I" + "V" + "II" = 152
"I" + "VI" + "I" = 161
"IV" + "I" + "I" = 411
"I" + "VII" = 17
"IV" + "II" = 42

Ok, that said, this is my Haskell code (first thing I write so far).

romanCombinations :: String -> Int
romanCombinations [] = 1
romanCombinations str = if length str == 1 then 1
  else foldr (+) 0 [ romanCombinations xs | (x, xs) <- sep , elem x possibles ]
  where
    sep = map (divide str) $ take (length str) [1..4]
    divide str n = (take n str, drop n str)
    possibles = ["X", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

What would you change in this Haskell code? I've never written anything before. Anything is welcome since I will probably learn from every comment. (I'm not asking about algorithms, but anything is welcome too)


texts: Splits up two comma separated items, if they exist

texts:
This method splits up two comma separated items, if they exist, and increments the amount if the are already in the list; otherwise add the item to the list

I want to know if this code can be optimized some more. Any suggestions?

The method below works 100% fine but I feel like it is not neatly done.

private void SeperateJoinedDisposables(IEnumerable<Models.Container> joinedDisposables)
{
    if (!joinedDisposables.Any())
        return;

    foreach (var item in joinedDisposables.ToList())
    {
        var amount = item.Amount;
        var container = item.Container;

        var disposable1 = container.Substring(0, container.IndexOf(","));
        var disposable2 = container.Substring(container.IndexOf(",") + 1);

        DisposablesModel.Containers.Remove(item);

        var disposableCointians1 = DisposablesModel.Containers.FirstOrDefault(x => x.Container.ToUpper().Contains(disposable1.ToUpper()));
        var disposableCointians2 = DisposablesModel.Containers.FirstOrDefault(x => x.Container.ToUpper().Contains(disposable2.ToUpper()));

        if (disposableCointians1 != null)
            disposableCointians1.Amount = (int.Parse(disposableCointians1.Amount) + int.Parse(amount)).ToString();
        else
            DisposablesModel.Containers.Add(new Models.Container { Amount = amount, Container = disposable1 });

        if (disposableCointians2 != null)
            disposableCointians2.Amount = (int.Parse(disposableCointians2.Amount) + int.Parse(amount)).ToString();
        else
            DisposablesModel.Containers.Add(new Models.Container { Amount = amount, Container = disposable2 });
    }
}

Here is my model class

    public class DisposablesModel
    {
        public string Barcode { get; set; }
        public string RushColor { get; set; }
        public string RushDescription { get; set; }
        public string Pollution { get; set; }
        public int NumberOfSamples { get; set; }
        public List<Container> Containers { get; set; }
        public bool IsSubcontracted { get; set; }
    }

    public class Container
    {
        public string Amount { get; set; }
        public string Container { get; set; }
    }


texts: Converting a range in excel to a single column with excel vba

texts:
I am very new to coding and know only the basics.  The first part of this code is running fine.  It converts a range of values to a single column.  However, with my data set the rows of data step down, as shown in the sample data set below, so that when they are converted to a single column there are large gaps of 0 values in the column.  I added a portion of code to the end to look at each cell in the column and delete any 0 values.  The problem is this code takes around 4-5 hours to run.  I am hoping there is a better way to write the code to speed up the processing time.

Any help is appreciated!

Sub CombineColumns()

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Dim rng As Range
Dim iCol As Long
Dim lastCell As Long
Dim k As Long

k = 484
'set K equal to the number of data points that created the range

Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1

For iCol = 2 To rng.Columns.Count
    Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
    ActiveSheet.Paste Destination:=Cells(lastCell, 1)
    lastCell = lastCell + rng.Columns(iCol).Rows.Count

Next iCol
Dim z As Long
Dim m As Long

z = k ^ 2

For row = z To 1 Step -1
    If Cells(row, 1) = 0 Then
    Range("A" & row).Delete Shift:=xlUp

   Application.StatusBar = "Progress: " & row & " of z: " & Format((z - row) / z, "Percent")
   DoEvents

    End If

Next

Application.StatusBar = False
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

End Sub


texts: Extract the IP address from the output of ipconfig when connected to multiple wireless networks

texts:
I am trying to extract the ip address of my machine when connected to multiple wireless networks. The motivation here is then I can make a socket connection on that ip when I have two networks that have the same default gateway. I am hoping that there is either a way to greatly improve the code or replace it with some functionality that does what I am doing in a more robust cleaner way. In particular, the part that worries me most is using the MAX_OFFSET to ensure that the code does not return the next ip address.

import os
import subprocess

if os.name == "nt":
    WIRELESS_ADAPTER0 = b"Wi-Fi:"
    WIRELESS_ADAPTER1 = b"Wi-Fi 2"
    COMMAND = "ipconfig"
    IPV4_LINE = b"IPv4"
    IPV6_LINE = b"IPv6"
    IP_INDEX = -1
    MAX_OFFSET = 5

else:
    WIRELESS_ADAPTER0 = b"wlan0"
    WIRELESS_ADAPTER1 = b"wlan1"
    COMMAND = "ifconfig"
    IPV4_LINE = b"inet"
    IPV6_LINE = b"inet6"
    IP_INDEX = 1
    MAX_OFFSET = 7

def get_ip(all_lines, start_index):
    try:
        search_lines = list(filter(lambda x: (IPV4_LINE in x) or (IPV6_LINE in x), all_lines[start_index:start_index+MAX_OFFSET]))
        return search_lines[0].split()[IP_INDEX]
    except IndexError:
        pass

all_lines = subprocess.check_output(COMMAND).split(b"\n")
for i in range(len(all_lines)):
    if WIRELESS_ADAPTER0 in all_lines[i]:
        ip0 = get_ip(all_lines, i)
    if WIRELESS_ADAPTER1 in all_lines[i]:
        ip1 = get_ip(all_lines, i)

I have included some sample output from ipconfig below:

    Wireless LAN adapter Wi-Fi 2:

       Media State . . . . . . . . . . . : Media disconnected
       Connection-specific DNS Suffix  . : lan

    Ethernet adapter Ethernet 5:

       Connection-specific DNS Suffix  . : enceptacorp.local
       Link-local IPv6 Address . . . . . : fe80::80f0:901c:f4d3:1c6%5
       IPv4 Address. . . . . . . . . . . : 192.168.128.226
       Subnet Mask . . . . . . . . . . . : 255.255.255.0
       Default Gateway . . . . . . . . . : 192.168.128.1

The reason I use MAX_OFFSET is to make sure that I don't get the next ip address down (i.e. the IP for Ethernet 5, when Wi-Fi 2 is disconnected). I have also noticed that sometimes when first connecting to the router, I won't get assigned an IPv4 Address right away, and that is why I have included IPv4 and IPv6. If anyone can comment on whether I will always get an IPv6 address (and thus can ignore IPv4), that would be useful to know. Is there a better way to get the IP address of a particular network interface?  Or even just a command like ipconfig that returns more concise/consistent/cleaner output?


texts:
I currently have a selection sorting algorithm, but need some help turning it into a insertion sort, I understand a insertion sort if faster?  The hand array is full, and it needs to sort from lowest to highest rank.

private void sort(PlayingCard[] hand)
    {
        PlayingCard temp;
        for(int i = 0; i < hand.length ; i++)
        {

           for(int j = i+1; j < hand.length ; j++)
           {
               int compareRank = hand[j].getRank().compareTo(hand[i].getRank());

               if(compareRank < 0){
                   temp = hand[i];
                   hand[i] = hand[j];
                   hand[j] = temp;
               }
           }

        }
    }


texts:
I wrote a function in Clojure to solve quadratic equations using the quadratic formula

The function

(defn solvequadeq [a b c]
 (let [D (- (* b b) (* 4 a c))]
      (if (< D 0) #{}
        (let [sqrtD (Math/sqrt D)
              x1 (/ (+ (- b) sqrtD) (* 2 a))
              x2 (/ (- (- b) sqrtD) (* 2 a))]
              (set [x1 x2])))))

Unit tests

(defn assertFuzzyEquals [act exp]    ;; From codewars.com
  (do (println "asserting equality over " act exp)
  (let [inrange (<= (Math/abs (- act exp)) 1e-2)]
    (if (= inrange false)
      (println "abs(actual - expected) must be <= 1e-2. Expected was " exp " but got: " act))
    (is (= inrange true))))
)

(defn assertSetsFuzzyEqual [act exp]
  (and (is (= (count act) (count exp)))
  (doall (map assertFuzzyEquals (sort (vec act)) (sort (vec exp))))))   ; (1)

(deftest a-test5
  (testing "Solve quadratic equations"
          (assertSetsFuzzyEqual (solvequadeq 1 0 0) #{0})
          (assertSetsFuzzyEqual (solvequadeq 1 -6 9) #{3})
          (assertSetsFuzzyEqual (solvequadeq 1 -4 3) #{1 3})
          (assertSetsFuzzyEqual (solvequadeq 1 -4 14) #{})
))

N.B.: assertFuzzyEquals is borrowed from a task of codewars.com, all the rest is my code.

While any remark, and suggestion is welcome, I would be interested most particularly in the following questions:

Is using a set a good solution for avoiding having the same return value twice, if the two solutions are equal? (I am worrying that they might not be always exactly equal, due to imprecision in calculation.)
If not, than what would be a better approach, to elegantly handle the case of one vs two solutions?
Independently whether sets should be used for this particular problem or not, is there a better way to compare two sets for equality, with a custom function between the elements? (C.f., line (1))

EDIT: Clarification of this last point, as per the answer of Josh.
The question is: what is the best practice, in Clojure, for checking the equality of two sets of floating point numbers?

Let's say, that we have a set with values #{1.0, 2.0}, and want to compare it against the set #{1, 2}.

Attempted solutions:

(= #{1.0, 2.0} #{1, 2})

; result false, since 1.0 != 1

(reduce #(and %1 %2)  (map #(> 0.01 (Math/abs (- %1 %2))) #{1.0,2.0}  #{2,1}))

; returns false, since ordering of elements in the set is not guaranteed

(reduce #(and %1 %2)  (map #(> 0.01 (Math/abs (- %1 %2))) (sort (vec #{1.0,2.0}))  (sort (vec #{2,1}))))

; returns true, because fixes the ordering, but is very complicated...

So, I am asking if there is a better way, to compare two sets, providing a custom function for equality checking (in this particular case, this custom function would be #(> 0.01 (Math/abs (- %1 %2)))).

I am thinking of something like this (pseudo-code only):
(sets-equal #(> 0.01 (Math/abs (- %1 %2))) #{1.0,2.0}  #{2,1}


texts:
I'm trying to pass a programming challenge where we are to replace all instances of a substring in a string until there are none left. So an input like

 Pibabakekezza
 bake

Has output

Pizza

And if there is nothing left say so. I fail an unknown test case because I take longer than 1 second.

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Runtime;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            GCLatencyMode oldMode = GCSettings.LatencyMode;

            // Make sure we can always go to the catch block,
            // so we can set the latency mode back to `oldMode`
            RuntimeHelpers.PrepareConstrainedRegions();

            try
            {
                GCSettings.LatencyMode = GCLatencyMode.LowLatency;
                //Your code goes here
                string s =Console.ReadLine();
                string b =Console.ReadLine();
                while(s.Contains(b))
                {
                    s=s.Replace(b, "");
                }
                if(s!="")
                {
                    Console.WriteLine(s);
                }
                else
                {
                    Console.WriteLine("FRULA");
                }
            }
            finally
            {
                // ALWAYS set the latency mode back
                GCSettings.LatencyMode = oldMode;
            }
        }
    }
}

Restrictions:

1≤|bigString|≤1 000 000

1≤|substring|≤36

bigString and the substring string consist of uppercase and lowercase letters of the English alphabet and digits 0, 1, …, 9. The characters in the substring are all different.

CPU Time limit: 1 second
Memory limit: 1024 MB


texts: Starting an activity after 1000ms from a splash screen with Runnable and Handler().postDelayed

texts:
I have implemented a splash screen which is the main activity of my Android app. This splash screen shows an image, and after 1000ms there is an animation to show another activity's layout.

The code I've written is the following:

public class SplashScreen extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);
        startTheTransitionAfterTheSplashScreen();
    }

    private void startTheTransitionAfterTheSplashScreen() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intentSplashScreenToActivityJustAfterSplashScreen = new Intent(SplashScreen.this, ActivityJustAfterSplashScreen.class);
                startActivity(intentSplashScreenToActivityJustAfterSplashScreen);
                overridePendingTransition(R.anim.animation_enter_activity, R.anim.animation_leave_activity);
                finish();
            }
        }, 1000);
    }
}

And for the animations:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="100%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="500" />
</set>

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="-100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="500" />
</set>

Question

What I would want to ask is especially about the startTheTransitionAfterTheSplashScreen (I think the animations are correctly written): should I actually use a Runnable with a Handler to delay the transition? (in other words: is it suitable for this splash screen, or is there a better way to do that?)

Edit

Implementing K.H.'s answer:

public class SplashScreen extends AppCompatActivity {

    private Handler the_transition_handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);
    }

    @Override
    protected void onStart() {
        super.onStart();
        startTheTransitionAfterTheSplashScreen();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        the_transition_handler.removeCallbacksAndMessages(null);
    }

    private void startTheTransitionAfterTheSplashScreen() {
        the_transition_handler = new Handler();
        the_transition_handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                final Intent intentSplashScreenToActivityJustAfterSplashScreen = new Intent(SplashScreen.this, ActivityJustAfterSplashScreen.class);
                startActivity(intentSplashScreenToActivityJustAfterSplashScreen);
                overridePendingTransition(R.anim.animation_enter_activity, R.anim.animation_leave_activity);
                finish();
            }
        }, 1000);
    }
}


texts:
I just started to practice for competitive programming and just started to solve the most solved problems on SPOJ.
This is what I made for ADDREV: Adding reversed numbers in Java (https://www.spoj.com/problems/ADDREV/)

The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.
Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.
ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).
Input
The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.
Output
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

import java.util.*;
import java.lang.*;

class Main
{

public static void main (String[] args) throws java.lang.Exception
{
    Scanner sc = new Scanner(System.in);
    sc.nextLine();
    while(sc.hasNextInt())
    {
        printNextNumber(sc);
    }

}

public static void printNextNumber(Scanner sc)
{
    int a = sc.nextInt();
    int b = sc.nextInt();
    int reversedA = reverseNumber(a);
    int reversedB = reverseNumber(b);
    int reversedSum = reverseNumber(reversedA+reversedB);
    System.out.println(reversedSum);
}

public static int reverseNumber(int number)
{
    return listToNumberMadeOfDigits(numberToListOfDigits(number));

}

public static List<Integer> numberToListOfDigits(int number)
{
    List<Integer> list = new ArrayList<>();
    while(number>0){
        list.add(number%10);
        number /= 10;
    }

    Collections.reverse(list);
    return list;
}

public static int listToNumberMadeOfDigits(List<Integer> digits)
{
    int number = 0;
    for(int i = 0; i < digits.size();i++){
        number += Math.pow(10,i)*digits.get(i);
    }
    return number;
}

 }

How is this code?
What should I avoid in the future?


texts: Find ASCII codes and replace with characters

texts:
I have a text file that uses the convention #\d+ to mean ASCII character number \d+. I want to replace any such representations with the actual character.  This is what I've come up with. It works but it feels kludgy. Suggestions to improve efficiency?

<?php

$line= 'stuff #65 more #66  and #67; other';
preg_match_all("/\#\d+/",$line,$p);//find any #numbers that should be translated to ascii
$r=array_map(
    function($x){ return chr(trim($x,'#')); },
    $p[0]); //assemble set of replacements

$line=str_replace($p[0],$r,$line); //replace
echo $line; //stuff A more B  and C; other
?>


texts:
I'm relatively new to PHP and have recently created a small website for friends and family to upload and share photos, protected by a very simple login system.

While I'm aware what I'm doing isn't best practice and you'd never use this in a "published" site, I'd like to use this as learning experience to improve my coding, and would appreciate any pointers as to best practice and efficiency/security improvements.

The website contains no sensitive information and the login was purely to prevent unwanted uploading of files. The username isn't checked against anything and is only used to log who's uploaded a file. The password is shared for all users.

This script, login.php, is included at the top of each page and checks if the user is logged in - if not then redirect to homepage where the login form is displayed. If already logged in, then display some internal links instead of form.

if(!isset($_SESSION)){ session_start(); }

/***********************************************************/
//check if home page
if (/*code to check if outside root directory*/) }{$notHomePage = true;}

if($notHomePage and ($_SESSION['allow'] == false or !isset($_SESSION['allow'])) ) {
    $_SESSION['error'] = 'Please enter your name and password!';
    header('Location: index.php');
    exit();
   }

/***********************************************************/
function readCookie() {
    if (isset($_COOKIE["username"])) {
        $name = $_COOKIE["username"];
    }
    return $name;
}

/***********************************************************/
function loginForm() {
    if($_SESSION['allow']) {
        //display internal links and logout link
        echo "
Logout
";
    }
    else {
        if(isset($_SESSION['error'])) {
            echo "
" . $_SESSION['error'] . "
";
            unset($_SESSION['error']);
        }

        $name = readCookie();
        echo "<form method=\"post\" action=\"login.php\">
            <input type=\"text\" value=\"$name\" name=\"name\">Name
            <input type=\"password\" name=\"password\">Password
            <button type=\"submit\" name=\"submit\">Login</button>
        </form>";
    }
}

/***********************************************************/
function login() {
    $days = 30;
    if(trim($_POST['name']) == "" || trim($_POST['password']) == "") {
        $_SESSION['error'] = 'Please enter your name and password!';
        header('Location: index.php');
        exit();
    }

    $name = $_POST['name'];
    $password = $_POST['password'];

    $pass = "password"; //passsword goes here

    if ($password != $pass) {
        $_SESSION['error'] = 'Please enter the correct password!';
        header('Location: index.php');
        exit();
    }
    else {
        $_SESSION['allow'] = true;
        header('Location: index.php');
    }

    if($days) $expire = time()+60*60*24*$days;
    setcookie("username", $name, $expire,"/");
}
/***********************************************************/
if($_SERVER['REQUEST_METHOD'] == "POST") {
   login();
}
if($_SERVER['QUERY_STRING'] == "logout") {
    $_SESSION['allow'] = false;
    header("Location: index.php");
    exit;
}

?>


texts:
The function serves two purposes as follows:

When dealing with the day of the week, Python will always assign 0 to Sunday and 6 to Saturday and I want to change that. The first part of the code is changing the start of the week from Sunday to users preference, i.e. Monday or Tuesday.
The second section is assigning the correct week number based on the new day of the week. For example, the new day of the week is Tuesday and the week assignment should be from Tuesday to Monday instead of Sunday to Saturday by default.

The code works (obviously), but I want to optimize it. The current code takes about 30 seconds for a dataset with over 2000 rows, which don't seem to be normal. The delay is mostly in the loop, I can't seem to optimize the loop because it's assigning week number based on a condition. The condition is simple, assign week number until it reaches a new merchant then the week resets.

def date_manipulate(df,startday):
    df['Month']=df.index.strftime("%B")
    df['DOW']=df.index.strftime("%A")
    week_offset = collections.OrderedDict()
    default_week =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    temp_week = default_week[startday:] + default_week[0:startday]
    for index, day in enumerate(temp_week):
        week_offset[day] = index
    df.replace({"DOW":week_offset},inplace=True)
    df=df.reset_index().sort_values(['merchant_name', 'date'],ascending=['True','True']).set_index(['date'])
    df['temp_date']=df.index.map(lambda x: x.toordinal())

    current_merchant=df['merchant_name'][0]
    offset=list(week_offset.values())[df['DOW'][0]]
    startdate=df['temp_date'][0]-(offset)
    enddate=startdate+6

    week=1
    df['week']=0
    df.reset_index(inplace=True)
    for counter, day in enumerate (df['temp_date']):
        if df['merchant_name'][counter]==current_merchant:
            if(df['temp_date'][counter])<=enddate:
                df.loc[counter,'week']=week
            else:
                enddate+=7
                week+=1
                df.loc[counter,'week']=week
        else:
            offset=list(week_offset.values())[df['DOW'][counter]]
            print(offset)
            current_merchant=df.loc[counter,'merchant_name']
            startdate=df.loc[counter,'temp_date']-(offset)
            enddate=startdate+6
            week=1
            df.loc[counter,'week']=week

    df.set_index('date',inplace=True)
    return df


texts:
I have wrote a program which prints sequence of numbers. But if number is divisible by 4 it prints x if divisible by 7 it prints y, if divisible by both 4 & 7 it prints xy otherwise it prints number.

var sequence_function = function () {
    var result_array = [],
        start = 1,
        limit = 10;

    for(i = start; i <= limit; i ++) {
        switch (true) {
            case (i % 4 === 0 && i % 7 === 0):
                result_array.push('xy');
                break;
            case (i % 4 === 0):
                result_array.push('x');
                break;
            case (i % 7 === 0):
                result_array.push('y');
                break;
            default:
                result_array.push(i);
                break;
        }
    }

    console.log(result_array.join(','));
};

So for limit 10 it gives output:

1,2,3,x,5,6,y,x,9,10

My question if how can i optimise this code? What is best thing to use here if else, switch, ternary operator or any other? Any suggestion will be helpful.


texts:
I'm teaching myself Ruby by rewriting PHP solutions, such as this one. The program should match words in a sentence with a dictionary of synonyms and then make combinations with them.

dict = {
    'hello' => ['hey', 'what\'s up'],
    'name' => ['nomenclature', 'epithet']
}

str = 'hello, my name is'

class SentenceMaker
    def initialize str, dict
        @thesaurus = []
        @template = str.gsub(/\w+/) {|match|
            if (dict[match])
                @thesaurus.push dict[match]
                '%%%d$s' % @thesaurus.length
            else
                match
            end
        }
    end

    def each
        @thesaurus.first.product(*@thesaurus.slice(1..-1)).each {|repl|
            yield @template % repl
        }
    end
end

SentenceMaker.new(str, dict).each {|sentence|
    puts sentence
}

Example output

hey, my nomenclature is
hey, my epithet is
what's up, my nomenclature is
what's up, my epithet is

Does this make enough use of the language expressions, or did I miss a few things?


texts:
I am working on a database migration tool, which should be database agnostic: https://github.com/adhesivee/database-migrator

When creating/updating a database the columns can have some optional parameters. This is how the API look like:

public interface Database {
    void createTable(String tableName, Collection<ColumnOptions> columnOptions);

    AlterTable alterTable(String tableName);

    boolean hasTable(String tableName);

    Connection getConnection();
}

And the ColumnOptions definition:

public class ColumnOptions {
    private final String columnName;
    private final Column.TYPE columnType;
    private final Boolean autoIncrement;
    private final Integer columnSize;
    private final String defaultValue;
    private final Boolean isNotNull;
    private final Boolean isPrimary;

    private ColumnOptions(Builder builder) {
        columnName = builder.getColumnName();
        columnType = builder.getColumnType();
        autoIncrement = builder.getAutoIncrement();
        columnSize = builder.getColumnSize();
        defaultValue = builder.getDefaultValue();
        isNotNull = builder.getNotNull();
        isPrimary = builder.getPrimary();
    }

    public String getColumnName() {
        return columnName;
    }

    public Column.TYPE getColumnType() {
        return columnType;
    }

    public Optional<Boolean> getAutoIncrement() {
        return Optional.ofNullable(autoIncrement);
    }

    public Optional<Integer> getColumnSize() {
        return Optional.ofNullable(columnSize);
    }

    public Optional<String> getDefaultValue() {
        return Optional.ofNullable(defaultValue);
    }

    public Optional<Boolean> getIsNotNull() {
        return Optional.ofNullable(isNotNull);
    }

    public Optional<Boolean> getIsPrimary() {
        return Optional.ofNullable(isPrimary);
    }

    public static class Builder {
        /** logic to build ColumnOptions */
    }
}

I tried to make it explicit by using Optional<>, but still I am curious if someone sees some improvments for this.


texts:
I'm using this code for checking if two List<T> are equal or not:

public static bool EqualsAll<T>(this IList<T> a, IList<T> b)
{
    if (a == null || b == null)
        return (a == null && b == null);

    if (a.Count != b.Count)
        return false;

    EqualityComparer<T> comparer = EqualityComparer<T>.Default;

    for (int i = 0; i < a.Count; i++)
    {
        if (!comparer.Equals(a[i], b[i]))
            return false;
    }

    return true;
}

Now assume that I'm using this code for checking two big lists. Is this code efficient?


texts:
PHP doesn't have a built-in functions for AES (specifically, AES-128) encoding/decoding, so I've had to implement my own, and this is what I have come up to (of course, taken from different many sources, mostly not coded by me).

My question is, are these correct? Not the code itself, but what they do. The correctness of the algorithm. I have tested them, and they apparently do work. But there might be a subtle error that I'm overlooking...

Encoding algorithm:

function aes128_encode($data, $mode)
{
        switch ($mode) {
        case "ECB":
        case "CBC":
            if ($mode === "ECB") {
                $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
            } else {
                $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            }

            $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND);
            $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher));

            if (mcrypt_generic_init($cipher, $key, $iv) != 1) {
                $cipherData = mcrypt_generic($cipher, $data);

                mcrypt_generic_deinit($cipher);
                mcrypt_module_close($cipher);

                if ($mode === "ECB") {
                    $sanitizedCipherData = trim(base64_encode($cipherData));
                } else {
                    $sanitizedCipherData = trim(base64_encode($iv)."_".base64_encode($cipherData));
                }

                return $sanitizedCipherData;
            } else {
                return false;
            }
            break;

        default:
            return false;
            break;
        }
    }

Decoding algorithm:

function aes128_decode($data, $mode)
{
    switch ($mode) {
    case "ECB":
        $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher));

        // Fake iv to call mcrypt_generic_init
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND);
        $cipherData = base64_decode($data);

        if (mcrypt_generic_init($cipher, $key, $iv) != -1) {
            $originalData = mdecrypt_generic($cipher, $cipherData);
            mcrypt_generic_deinit($cipher);
            mcrypt_module_close($cipher);

            return $originalData;
        } else {
            return false;
        }
        break;

    case "CBC":
        $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher));
        $parts = explode("_", $data);
        $iv = base64_decode($parts[0]);
        $cipherData = base64_decode($parts[1]);

        if (mcrypt_generic_init($cipher, $key, $iv) != -1) {
            $originalData = mdecrypt_generic($cipher, $cipherData);
            mcrypt_generic_deinit($cipher);
            mcrypt_module_close($cipher);

            return $originalData;
        } else {
            return false;
        }
        break;

    default:
        return false;
        break;
    }
}

NOTE: The $mode variable indicates which mode of operation will be used (ECB or CBC). The CIPHERKEY is a constant with a randomized value that should be only known by the admin of the website.


texts: Re-Ordering the draw order for my entities in my Isometric game

texts:
Introduction

I am making a 3D Isometric game. I have a Tower, filled with Block's in a 3D Tower map, which is made of nested ArrayList's, And Entity's which roam free in my game Not bound to a tile

I have no tile system in my game. To create my isometric projection, I use Graphics2D g2d.rotate() && g2d.scale().

I have a function with sorts my game objects  (Block's and Entity's) draw order. What I mean by this is the order in which they are drawn in my draw function. This is so I draw objects that are behind other objects, before the object they are behind. In order to stop images glitching through each other and the like.

Explanation

I have a function which is called at 60Hz, This function makes a new ArrayList and inserts my Entity's and Block's into this ArrayList.

My function then enters a for loop of the size of the ArrayList -1

In this loop, The function then proceeds to sort this ArrayList based on this expression

fx>=sx+sw || fx+fw<=sx-sz-sh || fy>=sy+sl || fy+fl<=sy-sz-sh || fz>=sz+sh

This expression simply says if the first object should be drawn infront of the second object, then swap these two objects around in the list. So that when it comes to drawing the objects, the first object is drawn after the second object.

Finally, the for loop runs its course, I then update the global drawList field so that my draw function can use it.

Question

What can I do optimise this code? More specifically, the expression and sorting of the draw list. Is there a better way to do this? A more concise and accurate expression? Mabye a non-reccursive method?

I call this function regually In my master update function so optimising this would greatly increase the greater preformance of my game.

Code

public void sortRenderOrder(){
    ArrayList<Object> drawObjects = new ArrayList<Object>();
    for (int e=0; e<entities.size();e++){
        Entity entity = entities.get(e);
        drawObjects.add(entity);
    }
    for (int h=0;h<tower.map.size();h++){
        for (int r=0;r<tower.map.get(h).size();r++){
            for (int c=0; c<tower.map.get(h).get(r).size();c++){
                Block block = tower.map.get(h).get(r).get(c);
                if (!(block.material.type.equals("air"))){
                    drawObjects.add(block);
                }
            }
        }
    }
    for (int i=0;i<drawObjects.size()-1;i++){
        int fx=0;int fy=0;int fz=0;int fw=0;int fl=0;int fh=0;String ft="";
        int sx=0;int sy=0;int sz=0;int sw=0;int sl=0;int sh=0;String st="";
        if (drawObjects.get(i) instanceof Entity){
            Entity e = (Entity)drawObjects.get(i);
            fx=e.d.x;fy=e.d.y;fz=e.d.z;fw=e.d.w;fl=e.d.h;fh=e.d.d;ft="entity";
        } else if (drawObjects.get(i) instanceof Block){
            Block b = (Block)drawObjects.get(i);
            fx=b.d.x;fy=b.d.y;fz=b.d.z;fw=b.d.w;fl=b.d.h;fh=b.d.d;ft="block";
        }
        if (drawObjects.get(i+1)instanceof Entity){
            Entity e = (Entity)drawObjects.get(i+1);
            sx=e.d.x;sy=e.d.y;sz=e.d.z;sw=e.d.w;sl=e.d.h;sh=e.d.d;st="entity";
        } else if (drawObjects.get(i+1) instanceof Block){
            Block b = (Block)drawObjects.get(i+1);
            sx=b.d.x;sy=b.d.y;sz=b.d.z;sw=b.d.w;sl=b.d.h;sh=b.d.d;st="block";
        }
        //
        if (!(st.equals("block") && ft.equals("block")) && (fx>=sx+sw || fx+fw<=sx-sz-sh || fy>=sy+sl || fy+fl<=sy-sz-sh || fz>=sz+sh)){
            Object temp = drawObjects.get(i);
            drawObjects.set(i, drawObjects.get(i+1));
            drawObjects.set(i+1, temp);
        }
    }
    drawList = drawObjects;
}

Thank you so much.


texts: Return the element of collection if the collection contains only one element

texts:
Recently I have found in my code several places where I was first gathering some solutions, and then continued processing them only if the solution was unique (solution collection contained only one element). Following code is an attempt to solve this in a more functional manner.

  implicit class GetOnlyOne[A](val coll: Iterable[A]) {
    def getonlyone = {
      if (coll.isEmpty) None
      else if (coll.tail.isEmpty) coll.headOption
      else None
    }
  }

The function can be used like:

Seq(1).getonlyone
Seq(1,2).getonlyone
Set(1).getonlyone

Is there anything missing to be idiomatic Scala, or to be more elegant?


texts:
This is my first MYSQL schema for caching location data (co-ordinates to place names) and referencing it with a country.

I was wondering what everyones feedback was on it, did I do a good job?

CREATE TABLE location (
id INT AUTO_INCREMENT PRIMARY KEY,
locality VARCHAR(20),
administrative_area_level_1 VARCHAR(20),
administrative_area_level_2 VARCHAR(20),
administrative_area_level_3 VARCHAR(20),
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17),
updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE country (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
iso VARCHAR(20),
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17),
updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);


texts:
This exercise involves taking an array of numbers and sorting them alphabetically. For example, [1,2,3,4] would return as [4,1,3,2]

I mapped the array first, returning an array of words, then sorted those words using Ruby's built-in sort function. Then, I mapped that array to return an array of integers.

It works, obviously. I want your suggestions and thoughts, different ideas and better ways I could do this in the future.

I know I could one-line the map functions, but thought this is better for readability. Example: alphabeticize = numbers.map {|num| alphas.fetch(:"#{num.to_s}")}.sort

def alphabetic_number_sort(numbers)
  alphas = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "10": "ten", "11": "eleven", "12": "twelve", "13": "thirteen", "14": "fourteen", "15": "fifteen", "16": "sixteen", "17": "seventeen", "18": "eighteen", "19": "nineteen"}

  alphabeticize = numbers.map do |num|
    alphas.fetch(:"#{num.to_s}")
  end.sort

  sorted_alphabetically = alphabeticize.map do |word|
    alphas.key(word).to_s.to_i
  end

  return sorted_alphabetically
end

p alphabetic_number_sort((0..19).to_a) == [
  8, 18, 11, 15, 5, 4, 14, 9, 19, 1, 7, 17,
  6, 16, 10, 13, 3, 12, 2, 0
]


texts:
I am solving the following problem:

  You are given two lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a list.

I wrote the following code:

let addTwoNumbers (a: int list) (b: int list) =
    let rec loop (a: int list) (b: int list) (c: int list) (carry: int) =
        match a, b, carry with
        | (h1::t1), (h2::t2), _ ->
            let q, r = Math.DivRem(h1 + h2 + carry, 10)
            loop t1 t2 (List.append c [r]) q
        | (h1::t1), [], _ ->
            let q, r = Math.DivRem(h1 + carry, 10)
            loop t1 [] (List.append c [r]) q
        | [], (h2::t2), _ ->
            let q, r = Math.DivRem(h2 + carry, 10)
            loop [] t2 (List.append c [r]) q
        | [], [], 0 ->
            c
        | [], [], carry ->
            let q, r = Math.DivRem(carry, 10)
            loop [] [] (List.append c [r]) q
    loop a b [] 0

Is there a way to simplify and possibly to de-duplicate some of this code?


texts: Speed up a program to find the minimum Hamming distance

texts:
I have a solution to the puzzle at https://kattis.csc.kth.se/problem?id=codes.
What can I do to make my algorithm much much faster? What the algorithm does is take an N×K matrix and search for the minimum distance — that is, the least number of 1 for all the products of the matrix and a vector that ranges from 00001 to 11111 (where the top is 2K - 1).

#include <iostream>

using namespace std;

void DataEntry(int &a, int &b, int** &matrix) {

    cin >> a >> b;

    matrix = new int*[a];

    for (int i = 0; i < a; i++) {
        matrix[i] = new int[b];
    }

    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            matrix[i][j] = -1;
            cin >> matrix[i][j];
        }
    }

}

int* BinaryAdd(int* a, int* b, int tam) {
    int* c;
    int ac = 0;
    c = new int[tam];

    for (int i = tam - 1; i > -1; i--) {
        c[i] = a[i] + b[i] + ac;
        if (c[i] == 2) {
            c[i] = 0;
            ac = 1;
        } else
            ac = 0;
    }

    return c;
}

int* MultiplyMatrices(int** a, int* b, int tamF, int tamC) {
    int * c;
    c = new int[tamF];
    for (int i = 0; i < tamF; i++) {
        c[i] = 0;
        for (int j = 0; j < tamC; j++) {
            c[i] = c[i] + (a[i][j] * b[j]);
            c[i] = c[i] % 2;
        }
    }
    return c;
}

int MinimumDistance(int* a, int tam) {
    int MD = 0;

    for (int i = 0; i < tam; i++) {
        if (a[i] == 1)
            MD++;
    }
    return MD;
}

int pot(int a, int b) {
    int c = 1;
    for (int i = 1; i < b + 1; i++) {
        c = a * c;
    }
    return c;
}

int main() {
    int t = 0, n = 0, k = 0, d = -1, max = -1;
    int ** lecc;
    int * pro;
    int * sal;
    int * sol;
    int * zero;
    int * uno;
    int * pro1;

    cin >> t;

    for (int p = 0; p < t; p++) {

        DataEntry(n, k, lecc);

        pro = new int[k];
        uno = new int[k];
        sal = new int[n];
        zero = new int[n];

        for (int i = 0; i < k; i++) {
            pro[i] = 0;
        }
        for (int i = 0; i < k - 1; i++) {
            uno[i] = 0;
        }
        uno[k - 1] = 1;

        for (int i = 0; i < n; i++) {
            zero[i] = 0;
        }

        pro1 = BinaryAdd(pro, uno, k);

        pro = pro1;

        max = pot(2, k);

        sal = MultiplyMatrices(lecc, pro, n, k);

        d = MinimumDistance(sal, n);

        for (int i = 0; i < max - 1; i++) {

            sal = MultiplyMatrices(lecc, pro, n, k);

            pro1 = BinaryAdd(pro, uno, k);

            pro = pro1;

            int ad = MinimumDistance(sal, n);

            if (ad < d)
                d = ad;
        }
        cout << d << endl;
    }

}

Edit: I give you a sample input and output

Sample input     Sample output
2
7 4
1 0 0 0
0 1 0 0
0 0 1 0           3
0 0 0 1           0
0 1 1 1
1 0 1 1
1 1 0 1
3 2
1 1
0 0
1 1


texts: improvements to this php function to calculate monthly returns from a set of price data

texts:
I have made this function that should take a set of price data and calculate a set of monthly returns. The idea is that is should be able to cope with irregular time intervals.
For example I have daily data for the S&P 500 but many hedge funds only release price data monthly.

Here is what I have come up with:

//Turns a price series into an array of monthly returns.
function monthlyReturns($dates, $prices, $startDate = "", $endDate = ""){
if ($endDate == "") $endDate = time();

if (count($dates) != count($prices)){
die("The dates array must be the same length as the prices array");
}
$i = 0; $firstPass = false;
foreach ($dates as $date){
  $d = strtotime($date);
  if ($startDate == "" || ($d >= $startDate && $d <= $endDate )) :
    $p = $prices[$i];
    $month = date('M',$d);
    $year = date('Y',$d);

    if ($i == 0 || $firstPass == false){
      $startPrice = $p;
      $lastMonth = $month;
    }

    if ($month != $lastMonth && $i != 0){
      $returnTable['date'][] = $dates[$i-1];
      $returnTable['return'][] = $p / $startPrice - 1;
      $startPrice = $p;
    }
    $lastMonth = $month;
    $firstPass = true;
  endif;
  $i++;
  }
  return $returnTable;
}

I noticed that for a fund with only monthly data the returns are off by a month. Can anyone see any major flaws with this function that could explain this or a solution to solve it.

For info, the monthly returns for hedge funds often come near the end of the month. E.g.

date       | Price
-----------------
2013-01-29 | 25.69
2013-02-28 | 27.62
2013-03-30 | 26.53
2013-04-29 | 28.45


texts:
I wrote a small script to manipulate fields of a file based on the input of a user. Is there something I could've done better, or perhaps a better refactor? I do know however that I need a way to validate for empty fields.

view_column() {
  for i in "$file_name"; do
    cat "$i" | awk -v col="$1" '{ print $col }'
  done
}

print_menu() {
  menu=( 'First' 'Last' 'Email' 'Exit' )
  for (( i=0; i<${#menu[@]}; i++ )); do
    printf "%2d. %s\n" "$((i+1))" "${menu[$i]}"
  done
}

main() {
  while true; do
    clear
    print_menu
    read -p 'Enter a choice: ' choice
    if (( "$choice" == 4 )); then
      break
    fi
    view_column "$choice"
    sleep 1.5
  done
}


texts:
I had implemented a simple Linked list Insert, print and insert at the nth position. It works fine.
Could someone review code and let me know where I could have done better (or) where I had gone wrong?

class Linkedlist
     {
       public Nodes current;
       public static Nodes headnode;
       public static int nodecount;
       public void Addatfirst(object d)
      {

          if (headnode == null)
          {
              headnode = new Nodes(d);
              nodecount++;
           }
          else
          {
              Nodes dummy = new Nodes(d);
              dummy.Next = headnode;
              headnode = dummy;
              nodecount++;
           }
         }

     public void Print()
    {
        current = headnode;

        while (current.Next != null)
        {
            Console.Write("|" + current.data + "| -> ");
            current = current.Next;
            if (current.Next == null)
            {
                Console.Write("|" + current.data + "| -> ");
            }
        }
    }

    public void AddatLast(object d)
    {
        current = headnode;
        while (current.Next != null)
        {
            current = current.Next;
            if (current.Next == null)
            {
                current.Next = new Nodes(d);
                nodecount++;
                return;
            }
        }
    }

    public void AddatNthPosition(object d, int position)
    {
        current = headnode;
        for (int i = 1; i < position; i++)
        {
            current = current.Next;
            if (position - i == 1)
            {
                var temp= new Nodes(d);
                temp.Next = current.Next;
                current.Next = temp;
            }
        }
    }
}
public class Nodes
{
    public object data;
    public Nodes Next;
    public Nodes(object d)
    {
        data = d;
    }
}


texts:
Use Case

_.pick creates a shallow clone of an object given a predicate that identifies which keys to keep. pickDeep would perform a deep clone of the object and would "pick" up all nested objects containing the given keys. All containers containing the nested objects would remain and would not be removed.

Requirements

Recursively apply a pick to each level in an object.
If a property is an object/array, then apply a pick.
Keep all object/array only if the descendant properties fulfill the pick.

Improvements

I'd like any constructive criticism to improve this code, but I'm mainly interested in advice pertaining to:

Readability
Flexibility
Performance
Implementing this with _.pick and _.cloneDeep

Function

(jsfiddle)

function pickDeep(collection, identity, thisArg) {
    var picked = _.pick(collection, identity, thisArg);
    var collections = _.pick(collection, _.isObject, thisArg);

    _.each(collections, function(item, key, collection) {
        var object;
        if (_.isArray(item)) {
            object = _.reduce(item, function(result, value) {
                var picked = pickDeep(value, identity, thisArg);
                if (!_.isEmpty(picked)) {
                    result.push(picked);
                }
                return result;
            }, []);
        } else {
            object = pickDeep(item, identity, thisArg);
        }

        if (!_.isEmpty(object)) {
            picked[key] = object;
        }

    });

    return picked;
}

Test Data

var data = {
    a: 5,
    b: 6,
    c: 7,
    d: {
        a: 65,
        z: 6,
        d: {
            a: 65,
            k: 5
        }
    },
    e: [
        {a : 5},
        {b : 6},
        {c : 7}
    ],
    f: [
        {
            b : [  { a: 5, z: 5 } ],
            c : 6
        },
        {
            g: 0
        }
    ]
};

Test Cases

var testCase1 = { a: 5, b: 6};
pickDeep(testCase1, 'a'); // {a : 5}
var testCase2 = { a: 5, b: { a: 1}, c: { b: 3}};
pickDeep(testCase2, 'a'); // {a: 5, b: {a: 1}}
var testCase3 = { a: 5, b: [ { a: 1}, { c: 2}, {d: 3} ], c: [ {c: 2}, {d : 3}]}
pickDeep(testCase3, 'a'); //{ a: 5, b: [ {a: 1} ]}
var testCase4 = [ {a: 5}, {b: 2}, {c: {a :3 }}, {d: [ {a: 4}] }, z: [ { f: 34}] ];
pickDeep(testCase4, 'a'); // [ {a:5}, {c: {a:3}}, {d: [ {a:4}]}];

Execution Code

function isIn(collection) {
    return function(value, key) {
        return _.contains(collection, key);
    }
}

console.log(pickDeep(data, isIn(['a', 'c'])));


texts: Excel VBA counting total-of-rows written on current day

texts:
On my work I maintain an Excel-sheet which contains information about the incident-tickets I've processed.

I've enhanced the sheet with some VBA-code which I use the following way:
In the beginning of the work shift I start a new section by entering the current date into the first column. The date has the format 'dd.mm.yyyy'.

I've defined a key-combination via the Excel-GUI which invokes the VBA-subprocedure.
Means: Pressing the key-combination shows the count of incidents, finished on the current day, via a message-box.

Here's a screenshot how the Excel-sheet looks:

Here's my code:

Public Sub CalcTotalOfTodaysIncidents()
    Dim TodayString As String
    Dim currentRow As Integer
    Dim TotalOfToday As Integer
    Dim Icon As VbMsgBoxStyle
    Dim maxRows As Long

    On Error GoTo GeneralErrorHandler

    TodayString = CDate(Date)
    currentRow = 2
    TotalOfToday = 0

    maxRows = Worksheets("Tickets").UsedRange.Rows.Count

    While (Cells(currentRow, 1).Value <> TodayString)
        currentRow = currentRow + 1

        If currentRow = maxRows Then
            GoTo NoDateFoundHandler
        End If
    Wend

    While (Cells(currentRow, 3).Value <> "")
        TotalOfToday = TotalOfToday + 1
        currentRow = currentRow + 1
    Wend

    If TotalOfToday < 10 Then
        Icon = vbCritical
    ElseIf TotalOfToday < 26 Then
        Icon = vbExclamation
    Else
        Icon = vbInformation
    End If

    MsgBox TodayString & ": " & TotalOfToday & " Incidents processed." _
        , Icon, "Incidents Processed Info"

    Exit Sub

NoDateFoundHandler:
    MsgBox "Have you entered the date of today into the first column?" _
        & vbCrLf & "Format required: dd.mm.yyyy", _
        vbCritical, _
        "Today's date couldn't be found!"
    Exit Sub

GeneralErrorHandler:
    MsgBox "Error has occured.", _
        vbCritical, _
        "Sub CorrectCellFormat"
    Exit Sub
End Sub

That's surely not great programming. But I use it already for a few months and it works for me.

But how could it be improved so that it becomes more general?

So that it could be given to colleagues which use Excel-sheets. This sheets are similar to mine but not exactly the same. Everyone has made his/her own.

Any other comments, hints and tipps concerning coding style, structure, error handling etc. appreciated too.


texts: Does this usage of AtomicLong look thread-safe?

texts:
I wanted to ensure that lastActivityTime is always the "latest" value based on current time, but I wonder if my "update" method is thread-safe? If it's not, what's a better solution besides just throwing "synchronized" around.

import java.util.concurrent.atomic.AtomicLong;

public class Widget {

    private AtomicLong lastActivityTime = new AtomicLong();

    public long getLastActivityTime() {
        return lastActivityTime.get();
    }

    public void update() {
        long now = System.currentTimeMillis();

        if (getLastActivityTime() < now) {
            lastActivityTime.set(now);
        }
    }

}


texts:
I'd like to read a line from stdin, excluding the newline character. I've written the function:
/* read in a line from stdin, NULL on failure
 * does not include trailing newline
 */
char*
readStdinLine() {
        char* buffer;
        size_t bufsize = 32;
        size_t characters;

        buffer = (char *) malloc(bufsize * sizeof(char));
        if (buffer == NULL)
                return NULL;

        characters = getline(&buffer, &bufsize, stdin);
        buffer[--characters] = '\0';

        char* text = (char *) malloc(characters);
        for (int i = 0; i < characters + 1; i++) {
                text[i] = buffer[i];
        }

        free(buffer);

        return text;
}

This seems inneficient, I'm essentially reading in the line twice, once in getline and once to remove the trailing newline. That doesn't seem like the most memory-efficient algorithm, and I would like to remove the newline without copying, if that is at all possible.
I'm very new to C (have used C++, Java, etc, but never a systems language without objects) so I would appreciate learning all the code style things I've done wrong as well. Thanks!


texts:
def is_prime(n):
    if n % 2 == 0 and n > 2:
        return False
    return all(n % i for i in xrange(3, int(math.sqrt(n)) + 1, 2))

The code works fine for a range of numbers after that it shows:

OverflowError: Python int too large to convert to C long

How can my code be made faster and more efficient?


texts:
I'm very new to python, however not new to programming as I've been doing C for some time.

So here is my practice of a merge sort, I looked at other questions however they were many more lines compared to mine. Which leaves me to believe I'm doing something wrong.

I come here to look for best practices in python, and I mean the best of the best. I want to know all the little details! Most importantly if there is anyway to shorten code without sacrificing efficiency.

#!/usr/bin/python

def merge_sort(array):
    ret = []
    if( len(array) == 1):
        return array;
    half  = len(array) / 2
    lower = merge_sort(array[:half])
    upper = merge_sort(array[half:])
    lower_len = len(lower)
    upper_len = len(upper)
    i = 0
    j = 0
    while i != lower_len or j != upper_len:
        if( i != lower_len and (j == upper_len or lower[i] < upper[j])):
            ret.append(lower[i])
            i += 1
        else:
            ret.append(upper[j])
            j += 1

    return ret

array = [4, 2, 3, 8, 8, 43, 6,1, 0]
ar = merge_sort(array)
print " ".join(str(x) for x in ar)
#>>> 0 1 2 3 4 6 8 8 43

Thanks CR.


texts: Dynamic Programming for printing additive numbers up to digits n

texts:
Edit: I am hoping to get some review / make sure I am understanding dynamic programming correctly.

I am trying to print out all additive numbers up to digits n using dynamic programming.  Additive numbers are those like 123, 1235, etc., where the sum of every 2 digits from left to right is equal to the third digit.  In this definition, non-trivial additive numbers must necessarily be at least 3 digits long, though for numbers of 2 digits or less one could trivially print out all digits 0-99.  Furthermore, this definition implies the set of additive numbers is finite and relatively tiny.

If there is a better definition of an additive number or I have misunderstood it, feel free to point out.

I believe dynamic programming is a good approach to this problem, because the solutions of n - 1 need to be re-used to compute the solutions to n.  A brute force algorithm is possible, but I think far more inefficient.

Here is my solution in Python.  It will print them all out and also return the trellis that contains the solutions for each digit.  Note that for n >= 9, there are no more additive numbers.

# -*- coding: utf-8 -*-

"""Dynamic programming
"""

BASE_CASE = 3

def print_additive_numbers(n=BASE_CASE):
    """Prints all additive numbers up to n digits

    Additive numbers are numbers of the form 123, 1235, etc.
    where the sum of every 2 digits is equal to the third digit
    in the digit expansion of the number.

    We use dynamic programming to iteratively generate
    additive numbers for increasing digits, as the solutions to
    n = 3 are re-used for n = 4, n = 5, etc.

    Args:
        n: the maximum number of digits for each representation

    Returns:
        A dictionary mapping each number of digits to all
        possible additive numbers.

    """
    if n < BASE_CASE:
        raise ValueError, "additive numbers always have 3 or more digits"
    #build the initial trellis
    trellis = {}
    trellis[BASE_CASE] = {}
    for i in xrange(1, 9):
        row = []
        for j in xrange(0, 9):
            if i + j <= 9:
                print str(i) + str(j) + str(i + j)
                row.append(str(j) + str(i + j))
        trellis[BASE_CASE][i] = row
    for m in xrange(BASE_CASE + 1, n + 1):
        trellis[m] = {}
        for key in trellis[m - 1].keys():
            row = []
            for digits in trellis[m - 1][key]:
                first_digit = int(digits[-2])
                second_digit = int(digits[-1])
                new_digit = first_digit + second_digit
                if new_digit <= 9:
                    row.append(digits + str(new_digit))
                    print str(key) + digits + str(new_digit)
            trellis[m][key] = row
    return trellis

t = print_additive_numbers(9)


texts: Hackerrank "Breaking the Record" solution

texts:
I have solved the hacker rank problem listed here. Given a sequence of scores, I need to count the number of times the records for the high and low scores have been broken.

Easiest way for me was to iterate the input for find the answer but i guess that would have meant O(n) complexity, so I thought of solving the problem using divide and conquer approach hoping it would reduce the complexity of the solution.

I have implemented the solution and it is working, but I am not sure whether I can reduce the complexity. Can you please review the code and provide feedback?

private static int minScore, maxScore;

static int[] breakingRecords(int[] score) {
    int firstScore = score[0];
    int[] result = new int[2];
    minScore = maxScore = firstScore;
    count(score,1, score.length - 1, result);

    return result;
}

private static void count(int[] scores, int start, int end, int[] result) {
    if(start == end || end < start) {
        int score = scores[start];
        if(score > maxScore) {
            maxScore = score;
            result[0] = result[0] + 1;
        } else if(score < minScore) {
            minScore = score;
            result[1] = result[1] + 1;
        }
        return;
    }

    int partition = (end + start) / 2;

    count(scores, start, partition, result);
    count(scores,partition + 1, end, result);

}


texts: Generating permutation of indices from seed ID

texts:
In my OpenCL kernel, I have the following logic:

size_t id = get_global_id(0);
uchar index0 = (id / 32760) % 16;
uchar index1 = (id / 2184) % 15;
uchar index2 = (id / 156) % 14;
uchar index3 = (id / 12) % 13;
uchar index4 = (id / 1) % 12;

if (index1 >= index0)
    ++index1;

if(index2 >= index0 ||
   index2 >= index1)
    ++index2;
if(index2 >= index1 && index2 >= index0)
    ++index2;

if(index3 >= index0 ||
   index3 >= index1 ||
   index3 >= index2)
    ++index3;
if(index3 >= index0 && index3 >= index1 ||
   index3 >= index1 && index3 >= index2 ||
   index3 >= index2 && index3 >= index0)
    ++index3;
if(index3 >= index0 && index3 >= index1 && index3 >= index2)
    ++index3;

if(index4 >= index0 ||
   index4 >= index1 ||
   index4 >= index2 ||
   index4 >= index3)
    ++index4;
if(index4 >= index0 && index4 >= index1 ||
   index4 >= index0 && index4 >= index2 ||
   index4 >= index0 && index4 >= index3 ||
   index4 >= index1 && index4 >= index2 ||
   index4 >= index1 && index4 >= index3 ||
   index4 >= index2 && index4 >= index3)
    ++index4;
if(index4 >= index0 && index4 >= index1 && index4 >= index2 ||
   index4 >= index1 && index4 >= index2 && index4 >= index3 ||
   index4 >= index2 && index4 >= index3 && index4 >= index0 ||
   index4 >= index3 && index4 >= index0 && index4 >= index1)
    ++index4;
if(index4 >= index0 && index4 >= index1 && index4 >= index2 && index4 >= index3)
    ++index4;

Now, in my testing, I've verified that this logic is correct and applies correct behavior to my variables. However, it is extremely cumbersome to read and maintain, and I'm looking for a way to optimize it such that it's much easier to read and understand. How can I rewrite this logic so that it's much easier to read, and possibly faster to execute?

The intent of this code is to take an input integer in the range [0, 16*15*14*13*12), and convert it into a permutation of 5 unique indices ranged [0,16). Like I said, this code works, but it's very confusing to read.

There are a few restrictions:

No Recursion. I'm aware that most OpenCL compilers will allow limited degrees of recursion by in-lining away recursive function calls, but I want this code to be as portable as possible, and that means adhering to the specifications set by the Official OpenCL spec.
Readability is more important than speed. Obviously, getting the algorithm faster would be ideal, but what I really care about is making this code less cumbersome to maintain, particularly if I expand it to add more variables to this algorithm.
I have limited access to OOP related functionality. This is OpenCL, so anything object-oriented needs to be compatible with OpenCL 2.0.


texts: jQuery function to display an alert when submitting blank fields

texts:
I am new to jquery and implemented following function in a js file in case of error-

function before_submit_check_if_has_blank_field() {
    $("[type=submit]").click(function(e) {
        var of_key_field = $('.key_field')
        var of_val_field = $('.val_field')
        var should_run = 1

        if (of_key_field.length === 1) {
            $('.key_field:not(:first)').filter(function() {
                if (this.value === "") {
                    alert('Please Fill In Or Remove The Blank Fields First')
                    e.preventDefault();
                    should_run = 0
                }
            });
        } else {
            $('.key_field').filter(function() {
                if (this.value === "") {
                    alert('Please Fill In Or Remove The Blank Fields First')
                    e.preventDefault();
                    should_run = 0
                }
            });
        }

        if (should_run != 0) {
            if (of_val_field.length === 1) {
                $('.val_field:not(:first)').filter(function() {
                    if (this.value === "") {
                        alert('Please Fill In Or Remove The Blank Fields First')
                        e.preventDefault();
                        should_run = 0
                    }
                });
            } else {
                $('.val_field').filter(function() {
                    if (this.value === "") {
                        alert('Please Fill In Or Remove The Blank Fields First')
                        e.preventDefault();
                        should_run = 0
                    }
                });
            }
        }

        update_config_field_from_key_value_field()
    });
}

The above code snippet is a part of my jquery where I am displaying a layout to the user with some fields and once those fields are empty then I am showing alert message while saving the form.

In above function I am repeating following lines of alert message which must be replaced by standard one-

if (this.value === "") {
    alert('Please Fill In Or Remove The Blank Fields First')
    e.preventDefault();
    should_run = 0
}

Can anyone please review my code and refactor it?


texts:
There are a lot of numerical properties to be invoked many times with an expensive calculation. Let’s say for the sake of example, they expose a Factorial:

public class Analysis
{
    public double n10 => F(10);
    public double n100 => F(100);
    double F(int n) =>
        n <= 1 ? 1 : n * F(n-1);
}

I was looking for a way to cache them while keeping syntax clean, so property calculation logic will not intermix with caching. A proposed solution is:

public class Analysis
{
    public double n10 => this.Cached() || F(10);
    public double n100 => this.Cached() || F(100);
    double F(int n) =>
        n <= 1 ? 1 : n * F(n-1);
}

Where library code is:

public static class Caching
{
    static ConditionalWeakTable<object, Dictionary<string, double>> Values { get; } =
        new ConditionalWeakTable<object, Dictionary<string, double>>();

    public static Value Cached(this object target, [CallerMemberName] string name = null) =>
        Values.GetOrCreateValue(target).ContainsKey(name) ?
            new Value(() => Values.GetOrCreateValue(target)[name], null) :
            new Value(null, v => Values.GetOrCreateValue(target)[name] = v);
}

And:

public class Value
{
    public static implicit operator Value(double value) => new Value(() => value, null);
    public static implicit operator double(Value value) => value.Getter();
    public static bool operator true(Value value) => value.Getter != null;
    public static bool operator false(Value value) => value.Getter == null;

    public static Value operator |(Value cached, Value computed)
    {
        cached.Setter(computed);
        return computed;
    }

    public Value(Func<double> getter, Action<double> setter)
    {
        Getter = getter;
        Setter = setter;
    }

    Func<double> Getter { get; }
    Action<double> Setter { get; }
}


texts:
I was asked to complete a coding challenge for an interview. The challenge being to write a test function to check whether or not a string was a broken record. A broken record is defined as a string that contains a sequential repeated substrings. For example:

# These are broken records
"This is is a broken record"
"This is a is a broken record"
"This is a broken record. This is a broken record."

# These are not broken records
"This is not is a broken record"
"This is a is This"
"This is a broken record. This is not a broken record."

This is the code that I was able to come up with (Python 2.7). Any criticisms, improvements, or suggestions are greatly appreciated.

# Author: Jeremiah Zucker
# brokenRecord.py
# A small module to test whether a substring is repeated
# immediately, like a broken record

def brokenRecord(sent):
   if sent == "": # Use defualt string if empty
      sent = "This is a a is This"
   print("Determining if broken record: %s" % sent)

   arr = sent.split(" ")

   # Create count array for the sentence
   carr = [0] * len(arr)
   for i in range(0,len(arr)):
      carr[i] = arr.count(arr[i])

   # For each element in the array, try to find the
   # repeat if one is possible
   for i in range(0,len(arr)):
      if carr[i] > 1 and findRepeat(arr, i):
         print("Is a broken record at %d!" % i)
         return
   print("Not a broken record.")

def findRepeat(arr, i):
   beg = arr[i]
   j = i

   # Find all other indices of 'beg'
   others = []
   while beg in arr[j+1:]:
      j = arr[j+1:].index(beg) + j + 1
      others.append(j)

   # For all other indices of 'beg'
   for j in others:
      # Get both substrings
      lenRep = j - i
      try:
         rep = arr[i:j]
         rep2 = arr[j:j+lenRep]
      except IndexError:
         continue

      # Are they equal?
      if rep == rep2:
         # print(rep)
         # print(rep2)
         return True

   # Nope
   return False

if __name__ == '__main__':
   # print usage
   print("brokenRecord.py")
   print("To use, type a string and hit ENTER.")
   print("If no string is provided, the default string will be used.")

   # do until ctrl+c
   while True:
      try:
         brokenRecord(raw_input("\nString: "))
      except KeyboardInterrupt:
         print("\nThanks for testing!")
         break


texts: Triangle style output, incrementing max line length


texts:
I've written the following Bash script used to duplicate a webapp/website you have (say, a Wordpress website) locally on your server environment, for testing purposes, indicating after 2 days if you have yet to delete it after you've finished your testing.

Here's the code:

cat <<-'DWA' > /opt/dwa.sh
    #!/bin/bash
    DWA() {
        tiesto='tiesto'
        read domain
        find /var/www/html ${domain} -exec cp ${domain} ${tiesto} {} \;
        sed -i 's/${domain}/${tiesto}'/g /var/www/html/tiesto/wp-config
        sed -i 's/${domain}/${tiesto}'/g /var/www/html/tiesto/wp-config
        mysql -u root -p << MYSQL
            create user '${tiesto}'@'localhost' identified by '${psw}';
            create database ${tiesto};
            GRANT ALL PRIVILEGES ON ${tiesto}.* TO ${tiesto}@localhost;
        MYSQL
        sleep 2d
        echo "If you haven't already, eliminate tiesto (dir & db)."
        tmux kill-session
    }
    DWA
DWA
chmod +x /opt/dwa.sh && cat >> /etc/bash.bashrc <<< "alias dwa='tmux new-session -d bash /opt/dwa.sh'"

After a reboot (due to the added alias), run it by the alias + an argument to indicate the app you're working on.

For example, if you named the app/site as example.com (I assume you named the site's dir, the DB user, and the DB instance the same), execute this in Bash:

dwa example.com

The webapp/site should be duplicated.

I would appreciate your review.


texts:
The code takes a very simple xml and converts it into a dataframe in csv file.

This is the Xml file

<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Phones>
    <Date />
    <Prog />
    <Box />
    <Feature />
    <WIN>MAFWDS</WIN>
    <Set>234234</Set>
    <Pr>23423</Pr>
    <Number>afasfhrtv</Number>
    <Simple>dfasd</Simple>
    <Nr />
    <gt>6070106091</gt>
    <Reno>1233</Reno>
    <QW>3234</QW>
    <ER />
    <VR />
    <Use />
    <Dar>sdfsd</Dar>
    <age />
    <name1>sdfsfdfs</name1>
    <Sys>IVECO E.A.SY.</Sys>
    <aac>2019-05-29</aac>
    <time>02:00</time>
    <nuk name="This is some text" text_g="asadsdas" text_h="2">fsdfsfd3432fdf</nuk>
  </Phones>

</Data>

This is my code.
It works, it just gets way too long when I want to include all the children of the father phones.
Looking for some help on how to shorter the code but it performing the same purpose.

This is the code

import xml.etree.cElementTree as et
import pandas as pd

df = pd.DataFrame()

def getvalueofnode(node):
    """ return node text or None """
    return node.text if node is not None else None

def main():
    """ main """
    parsed_xml = et.parse("short.xml")
    dfcols = ['Date', 'Prog', 'Box', 'Feature', 'WIN']
    df_xml = pd.DataFrame(columns=dfcols)

    for node in parsed_xml.findall('Phones'):
        Date = node.find("Date")
        Prog = node.find('Prog')
        Box = node.find('Box')
        Feature = node.find('Feature')
        WIN = node.find('WIN')

        df = df_xml.append(
            pd.Series([getvalueofnode(Date), getvalueofnode(Prog), getvalueofnode(Box),
                       getvalueofnode(Feature), getvalueofnode(WIN)],  index=dfcols),
            ignore_index=True)

    df.to_csv("./export.csv")

main()

This is all the columns declared fro dfcols

dfcols = ['Date', 'Prog', 'Box', 'Feature', 'WIN',
          'Set', 'Pr', 'Number','Simple','Nr',
          'gt', 'Reno','QW', 'ER','VR', 'Use',
          'Dar','age','name1', 'Sys' 'aac',
          'time', 'nuk']

Additional

The element nuk has multiple attributes so each attributes gets its own column
Example

nuk_name, nuk_text_g, nuk_text_h