texts: Generic wrapper with variable number of arguments

texts:
I had to write a generic wrapper that enables me to pass variable number of arguments for execution of some methods and repeat it up to a few times when it fails because of network connection problems.

What I came up is this class and a helper method. Well I can't say it's perfect - it is sufficient for my need, but is there anything that I could have done better ?

The main idea is behind command class

public abstract class Command<R, A1, A2, A3> {

    protected final SomeService someService;
    private Bundle<A1, A2, A3> bundle;

    public Command(SomeService someService) {
        this.someService = someService;
    }

    public void setBundle(Bundle<A1, A2, A3> bundle) {
        this.bundle = bundle;
    }

    public Bundle<A1, A2, A3> getBundle() {
        return bundle;
    }

    public abstract R execute(Bundle<A1, A2, A3> bundle) throws Exception;
}

I have to implement an execute method, which holds some logic which will be performed during runtime of the application. But, it may take up to three arguments and return any type.

An auxiliary class that helps to pass arguments to the Command class is the Bundle class.

public class Bundle<A1, A2, A3> {
    A1 arg1;
    A2 arg2;
    A3 arg3;

    public Bundle(A1 arg1, A2 arg2, A3 arg3) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
    }

    public A1 getArg1() {
        return arg1;
    }

    public A2 getArg2() {
        return arg2;
    }

    public A3 getArg3() {
        return arg3;
    }

    public static <T1> Bundle<T1, Void, Void> bundleOf(T1 arg1) {
        return new Bundle<>(arg1, null, null);
    }

    public static <T1, T2> Bundle<T1, T2, Void> bundleOf(T1 arg1, T2 arg2) {
        return new Bundle<>(arg1, arg2, null);
    }

    public static <T1, T2, T3> Bundle<T1, T2, T3> bundleOf(T1 arg1, T2 arg2, T3 arg3) {
        return new Bundle<>(arg1, arg2, arg3);
    }
}

It creates a generic parameter container that is passed to the Commands
execute method.

Finally, the method that we currently need, must repeat some operation up to three times (because of often disconnects), so I came up with this methods based on some SO questions:

private <R, A1, A2, A3> R executeCommand(Command<R, A1, A2, A3> command) {
    R result = null;
    for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
        try {
            return command.execute(command.getBundle());
        } catch (Exception e) {
            logger.error("Exception during performing operation, retrying for the " + attempt + " time", e);
            sleepForNMinutes(attempt);
            loginToApp();
        }
    }
    return result;
}

Instantation of the Command class:

Command<Person, String, Void, Void> retrievePersonByNetwork;

retrievePersonByNetwork= new Command<Person, String, Void, Void>(someService) {
    public Person execute(Bundle<String, Void, Void> bundle) throws Exception {
        return this.someService.retrievePerson(bundle.getArg1());
    }
};

Execution:

Bundle<String, Void, Void> bundle = Bundle.bundleOf("userName");
retrievePersonByNetwork.setBundle(bundle);
Person person = executeCommand(retrievePersonByNetwork);


texts: Function that transforms input file based on a numpy poly1d function

texts:
I have written a function that gets a function as input (acquired from numpy.poly1d). The function has access to the GUI variables self.batch and self.inputFile, these variables specify if the function is called in batch mode or not and what the current inputFile (for transformation is).

My main concerns are:

Would you understand the function based on my documentation?
Is vectorizing only the values to be transformed correct?
Is the function in general correct (meaning pythonic?)

The function:

def transformFile(self, f):
    """ This function gets a single function as input, reads the
    raw data file and transforms the read m/z values in the raw data
    file with the given function. The transformed m/z values are
    stored in a calibrated_<inputfile>.xy file (if program is running
    in batchProcess mode) or asks the user for a filepath to save
    the calibrated file (if program is running in single spectrum mode).

    INPUT: a numpy polynomial (poly1d) function
    OUTPUT: a calibrated data file
    """
    # Prepare variables required for transformation
    outputBatch = []
    mzList = []
    intList = []
    with open (self.inputFile,'r') as fr:
        if self.batch == False:
            output = tkFileDialog.asksaveasfilename()
            if output:
                pass
            else:
                tkMessageBox.showinfo("File Error","No output file selected")
                return
        else:
            parts = os.path.split(str(self.inputFile))
            output = "calibrated_"+str(parts[-1])
        if self.log == True:
            with open('MassyTools.log','a') as fw:
                fw.write(str(datetime.now())+"\tWriting output file: "+output+"\n")
        for line in fr:
            line = line.rstrip('\n')
            values = line.split()
            mzList.append(float(values[0]))
            intList.append(int(values[1]))
        # Transform python list into numpy array
        mzArray = numpy.array(mzList)
        newArray = f(mzArray)
        # Prepare the output as a list
        for index, i in enumerate(newArray):
            outputBatch.append(str(i)+" "+str(intList[index])+"\n")
        # Join the output list elements
        joinedOutput = ''.join(outputBatch)
        with open(output,'w') as fw:
            fw.write(joinedOutput)
        if self.log == True:
            with open('MassyTools.log','a') as fw:
                fw.write(str(datetime.now())+"\tFinished writing output file: "+output+"\n")


texts:
Here is a small project to implement a basic shell. It is a personal ongoing project to keep system call usage fresh. It currently does background processes and some basic signal handling.

I am actually looking for code feedback in regards to professionalism. I want to know if my code is clear and easy to understand. I know my main function is currently doing too much and that I will handle in the short future.

/*
Description: This is a light implementation of a Linux shell
*/

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAX_LEN 4096
#define MAX_ARGS 256

struct proc_st {
    int bg;
    int exec;
    int commc;
    int fd_out;
    int fd_in;
    pid_t pid;
    char pbuff[MAX_LEN];
    char *commv[];
};

/* function prototypes */
void error_msg(char *);
void sig_handler(int);
void comm_identi(struct proc_st *, char *);

int main()
{
    struct proc_st *proc;
    char buff[MAX_LEN];
    pid_t pid;
    int status;

    /* initialize signal handlers */
    signal(SIGINT, SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGCHLD, sig_handler);

    printf("[SHELL]> ");
    for (;;) {

        while (fgets(buff, MAX_LEN, stdin) != NULL) {

            proc = malloc(sizeof(struct proc_st) + MAX_ARGS);

            /*initialize to zero */
            memset(proc, 0, sizeof(struct proc_st));
            proc->exec = 1;
            comm_identi(proc, buff);

            if (proc->exec == 1) {
                if ((pid = fork()) < 0 ) {
                    printf("fork error");
                } else if (pid == 0) { /* child */
                    if (execvp(*(proc->commv),
                        proc->commv) < 0 )
                        error_msg("could not execute");
                    free(proc);
                }

                /* parent */
                if (proc->bg == 0) {
                    if ((pid = waitpid(pid, &status, 0))
                            < 0)
                        error_msg("waitpid error");
                } else
                    printf("PID %d %s\n", pid, proc->pbuff);
            }
            free(proc);
            printf("[SHELL]> ");
        }
    }
    exit(0);
}

void sig_handler(int signal)
{
    pid_t pid;

    while ((pid = waitpid(-1, NULL, WNOHANG | WUNTRACED)) > 0) {
        printf("Child Process [%d]: Terminated", (int)pid);
    }
    if (errno != ECHILD)
        error_msg("waitpid() error");
}

void error_msg(char * msg)
{
    fprintf(stderr, "%s: %s\n", msg, strerror(errno));
    exit(0);
}

void comm_identi(struct proc_st *proc, char *buffer)
{
    char *tmp;

    /* replace newline with null */
    if (buffer[strlen(buffer) - 1] == '\n')
        buffer[strlen(buffer) - 1] = 0;
    strncpy(proc->pbuff,buffer,MAX_LEN);

    tmp = strtok(buffer, " ");
    while (tmp != NULL) {
        proc->commv[(proc->commc)++] = tmp;
        tmp = strtok(NULL, " ");
    }

    proc->commv[proc->commc] = NULL;

    /* check for built-in functions */
    if (proc->commc >= 1) {
        if(!strcmp(proc->commv[0], "exit")) {
            free(proc);
            exit(EXIT_SUCCESS);
        }

        if(!strcmp(proc->commv[0], "cd")) {
            proc->exec = 0;
            if (chdir(proc->commv[1]) != 0)
                error_msg("chdir() error");
        }

        /* check if it is a background process */
        if (*proc->commv[(proc->commc) - 1] == '&') {
            proc->bg = 1;
            proc->commv[(proc->commc) - 1] = NULL;
        }
    }

    return;
}

This code and updates are available in the github repo.


texts:
My site is generated by Middleman. I know I could be using HAML, and Sass, and other optimizations are possible, but what I'm curious about at this stage is DRYing up code in my  custom helpers, and optimizing my use of them. (I also know I'm not using link_to and img_tag helpers, that's coming...)

It is probably easiest to just look at the project on github but I don't want to break the rules so here is some code:

_header.erb

<head>
<title><%= page_title %></title>

<!--
   _____                  _              ____        __          __
  / ___/__  ______  _____(_)_______     / __ \____  / /_  ____  / /_
  \__ \/ / / / __ \/ ___/ / ___/ _ \   / /_/ / __ \/ __ \/ __ \/ __/
 ___/ / /_/ / / / / /  / (__  )  __/  / _, _/ /_/ / /_/ / /_/ / /_
/____/\__,_/_/ /_/_/  /_/____/\___/  /_/ |_|\____/_.___/\____/\__/
Founded with love and care by Michael Edwards & David Lyons.
Content, code, and design Copyright © 2015 Sunrise Robot, LLC.
-->

<!-- meta -->
<%= partial "layouts/meta" %>
<link href="/stylesheets/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Fugaz+One|Oswald:400,300,700|Open+Sans:300italic,400italic,700italic,700,300,400' rel='stylesheet' type='text/css'>
<link href="/stylesheets/sr.css" rel="stylesheet" media="screen">
<% if @show %>
<link href="http://sunriserobot.net/<%= @show["prefix"] %>/feed.xml" rel="alternate" title="<%= @show["title"] %> RSS Feed" type="application/rss+xml">
<% end %>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="../../assets/js/html5shiv.js"></script>
  <script src="../../assets/js/respond.min.js"></script>
<![endif]-->

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-59251006-1', 'auto');
  ga('send', 'pageview');
</script>
</head>

custom_helpers.rb

module CustomHelpers
  def site_url
    "http://sunriserobot.net"
  end

  def page_title
    if current_article && !(blog.options.name == "blog")
      episode_title
    elsif @show
      show_title
    elsif current_article && (blog.options.name == "blog")
      "#{current_page.data.title} | #{blog_title}"
    else
      "#{current_page.data.title}"
    end
  end

  def show_title
    "#{@show["title"]} | Sunrise Robot"
  end

  def episode_title
   "#{@show["title"]} ##{current_article.data.number}: #{current_article.title} | Sunrise Robot"
  end

  def blog_title
    "H3LiOS' Log: the Sunrise Robot blog"
  end

  def page_description
    if current_article && !(blog.options.name == "blog")
      episode_description
    elsif @show
      show_description
    else
      "Sunrise Robot | Podcasts for technologists, gamers, artists and cultural enthusiasts."
    end
  end

  def show_description
    @show["description"]
  end

  def episode_description
    current_article.data.description
  end

  def page_image
    if @show
      "#{site_url}/images/#{@show["social_art"]}"
    else
      "#{site_url}/images/sunriserobot_social.png"
    end
  end
end


texts:
I have binary files containing sparse matrices. Their format is:

number of rows int
    length of a row int
        column index int
        value float

Reading each row with a single struct call instead of looping through each row with single struct calls gave me roughly a 2-fold speedup. I'm parsing 1 GB sized matrices and I would like to speed this proces up even further.

from scipy.sparse import coo_matrix
import struct
def read_sparse_matrix(handle):
    cols = []
    rows = []
    weights = []
    numrows = struct.unpack('i' , handle.read(4))[0]
    shape = numrows
    for rownum in range(numrows):
        rowlen = struct.unpack('i', handle.read(4))[0]
        row = list(struct.unpack("if" * rowlen, handle.read(8 * rowlen)))
        cols += row[::2]
        weights += row[1::2]
        rows += [rownum] * rowlen
    return coo_matrix((weights, (rows, cols)), shape=(shape, shape))

A file contains multiple of these matrices, and other informatinon, so the size of the file is not informative about the structure of the matrix.


texts:
I wrote a test that parses links from a web page, and in a loop, clicks on each of them, and then returns to the main page. But, each iteration is accompanied by parsing the entire web page again and again and overwriting the links array, although only one link is needed per iteration. I understand that this is inefficient. How can I optimize this?

I tried parsing the links only once and then iterating through them in a loop. After the first iteration, it goes back (to the main page) and tries to click on the second link, but it's not interactive (I think it's because of the web elements that are stored in the links array changing every time you go to the page).

def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get('https://yandex.ru')

def test_01(self):
    driver = self.driver
    links = []
    time.sleep(3)
    links = driver.find_elements_by_css_selector("a")
    for i in range(len(links)):
        links = driver.find_elements_by_css_selector("a")
        links[i].click()
        driver.get('https://yandex.ru')
        time.sleep(3)


texts:
Recently, I perform re-factor on one of my frequent used custom enum, by removing its getter.

My rational for doing so it.

The enum's custom fields are immutable
Only use getters when it is necessary.
Less typing. Reduce verbosity.
This is a very stable class, with only 17 commits, since 2008. Its getters behavior had never been changed. It merely perform dummy return on its internal data, without any additional logic. (History of Country.java)

Before Refactor

public enum Country {
    Australia("/images/16x16/au.png", "Australia", Currency.getInstance("AUD")),
    Austria("/images/16x16/at.png", "Austria", Currency.getInstance("EUR")),
    ...

    Country(String fileName, String humanReadableString, Currency currency) {
        this.icon = new javax.swing.ImageIcon(this.getClass().getResource(fileName));
        this.humanReadableString = humanReadableString;
        this.currency = currency;
    }

    public ImageIcon getIcon() {
        return icon;
    }

    public String toHumanReadableString() {
        return humanReadableString;
    }

    public Currency getCurrency() {
        return currency;
    }

    private final ImageIcon icon;
    private final String humanReadableString;
    private final Currency currency;
}

After Refactor

public enum Country {
    Australia("/images/16x16/au.png", "Australia", Currency.getInstance("AUD")),
    Austria("/images/16x16/at.png", "Austria", Currency.getInstance("EUR")),
    ...

    Country(String fileName, String humanString, Currency currency) {
        this.icon = new javax.swing.ImageIcon(this.getClass().getResource(fileName));
        this.humanString = humanString;
        this.currency = currency;
    }

    public final ImageIcon icon;
    public final String humanString;
    public final Currency currency;
}

I was wondering, do you think this is a good re-factoring approach? Would you accept such re-factoring?


texts:
I want to have the same experiance with slq/dapper for my navigation properties just like in Entity Framework.
But I'm not sure which sql query i should use.
As you see, every single Resource entity calls a "select query" for retrieving it's related Language.
Does it effect the performance? Maybe i should use single "join query"?

public class Resource  {
    public int Id { get; set; }
    public string Name { get; set; }
    public int LanguageId { get; set; }
    public Language Language = {
         return connection.Query<Language>("select * from Language where Id = @Id", new { Id = LanguageId }).First();
    }
}

public class Language {
    public intId { get; set; }
    public string Name { get; set; }
    public List<Resource> Resources => {
         return connection.Query<Resource>("select * from Resource where LanguageId = @LanguageId", new { LanguageId = Id }).ToList();
    }
}


texts:
I took the code from kostyas benchmarks for the Rust Brainfuck interpreter and tried to optimize it. There is also a discussion on Reddit about the poor performance of Rust in the Benchmark.

Before my improvements the code needed 16.81s to complete the benchmark and used 6.2Mb of memory, after that the code only needs 4.89s to run but the memory consumption is nearly unchanged.

How can I improve the code and maybe reduce memory usage?

The file with my changes is also on Github.

use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use std::vec::Vec;
use std::io;
use std::env;
use std::collections::BTreeMap;

struct Tape {
  pos: usize,
  tape: Vec<isize>
}

impl Tape {
  fn new() -> Tape { Tape { pos: 0, tape: vec![0] } }
  fn get(&self) -> isize { self.tape[self.pos] }
  fn getc(&self) -> u8 { self.get() as u8 }
  fn inc(&mut self) { self.tape[self.pos] += 1; }
  fn dec(&mut self) { self.tape[self.pos] -= 1; }
  fn advance(&mut self) { self.pos += 1; if self.tape.len() <= self.pos { self.tape.push(0) } }
  fn devance(&mut self) { if self.pos > 0 { self.pos -= 1; } }
}

struct Program {
  code: Vec<u8>,
  bracket_map: BTreeMap<usize, usize>
}

impl Program {
  fn new(content: Vec<u8>) -> Program {
    let mut code = Vec::new();
    let mut bracket_map = BTreeMap::new();
    let mut leftstack = Vec::new();

    for (pc, b) in content.iter().filter(|&&x| x == b'+' || x == b'-' || x == b'.' || x == b','
            || x == b'<' || x == b'>' || x == b'[' || x == b']').map(|&x| x).enumerate() {
      if b == b'[' {
        leftstack.push(pc);
      } else if b == b']' {
        if let Some(left) = leftstack.pop() {
          bracket_map.insert(left, pc);
          bracket_map.insert(pc, left);
        }
      }
      code.push(b);
    }
    Program{ code: code, bracket_map: bracket_map }
  }

  fn run(&self) {
    let mut pc: usize = 0;
    let mut tape = Tape::new();
    let mut stdout = io::stdout();

    while pc < self.code.len() {
      match self.code[pc] {
        b'+' => tape.inc(),
        b'-' => tape.dec(),
        b'>' => tape.advance(),
        b'<' => tape.devance(),
        b'[' => { if tape.get() == 0 { pc = self.bracket_map[&pc]; } },
        b']' => { if tape.get() != 0 { pc = self.bracket_map[&pc]; } },
        b'.' => { stdout.write(&[tape.getc()]).unwrap(); stdout.flush().unwrap() },
        _ => unreachable!()
      }
      pc += 1;
    }
  }
}

fn main() {
  let mut buf = Vec::new();
  {
    let arg1 = env::args().nth(1).unwrap();
    let path = Path::new(&arg1);
    let mut file = File::open(&path).unwrap();
    file.read_to_end(&mut buf).unwrap();
  }
  Program::new(buf).run();
}

More information: The program is compiled with rustc -C opt-level=3 brainfuck/brainfuck.rs -o brainfuck_rs, the memory usage is determined by a ruby script. C++ performs a lot better regading memory usage it only needs 1.6Mb.

Brainfuck rogram used for benchmark:

 Benchmark brainf*ck program
>++[<+++++++++++++>-]<[[>+>+<<-]>[<+>-]++++++++
[>++++++++<-]>.[-]<<>++++++++++[>++++++++++[>++
++++++++[>++++++++++[>++++++++++[>++++++++++[>+
+++++++++[-]<-]<-]<-]<-]<-]<-]<-]++++++++++.

I am using Rust nightly rust-nightly-bin-1.2.0_2015.06.06-1 on Arch Linux running on 4 Intel(R) Core(TM) i5-2450M CPU @ 2.50GHz.


texts: Prepend one value to a list 'x' number of times

texts:
I want to add a value multiple times at the beginning of a list, what I have is...

internal static class Helper
{
  public static void Prepend(this IList<double> source, double value, int count)
  {
    for (var i = 0; i < count; ++i)
    {
      source.Insert( 0, value );
    }
  }
}

Then use it as follow

// create
var mylist = new List(){ ... };  // create the list
mylist.Prepend( 0, 10 );  // prepend 0 to the list

But I wonder if there isn't a more efficient way of doing the same thing?


texts:
Yesterday I stumbled upon a Stack Overflow question that asked if it was possible to implement Tab-triggered auto-completion in a console application.

I thought that was an interesting idea, so I went ahead and wrote a small program that does just that, given a hard-coded string[] - I might eventually refactor it into its own class and reuse it in my own projects if I ever actually need auto-completion in a console app, but before I do that I'd like some feedback on the way it's implemented, given static aside, the logic itself is pretty much the way I'll have it regardless of whether it's in a dedicated class as part of something much bigger, or right there in a console application that does nothing but verify that the code works.

Pressing Tab when there's no input will change the current line to say Bar; because there's a word in data that starts with Bar, pressing Tab again will autocomplete to Barbec; another Tab will make it Barbecue, and then any subsequent Tab will have no effect, because nothing in the data starts with Barbecue - but then you could Backspace until the input is Ba, type a t to make it Bat, and when you press Tab then it autocompletes to Batman.

In other words, it all works exactly as it should. But does it look right?

class Program
{
    static void Main(string[] args)
    {
        var data = new[]
        {
            "Bar",
            "Barbec",
            "Barbecue",
            "Batman",
        };

        var builder = new StringBuilder();
        var input = Console.ReadKey(intercept:true);

        while (input.Key != ConsoleKey.Enter)
        {
            if (input.Key == ConsoleKey.Tab)
            {
                HandleTabInput(builder, data);
            }
            else
            {
                HandleKeyInput(builder, data, input);
            }

            input = Console.ReadKey(intercept:true);
        }
        Console.Write(input.KeyChar);
    }

    /// <remarks>
    /// https://stackoverflow.com/a/8946847/1188513
    /// </remarks>>
    private static void ClearCurrentLine()
    {
        var currentLine = Console.CursorTop;
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, currentLine);
    }

    private static void HandleTabInput(StringBuilder builder, IEnumerable<string> data)
    {
        var currentInput = builder.ToString();
        var match = data.FirstOrDefault(item => item != currentInput && item.StartsWith(currentInput, true, CultureInfo.InvariantCulture));
        if (string.IsNullOrEmpty(match))
        {
            return;
        }

        ClearCurrentLine();
        builder.Clear();

        Console.Write(match);
        builder.Append(match);
    }

    private static void HandleKeyInput(StringBuilder builder, IEnumerable<string> data, ConsoleKeyInfo input)
    {
        var currentInput = builder.ToString();
        if (input.Key == ConsoleKey.Backspace && currentInput.Length > 0)
        {
            builder.Remove(builder.Length - 1, 1);
            ClearCurrentLine();

            currentInput = currentInput.Remove(currentInput.Length - 1);
            Console.Write(currentInput);
        }
        else
        {
            var key = input.KeyChar;
            builder.Append(key);
            Console.Write(key);
        }
    }
}


texts:
In our application we watch file changes using .NET FileSystemWatcher. After each file change we process the new content asynchronously. In order to make everything flexible and smooth, we used TPL BufferBlock<T>

After deployment and some real tests we realized, that watcher might be triggered too much times on the same file. And while we process only one file simultaneously, we anyway re-work the same content.

So, basically, we want the following:

Have easy-to-use collection that works similarly to queue and provides a possibility to wait for new items without any while (true) loops.
Thread-safety.
Items inside should be unique.

Since we are not able to extend BufferBlock (it is sealed) and we don't have access to the full items collection inside BufferBlock, we ended with the following solution:

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

public class UniqueBufferBlock
{
    private readonly BufferBlock<string> _buffer = new BufferBlock<string>();
    private readonly HashSet<string> _hashSet = new HashSet<string>();
    private readonly object _locker = new object();

    public void Post(string value)
    {
        lock (_locker)
        {
            if (_hashSet.Add(value))
            {
                _buffer.Post(value);
            }
        }
    }

    public string Recieve()
    {
        lock (_locker)
        {
            var value = _buffer.Receive();
            _hashSet.Remove(value);
            return value;
        }
    }

    public Task<bool> OutputAvailable(CancellationToken cancelToken)
    {
        return _buffer.OutputAvailableAsync(cancelToken);
    }
}

Typical usage:

fileWatcher.FileChanged += (_, fileName) => uniqueBufferBlock.Post(fileName);

// ...

while (await uniqueBufferBlock.OutputAvailable(cancelToken))
{
    var fileName = uniqueBufferBlock.Receive();
    await ProcessFile(fileName, cancelToken);
}

What drawbacks could we face with it and what can be improved?


texts: HackerRank Left rotation code using Java 8

texts:
I tried to solve this Left Rotation problem on HackerRank. My code works out for most test cases, but for some it doesn't, probably because they have large number of data. So there seems to be some optimization or performance issue in my code, and I can't really figure out how to fix it. Any help will be greatly appreciated :)

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String[] nd = scanner.nextLine().split(" ");
        int c;
        int n = Integer.parseInt(nd[0]);

        int d = Integer.parseInt(nd[1]);

        int[] a = new int[n];

        int arr[] = new int[n];

        String[] aItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int aItem = Integer.parseInt(aItems[i]);
            a[i] = aItem;
        }

        scanner.close();

        for (int k=1;k<=d;k++) {
            for (int j=0;j<n;j++) {
                if (j==n-1)
                { c=0;}
                else
                { c=j+1;}
                arr[j]=a[c];
            }
            System.arraycopy(arr, 0, a, 0, n);
        }

        for (int j=0;j<n;j++) {
            System.out.print(arr[j]+ " ");
        }
    }
}


texts:
So I've been thinking alot about simple/convenient ways to implement simple 2D animation using a bare-bones graphics library I'm using for school (Animation is way out of the scope of the class, I'm just experimenting.)

I thought of using a custom function passed to the class to allow the "user" of the code to just write their own code to do whatever they want to the sprite, then return control to the sprite's Update() function.  Here's what I have so far:

// SpriteStuff.h

typedef bool (AnimationStep*)(Sprite* sprite) ANIMATIONSTEP

class Sprite {
    //...
    ANIMATIONSTEP m_currentAnimation;

    void BeginAnimation(ANIMATIONSTEP step);
    void EndAnimation();

    void Update();
    //...
};

void Sprite::BeginAnimation(ANIMATIONSTEP step) {
    if (step != NULL)
        m_currentAnimation = step;
}
void Sprite::EndAnimation() {
    m_currentAnimation = NULL;
}

void Sprite::Update() {
    //...
    if (m_currentAnimation != NULL)
        if (!m_currentAnimation(this)) EndAnimation();
    //...
}

// (off in some other code...)
void DoAnimateThing() {
    mySprite->BeginAnimation(GeneralFallAnimationStep);
}

bool GeneralFallAnimationStep(Sprite* sprite){
    return sprite->y++ > SOME_LIMIT_SOMEWHERE;
}

// Could possibly end it early...
void CancelAnimationOnThing() {
    mySprite->EndAnimation();
}

It seems like a pretty simple design that will do what I need, but almost too simple.  I'm doing something terribly wrong, huh?

EDIT:  So I've gotten some good input on this, but now I'm curious... Any suggestions how controlling the speed of these animations?  Can this be done well in the Sprite class, or should that be handled strictly by the ANIMATIONSTEP?


texts: Generate set of random numbers and remove lowest

texts:
I'm learning some Python with my kids, and we're making a program to generate D & D characters from user input.

One portion of the code is to generate stats, which are a set of six numbers where each number is the sum of three random values from 1-6. We're total softies, though, so for each value, we're generating four values from 1-6 and tossing out the lowest. We're also doing this seven times, and throwing out the lowest of the seven, to end up with a list of six values.

import random

stats = []

for i in range(7):
    rolls = []

    for j in range(4):
        roll = random.randint(1,6)
        rolls.append(roll)

    stat = sum(rolls) - min(rolls)
    stats.append(stat)

stats.remove(min(stats))

print stats

It works, but I feel like there might be more elegant solutions/more Pythonic approaches. Any suggestions?


texts: Creating two different posts types on my Gatsby site - rewriting my gatsby-node.js

texts:
I need to identify the different markdown files I have so I can create a unique url structure for them. I can already identify "notes" files, and want to create a second type called "projects".
My gatsby-node.js file looks like this right now
const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');

// Look at every node when it is created
exports.onCreateNode = ({node, getNode, actions}) => {
    // Check for markdown nodes
    const { createNodeField } = actions;
    if(node.internal.type === 'MarkdownRemark') {
        // Create a slug out of the markdown filepath name
        const slug = createFilePath({
            node,
            getNode,
            basePath: 'notes'
        });
        // Add the newly created slug to the node itself
        createNodeField({
            node,
            name: 'slug',
            value: `/note${slug}`
        });
    }
};

exports.createPages = ({ graphql, actions }) => {
    const { createPage } = actions
    return new Promise((resolve, reject) => {
      graphql(`
        {
          allMarkdownRemark {
            edges {
              node {
                fields {
                  slug
                }
              }
            }
          }
        }
      `).then(result => {
        result.data.allMarkdownRemark.edges.forEach(({ node }) => {
          createPage({
            path: node.fields.slug,
            component: path.resolve(`./src/templates/note.js`),
            context: {
              // Data passed to context is available in page queries as GraphQL variables.
              slug: node.fields.slug,
            },
          })
        })
        resolve()
      })
    })
  };
```


texts:
I've started learning Rust recently using the Rust book.

In one of the chapters, the authors encourage the reader to experiment with closures, and try to create a generic cache implementation.

I've managed to get it working as below. However, it irks me that I need to add Clone trait on the input argument in the get() method. I was wondering if there was a better way of doing this?

Any other comments are also welcome (apart from the main() method which is a sample driver).

use std::collections::HashMap;
use std::thread;
use std::time::Duration;
use std::hash::Hash;
use std::clone::Clone;

struct Cache<T, U, W>
    where T: Fn(U) -> W,
          U: Eq + Hash + Clone {
    calculator: T,
    values: HashMap<U, W>,
}

impl<T, U, W> Cache<T, U, W>
    where T: Fn(U) -> W,
          U: Eq + Hash + Clone {
    fn new(calculator: T) -> Cache<T, U, W> {
        Cache {
            calculator,
            values: HashMap::new(),
        }
    }

    /*
     * The ugliest part in this function is the constraint that we have to clone the input.
     * HashMap::entry() moves the key, which renders it unusable for subsequent calculations.
     * So we can either
     * - always perform the expensive computation
     * (OR)
     * - clone the input so that it can be re-used later
     *
     * Another problem is that defining a closure in or_insert_with borrows the Cache::calculator, and that creates a problem
     * when we attempt to borrow it again by invoking self.calculator. This is why the following line won't work:
     * self.values.entry(input.clone()).or_insert_with(|| { (self.calculator)(input) })
     */
    fn get(&mut self, input: U) -> &W {
        let calc = &self.calculator;
        self.values.entry(input.clone()).or_insert_with(|| { (calc)(input) })
    }
}

fn main() {
    println!("Hello, world!");
    let mut c = Cache::new(|x: &str| {
        println!("performing an expensive calculation with input: {}", x);
        thread::sleep(Duration::from_secs(2));
        format!("Original input: {}", x)
    });

    let x = c.get("10");
    println!("x: {}, cacher after getting {}", x, 10);

    let x = c.get("10");
    println!("x: {}, cacher after getting {}", x, 10);

    let x = c.get("20");
    println!("x: {}, cacher after getting {}", x, 20);

    let x = c.get("10");
    println!("x: {}, cacher after getting {}", x, 10);

    let x = c.get("10");
    println!("x: {}, cacher after getting {}", x, 10);

    let x = c.get("20");
    println!("x: {}, cacher after getting {}", x, 20);
}


texts: Reach certain Wiki page through random links

texts:
I just read about Wiki game on Wikipedia and wanted to implement it as a fun project for myself using python.

Task:To reach Mathematics Wikipedia page using wikipedia hyperlinks randomly.

Using Beautiful Soup documentation,I was able to create following crude code which is quite slow for my purpose.

import random
import requests
from bs4 import BeautifulSoup

r = requests.get("https://en.wikipedia.org/wiki/Main_Page")
soup = BeautifulSoup(r.content)
a = [link.get('href') for link in soup.find_all('a')]
del a[0:6]
while(soup.title.text != 'Mathematics - Wikipedia'):
    a = [link.get('href') for link in soup.find_all('a')]
    del a[0:6]

    if (a == []):
        add = "/wiki/Special:Random"
    else:
        add = random.choice(a)
        if(add == None):
            add = random.choice(a)

    url = "https://en.wikipedia.org/"+add
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    print(soup.title.text)

First,I would like to reduce the useless links that this program goes through such as About Wiki,user login,etc.
I knew I can simply use if-else statements but wanted to know if there is another simpler or faster implementation for it in beautiful soup or something else.

Secondly,Any suggestions to improve code would be welcome including additional reading resources.


texts:
There is a huge documentation about using and generating hashcodes for objects that will go into a dictionary, really few more if you try to look about hashcode of a dictionary.

No, the default Dotnet dictionary doesn't override the Object.GetHashCode() method, so two different dictionary with same keys and same values will have different hashcodes.

Taking inspiration from this Stack Overflow question, I made this implementation in my object.

The object is a simple wrapper over a dictionary, which takes different values and save them with the number of times they have been added (values are keys of the dictionary, occurrences are values).

The starting value for the hashcode is zero (for empty dictionary) and it's calculated and stored every time a value is added, to avoid the necessity of enumerate the whole dictionary every time the hashcode is requested.

What do you think about it?

private int hascode = 0;

public bool Add(T item)
{
    values[item] = values.ContainsKey(item) ? values[item]++ : 1;

    unchecked
    {
        hashcode += 486187739 * item.GetHashCode();
        hashcode += 982451653 * values[item];
    }
    return true;
}


texts:
I have a tracking software. At first I just send the position to the web Service

[Table("Positions")]
public class SalesmanPosition
{
    [PrimaryKey, AutoIncrement]
    public int PositionId { get; set; }
    public int SalesmanId { get; set; }
    public double X_long { get; set; }
    public double Y_lat { get; set; }
    public DateTime Event_time { get; set; }
}

private void PositionSaveWeb(SalesmanPosition sp)
{
    var httpWebRequest = (HttpWebRequest)WebRequest
                           .Create("http://myserver.com/ApiTest/api/salesmanPosition");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
            | SecurityProtocolType.Tls11
            | SecurityProtocolType.Tls;

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = JsonConvert.SerializeObject(sp);
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }

    string result = TryWebRequest(httpWebRequest);
}

But then realize sometimes internet connection isn't available so I decide store the position on a sqlite db until the connection is available again. So I create another class to handle the db.

public static class OrmExample
    {
        private static string dbPath = "/storage/emulated/0/DCIM/myDatabase.db3";

        public static void StartDatabase()
        {
            SQLiteConnection db = new SQLiteConnection( dbPath, false);
            db.CreateTable<SalesmanPosition>();
        }

        public static List<SalesmanPosition> GetPendingPositions()
        {
            List<SalesmanPosition> query;
            using (SQLiteConnection db = new SQLiteConnection(dbPath, false))
            {
                query = db.Query<SalesmanPosition>("SELECT * FROM [Positions]");
            }
            return query;
        }

        public static void PositionDelete((SalesmanPosition sp))
        {
            using (SQLiteConnection db = new SQLiteConnection(dbPath, false))
            {
                db.Delete(sp);
            }
        }

        public static void PositionInsert(SalesmanPosition sp)
        {
            using (SQLiteConnection db = new SQLiteConnection(dbPath, false))
            {
                db.Insert(sp);
            }
        }
  }

Right now In my main code I have

private void SavePosition ( SalesmanPosition newPosition ) {

    GetConnectionStatus();

    if (isOnline)
    {
        PositionSaveWeb(newPosition);

        foreach( SalesmanPosition sp in OrmExample.GetPendingPositions() {
           PositionSaveWeb(sp);
           PositionDelete(sp);
        }
    }
    else
    {
        OrmExample.PositionInsert(newPosition);
    }
}

But not sure I should add all those function as method for the class SalesmanPosition

SavePosition
PositionInsert
PositionDelete

And on the Orm only the StartDatabase and GetPendingPositions()

So should be resume to

 newPosition.Save(); // include connection check and decide if send web or save locally.
 if (isOnline)
 {
    foreach( SalesmanPosition sp in OrmExample.GetPendingPositions() {
       sp.Save();
       sp.Delete();
    }
 }


texts: Decreasing the runtime of this non-abundant sums solution

texts:
I have written a solution to problem 23 of Project Euler, and after doing some testing and editing, I've managed to get the run time down from 1.7443 seconds to 1.56616 seconds. The problem is

  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

What are some other ways that I could improve this program? I'm pasting it entirely, and it should be noted that I'm compiling with g++ -o3.

#include <chrono>
#include <cmath>
#include <iostream>
#include <ctime>
#include <ratio>

int main()
{
//Value given in the question
const int LIMIT = 28124;
//Used to measure the runtime
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();

//Sieve of Erasthotenes to remove a significant number of iterations in the next step
int rootMax = (int)sqrt((double)LIMIT);

bool set[LIMIT+1] = {0};

for(int i = 2; i <= rootMax; ++i)
{
    if(!set[i])
    {
        for(int j = (i*i); j <= LIMIT; j += i)
        {
            set[j] = true;
        }
    }
}

bool isSumOfAb[LIMIT] = {0};

int abundant[6965];
int count = 0;
for(int i = 12; i < LIMIT; ++i) //This can start at 12, as we know that 12 is the 1st abundant number
{
    if(!set[i]) // Prime numbers won't be abundant, so next number
    {
        continue;
    }

    int sum = 0;
    for(int j = 1; j < i; ++j)
    {
        if(i % j == 0)
        {
            sum += j;
        }
    }

    if(sum > i)
    {
        abundant[count] = i;
        ++count;
    }
}

//Lots of work to do here.
//Establish all of the sums and compare
int a, c;
for(int i = 0; i < 6965; ++i)
{
    a = abundant[i];

    for(int j = i; j < 6965; ++j)
    {
        c = a + abundant[j];
        //Big speed increase when made like this as opposed to `if(c <= LIMIT) isSumOfAb[c] = true;`
        if(c > LIMIT)
        {
            break;
        }else
        {
            isSumOfAb[c] = true;
        }
    }
}

int sum = 0;
for(int i = 24; i < LIMIT; ++i) //can start at 24, as that is the 1st sum of 2 abundant numbers
{
    if(!isSumOfAb[i])
    {
        sum += i;
    }
}

std::cout << "Sum: " <<  sum;
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "\nIt took me " << time_span.count() << " seconds.";
}


texts: Human-readable number of bytes in Haskell

texts:
This is a tiny etude on a theme given here, using Python: Provide a function that generates a human readable file size such as 10.0GiB, 13B, 42.2TiB from a given integer number. (A similar Ruby etude is here.) The function should

gracefully handle any input (even negative numbers, although they don't make  sense for counting bytes - maybe they could represent negative offsets)
print numbers smaller than 1024 without a decimal point
print all other numbers with one decimal place and the appropriate unit (KiB, MiB, etc.)

It's more verbose than the python counterpart, so the question is whether this can be made more terse.

    humanReadableBytes :: Integer -> String
    humanReadableBytes size | null pairs = printf "%.0fZiB" (size'/1024^7)
                            | otherwise  = if unit=="" then printf "%dB" size
                                           else printf "%.1f%sB" n unit
    where
        (n, unit) = head pairs
        pairs = dropWhile ((1024<).abs.fst)
             (zip (map ((size'/).(1024^)) [0..]) units) :: [(Double, String)]
        size' = fromIntegral size
        units = ["","Ki","Mi","Gi","Ti","Pi","Ei","Zi"]

Right away it can be noted that the use of String is suboptimal, but Text.Printf does not allow Text, so printf ought to be replaced.


texts: Script for initialising i18n for a Flask site using pybabel and goslate

texts:
I haven't thought of a nice way to remove #, fuzzy from the files. I think process_babel_file might possibly become its own module, but on the other hand, having all methods in one script is quite nice for the mean time. I expect there to be bugs, although it works for the languages I've tried.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setuptranslations.py

Generate and manipulate translation files for a flask app.
Assumes areas in jinja2 templates are marked with {% trans %}..{% endtrans %}
or gettext, _, or other gettext variants.
Related: flask, flask-babel, pybabel, jinja2, i18n, gobabslate
    1. Run pybabel with extract option
        pybabel extract -F babel.cfg -o messages.pot .
    2. Run pybabel with init option for each language
        pybabel init -i messages.pot -d translations -l fr
        pybabel init -i messages.pot -d translations -l de
    3. Pull translations from Google Translate API into babel files
    4. Remove #fuzzy from message.po files.
    5. Run pybabel with compile option
        pybabel compile -d translations
"""
import sys
import codecs
from subprocess import Popen
from goslate import Goslate

pybabel_extract = ['pybabel', 'extract', '-F' 'babel.cfg',
                                         '-o' 'messages.pot', '.']
pybabel_init_lang = ['pybabel', 'init', '-i', 'messages.pot',
                                        '-d', 'translations', '-l']
pybabel_compile = ['pybabel', 'compile', '-d', 'translations']

def get_language_codes():
    try:
        from config import LANGUAGES, LANGUAGE_DEFAULT
        return [lang for lang in LANGUAGES.keys() if lang != LANGUAGE_DEFAULT]
    except:
        return ['fr', 'de']

def return_code(args):
    return Popen(args).communicate()[0]

def process_babel_file(lang, remove_fuzzy=False):
    gs = Goslate()
    filename = 'translations/' + lang + '/LC_MESSAGES/messages.po'
    file_stream = codecs.open(filename,          'r', 'utf-8')
    file_output = codecs.open(filename + '.tmp', 'w', 'utf-8')
    finding_input, data = False, u''
    for line in file_stream:
        if finding_input is True and line == u'msgstr ""\n':
            finding_input = False
            new_text = gs.translate(data, lang).replace('"', '\\"')
            file_output.write(u'msgstr "' + new_text + u'"\n')
            continue
        elif finding_input is True:
            data += line.replace('\n', ' ').replace('\\n"', ' ').strip('"')\
                        .replace('\\"', '"')
        elif line == u'msgid ""\n' or line[:7] == u'msgid "':
            finding_input = True
            data = u'' if line == u'msgid ""\n' else line[7:].strip()\
                .strip('"').replace('\\"', '"')
        elif line == '#, fuzzy\n' and remove_fuzzy:
            continue
        file_output.write(line)
    file_stream.close()
    file_output.close()
    Popen(['cp', filename + '.tmp', filename]).communicate()

def main():
    if return_code(pybabel_extract) is not None:
        sys.exit('pybabel failed to extract translations')
    for language_code in get_language_codes():
        if return_code(pybabel_init_lang + [language_code]) is not None:
            print('Failed to add language: %s', language_code)
            continue
        process_babel_file(language_code, remove_fuzzy=True)
    if return_code(pybabel_compile) is not None:
        sys.exit('pybabel was unable to compile translations')

if __name__ == '__main__':
    main()


texts:
I have written a custom HashSet and though it isn't completed yet (this code does not consider test cases with collisions), I would like to know if there is anything I can improve in areas of clean code conventions and logic errors. Kindly review my code. Thanks in advance.

import java.util.Arrays;

public class HashSet {

private int[] values;
private int size;
private int ratio;
private int[] values_temp;
private ProbeStrategy strategy;
private int current_length;

public HashSet(int initArrayLength, int ratio, ProbeStrategy strategy) {
    values = new int[initArrayLength];
    Arrays.fill(values, -1);
    this.ratio = ratio;
    this.strategy = strategy;
    current_length = values.length;
}

public boolean add(int value) {
    if (size == 0) {
        int bucket = value % current_length;
        values[bucket] = value;
        size++;
        return true;
        }
        if (value >= 0) {
            int bucket = value % current_length;
            values[bucket] = value;
            if (current_length <= ratio * size) {
                int new_length = (current_length * 2) + 1;
                values_temp = new int[new_length];
                for (int i = 0; i < current_length; i++) {
                    if (values[i] == -1) {
                        continue;
                    }
                    int bucket_temp = values[i] % new_length;
                    values_temp[bucket_temp] = values[i];
                }
                values = values_temp;
                current_length = new_length;
                for (int i = 0; i < current_length; i++) {
                    if (values[i] == 0) {
                        values[i] = -1;
                    }
                }
            }
            size();
            return contains(value);
    }
    return false;
}

public boolean contains(int value) {
    for (int i = 0; i < values.length; i++) {
        if (values[i] == value) {
            return true;
        }
    }
    return false;
}

public boolean remove(int value) {
    for (int i = 0; i < values.length; i++) {
        if (values[i] == value) {
            values[i] = -1;
        }
    }
    size();
    return !contains(value);
}

public int size() {
    int count = 0;
    for (int i = 0; i < current_length; i++) {
        if (values[i] == -1) {
            count++;
        }
        size = current_length - count;
    }
    return size;
}

public int[] toArray() {
    int[] result = new int[this.values.length];
    for (int i = 0; i < this.values.length; i++) {
        result[i] = this.values[i];
    }
    return result;
}

public static void main(String[] args) {
    ProbeStrategy linear = new SimpleLinearProbe();
    HashSet set = new HashSet(6, 2, linear);

    int[] numbers = {77254, 135170, 19331, 173763, 154470, 154471};
    for (int i = 0; i < numbers.length; i++) {
        // add the number
        set.add(numbers[i]);

        //print out the array
        int[] array = set.toArray();
        for (int j = 0; j < array.length; j++) {
            System.out.print(array[j] + ", ");
        }
        System.out.println();
    }
}

}


texts: SQL Query - records within the last year

texts:
Bit of a complicated one for me.

I have a database full of hundreds of thousands of records, many of which are duplicated.

I need to get all records within the last year but making sure every instance of that record is within the last year, e.g. if a record is duplicated and one is older than a year this shouldn't be included.

So far I have the below...

Step 1 - find out earliest date for each record

SELECT MIN(CreateDate) AS Date, Email FROM Results R
WHERE (R.Email IS NOT NULL AND R.Email <> '')
GROUP BY R.Email

I created this as a view and called it [EarliestInteraction]

Step 2 - grab all within the last year

Note: I need records within the last year but they also need to be in a log table also. So all records within the last year that are also present in some log tables.

So far I have done this...

SELECT * FROM EarliestInteraction ECI
WHERE ( CAST(ECI.Date AS DATE) >= CAST(GETDATE() - 365 AS DATE) )
AND (

    EXISTS (
        SELECT Id FROM LOG1 R
        WHERE Source = 'LOGGED'
        AND R.Email = ECI.Email
    )

    OR

    EXISTS (
        SELECT Id FROM LOG2 R WHERE (R.Email IS NOT NULL AND R.Email <> '')
        AND R.Email = ECI.Email
            AND R.EventType IN (
            'LOGGED'
    ))
)

My question is, is this a good way of doing this and accurate?

Or am I missing something that would bring back earlier duplicates...

Any thoughts on if this is accurate or achieves the brief would be great.


texts: Execute edit in a stored procedure based on database value

texts:
I have code below which is set to check the date of DateToComplete, and if the date is 2 weeks or more ago, change the status of Complete from 3 to 2.

Is this the best way?

USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[spChanger]

AS
BEGIN

Execute ('UPDATE [TblActions] SET Complete = 2 WHERE DateToComplete < Date.Now.AddDays(14) AND Complete = 3' )

END


texts:
I'm tasked with getting emails from a .csv file and using them to submit a form.  I am using the csv and mechanize Python libraries to achieve this.

import re
import mechanize
import csv

def auto_email(email):
    br = mechanize.Browser()
    br.open("URL")
    br.select_form(name="vote_session")
    br['email_add'] = '%s' % (email) #email address
    br.submit()

def csv_emails():
    ifile  = open('emails.csv', "rb")
    reader = csv.reader(ifile)
    rownum = 1
    for row in reader:
        auto_email(row[0])
        print "%d - %s processed" %(rownum, row[0])
        rownum += 1
    print 'List processed.  You are done.'
    ifile.close()

print csv_emails()

The code works, but I am very much a beginner in Python.

I was wondering whether I have any inefficiencies that you can help me get rid of and optimize the script?


texts: Simple Rock, Paper, Scissors Python Game

texts:
I tried to learn Python during the weekend and after getting some knowledge decided to make a small rock-paper-scissors game. I would be grateful for your input on how I could improve my code. All feedback is highly appreciated.

import random

def round_winner(choice):
    ai_chosen = str(random.randint(1, 3))
    print(f'AI chose {ai_chosen}')

    if choice == '1' and ai_chosen == '2':
        return 'ai'
    elif choice == '2' and ai_chosen == '3':
        return 'ai'
    elif choice == '3' and ai_chosen == '1':
        return 'ai'
    elif choice == ai_chosen:
        return 'tie'
    else:
        return 'player'

def display_round_winner(winner):
    if winner == 'tie':
        print('This round is tied!')
    else:
        print(f'The winner this round is the {winner.upper()}')

    print(f'''
    Current points as follows:
    Player: {counter['player']}
    AI: {counter['ai']}
    Rounds Tied: {counter['tie']}
    ''')

def score_checker():
    global game_ongoing
    for key, value in counter.items():
        if value == 2:
            print(f'{key.upper()} wins the game!')
            game_ongoing = False

def initializer():
    global counter
    message = '''
    Please choose one of the following:
    1: Rock
    2: Paper
    3: Scissors
    '''

    print(message)

    choice_of_obj = input('What will it be: ')
    if choice_of_obj in ['1', '2', '3']:
        winner = round_winner(choice_of_obj)
        counter[winner] += 1
        display_round_winner(winner)
        score_checker()
    else:
        print('Out of bounds')

counter = {
    'player': 0,
    'ai': 0,
    'tie': 0
}

game_ongoing = True

while game_ongoing:
    initializer()


texts:
I have to deal with a really ugly looking response I get back from a particular device. The string represents a table. Each section of the string represents the form:

["id", "date_time", "path", "type","duration","count", "rate"]

Which as an example looks like:

"1,2014-4-3 10:1:10,somerandompath,some/screwy!stringwithstufflike[0,0,0,0]inIt,0,0;"

all table entries as you can see are terminated by ; and have their elements separated by ,

But some entries like in some/screwy!stringwithstufflike[0,0,0,0]inIt have commas within their data,.. and times/dates 10:1:10 aren't padded with 0's to be consistent

This is what I have so far, but it doesn't feel very optimized...

def GetEventTable(self):
        # After I split by ',' commas can be inside of [..],
        # so I combine entries until their number of starting/end braces match
        def split_entry(entry):
            splitentry = entry.split(',')
            for ii in range(len(splitentry))[::-1]:
                start_bracket = splitentry[ii].count('[')
                end_bracket = splitentry[ii].count(']')
                if not start_bracket == end_bracket:
                    splitentry[ii-1:ii+1] = [splitentry[ii-1] + ',' + splitentry[ii]]
            return splitentry
        event_lable = ["id", "date_time", "path", "type","duration","count", "rate"]
        ## This section just talks to the remote device and gets the unformatted string ###
        print "Sending: GET EVENT TABLE"
        stat, raw_data = SendRecieve(self, "GET EVENT TABLE")
        if IsError(stat):
            raise Exception("Error type '{}': {}".format(stat, raw_data))
        print raw_data
        ##################################################################################
        events = raw_data.split(';')[:-1]
        event_table = [{key:value for key,value in zip(event_lable,split_entry(entry) )} for entry in events ]
        return event_table

How can I improve the efficiency and also the readability?

It returns a list of dictionaries with keys ["id", "date_time", "path", "type","duration","count", "rate"]


texts: A timer to track time spent practicing Python

texts:
I made this to record the time I spend practicing Python. I'll eventually add in functionality to visualize the data. I'd appreciate any feedback that will help me improve.

# timer.py - A timer to track time spent practicing python

from datetime import timedelta
from datetime import datetime as Datetime
# used json b/c I wanted to practice it
import json
import os

# dict with all python practice options
options = ["Code Review",
           "Project",
           "Puzzles (Project Euler, Finxter, kaggle)",
           "Courses, Books, or Videos",
           "Read Docs"]

# Prompts user what type of practice they would like to do. User enters int.
def practice_choice():
    print("Pick a form of practice:\n")

    # print each option in options then ask user to select
    num = 1
    for option in options:
        print(str(num) + ". " + option)
        num += 1
    selection = input("\nPick a number: ")

    return options[int(selection) - 1]

def timer(selection):
    # store notes about practice session
    notes = input("Enter notes... ")

    # start timing session and get start time
    input("Hit Enter to begin practice...")
    start_dt = Datetime.now()

    # loop to allow for pausing. infinite loop that breaks when user clicks enter to stop session.
    var = 1
    total_so_far = 0
    while var == 1:
        pause_or_stop = input("Hit Enter to stop or space to pause...")

        # when user hits enters space char
        if pause_or_stop == ' ':

            # gets time session was paused. Calculates time practicing so far. Stores for later
            # Allows user to pause multiple times
            pause_dt = Datetime.now()
            total_so_far += int((start_dt - pause_dt) / timedelta(seconds=1))  # used sec for easier testing.

            # resume on enter key and overwrites old start time
            input("Hit Enter to resume")
            start_dt = Datetime.now()

        # breaks if enter key
        elif pause_or_stop == '':
            break

        # catch bad input
        else:
            print("Key not recognized")

    # get stop time and find total time in minutes
    end_dt = Datetime.now()
    total_mins = int((end_dt - start_dt) / timedelta(seconds=1)) + total_so_far  # used sec for easier testing.

    # add value to data[selection] dict. value is a list of datetime info, noes, total_minutes
    data[selection].append({'day': Datetime.now().strftime("%A"),  # %b %d %Y %H:%M),
                            'date': Datetime.now().strftime("%m-%d-%y"),
                            'time': Datetime.now().strftime("%H:%M"),
                            'notes': notes,
                            'minutes': total_mins})

    # convert dict to JSON object
    with open(target_file, 'w') as json_file:
        json.dump(data, json_file, indent=4)

# prompt user for type of practice
choice = practice_choice()

# practice_log file with all practice sessions are stored
target_file = "practice_log.json"

# initialize data dict which will hold practice logs
data = {}

# creates json file if it doesn't exist
if not os.path.exists(target_file):
    # top level values of json are created corresponding to practice type
    for each_item in options:
        data[each_item] = []
    with open(target_file, 'w') as json_file:
        json.dump(data, json_file, indent=4)

# open json file and load into target_files
with open(target_file, 'r') as json_file:
    data = json.load(json_file)

# starts timer
timer(choice)


texts: Run several Python programs and check for errors

texts:
For a post-graduate subject that I present, I maintain a repository of examples (on GitHub) from the textbook which is contributed and edited by my students, who are not very Python literate. I have written this code to run all the programs associated with figures, examples and exercises in the book and use it to alert me if a pull request has broken anything via Travis. Each program is a simple Python script which does not use any special stuff to do what it does. I don't check for correctness, just if the program actually runs. Many of the programs produce figures, so I've had to do some dirty things with matplotlib's show command so that these programs don't halt execution. This works but it all feels very hacky to me, and I'd be interested in suggestions to improve this checking.

You can check the repo for all the example files, but the main running script is here:

#!/usr/bin/env python

from __future__ import print_function
from past.builtins import execfile
import os
import traceback
import re
from collections import Counter
import sys

# disable show in figures
import matplotlib.pyplot as plt
plt.show = lambda: None

statuscounter = Counter()

itemparser = re.compile('(?P<kind>.*) (?P<chapter>.*)\.(?P<number>.*)')
allitems = open('allitems.txt').read().splitlines()

kinds = ['Figure', 'Example', 'Exercise']

faillist = []

if __name__ == "__main__":
    for item in allitems:
        kind, chapter_c, number_c = itemparser.match(item).groups()

        number = int(number_c)

        if chapter_c.isdigit():
            chapter = int(chapter_c)
            mask = '{}_{:02d}_{:02d}.py'
        else:
            chapter = chapter_c
            mask = '{}_{}_{}.py'

        filename = mask.format(kind, chapter, number)
        if os.path.exists(filename):
            try:
                execfile(filename)
                status = 'Success'
            except Exception as err:
                status = 'Failed'
                message = traceback.format_exc()
        else:
            status = 'Not implemented'

        statuscounter[status] += 1

        if status != 'Not implemented':
            print(kind, chapter, number, status)

        if status == 'Failed':
            faillist.append([kind, chapter, number])
            print(message)

    for items in statuscounter.items():
        print("{}: {}".format(*items))
    print("Failed items:")
    for items in faillist:
        print("  {} {} {}".format(*items))

    sys.exit(statuscounter['Failed'])


texts:
Basically, what this program does is that this generates a random number, and asks the user to guess it with multiple chances. So, if the user is close, it says that the user is close, and if the user is not close, then it says that the user is too high/low and if the user guesses it right, it congratulates the user.

So, you must now be wondering what I expect from this code review. Well I expect these stuff:

I expect you to point out flaws
I expect you to identify spots which are inefficient and can be optimised.
I expect you to comment on the use of concepts and how I have not used them right.

Main.java:

package com.GuessMyNumber;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        GuessMyNumber guessMyNumber = new GuessMyNumber();
        Scanner scanner = new Scanner(System.in);
        int input;

        guessMyNumber.generateNumber(1, 75);

        System.out.println("Hey there! Let's play Guess my number! Start guessing my number once you're ready.");

        while (!guessMyNumber.numberFound) {
            input = Integer.parseInt(scanner.next());
            System.out.println(guessMyNumber.validateInput(input));
        }
    }
}

GuessMyNumber.java:

package com.GuessMyNumber;

import java.util.Random;

public class GuessMyNumber {
    int randomNumber;
    String response;
    boolean numberFound = false;

    public GuessMyNumber()
    {

    }

    public int generateNumber(int min, int max)
    {
        Random random = new Random();

        this.randomNumber = random.nextInt((max - min) + 1) + min;

        return this.randomNumber;
    }

    public String validateInput(int guessedNumber)
    {
        if(guessedNumber < this.randomNumber && (this.randomNumber - guessedNumber) < 5) {
            this.response = "You're close!";
        }
        if(guessedNumber < this.randomNumber && (this.randomNumber - guessedNumber) > 5) {
            this.response = "You're too low!";
        }
        if(guessedNumber > this.randomNumber && (guessedNumber - this.randomNumber) < 5) {
            this.response = "You're close!";
        }
        if(guessedNumber > this.randomNumber && (guessedNumber - this.randomNumber) > 5) {
            this.response = "You're too high!";
        }
        if(guessedNumber == this.randomNumber) {
            this.response = "Congratulations! You guessed my number!";
            this.numberFound = true;
        }

        return this.response;
    }
}


texts:
A small greedy algorithm to position boxes in a grid.

Version A

int lCurrentIndex = 0;
BoxInchesInterface lPreviousBbox = lSortedBboxes.iterator().next();
  double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
for (BoxInchesInterface lBbox : lSortedBboxes)
{
    boolean lIsFirstIteration = lBbox == lPreviousBbox;
    if (!lIsFirstIteration && pDimension.getStart(lBbox) >= lEndPositionForCurrentIndex) {
        lCurrentIndex += 1;
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    } else if (pDimension.getEnd(lBbox) < lEndPositionForCurrentIndex) {
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    }
    lIndexFromBbox.put(lBbox, lCurrentIndex);
    lPreviousBbox = lBbox;
}
return lIndexFromBbox;

Version B

int lCurrentIndex = 0;
Iterator<BoxInchesInterface> lItor = lSortedBboxes.iterator();
BoxInchesInterface lPreviousBbox = lItor.next();
double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
lIndexFromBbox.put(lPreviousBbox, lCurrentIndex);
while (lItor.hasNext())
{
    BoxInchesInterface lBbox = lItor.next();
    if (pDimension.getStart(lBbox) >= lEndPositionForCurrentIndex)
    {
        lCurrentIndex += 1;
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    } else if (pDimension.getEnd(lBbox) < lEndPositionForCurrentIndex) {
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    }
    lIndexFromBbox.put(lBbox, lCurrentIndex);
    lPreviousBbox = lBbox;
}

Version A has the advantage of fewer variables but has to make sure to check for the first case when the lBbox is equal to lPreviousBox. Version B has the advantage that lPreviousBox is always different from lBbox, but has to deal with the iterator.

Which one would be better practice? Any suggestions for improvement?

(and I should add that concurrency is not an issue in this case.)


texts: Convert Byte array into collection of items of different types

texts:
I'm recieving UDP messages as byte arrays and depending on details in some of the first byte, I need to convert remaining bytes into a multitude of different possible arrangements of other data types.

These data types are primarily 'uint', 'ushort' and just 'byte' but can be in any order, and there can be any number of them. Each of these items will have a named variable.

I've tried using quite a few different options and am getting close, but feel that the methods I've created are not the best they could be. In places I've wanted to use 'sizeof' but don't want to mark the code as 'unsafe'. I've tried to use the 'params' keyword on the input, but this cannot be in conjunction with 'ref'. I've wanted to pass them with a maximum number of T1, T2, etc. using generics, but realised I can't enumerate these. I'm now passing an array of variables in conjunction with the 'ref' keyword, which means creating the array in memory but only the array gets updated with the changed and not the original variables.

byte[] message = new byte[] { }; //some byte array
ushort item1 = default(ushort);
byte item2 = default(byte);
var argumentArray = new object[] { item1, item2 };
ConvertArray(response, ref argumentArray);

private void ConvertArray(byte[] response, ref object[] items)
{
    int index = 0;
    for (int i = 0; i < items.Length; i++)
    {
        var item = items[i];
        var itemType = item.GetType();
        var itemSize = SizeOf(item.GetType());

        if (itemSize == 0)
        {
            continue;
        }
        else if (itemSize == 1)
        {
            items[i] = response[index];
        }
        else
        {
            var method = typeof(BitConverter).GetMethod($"To{itemType.Name}");
            var returned = method.Invoke(null, new object[] { response, index });
            items[i] = Convert.ChangeType(returned, itemType);
        }

        index = index + itemSize;
     }
}

private int SizeOf(Type type)
{
   switch (type.Name)
   {
       case nameof(UInt16):
           return 2;

       case "Byte":
           return 1;

       default:
           return 0;
   }
}

So this is partially working in that 'argumentArray' is updating with the values from the 'ConvertArray' method, but I'm sure there is a neater way to do this using Types.

Ideally I wouldn't need to create the 'argumentArray' and just pass the items (e.g. Item1 and Item2) directly as arguments to the method.


texts: Merge inserted and deleted tables in SQL trigger

texts:
I have a table with a Balance column of type decimal(18,0).

I want to get updates to its Balance field and reflect the changes in the parents of the updated row.

Currently I can easily subtract parent values by selecting from deleted table and add to parent values by selecting from inserted table in two different queries. Since the updates will trigger an other update and so the concept of recursive triggers (enabled in my database) comes to scene, I want to have the minimum number of updates.

Is the following the best way to merge inserted and deleted table and to get the real difference in Balance field?

Update MyTable
Set Balance += updated.Price
From (
    Select  IsNull(inserted.ParentID, deleted.ParentID) As ParentID,
            (IsNUll(inserted.Balance,0) - IsNull(deleted.Balance,0))  As Price
            From inserted
            Full join deleted
            on inserted.ID = deleted.iD
            WHERE IsNull(inserted.ParentID, deleted.ParentID) IS NOT NULL
) As updated
INNER JOIN MyTable
ON MyTable.ID = updated.ParentID
Where updated.ParentID IS NOT NULL

For example changing Balance from 1000 to 800 should yield to -200 change in parent Balance fields.

Also, my code fires the trigger one extra time, so that for an update in level 3 I get 4 updates (trigger-firing) instead of 3.

This is on SQL Server 2012.


texts:
I am solving interview questions from here.

  Problem : Given an array of integers, sort the array into a wave like array and return it, in other words, arrange the elements into a
  sequence such that a1 >= a2 <= a3 >= a4 <= a5.

  Note - If there are multiple answers possible than return the one that is lexicographically smallest.

  Approach : First sort the array then swap every second number with previous number.

This is my solution:

def wave(array):
    """Returns array in wave pattern by first sorting
    the array and then swapping the adjacent digits"""

    array.sort()  ##sort the given array
    for i in range(0,(len(array)-1),2):  ##skip every second number
        array[i], array[i+1] = array[i+1], array[i]  ##swap adjacent numbers

    return array

print wave([6,7,8,1,2,3,4])
print wave([5,1,3,4,2])
print wave([11,3,5,2,7,1,6,8,10,9,4])

How can i make this code better? Is there any other approach to solve this problem?


texts:
I have this code working but its using IndexOf I am not sure if that is the best or only option for search for a string value. What I have is a list that will need to remove a world from the child name if it is the same as the name.

  Is this the best way to complete this task?

namespace DupName
{
    public class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sbchildName = new StringBuilder();

            List<Item> items = new List<Item>()
            .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A3 Premium Plus" })
            .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "Audi A5 Premium Plus" })
            .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A6 Premium Plus 55 TFSI quattro" })
            .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S5 Premium Plus 3.0 TFSI quattro" })
            .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S3 Premium Plus 3.0 TFSI quattro" });

        foreach (var item in items)
        {
            if (item.ChildName.IndexOf(item.Name) != -1)
            {
                string temp = string.Format("{0} {1}", item.ChildName.Replace(item.Name, ""), "Car");
                Console.WriteLine(temp.Trim());
                childName.AppendFormat(temp.Trim());
            }
            else
            {
                string temp = string.Format("{0} {1}", item.ChildName, "Car");
                Console.WriteLine(temp.Trim());
                childName.AppendFormat(temp.Trim());
            }
        }
    }

    public static class Extensions
    {
        public static List<T> AddAlso<T>(this List<T> list, T item)
        {
            list.Add(item);
            return list;
        }
    }

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ChildName { get; set; }
    }
}

output:

A3 Premium Plus Car
A5 Premium Plus Car
A6 Premium Plus 55 TFSI quattro Car
S5 Premium Plus 3.0 TFSI quattro Car
S3 Premium Plus 3.0 TFSI quattro Car


texts:
Here is a namespace for wrapping boost accumulators for use in a broader code base. I love these accumulators but re-typedefing them everywhere is ugly and a pain.

I am not interested in C++11 alternatives. My code base does not put the starting bracket on a new line. My code base uses doxygen. Most of the style choices are deliberate.

I'm interested in any issues with using this in a broader code base. If anyone has tips on doxygen style for this type of thing, that would be helpful too.

#ifndef ACCUMULATORS
#define ACCUMULATORS

#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/mean.hpp>

//! The Accumulators namespace provides min, max, and average accumulators to the broader code base.
/*!
    This namespace defines accumulator types from boost. Also provided are specific extactors
    that will return the accumulator's current value.
*/
namespace Accumulators{

    //typedefs
    typedef boost::accumulators::accumulator_set< double,
        boost::accumulators::stats< boost::accumulators::tag::min>  > MinAccumulator;

    typedef boost::accumulators::accumulator_set< double,
        boost::accumulators::stats< boost::accumulators::tag::max>  > MaxAccumulator;

    typedef boost::accumulators::accumulator_set< double,
        boost::accumulators::stats< boost::accumulators::tag::mean> > MeanAccumulator;

    //extractors
    inline double extractMin(const MinAccumulator &acc){
        return  boost::accumulators::min(acc);
    }

    inline double extractMax(const MaxAccumulator &acc){
        return  boost::accumulators::max(acc);
    }

    inline double extractMean(const MeanAccumulator &acc){
        return  boost::accumulators::mean(acc);
    }
};
#endif

I would use this in another locations by including.

#include <Accumulators.h>

Then creating a one.

Accumulators::MaxAccumulator myMax;

Adding values

myMax(42); //... this is defined by boost

And then extracting the value for some other use.

Accumulators::extractMax(myMax);

Any issues with this or improvements that you can come up with?


texts: Memory efficient alternative passing mostly static variables w/ 1 dynamic variable to an external function (COM) instead of a for loop in Python

texts:
Massive data problem, 7/8 variables are repeated 1000 times in a for loop, sending 8 input vectors * 50,000 values per loop for each function call. Only 1 input vector changes in each loop iteration. The function being called is vectorized accepting list inputs and can accept any length vectors. The function returns its values into the variable FEUPnL.

Is there a way to vectorize the entire for loop without making copies of the input data that stays constant?  Or just not make copies of the static data. Memory issue otherwise, and very slow.

(Pandas DataFrame: FEU (input data), NumPy array S (changing values each loop))

import pandas as pd
import numpy as np

FEU = pd.read(FEU_inputs.csv)

#function outputs tuple format
FEUPnL = np.zeros(sims+1*len(FEU),dtype=tuple)
FEUPnL.resize(sims+1,len(FEU))

#function takes list inputs (FEU.x from a Pandas DataFrame)
FEU_strike = FEU.STRIKE.reset_index().values[:,1].tolist()
FEU_texpiry = FEU.TIMETOEXPIRYYEARS.reset_index().values[:,1].tolist()
FEU_vol = FEU.VOLATILITY.reset_index().values[:,1].tolist()
FEU_callput = FEU.CALL_FLAG.reset_index().values[:,1].tolist()
FEU_IR = FEU.IR.reset_index().values[:,1].tolist()
FEU_premium = np.zeros(len(FEU)).tolist()

for i in range(0,1001):
    FEUPnL[i] = optionpricer('p', FEU_callput, S[FEU.RFmap.values,i].tolist(), FEU_vol, FEU_strike, FEU_texpiry, FEU_IR, FEU_premium)


texts: Searching all diagonals of a 2D M x M array

texts:
I've started writing a piece of code to help me search for an object in all the objects found in the diagonals of an M x M 2D array.

Though the code works, I'd like to know if there is a way I can improve on it or there exists a different technique I could use to achieve the same result with fewer lines of code. I just don't want to re-invent the wheel.

// board must be a square matrix
bool allDiagonals(string[] board, string strToFind)
{
    string s = "";
    for (int col = board[0].Length - 1; col >= 0; col--)
    {

        int row = 0;
        int j = col;
        s = "";
        while (j <= board[0].Length - 1)
        {
            s += board[row++][j++];
        }
        if (s.Contains(strToFind))
            return true;
    }

    for (int row = board.Length - 1; row > 0; row--)
    {
        int colmin = 0;
        s = "";
        for (int i = row; i < board.Length; i++)
        {
            s += board[i][colmin++];
        }
        if (s.Contains(strToFind))
            return true;
    }

    for (int col = 0; col <= board[0].Length - 1; col++)
    {

        int row = 0;
        int j = col;
        s = "";
        while (j >= 0)
        {
            s += board[row++][j--];
        }
        if (s.Contains(strToFind))
            return true;
    }
    for (int row = board.Length - 1; row > 0; row--)
    {
        s = "";
        int colmax = board[0].Length - 1;
        //scan from bottom right to main diagonal
        for (int i = row; i < board.Length; i++)
        {
            s += board[i][colmax--];
        }
        if (s.Contains(strToFind))
            return true;
    }
    return false;
}


texts: Installing charts in parallel using go routines

texts:
I use the following code which works and install helm chart (in the loop) in parallel,
it get a kubeconfig file (to access to k8s) create a helm client and install the charts from the defined location and waits (upgradeAction.Wait = true) that each chart installation will finished successfully.
At first I do it in sequence and now I added a wait.group to be able to reduce the installation time and install it in parallel, do I miss something? error handling etc?
    package main

    import (
        "fmt"
        "os"
        "strings"
        "sync"
    )

    func main() {
      log.Info("tools Installation")

    kcfgFilePath, err := kubeFile(cfg)
    defer os.Remove(kcfgFilePath)
    if err != nil {
        return err
    }
    settings := cli.New()
    actionConfig := new(action.Configuration)
    clientGetter := genericclioptions.NewConfigFlags(false)
    clientGetter.KubeConfig = &kcfgFilePath
    // install all relevant components
    var wg sync.WaitGroup

    for _, chartInstallation := range charts {
        wg.Add(1)
         go installChart(&wg,chartInstallation, releaseName, actionConfig, clientGetter, settings, log)
    }
    return nil
}

func installChart(wg *sync.WaitGroup,chartInstallation Installation, releaseName string, actionConfig *action.Configuration, clientGetter *genericclioptions.ConfigFlags, settings *cli.EnvSettings, log logr.Logger) (error, bool) {
    defer wg.Done()
    chart, err := loader.Load(chartInstallation.Path)
    if err != nil {
        return err, true
    }
    releaseName = releaseName + "-" + chartInstallation.Name
    if err := actionConfig.Init(clientGetter, settings.Namespace(), os.Getenv("HELM_DRIVER"), func(format string, v ...interface{}) {
        r := fmt.Sprintf(format, v)
        log.Info("Helm Installation", "deploy status", r)
    }); err != nil {
        return err, true
    }
    releasePresent := true
    status, err := action.NewStatus(actionConfig).Run(releaseName)
    if err != nil {
        //if errors.Is(err, driver.ErrReleaseNotFound) {
        if strings.Contains(err.Error(), driver.ErrReleaseNotFound.Error()) {
            releasePresent = false
        } else {
            return err, true
        }
    }

    if !releasePresent {
        // install chart
        installAction := action.NewInstall(actionConfig)
        installAction.CreateNamespace = true
        installAction.Namespace = chartInstallation.Namespace
        installAction.ReleaseName = releaseName

        installAction.Wait = true
        // install new
        _, err := installAction.Run(chart, nil)
        if err != nil {
            return err, true
        }
        log.Info("installed: ", "releaseName", releaseName)
    }

    if status != nil {
        if releasePresent && status.Info.Status.String() == release.StatusFailed.String() { // upgrade if broken
            upgradeAction := action.NewUpgrade(actionConfig)
            upgradeAction.Atomic = false
            upgradeAction.CleanupOnFail = true
            upgradeAction.Wait = true
            upgradeAction.ReuseValues = false
            upgradeAction.Recreate = false
            _, err := upgradeAction.Run(releaseName, chart, nil)
            if err != nil {
                return err, true
            }
        }
    }
    return nil, false
}


texts: Update the value of a user based on the click of a checkbox

texts:
In an admin view on an intranet I maintain, there is a table of users present that allows admins to validate or delete users. Right now, the way the user is validated (or how they have their validation revoked) is by clicking a checkbox (i.e. a check in the checkbox signifies the user is validated, but no check means the user is not validated).

And right now I have an if/else statement that looks to see if the box has just been checked (or unchecked) and then sends the data to the server to achieve the desired outcome.

The code is not DRY at all, because the only difference in the code from the if/else statement is the state of the checkbox. How can I make the following code more DRY?

const chkBox = document.querySelectorAll("input[type=checkbox]");

for (box of chkBox) {
    box.addEventListener("change", updateUser, false);
}

function updateUser() {

    const messageBox = document.getElementById("message");

    if (this.checked) {

    // Getting the values to post to the server and the initialization requirements
        const postingValues = JSON.stringify({id:this.value, validated:true});
        const fetchInit = {method: "POST", headers: {"Content-type": "application/json"}, body: postingValues};

    // Making the fetch call and returning the message to the user
        fetch("index.php?action=updateLogin", fetchInit).then(function(response) {
            response.text().then(function(value) {
                messageBox.innerHTML = value;
            });
        });
    } else {

    // Getting the values to post to the server and the initialization requirements
        const postingValues = JSON.stringify({id:this.value, validated:false});
        const fetchInit = {method: "POST", headers: {"Content-type": "application/json"}, body: postingValues};

    // Making the fetch call and returning the message to the user
        fetch("index.php?action=updateLogin", fetchInit).then(function(response) {
            response.text().then(function(value) {
                messageBox.innerHTML = value;
            });
        });
    }
}


texts:
A date is un-ambiguous when each number may be
    decided to be day or month or year given the range
    limitation of these numbers.

For example

\$14\$ cannot be a month number
\$2008\$ cannot be a day number

@param un_ambiguous_date: an un-ambiguous scrambled date,
    of the format X/Y/Z where X, Y, Z correspond to
    day, month, year but not necessarily in this order.

@return The date in the order 'DAY/MONTH/YEAR'.

I am particularly interested in full input validation and nice error producing, so tell me any lack of clarity/corner case missed.

For example usage see the doctests included with the function:

def order_date(un_ambiguous_date):
    """
    @param un_ambiguous_date: an un-ambiguous scrambled date,
    of the format X/Y/Z where X, Y, Z correspond to
    day, month, year but not necessarily in this order.

    @return: The date in the order 'DAY/MONTH/YEAR'.

    A date is un-ambiguous when each number may be
    decided to be day or month or year given the range
    limitation of this numbers.
    (For example 14 cannot be a month number, and
    2008 cannot be a day number)

    >>> order_date('3/2015/13')
    '13/3/2015'

    >>> order_date('2012/20/4')
    '20/4/2012'

    # Here both 3/4/1000 and 4/3/1000 are possible.
    >>> order_date('3/4/1000')
    Traceback (most recent call last):
    ...
    ValueError: Ambiguous date was given

    >>> order_date('3/3/2050')
    '3/3/2050'

    >>> order_date('1/1/1')
    Traceback (most recent call last):
    ...
    ValueError: The date cannot be valid

    >>> order_date('12/6')
    Traceback (most recent call last):
    ...
    ValueError: The date is too short, format should be X/Y/Z

    >>> order_date('2000/2000')
    Traceback (most recent call last):
    ...
    ValueError: The date is too short, format should be X/Y/Z

    >>> order_date('Foo/Bar/Baz')
    Traceback (most recent call last):
    ...
    TypeError: The date should be made up of '/' separated INTEGERS

    """
    try:
        x, y, z = un_ambiguous_date.split('/')
    except ValueError:
        raise ValueError("The date is too short, format should be X/Y/Z")

    try:
        x, y, z = map(int, (x, y, z))
    except ValueError:
        raise TypeError("The date should be made up of '/' separated INTEGERS")

    day = [i for i in (x,y,z) if i < 31]
    month = list(set(i for i in (x,y,z) if i < 12))
    year = [i for i in (x,y,z) if i > 31]
    day = list(set(day) - set(month))
    if not day:
        day = month
    # print(day, month, year)
    if any(len(x) > 1 for x in (day, month, year)):
        raise ValueError("Ambiguous date was given")
    try:
        return '/'.join(map(str, (day[0], month[0], year[0])))
    except IndexError:
        raise ValueError("The date cannot be valid")


texts:
I have a little experience with Python and am trying to become more familiar with it. As an exercise, I've tried coding a program where the ordering of a list of players is determined by the roll of a die. A higher number would place the player ahead of others with lower numbers. Ties would be  broken by the tied players rolling again.

Here is an example:

                           player 1, player 2, player 3
                            rolls 6, rolls 6, rolls 1
                                 /           \
                                /             \
                       player 1, player 2    player 3
                        rolls 5, rolls 4
                         /       \
                        /         \
                   player 1    player 2

Final order: player 1, player 2, player 3

I'm interested in how I could have done this better. In particular, I'm not familiar with much of the Python style guide so making it more pythonic would be nice. Also, I'm not that familiar with unit testing. I've used unittest instead of nose since I was using an online IDE that supports it.

from random import randint
from itertools import groupby
import unittest

def rank_players(playerList, die):
    tree = [playerList]
    nextGeneration = []
    keepPlaying = True
    while keepPlaying:
        keepPlaying = False
        for node in tree:
            if len(node) == 1:
                nextGeneration.append(node)
            else:
                keepPlaying  = True
                rolls = [die.roll() for i in range(len(node))]
                turn = sorted(zip(rolls,node), reverse=True)
                print 'players roll:', turn
                for key, group in groupby(turn, lambda x: x[0]):
                    nextGeneration.append(list(i[1] for i in group))
        tree = nextGeneration
        nextGeneration = []
    return [item for sublist in tree for item in sublist]

class Die:
    def __init__(self,rolls=[]):
        self.i = -1
        self.rolls = rolls

    def roll(self):
        self.i = self.i + 1
        return self.rolls[self.i]

class RankingTest(unittest.TestCase):

    def testEmpty(self):
        die = Die()
        players = []
        self.assertEquals(rank_players(players,die),[])

    def testOnePlayer(self):
        die = Die()
        player = ['player 1']
        self.assertEquals(rank_players(player,die),['player 1'])

    def testTwoPlayer(self):
        die = Die([6, 1])
        players = ['player 1', 'player 2']
        self.assertEquals(rank_players(players,die),['player 1', 'player 2'])

    def testThreePlayer(self):
        die = Die([6, 6, 1, 4, 5])
        players = ['player x', 'player y', 'player z']
        self.assertEquals(rank_players(players,die),['player x', 'player y','player z'])

    def testRunAll(self):
        self.testEmpty()
        self.testOnePlayer()
        self.testTwoPlayer()
        self.testThreePlayer()

if __name__ == '__main__':
    unittest.main()


texts:
I want to make it lightweight (fastest, best performance) as it possible for browser, but I have no idea - I haven't huge knowledge about JavaScript.

That code run parallax effect on my web page. I have three parallax containers, which are different position background image. Script call on scroll event and when some container exist it's making it parallax-y. The first container ('.parallax-top') exists always and hasn't any offset of image - it is always top-positioned. Second and third have offsets (1700 and 1400).

My page have a lot of content, scripts, images and I want to make all of them lightweight as it is possible.

if ($(window).width() > 1200) {
    (function() {
        var parallaxTop = document.querySelectorAll(".parallax-top");
        if ($(".parallax-center").length) {
            var parallaxCenter = document.querySelectorAll(".parallax-center");
            var centerPosition = $(".parallax-center").position().top;
        }

        if ($(".parallax-bottom").length) {
            var parallaxBottom = document.querySelectorAll(".parallax-bottom");
            var bottomPosition = $(".parallax-bottom").position().top;
        }
        var speed = 0.4;
        window.onscroll = function() {

            [].slice.call(parallaxTop).forEach(function(el, i) {
                var windowYOffset = window.pageYOffset,
                    elBackgrounPos = "center " + "-" + (windowYOffset * speed) + "px";
                el.style.backgroundPosition = elBackgrounPos;
            });
            if ($(".parallax-center").length)
                [].slice.call(parallaxCenter).forEach(function(el, i) {
                    var windowYOffset = window.pageYOffset,
                        elBackgrounPos = "center " + "" + ((windowYOffset - centerPosition) * speed + 1700) + "px";
                    el.style.backgroundPosition = elBackgrounPos;
                });
            if ($(".parallax-bottom").length)
                [].slice.call(parallaxBottom).forEach(function(el, i) {
                    var windowYOffset = window.pageYOffset,
                        elBackgrounPos = "center " + "" + ((windowYOffset - bottomPosition) * speed + 1400) + "px";
                    el.style.backgroundPosition = elBackgrounPos;
                });
        };
    })();
}


texts:
Using Python 2.7.12 I wrote a simple little script, psk_validate.py, that prompts the user for a potential password and checks if it has upper and lower-case characters, numbers, special characters, and that it has a length of at least 8 characters.

From what I understand one could use the regex library to write this much more efficiently, however, I have yet to learn about regex.

The program seems to work just fine, and with a program this small I think that not using regex is also just fine.

I'd like any and all feedback about this program. In particular, I'd like to know if a program written this simply could be used in real-world applications. I'd also like to know if there are any logical errors and/or bugs in the program.

from sys import exit

def check_upper(input):
    uppers = 0
    upper_list = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split()
    for char in input:
        if char in upper_list:
            uppers += 1
    if uppers > 0:
        return True
    else:
        return False

def check_lower(input):
    lowers = 0
    lower_list = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split()
    for char in input:
        if char in lower_list:
            lowers += 1
    if lowers > 0:
        return True
    else:
        return False

def check_number(input):
    numbers = 0
    number_list = "1 2 3 4 5 6 7 8 9 0".split()
    for char in input:
        if char in number_list:
            numbers += 1
    if numbers > 0:
        return True
    else:
        return False

def check_special(input):
    specials = 0
    special_list = "! @ $ % ^ & * ( ) _ - + = { } [ ] | \ , . > < / ? ~ ` \" ' : ;".split()
    for char in input:
        if char in special_list:
            specials += 1
    if specials > 0:
        return True
    else:
        return False

def check_len(input):
    if len(input) >= 8:
        return True
    else:
        return False

def validate_password(input):
    check_dict = {
        'upper': check_upper(input),
        'lower': check_lower(input),
        'number': check_number(input),
        'special': check_special(input),
        'len' : check_len(input)
    }
    if check_upper(input) & check_lower(input) & check_number(input) & check_special(input) & check_len(input):
        return True
    else:
        print "Invalid password! Review below and change your password accordingly!"
        print
        if check_dict['upper'] == False:
            print "Password needs at least one upper-case character."
        if check_dict['lower'] == False:
            print "Password needs at least one lower-case character."
        if check_dict['number'] == False:
            print "Password needs at least one number."
        if check_dict['special'] == False:
            print "Password needs at least one special character."
        if check_dict['len'] == False:
            print "Password needs to be at least 8 characters in length."
        print

while True:
    password = raw_input("Enter desired password: ")
    print
    if validate_password(password):
        print "Password meets all requirements and may be used."
        print
        print "Exiting program..."
        print
        exit(0)


texts:
In reading a file, I found blank lines (even at the bottom) crash the program. To fix this, I've added the following if statement:

string line;
while(getline(inFile, line))
{
    if(line.length() < 1 || (line.length() == 1 && isspace(line.at(0))))//this was added
        continue;
    string result = process(line);
    aStruct.field1 = result;
    //...rest of code
}

For what it's worth, it can be assumed there isn't going to be a bizarre mix of white space making an entire line. For example, one line isn't going to be six spaces (maybe one space, by mistake). This solution isn't exactly elegant.