texts: Moving window with complete boundary in Python

texts:
I asked this question a few days ago. The question is about producing moving/rolling windows of an array in Python as in the following example:

from skimage.util import view_as_windows
view_as_windows(np.arange(10*10).reshape(10,10), (4,4),4)

Out[14]:
array([[[[ 0,  1,  2,  3],
         [10, 11, 12, 13],
         [20, 21, 22, 23],
         [30, 31, 32, 33]],

        [[ 4,  5,  6,  7],
         [14, 15, 16, 17],
         [24, 25, 26, 27],
         [34, 35, 36, 37]]],

       [[[40, 41, 42, 43],
         [50, 51, 52, 53],
         [60, 61, 62, 63],
         [70, 71, 72, 73]],

        [[44, 45, 46, 47],
         [54, 55, 56, 57],
         [64, 65, 66, 67],
         [74, 75, 76, 77]]]]).

However, this removes elements of the original arrays that don't fit into another window. It was suggested that I should fill the arrays with zeros in order to get a full window, so I wrote the following code for doing so and I thought it would be nice to have a review in case I missed corner cases:

import numpy as np

def extend_image(image, steps=16):
    # Required number of rows
    required_rows = np.mod(image.shape[0], steps)
    # Required number of columns
    required_cols = np.mod(image.shape[1], steps)
    # Concatenate original array with rows filled with zeros
    partial = np.concatenate((image, np.zeros((required_rows,image.shape[1]))))
    # Concatenate partial array with columns filled with zeros
    extended = np.concatenate((partial, np.zeros((partial.shape[0], required_cols))), axis=1)
    return extended

This should work as follows:

view_as_windows(extend_image(np.arange(10*10).reshape(10,10), steps=4), (4,4),4)

array([[[[  0.,   1.,   2.,   3.],
         [ 10.,  11.,  12.,  13.],
         [ 20.,  21.,  22.,  23.],
         [ 30.,  31.,  32.,  33.]],

        [[  4.,   5.,   6.,   7.],
         [ 14.,  15.,  16.,  17.],
         [ 24.,  25.,  26.,  27.],
         [ 34.,  35.,  36.,  37.]],

        [[  8.,   9.,   0.,   0.],
         [ 18.,  19.,   0.,   0.],
         [ 28.,  29.,   0.,   0.],
         [ 38.,  39.,   0.,   0.]]],

       [[[ 40.,  41.,  42.,  43.],
         [ 50.,  51.,  52.,  53.],
         [ 60.,  61.,  62.,  63.],
         [ 70.,  71.,  72.,  73.]],

        [[ 44.,  45.,  46.,  47.],
         [ 54.,  55.,  56.,  57.],
         [ 64.,  65.,  66.,  67.],
         [ 74.,  75.,  76.,  77.]],

        [[ 48.,  49.,   0.,   0.],
         [ 58.,  59.,   0.,   0.],
         [ 68.,  69.,   0.,   0.],
         [ 78.,  79.,   0.,   0.]]],

       [[[ 80.,  81.,  82.,  83.],
         [ 90.,  91.,  92.,  93.],
         [  0.,   0.,   0.,   0.],
         [  0.,   0.,   0.,   0.]],

        [[ 84.,  85.,  86.,  87.],
         [ 94.,  95.,  96.,  97.],
         [  0.,   0.,   0.,   0.],
         [  0.,   0.,   0.,   0.]],

        [[ 88.,  89.,   0.,   0.],
         [ 98.,  99.,   0.,   0.],
         [  0.,   0.,   0.,   0.],
         [  0.,   0.,   0.,   0.]]]])


texts:
Report time at whole hours

#!/usr/bin/python3
import time
from datetime import datetime
from pydub import AudioSegment
from pydub.playback import play

bell_sound = AudioSegment.from_wav("/home/me/Music/audio/bell.wav")

while True:
    now = datetime.now()
    # repeats = 1 if now.hour % 3 == 0 else now.hour % 3
    repeats = now.hour % 3 + 1

    if now.hour < 6:
        break
    # report on whole hour
    if now.minute == 0:
        for _ in range(repeats):  # bell the hours
            play(bell_sound)
        time.sleep(60 * 58)  # save the computation
    if now.minute != 0:
        time.sleep(10)
    # quit 23 later
    if now.hour == 23:
        break

Any ideas to improve it?


texts:
I have 2 objects and I am comparing them to see which fields are equal and which are different.

But I am not sure my loop is 100% correct. Does this look ok?  If so, what other ways could this be coded to make it 'neater'.  e.g. using LINQ

I want to: loop through each DocumentType in both objects, and for each documentType - I want to loop through each DocumentTypeVersion and compare this.

foreach (DocumentType documentType in documentTypes)
{
    foreach (DocumentType importDocumentType in importedDocumentTypes)
    {

        if (documentType.Id == importDocumentType.Id)//ensure its the same documentType we are comparing
        {
            foreach (DocumentTypeVersion version in documentType.Versions)
            {
                foreach (DocumentTypeVersion importedVersion in importDocumentType.Versions)
                {
                    if (version.Id == importedVersion.Id)//ensure its the same documentTypeVersion we are comparing
                    {
                        //check if the versions are equal
                        bool areVersionsEqual = Equals(version, importedVersion);

                    }

                }
            }
        }
    }
}


texts: Split large import task into smaller subtasks

texts:
I have a large import task that runs as a cronjob and I want
to split that task in smaller subtasks. Each subtask should be handled by
an own class.

At the cronjob entry point I prepare the import-file and want to pass it to
sub-functions e.g.

$category = new categoryImport($param1, $param2);
$category->importCategories()

$articles = new articlesImport($param1, $param2);
$articles->importArticles();

But it feels wrong to instantiate a class to run a single method and after that the
instance isn't necessary anymore.

My second thought was to use a static method.

categoryImport::importCategories($param1, $param2);
articlesImport::importArticles($param1, $param2);

But inside the class (e.g. categoryImport) a few more methods are needed to split the task in smaller tasks. And some basic information are needed in many of them.

In the normal class context I would use member variables and use $this->$var in every method that needs this information but with static methods this is not working.

I could pass all informations as parameters to all methods that need them but that feels wrong too. (Yes I know dependency injection).

Now I am unsure what is the 'right' solution for this task and I look forward to your feedback.


texts:
I'm writing a finite state machine based on a transition table in C++ 14.
My code so far looks like:

#include <array>
#include <functional>

template < typename _State, typename _Event >
class FSM {
  static constexpr size_t state_count = static_cast<size_t>(_Event::_);
  static constexpr size_t event_count = static_cast<size_t>(_State::_);

  using _FuncPtr = typename std::function<_State(_State)>;
  using _Table   = typename std::array< std::array< _FuncPtr, state_count >, event_count >;

  _State _current;
  _Table _transitions;

public:
  FSM(_State initial, _Table transitions) : _current(initial), _transitions(transitions) {};

  void operator()(const _Event& event) {
    _current = _transitions[static_cast<size_t>(event)][static_cast<size_t>(_current)](_current);
  }

  _State state() const { return _current; }
};

The usage looks like:

/*            States & Events            */
enum class State : char { Locked, Unlocked,    _ };
enum class Event : char { Pass, Coin,          _ };

/*              Transitions              */
State alarm(State current) {
  cout << "Alarm" << endl;
  return current;
}

State unlock(State current) {
  cout << "Unlock" << endl;
  return State::Unlocked;
}

State lock(State current) {
  cout << "Lock" << endl;
  return State::Locked;
}

State thankyou(State current) {
  cout << "Thankyou" << endl;
  return current;
}

void main() {
  auto fsm = FSM< State, Event >(State::Locked, {{
    // Locked    Unlocked
    {  alarm,    lock      },  // Pass
    {  unlock,   thankyou  }   // Coin
  }});

  // To switch states
  fsm(Event::Coin);
  fsm(Event::Pass);
}

Is there some way I can further simplify it?


texts:
win_xept.hpp - a basic windows api exception
#include "../utl_macro.hpp"

namespace xept
{
    using win_t = struct utl_exception // utl_exception randomly generates a name
                                       // this hides exception names from rtti
    {
        DWORD e = GetLastError( );
    };
}

ramfile.hpp - an interface for any type of file where the data is needed in ram
#pragma once

class ramfile_t
{
public:
    virtual std::uintmax_t size( ) = 0;
    virtual std::vector< std::byte > raw( ) = 0;
    virtual void overwrite( std::vector< std::byte > const & raw,
                            std::size_t const & off = 0 ) = 0;
    virtual void set( std::vector< std::byte > const & raw ) = 0;
};

ramfile_xept.hpp - the basic ramfile exception
#include "../win_xept.hpp"

namespace xept
{
    using ramfile_t = struct utl_exception:
        win_t
    { };
}

ramfile_disk.hpp - basic file for disk
class ramfile_disk_t:
    public ramfile_t
{
public:
    ramfile_disk_t( std::filesystem::path path ):
        path( std::move( path ) ),
        file_guard( file_locks[ this->path.c_str( ) ] )
    {
        assert( path.is_absolute( ) );
    }

    std::uintmax_t size( ) final
    {
        return std::filesystem::file_size( path );
    }

    std::vector< std::byte > raw( ) final
    {
        std::basic_ifstream< std::byte > file( path,
                                               std::ofstream::binary );

        assert( file.is_open( )
                && file.good( ) );

        file.seekg( 0 );

        return std::vector< std::byte >( std::istreambuf_iterator< std::byte >( file ),
                                         std::istreambuf_iterator< std::byte >( ) );
    }

    void set( std::vector< std::byte > const & data ) final
    {
        std::basic_ofstream< std::byte > file( path,
                                               std::ofstream::binary | std::ofstream::trunc );

        assert( file.is_open( )
                && file.good( ) );

        file.write( data.data( ),
                    data.size( ) );
    }

    void overwrite( std::vector< std::byte > const & data,
                    std::size_t const & off = 0 ) final
    {
        std::basic_ofstream< std::byte > file( path,
                                               std::ofstream::binary );

        assert( file.is_open( )
                && file.good( ) );

        file.seekp( off ).write( data.data( ),
                                 data.size( ) );
    }

    void set_attr( bool readonly,
                   bool hidden )
    {
        DWORD attr = 0;

        if ( readonly )
            attr |= FILE_ATTRIBUTE_READONLY;
        if ( hidden )
            attr |= FILE_ATTRIBUTE_HIDDEN;

        if ( 0 == SetFileAttributes( path.c_str( ),
                                     attr
                                         ? attr
                                         : FILE_ATTRIBUTE_NORMAL ) )
            throw xept::ramfile_disk_attr_t( );
    }

protected:
    std::filesystem::path path;

private:
    using file_locks_t = std::unordered_map< std::wstring_view,
                                             std::mutex >;
    static file_locks_t file_locks;

    std::lock_guard< file_locks_t::mapped_type > file_guard;
};

ramfile_disk_xept.hpp - exceptions throwable from ramfile_disk
#include "ramfile_xept.h"

namespace xept
{
    using ramfile_disk_attr_t = struct utl_exception:
        ramfile_t
    { };
}


texts: Reverse a sentence quickly without pointers

texts:
I am trying to reverse a sentence contained in a string and return a string in the quickest way possible using the least amount of memory. Also I don't want to use any unsafe code, so no pointers are allowed. Please let me know if anything can be improved.

My input example is

string mystring = "Hello! my name is";

My result is

  "is name my Hello!"

My results on i7 4770S for 1000000 iterations is on average around 650ms.

public static string ReverseTheString(string MyString)
{

    int Length = MyString.Length;
    Char[] NormalArray = new char[Length];
    Char[] FinalArray = new char[Length];

    for (int i = 0; i < Length; i++)
    {
        NormalArray[i] = MyString[i];
    }
    Length = Length - 1; //use for last index
    int SpacesCount = 0;
    int AlphaCount = 0;

    Stack<char[]> ReversedArray = new Stack<char[]>();

    for (int i = 0; i < NormalArray.Length; i++)
    {
        if (NormalArray[i] == ' ' && i != Length)//Space
        {
            if (i != Length)
            {
                if (AlphaCount > 0)
                {
                    char[] temparray = new char[AlphaCount];
                    int tempindex = i - AlphaCount;
                    for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    AlphaCount = 0;
                    temparray = null;
                }

                SpacesCount++;
            }
            else
            {

                SpacesCount++;
                if (SpacesCount > 0)
                {
                    char[] temparray = new char[SpacesCount];
                    int tempindex = i + 1 - SpacesCount;
                    for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    SpacesCount = 0;
                    temparray = null;
                }

            }
        }

        if (NormalArray[i] != ' ' ) //alpha
        {
            if (i != Length)
            {
                if (SpacesCount > 0)
                {
                    char[] temparray = new char[SpacesCount];
                    int tempindex = i - SpacesCount;
                    for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    SpacesCount = 0;
                    temparray = null;
                }
                AlphaCount++;
            }
            else
            {
                AlphaCount++;
                if (AlphaCount > 0)
                {
                    char[] temparray = new char[AlphaCount];
                    int tempindex = i + 1 - AlphaCount;
                    for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    AlphaCount = 0;
                    temparray = null;
                }
            }
        }
    }

    int Pos = 0;
    while (ReversedArray.Count > 0)
    {
        char[] temparray = ReversedArray.Pop();

        for (int j = 0; j < temparray.Length; j++)
        {
            FinalArray[Pos] = temparray[j];
            Pos++;
        }
    }

    return new string(FinalArray);
}


texts:
I wrote a function that joins a collection of Strings with a delimiter. It's based on Java's version of the function. I'm assuming C has some similar built-in.

Example:

int main() {
    char* coll[] = {"Hello", "World", "This", "Should", "Be", "Joined!"};
    char* joined = awfulJoinStr(", ", coll, 6);

    printf("%s\n", joined);
    // Prints "Hello, World, This, Should, Be, Joined!"
}

Basically how it works is, it alternates between iterating the collection strings and the delimiter. It writes the current word to the buffer until it hits a null terminator, then it switches to either writing the next word, or to the delimiter.

I'm new to C, so I'd like comments on anything in the code. My main concerns:

It's super inefficient. All the strings need to be iterated at the start to get a total length so I know how big of a buffer to allocate later. I can't see how else I'd do it though unless I do reallocations while writing, but that seems like it would be even more inefficient.
It requires three iteration counters (stringI, charI, and bufferI) and a flag. I need to keep track of the current word that I'm writing, my position in it, and need to track where I am in the buffer. I also need a flag to track when I'm currently writing a delimiter or word.
It requires passing in how many strings I want to join (nStrings). This seems like it's necessary as well since I can't know the length of strArr, but it's unfortunate.
It's huge. It doesn't fit in one screen at a comfortable zoom.

I also included my version of strlen for kicks, and because I used it instead of the built-in.

#include <stdlib.h>
#include <stdbool.h>

size_t myStrLen(char* str) {
    size_t length = 0;

    while (str[length] != '\0') {
        length++;
    }

    return length;
}

char* awfulJoinStr(char* delimiter, char** strArr, size_t nStrings) {
    size_t delimiterSize = myStrLen(delimiter);
    size_t totalDelimiterSize = (nStrings - 1) * delimiterSize;

    size_t totalStringSize = 0;
    for (size_t i = 0; i < nStrings; i++) {
        totalStringSize += myStrLen(strArr[i]);
    }

    size_t bufferSize = totalDelimiterSize + totalStringSize + 1;
    char* buffer = malloc(sizeof(char) * bufferSize);
    buffer[bufferSize - 1] = '\0';

    bool inDelim = false;
    size_t charI = 0;
    size_t stringI = 0;
    for (size_t bufferI = 0; bufferI < bufferSize - 1;) {
        char current = inDelim ? delimiter[charI] : strArr[stringI][charI];

        if (current == '\0') {
            // Start at the beginning of the word and toggle what we're writing
            charI = 0;

            if (!inDelim) {
                stringI++;
            }

            inDelim = !inDelim;

        } else {
            buffer[bufferI] = current;

            charI++;
            bufferI++;
        }
    }

    return buffer;
}


texts:
Here I want to lock when populating a particular cache object, without blocking other calls to the same method requesting Foos for other barIds. I realise the MemoryCache will be thread safe, but if two or more concurrent calls come in it seems like it would be better if only one of them populates the cache and locks the others out while this is done.

using System.Runtime.Caching;
using Microsoft.Practices.Unity;

public class FooCacheService : IFooService
{
        private static readonly ConcurrentDictionary<string, object> FooServiceCacheLocks = new ConcurrentDictionary<string, object>();

        [Dependency("Explicit")]
        public IFooService ExplicitService { get; set; }

        public IEnumerable<Foo> GetFoosForBar(int barId)
        {
            string key = barId.ToString();

            object lockObject = FooServiceCacheLocks.GetOrAdd(key, new object());

            object cached = MemoryCache.Default[key];

            if (cached == null)
            {
                lock (lockObject)
                {
                    cached = MemoryCache.Default[key];

                    if (cached == null)
                    {
                        IEnumerable<Foo> foosForBar = this.ExplicitService.GetFoosForBar(barId);

                        MemoryCache.Default.Add(key, foosForBar, DateTime.Now.AddMinutes(5));

                        return foosForBar;
                    }
                }
            }

            return (IEnumerable<Foo>)cached;
        }
}

Assume GetFoosForBar is a CPU/IO intensive process and takes a short while to complete. Does this seem like a reasonable way to achieve this? I'm surprised that System.Runtime.Caching does not provide any support for this as default - or have I overlooked something?


texts:
I am trying to learn Java by doing some (easy) ACM ICPC problems. The problem consist to check if the knight in a chess game can move from a point A(r1, c1) to B(r2, c2) with one move only.

package dalia;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Dalia {
  static int[] moves = { -1, 2, -1, -2, 1, 2, 1, -2, -2, 1, -2, -1, 2, 1, 2, -1 };

  public static void main(String[] args) throws IOException {
    File fin = new File("./dalia.in");
    knight(fin);
  }

  private static void knight(File fin) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(fin))) {
      String line;
      // Read the number of cases.
      int numberOfCases = Integer.parseInt(br.readLine());

      int[] cord = new int[5];
      String[] parts;
      int i = 0;
      // Solve each case
      while ((line = br.readLine()) != null && i < numberOfCases) {
        // Split the line to array of integer
        parts = line.split(" ");
        for (int j = 0; j < 5; j++) {
          cord[j] = Integer.parseInt(parts[j]);
        }
        // Print case number
        i++;
        System.out.print("Case " + i + ": ");
        // Check if the knight can move
        if (validMove(cord[0], cord[1], cord[2], cord[3], cord[4]))
          System.out.println("YES");
        else
          System.out.println("NO");
      }
      br.close();

    }
  }

  private static boolean validMove(int n, int r1, int c1, int r2, int c2) {
    // Return True if the knight can move from (r1, c1) to (r2, c2) in one
    // move
    for (int i = 0; i < moves.length; i = i + 2) {
      if (r1 == r2 + moves[i] && c1 == c2 + moves[i + 1] && stillInTheBoard(n, r2, moves[i])
          && stillInTheBoard(n, c2, moves[i + 1]))
        return true;

    }
    return false;
  }

  private static boolean stillInTheBoard(int n, int x1, int x2) {
    // Check if the knight still in the board after making the move
    return (1 <= x1 + x2 && x1 + x2 <= n);
  }

}

Example:

Input:

2
4 1 2 2 4
5 1 1 3 3

Output:

Case 1: YES
Case 2: NO

Where the first number is n, the number of block in the Chess board (in the normal Chess board n = 8).

I'm looking for a review in terms of best practices, things I should or shouldn't do, or things I should do in another way.


texts: Precompiled templates with initializators (factory pattern) or single interface and method or what else?

texts:
PROBLEM

I'm trying to use authboss (https://github.com/volatiletech/authboss) with quicktemplate (https://github.com/valyala/quicktemplate).

The authboss rendering system is defined by one interface: Renderer.

I have created two different versions of the solution and would like to know which one is best or if there is a third one better.

https://github.com/frederikhors/authbossQuicktemplate_1, with factory pattern and initializators
https://github.com/frederikhors/authbossQuicktemplate_2, with interface and a SetData(data authboss.HTMLData) (page PageImpl) method

QUESTIONS

I don't know what to improve for performances.

Is it possible to do the same thing differently and less in terms of hardware resources?
Do you think I can improve using pointers somewhere?

RELEVANT CODE

Solution with Factory pattern and initializators:

type HTML struct {
  templates map[string]func(authboss.HTMLData) templates.PageImpl
}

func (h *HTML) Load(names ...string) error {
  for _, n := range names {
    switch n {
    case "login":
      h.templates[n] = InitializeLoginPage
    case "recover":
      h.templates[n] = InitializeRecoverPage
    }
  }
  return nil
}

func (h *HTML) Render(ctx context.Context, page string, data authboss.HTMLData) (output []byte, contentType string, err error) {
  buf := &bytes.Buffer{}
  tpl, ok := h.templates[page]
  if !ok {
    return nil, "", errors.Errorf("template for page %s not found", page)
  }
  templates.WritePage(buf, tpl(data))
  return buf.Bytes(), "text/html", nil
}

func InitializeLoginPage(data authboss.HTMLData) templates.PageImpl {
  return &templates.LoginPage{Data: data}
}

func InitializeRecoverPage(data authboss.HTMLData) templates.PageImpl {
  return &templates.RecoverPage{Data: data}
}

Solution with interface with a method

type HTML struct {
  templates map[string]templates.AuthPageImpl
}

func (h *HTML) Load(names ...string) error {
  for _, n := range names {
    switch n {
    case "login":
      h.templates[n] = &templates.LoginPage{}
    case "recover":
      h.templates[n] = &templates.RecoverPage{}
    }
  }
  return nil
}

func (h *HTML) Render(ctx context.Context, page string, data authboss.HTMLData) (output []byte, contentType string, err error) {
  buf := &bytes.Buffer{}
  tpl, ok := h.templates[page]
  if !ok {
    return nil, "", errors.Errorf("template for page %s not found", page)
  }
  template := tpl.SetData(data)
  templates.WritePage(buf, template)
  return buf.Bytes(), "text/html", nil
}

type AuthPageImpl interface {
  SetData(data authboss.HTMLData) PageImpl
}

type LoginPage struct {
  Data authboss.HTMLData
}

type RecoverPage struct {
  Data authboss.HTMLData
}

func (p *LoginPage) SetData(data authboss.HTMLData) (page PageImpl) {
  p.Data = data
  return p
}

func (p *RecoverPage) SetData(data authboss.HTMLData) PageImpl {
  p.Data = data
  return p
}
```


texts:
After a successful fgets(buffer, ...), it is often desirable to trim a potential End-of-Line '\n'.

Of the following 2 methods, are there any shortcomings?

#include <stdio.h>

char buffer[100];

// Method 1
while (fgets(buffer, sizeof buffer, stdin) != NULL) {
  size_t len = strlen(buffer);
  if (len > 0 && buffer[len - 1] == '\n')
    buffer[--len] = '\0';

  // use buffer
  printf("\"%s\"\n", buffer);
}

// Method 2
while (fgets(buffer, sizeof buffer, stdin) != NULL) {
  strtok(buffer, "\n");

  // use buffer
  printf("\"%s\"\n", buffer);
}

Notes:

When reading text files from alternate file systems, strtok(buffer, "\r\n") looks useful.
strtok() may incur an issue with another strtok() sequence.


texts: Prioritizing the most important value in an array

texts:
I have an array of names where I need to find the most important person.

This is my array. I cannot edit this array unless I create a copy of it

$data = [
    'Jack',
    'Josh',
    'Boris',
    'Bob',
    'Boris',
    'Jack',
    'Josh'
];

The most important person is number 1. After number 1 the most improtant person is number 2 and so on. These are the priorities.

Jack
Bob
Boris
Josh

The best way of tackling this issue I could think of is like the following:

$i = 5;
foreach ($data as $val) {
    if ($val == 'Jack' && $i > 1) {
        $myValue = $val;
        $i = 1;
        break;
    } else if ($val == 'Bob' && $i > 2) {
        $myValue = $val;
        $i = 2;
    } else if ($val == 'Boris' && $i > 3) {
        $myValue = $val;
        $i = 3;
    } else if ($val == 'Josh' && $i > 4) {
        $myValue = $val;
        $i = 4;
    }
}

It works great. But it just doesn't feel right.

Is prioritizing it like this common practice?


texts: Function that performs a test of whether a number is greater or less than some expected result

texts:
The program that contains the function I'm asking (handle_non_exact_answer) about has several instances of a class Test, with some options the user can set that determines the behavior of the class. If the class has certain options, we handle the class differently, so I deal with these cases in a separate function, which is below.

I would like to learn a) how to better write the function (ideally in the "most pythonic" way,) and b) how to resolve a pylint warning related to this function: Unnecessary "else" after "return".

import random
class Test:
    def __init__(self):
        self.precision = None
        self.expected_result = None

def handle_non_exact_answer(test, answer):
    if test.precision not in {"less", "more", "lesser", "greater"}:
        return False
    else:
        if test.precision == "less" and answer < test.expected_result:
            print("passed")
        elif test.precision == "more" and answer > test.expected_result:
            print("passed")
        elif test.precision == "lesser" and answer <= test.expected_result:
            print("passed")
        elif test.precision == "greater" and answer >= test.expected_result:
            print("passed")
        else:
            print("failed")
    return True

def main():
    test = Test()
    test.precision = "greater"
    test.expected_result = 0
    test1 = Test()
    test1.precision = "lesser"
    test1.expected_result = 0
    test2 = Test()
    test2.precision = "more"
    test2.expected_result = 0
    test3 = Test()
    test3.precision = "less"
    test3.expected_result = 0

    tests = [test, test1, test2, test3]

    for test in tests:
        handle_non_exact_answer(test, random.randint(-10,10))

if __name__ == "__main__":
    main()


texts: Optimizing hundreds of millions of SQLite database inserts in Python

texts:
Some background

Feel free to skip this if you're not interested.

There is a very popular bioinformatics program called tabix that permits interval-based searches for genetic variants in VCF files. To list all variants from position 100000 to 150000 on chromosome 1, one would invoke tabix db.vcf chr1:100000-150000.

I created a program named rsidx that permits similar queries, but using variant identifiers (rsIDs) instead of chromosome coordinates. rsidx index creates an index, and rsidx search performs the search. Under the hood, rsidx index simply creates an SQLite database with a mapping of rsIDs to chromosome coordinates. Once the index is constructed, rsidx search returns the coordinates associated with a variant, and then uses tabix to retrieve the variant at that coordinate.

The code

The following code is used to populate an SQLite database, mapping each rsID to a chromosome coordinate. vcfstream is a generator that scans an input file and retrieves the relevant data to populate the database.

The full code is here.

def index(dbconn, vcffh, cache_size=None, mmap_size=None, logint=1e6):
    c = dbconn.cursor()
    c.execute(
        'CREATE TABLE rsid_to_coord ('
        'rsid INTEGER PRIMARY KEY, '
        'chrom TEXT NULL DEFAULT NULL, '
        'coord INTEGER NOT NULL DEFAULT 0)'
    )
    if cache_size:
        c.execute('PRAGMA cache_size = -{:d}'.format(cache_size))
    if mmap_size:
        c.execute('PRAGMA mmap_size = {:d}'.format(mmap_size))  # bytes
    dbconn.commit()

    vcfstream = parse_vcf(vcffh, updateint=logint)
    c.executemany('INSERT OR IGNORE INTO rsid_to_coord VALUES (?,?,?)', vcfstream)
    dbconn.commit()

The problem

Often, the input files contain hundreds of millions of records. Obviously I expect it to take some time to populate the database, but sometimes the performance seems extremely slow. I've done a lot of searching found several recommendations for improving the performance of insert-intensive tasks.

increasing the cache size
increasing the mmap size
disabling syncs (c.execute('PRAGMA synchronous = 0'))
enabling write-ahead logging (c.execute('PRAGMA journal_mode = wal'))
wrapping the inserts in BEGIN TRANSACTION; and COMMIT;

I've tried several combinations of these recommendations, but they don't seem to have much effect on overall performance. Should I chalk this up to the size of the input, or is there something I'm missing here that can substantially improve performance?

Example

If you're looking for a real-world example to test on, you can try this.

pip install git+https://github.com/bioforensics/rsidx
wget -O dbSNP.vcf.gz https://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b151_GRCh37p13/VCF/All_20180418.vcf.gz
rsidx index dbSNP.vcf.gz dbSNP.rsidx


texts:
This function divides a sequence into partitions, where a partition is a list of consecutive matching elements.

Example
Input: (A, A, B, B, B, A, C, C)
Output: ((A, A), (B, B, B), (A), (C, C))

I've tried to make this code "obviously correct", but it still doesn't look that way to me.
public static IEnumerable<List<T>> PartitionBy<T, PK>(this IEnumerable<T> sequence, Func<T, PK> partitionKey)
{
    return sequence.PartitionBy(partitionKey, EqualityComparer<PK>.Default);
}

public static IEnumerable<List<T>> PartitionBy<T>(this IEnumerable<T> sequence, IEqualityComparer<T> comparer)
{
    return sequence.PartitionBy(item => item, comparer);
}

public static IEnumerable<List<T>> PartitionBy<T, X>(this IEnumerable<T> sequence, Func<T, X> partitionKey, IEqualityComparer<X> comparer)
{
    var itr = sequence.GetEnumerator();
    if (!itr.MoveNext())
    {
        // empty sequence was passed in, so return empty sequence
        yield break;
    }

    // Start the first partition.
    var currentList = new List<T>(new[] { itr.Current });

    while (itr.MoveNext())
    {
        var key1 = partitionKey(currentList[0]);
        var key2 = partitionKey(itr.Current);

        if (comparer.Equals(key1, key2))
        {
            // continue current partition
            currentList.Add(itr.Current);
        }
        else
        {
            // yield current partition and start a new one
            yield return currentList;
            currentList = new List<T>(new[] { itr.Current });
        }
    }

    // We know it has at least 1 element here.
    yield return currentList;
}


texts:
Problem: Write a method that takes in a string. Your method should return the most common letter in the array, and a count of how many
  times it appears.

Note: I solved it with Ruby, but the solution will be almost the same with  other OOP language which have arrays and hashes.

Solution:

Split the string into an array of its characters/letters.
Put each char in a hash as key and starting value = 1.
When you find a character again, increase its value by 1.
Iterate your hash to find the most common character.

My solution works, but, is there a simpler & better way to do it?

What are the disadvantages of my solution?

def most_common_letter(string)
    hash = {}
    arr = string.split("")
    i = 0
    ge = "" # the char which occurs the most times in string
    max = 0 # number of times ge occurs in string
    while i < arr.length
        e = arr[i]
        if hash.has_key? e
            hash[e] += 1
        else
            hash[e] = 1
        end
        i = i + 1
    end

    # Find most common character
    hash.each do |k,v|
        if(v > max)
            max = v
            ge = k
        end
    end
    return ge.to_s + ":" + max.to_s
end

#Test
puts most_common_letter("abca")
puts most_common_letter("g")


texts:
I need to query MongoDB and check if an item exists or not:

class MongoDBPipeline(object):

    def __init__(self):
        connection = pymongo.MongoClient(
            settings['MONGODB_SERVER'],
            settings['MONGODB_PORT']
        )
        db = connection[settings['MONGODB_DB']]
        self.collection = db[settings['MONGODB_COLLECTION']]

    def process_item(self, item, spider):
        dup_check = self.collection.find({'image':item['image']}).count()
        if dup_check == 0 :
            self.collection.insert(dict(item))
            log.msg("Image added to MongoDB database!",
                     level=log.DEBUG, spider=spider)
            print "image Added!"
        else:
           print "Image Exist"
        return item

For now it works, but I want to know if I am doing it the right way or if there is a better solution.


texts:
Please help review my code.

public class Maze {
    // question: give a maze. Find shortest path from left top corner to right bottom corner.
    // 1 is wall. cannot go thru.
    int minFoundLen = Integer.MAX_VALUE;
    int m = 0;
    int n = 0;
    public void findPath(int[][] mazePlan){
        if(mazePlan.length == 0) return;

        m = mazePlan.length;
        n = mazePlan[0].length;
        int[][] path = new int[m][n];

        helper(mazePlan, 0, 0, 0,path);
        System.out.println("shortest path is " + minFoundLen);
    }

    private void helper(int[][] maze, int x, int y, int pathLen,int[][] path){
        if(x < 0 || y < 0 || x >= m || y >= n){
            return;
        }
        if(path[x][y]!=0){
            return;
        }
        if(maze[x][y] != 0){
            return;
        }
        if(x == m-1 && y == n-1){
            minFoundLen = Math.min(minFoundLen, pathLen);
            return;
        }
        path[x][y] = 1;
        helper(maze, x+1,y,pathLen+1,path);
        helper(maze, x-1,y,pathLen+1,path);
        helper(maze, x,y+1,pathLen+1,path);
        helper(maze, x,y-1,pathLen+1,path);
        path[x][y] = 0;

    }
    public static void main(String[] args){
        int[][] mazePlan = {
        {0,1,0,0,0},
        {0,0,0,1,0},
        {0,0,0,0,0},
        {1,1,1,0,0},
        {0,0,0,0,0}
        };

        Maze maze = new Maze();
        maze.findPath(mazePlan);
    }
}


texts:
I am working on one question, Find max path sum from two leaves

  Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.

class TreeNode:
    def __init__(self, x=None):
        self.val = x
        self.left = None
        self.right = None

def maxPathSum(root: TreeNode) -> int:
    res = float('-inf')

    def traversal(node, pathsum):
        nonlocal res

        if node is None:
            return 0
        if node.left is None and node.right is None:
            return node.val
        ln_value = traversal(node.left, pathsum)
        rn_value = traversal(node.right, pathsum)
        if node.left is not None and node.right is not None:
            res = max(res, node.val + ln_value + rn_value)
            return max(ln_value, rn_value) + node.val

        if node.left is None:
            return rn_value + node.val
        else:
            return ln_value + node.val

    traversal(root, res)
    return res


texts: Int extension for translating integer to plain English

texts:
This code was inspired by this question: Number to Words

import Foundation

extension Int {
    func plainEnglish (negativeSign: String = "negative") -> String {
        func singleNumberName (number: Int) -> String {
            switch (number) {
            case 1: return "one"
            case 2: return "two"
            case 3: return "three"
            case 4: return "four"
            case 5: return "five"
            case 6: return "six"
            case 7: return "seven"
            case 8: return "eight"
            case 9: return "nine"
            default:return ""
            }
        }

        func tensNumberName (number: Int) -> String {
            switch (number) {
            case 2: return "twenty"
            case 3: return "thirty"
            case 4: return "fourty"
            case 5: return "fifty"
            case 6: return "sixty"
            case 7: return "seventy"
            case 8: return "eighty"
            case 9: return "ninety"
            default:return ""
            }
        }

        func teensNumberName (number: Int) -> String {
            switch (number) {
            case 0: return "ten"
            case 1: return "eleven"
            case 2: return "twelve"
            case 3: return "thirteen"
            case 5: return "fifteen"
            default:return singleNumberName(number) + "teen"
            }
        }

        var number = self
        var digits: [Int] = []

        while number != 0 {
            digits.append(abs(number%10))
            number /= 10
        }

        var plainEnglish: [String] = []

        var isTeen = false
        let totalPlaces = digits.count
        var currentPlace = 0

        for (index, digit) in enumerate(digits.reverse()) {
            currentPlace = totalPlaces - index
            if currentPlace % 3 == 0 && digit > 0 {
                plainEnglish.append(singleNumberName(digit) + " hundred")
            } else if (currentPlace + 1) % 3 == 0 {
                if digit == 1 {
                    isTeen = true
                    continue;
                } else {
                    isTeen = false
                    plainEnglish.append(tensNumberName(digit))
                }
            } else {
                if isTeen {
                    plainEnglish.append(teensNumberName(digit))
                } else {
                    plainEnglish.append(singleNumberName(digit))
                }
            }

            if currentPlace == 4 {
                plainEnglish.append("thousand")
            } else if currentPlace == 7 {
                plainEnglish.append("million")
            } else if currentPlace == 10 {
                plainEnglish.append("billion")
            }
        }

        let initial = (self < 0) ? negativeSign : ""

        func combine (first: String, second: String) -> String {
            return first + " " + second
        }

        let finalString = plainEnglish.reduce(initial, combine: combine)

        return finalString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    }
}

This is implemented as an extension on the Int data type, so you can use it via dot notation on any integer (including literals).  Example usage:

let payamount = 98327
let dollars = payamount / 100
let cents = payamount % 100
let checkString = dollars.plainEnglish() + " dollars and " + cents.plainEnglish() + " cents"

Which results in a string that reads:

"nine hundred eighty three dollars and twenty seven cents"


texts:
I made simple login module that is responsible for handling registration, and signing in my application. How can I improve this code? Are there any conventions for this case?

The idea is to create siteUser and link him to his unique Account with cash info. Then let him login to app.

package auctionsite.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import auctionsite.stuff.IRegister;

public class LoginHandler implements IRegister {
    public static LoginHandler instance = null;
    private static final String DB_URL = "jdbc:derby:auction_site;create=true";
    private Connection conn = null;

    public static LoginHandler getInstance() {
        return instance == null ? new LoginHandler() : instance;
    }

    private int getUserID(String username) {
        try {
            Connection conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn.prepareStatement("SELECT userId FROM SiteUser WHERE name =?");
            prepStmt.setString(1, username);
            ResultSet rs = prepStmt.executeQuery();
            rs.next();
            return rs.getInt(1);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void insertNewUser(String username, String pass) {
        try {
            Connection conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn.prepareStatement("INSERT INTO SiteUser (name,password) VALUES (?,?)");
            prepStmt.setString(1, username);
            prepStmt.setString(2, pass);
            prepStmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void createAccountForUser(String username) {
        try {
            Connection conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn.prepareStatement("INSERT INTO PaymentAccount (cash,userId) VALUES (?,?)");
            prepStmt.setDouble(1, 0.00);
            prepStmt.setInt(2, getUserID(username));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int register(String username, String pass) {
        PreparedStatement prepStmt = null;
        try {
            conn = DriverManager.getConnection(DB_URL);
            prepStmt = conn.prepareStatement("SELECT COUNT(*) FROM SiteUser WHERE name=?");
            prepStmt.setString(1, username);
            ResultSet rs = prepStmt.executeQuery();
            rs.next();
            if (rs.getInt(1) <= 0) {
                if (validatePass(pass) && validateUsername(username)) {
                    insertNewUser(username, pass);
                    createAccountForUser(username);
                    return 1;
                } else {
                    return 0;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    private boolean validateUsername(String username) {
        return username.length() > 3;
    }

    private boolean validatePass(String pass) {
        return pass.length() >= 10 & pass.matches(".*\\d+.*");
    }

    @Override
    public void delete() {
    }

    @Override
    public int login(String userName, char[] pass) {
        try {
            conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn
                    .prepareStatement("SELECT name,password FROM SiteUser WHERE name=? AND password=?");
            prepStmt.setString(1, userName);
            prepStmt.setString(2, new String(pass));
            ResultSet rs = prepStmt.executeQuery();
            if (rs.next()) {
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}


texts:
In a producer-consumer scenario sometimes we have to deal with the producer being much faster than consumer. The data loss is unavoidable, and we are OK with it, as long as the consumer always has the most recent data.

The answer is triple buffering. Endow the system with three buffers, which assume the roles of being presented, ready, and inprogress, and let them change their roles according to the rules:

Once the presented buffer is completely presented, swap roles with ready.
Once the inprogress buffer is completely produced, swap roles with ready.

It is possible (unlikely but still possible) for producer to fall behind. Consumer must detect such situation, and not present a stale buffer. In other words, the presented/ready swap shall happen only if ready has been updated since the last swap.

I am particularly not proud with the stale flag being a part of termination flow.

PS: The fine-grain controls such as start and stop methods are intentionally not designed in.

Meanwhile, triple-buffer.h

#include <atomic>
#include <thread>

template<typename buffer, void produce(buffer *), void consume(buffer *)>
class triple_buffer {
    std::atomic<buffer *> present;
    std::atomic<buffer *> ready;
    std::atomic<buffer *> inprogress;

    std::atomic<bool> stop;
    std::atomic_flag stale;

    std::thread consumer_thread;
    std::thread producer_thread;

    void producer()
    {
        while (!stop) {
            produce(inprogress.load());
            inprogress = ready.exchange(inprogress);
            stale.clear();
        }
    }

    void consumer()
    {
        while (!stop) {
            consume(present.load());
            while (stale.test_and_set())
                ;
            present = ready.exchange(present);
        }
    }

public:
    triple_buffer() = delete;
    triple_buffer(triple_buffer& other) = delete;
    triple_buffer(triple_buffer&& other) = delete;
    triple_buffer& operator=(triple_buffer& other) = delete;

    triple_buffer(buffer bufs[3])
        : present(&bufs[0])
        , ready(&bufs[1])
        , inprogress(&bufs[2])
    {
        stop.store(false);
        stale.test_and_set();

        produce(present);

        consumer_thread = std::move(std::thread([this] { consumer(); }));
        producer_thread = std::move(std::thread([this] { producer(); }));
    }

    ~triple_buffer()
    {
        stop.store(true);
        producer_thread.join();

        stale.clear();
        consumer_thread.join();
    }
};

and a short demo.cpp

#include "triple-buffer.h"
#include <iostream>
#include <chrono>
#include <thread>

struct buffer {
    int id;
    int value;
};

void produce(buffer * buf)
{
    static int value = 0;
    buf->value = value++;
}

void consume(buffer * buf)
{
    std::cout << buf->id << ": " << buf->value << '\n';
}

int main()
{
    buffer bufs[3] { {0}, {1}, {2} };
    triple_buffer<buffer, produce, consume> tb(bufs);
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
}


texts: World resource system for Adventure Game/RPG

texts:
I'm beginning the long process of developing an Adventure Game/RPG and I was hoping to get some review on a resource system I'm coming up with.  How it works is, a resource is generic to every resource in the world.  Each resource will have a name, a random yield, and a random quality. So I've created an interface for the generic properties and function each resource will have.

Interface

public interface IResource{
    string Name {get;set;}
    string Quality {get;set;}
    int Yield{get;set;}
    string ConvertQualityToString();
    int GetResourceYield();
}

Then I implement the interface in an actual resource base class.

Implementation

public class Resource : MonoBehaviour, IResource{
    public string Name { get; set; }
    public string Quality { get; set; }
    public int Yield { get; set; }

    public string ConvertQualityToString(){
        var val = Random.Range(0, 3);
        string quality;
        switch (val){
            case 1:
                quality = "Good";
                break;
            case 2:
                quality = "Great";
                break;
            default:
                quality = "Poor";
                break;
        }
        return quality;
    }

    public int GetResourceYield(){
        var val = Random.Range(1, 25);
        return val;
    }
}

And finally, I create the specific resource itself and attach it to my game object in the inspector.

Resource Class

public class Granite : Resource{
    void Start(){
        Name = "Granite";
        Quality = ConvertQualityToString();
        Yield = GetResourceYield();
    }
}

Is this the proper way to work this system?  Obviously, the system actually does work as when I log the values on startup, Yield and Quality are randomized and the Name for each resource object I create is correct.  Is there a better way to do this?  Are there things I should change?  Thanks in advance.


texts: Simple beginner Rust CLI file reader that prints to stdout

texts:
Q: Am I approaching writing idiomatic Rust code correctly?

Hi CodeReview, I'm a beginner Rustacean coming from Python going through Rust books (The Rust Book, Rust in Action). A lot of the beginner code has unwrap everywhere and I'd like to write more idiomatic Rust.

I wrote 2 versions of a simple CLI program that reads a file and prints it to stdout, one with .unwrap and one without.

Both version execute successfully and do the same thing, only differing in the error-handling.

I tried to expand out all cases of .unwrap based on things in the official docs about using .unwrap[1][2][3].

Protoyping

extern crate clap;

use std::{
    prelude,
    io::{BufRead, BufReader},
    fs::File,
};
use clap::{App, Arg};

fn main() {
    let matches = App::new("File reader")
        .about("Read a file line by line")
        .help("The help text")
        .version("0.1")
        .arg(Arg::with_name("input")
            .value_name("INPUT")
            .takes_value(true)
            .help("Any text file to be read"))
        .get_matches();

    // Get input argument, ensure it is valid
    let input = matches.value_of("input").unwrap();

    // Try and open the file
    let f = File::open(input).unwrap();

    // Load the file into BufReader
    let reader = BufReader::new(f);

    // Read the lines of the file
    for line_ in reader.lines() {
        let line = line_.unwrap();
        println!("{}", line);
        }
    }

Improving robustness

use std::{
    error::Error,
    // prelude::*,
    io::{BufRead, BufReader},
    fs::File,
};
use clap::{App, Arg};

fn main() -> Result<(), Box<dyn Error>> {
    let matches = App::new("File reader")
        .about("Read a file line by line")
        .help("The help text")
        .version("0.1")
        .arg(Arg::with_name("input")
            .value_name("INPUT")
            .takes_value(true)
            .help("Any text file to be read"))
        .get_matches();

    // Get input argument, ensure it is valid
    let input = matches.value_of("input");

    let input = match input {
        Some(file) => file,
        None => matches.usage(),
    };

    // Try and open the file
    let f = File::open(input)?;

    // Load the file into BufReader
    let reader = BufReader::new(f);

    // Read the lines of the file
    // "if let" reads "if 'let' destructures line_ into Ok(line) value, evaluate {}"
    for line_ in reader.lines() {
        if let Ok(line) = line_ {
            println!("{}", line);
        };
    }
    Ok(())
}

Am I approaching making my code more idiomatic correctly?

Edit 2: My second take at making it more readable/idiomatic (fn main only)

fn main() -> Result<(), Box<dyn Error>> {
    let matches = App::new("File reader")
        .about("Read a file line by line")
        .help("The help text")
        .version("0.1")
        .arg(Arg::with_name("input")
            .value_name("INPUT")
            .takes_value(true)
            .help("Any text file to be read"))
        .get_matches();

    // Get input argument, ensure it is valid
    let input = match matches.value_of("input") {
        Some(input) => input,
        None        => matches.usage(),
    };

    // Try and open the file
    if let Ok(f) = File::open(input){
        // If valid, load into BufReader then read the file line by line
        let reader = BufReader::new(f);
        for line_ in reader.lines() {
            if let Ok(line) = line_ {
                println!("{}", line);
            };
        };
    } else {
        // If file is not valid, print the CLI usage
        println!("{}", matches.usage())
    };
    Ok(())
}


texts: Is there a better way to convert two-dimentional array to string?

texts:
For logging purposes, I need to output a double[,] to the log file. So I need to represent the array as a string.

The following code gets the job done using basic C# 1 features, but I was wondering if there is a more elegant solution using Linq:

private static string OneRowPerLine(double[,] numbers)
{
    var ret = new StringBuilder();
    for(var i=numbers.GetLowerBound(0);i<=numbers.GetUpperBound(0);i++)
    {
        for (var j = numbers.GetLowerBound(1); j <= numbers.GetUpperBound(1); j++)
        {
            if(j>numbers.GetLowerBound(1))
            {
                ret.Append(",");
            }
            ret.Append(numbers[i, j]);
        }
        ret.Append(Environment.NewLine);
    }
    return ret.ToString();
}


texts:
I came to work at a place not really understanding data binding. I have been working with it for about a year now, and I'd like to get some clarification on what is going on.

Particularly, I'd like to know if there any difference between the following two types of calls.

Given this simplistic example of the data:

public class TableType {
    public int ID;
}

public System.Data.Linq.Table<TableType> TableTypes
{
    get
    {
        return this.GetTable<TableType>();
    }
}

Version 1:

private BindingList<TableType> _tableTypeList;

public BindingList<TableType> TableTypesList1
{
    get
    {
        if (_tableTypeList == null)
        {
            var temp = TableTypes.OrderBy(t => t.ID);
            _tableTypeList = ((IListSource)temp).GetList() as BindingList<TableType>;
        }
        return _tableTypeList;
    }
}

The Senior Developer here wrote lots of database code using Version 1.

Looking at it, you would think that it would prevent redundant database calls, but that does not seem to be the case. A breakpoint on the code never gets hit again.

Version 2:

public BindingList<TableType> TableTypesList2
{
    get
    {
        var query = from t in TableTypes orderby t.ID select t;
        var result = new BindingList<TableType>(query.ToList());
        return result;
    }
}

The Senior Developer left about 6 months ago, so now I am writing the database calls.

I have been using Version 2, which looks much cleaner to me and appears to do the exact same thing.

Is one version any better than the other? Is there anything one version does that another does not? How do I get a better feel for what is going on?

Particularly, I was surprised to find that another call to TableTypesList1 did not call the getter.


texts:
I'm building a RESTful API in PHP using the Phalcon framework. The API will consist of multiple modules (e.g. api.example.com/mail/users, api.example.com/web/users, etc). So I want to put all module specific logic at one place as much as possible.

I have a lot of programming experience but PHP is all pretty new to me. So if you could help me determine if I'm on the right track, so that this code won't give me future problems, or if I'm missing something or if the code could be abstracted even more, then that would be great.

Directory structure:

app/
    collections/
        MailCollection.php
    config/
        collections.php
    controllers/
        MailController.php
public/
    index.php

index.php

// Set path variables
$dir = dirname(__DIR__);
$appDir = $dir . '/app';

// Create autoLoader
$loader = new \Phalcon\Loader();

// Register namespaces
$loader->registerNamespaces(
    array(
        'Controllers' => $appDir . '/controllers'
    )
)->register();

// Create dependency injector
$di = new \Phalcon\DI\FactoryDefault();

// Create micro application
$app = new Phalcon\Mvc\Micro($di);

// Mount the collections
$collections = include_once($appDir . '/config/collections.php');
foreach($collections as $collection) {
    $app->mount($collection);
}

// Handle request
$app->handle();

collections.php

// Add collections
$collections[] = (
    include_once($dir . '/app/collections/MailCollection.php')
);

return $collections;

MailCollection.php

use \Phalcon\Mvc\Micro\Collection as MicroCollection;

// Setup Collection
$mail = new MicroCollection();
$mail->setHandler('Controllers\MailController', true);
$mail->setPrefix('/public/mail');

// Define routes
$mail->get('/test', 'testAction');

return $mail;

MailController.php

namespace Controllers;

class MailController extends \Phalcon\Mvc\Controller
{
    public function testAction()
    {
        echo('test');
    }
}


texts:
Is this the simplest way to write this? This code evaluates if a textbox value exceeds 20 characters, and then displays the proper message (essentially truncating the string and then adding an ellipses to the end.)

I've tried using a tertiary operator but doesn't seem to work with appending data to an element as it overwrites what was previously appended.)

if (searchBoxValue.length > numCharToDisplay) {
    searchDropDown.append('
Searching "' +
    searchBoxValue.trim().substring(0, numCharToDisplay) +
    '..." Found No Results
');
} else {
    searchDropDown.append('
Searching "' +
    searchBoxValue.trim() + '" Found No Results
');
}


texts:
I have written code to return anagrams from a list of words. I'm a newbie in time complexity analysis so pardon my ignorance if this is a blatantly obvious question. Am I right in thinking this is in O(n log n) time, since it's just performing a quicksort and the rest is done in O(1) time because it's hashmaps? Also any suggestions on improving the code?

    public class anagram {

public static ArrayList<String> anagrams(String[] original) {

    HashMap<String, ArrayList<String>> map = new HashMap();

    for(String str : original) {

        String key = sortChars(str);

        if(!map.containsKey(key)) {
            map.put(key, new ArrayList<String>());
        }

        ArrayList<String> anagramList = map.get(key);
        anagramList.add(str);
    }

    ArrayList<String> result = new ArrayList();

    for(String key : map.keySet()) {

        ArrayList<String> anagramList = map.get(key);

        if(anagramList.size() > 1) {

            result.addAll(anagramList);
        }
    }

    return result;
}


texts: Parsing airline reservation using JS regular expressions

texts:
I'm searching a set text for multiple values, which will later be stored in a database.

I am using RegExp and worked with the official documentation and help to get the code to be two separate while loops. The question is if it's possible combine those into one, adding more and more regular expressions, or if they each need a for-loop of their own.

const regex = /PREPARED FOR([^]*?)RESERVATION/g;
const regex2 = /AIRLINE RESERVATION CODE (.*)/g;

const str = `30 OCT 2017  04 NOV 2017
Distance (in Miles):500
Stop(s): 0
Distance (in Miles):500
Stop(s):0
TRIP TO KRAKOW, POLAND
PREPARED FOR
DOE/JANE MRS
APPLESEED/JOHN MR
RESERVATION CODE   UVWXYZ
AIRLINE RESERVATION CODE DING67 (OS)
AIRLINE RESERVATION CODE HDY75S (OS)`;
let m;
let x;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    console.log(m[1])

}

while ((x = regex2.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (x.index === regex2.lastIndex) {
        regex2.lastIndex++;
    }
    console.log(x[1])

}
console.log("We're done here")

Now, this works perfectly fine as is, but I will be adding more filters and searches to it, which means I may get to a total of 8-9 while loops, which may slow the process down, or be inefficient.


texts:
I want to use python -c to remove wheel files from the dist/ directory in my project. (*)
Actually, I use the following command:
python -c "from pathlib import Path; [p.unlink() for p in Path('dist').glob('Pascal_Scraper-*.whl')]"

Is there a shorter/cleaner way to do that?

(*) the setuptools command python setup.py rotate --keep=1 --match=.whl doesn't work for me.


texts: Yet Another Regex-Based MarkDown to HTML converter

texts:
I wrote a simple script to translate (a subset of) StackExchange markdown to HTML. I used Regex for this task, but luckily I only had to use simple patterns.

Modularization

I also wrote a Regexp-generating function as I noticed that in Markdown you are always looking for things inside such and such symbols, I feel like it simplified the code.

What I do not like

The massive and mindless use of .tr to remove surrounding mark-up before applying HTML tags.

Tests

The code has 9 testcases, one for each feature.

Code / Tests ratio.

The code is pretty compact, totalling 16 lines of logic supported by 50 blank/end-only/comments/tests lines.

Testing bug

I used my own testing framework, but sadly it has a bug that does not allow to use # inside tests, so I replaced it with 35.chr

Links trickiness

The code is a bit longer when handling HTML links as they are a bit more complex than tags like bold or italics

Limitations

The code does not escape tags contained in:

``

It also has no support for lists of any kind and gives results visually more ugly (still correct) than the markdown implemented on this site.

It works on my basic example.

(On-topic, as I acknowledge that this code is not perfect but I do not ask you to fix it.)

The code

require "arrow_test"

# Returns a Regex that matches anything inside the delimiter.
# The given delimiter is escaped to allow the use of special characters.
#
# anything_inside("**") #=> /\*\*.*\*\*/
def anything_inside(start, ending=nil)
  start = "\\" + start.chars.join("\\")
  ending = start if ending == nil
  Regexp.new(start + ".*" + ending)
end

# This function translates MarkDown to HTML.
#
# markdown_to_html("plaintext") #=> "plaintext"
# markdown_to_html("**bold only**") #=> "bold only"
# markdown_to_html("_italics only_") #=> "italics only"
# markdown_to_html("`code only`") #=> "code only"
# markdown_to_html("    code by indentation") #=> "code by indentation"
# markdown_to_html("> To be or not to be\n\n") #=> "<q> To be or not to be</q>"
# markdown_to_html(35.chr + "Title\n") #=> "
Title
"
# markdown_to_html("\npara\n") #=> "\n
para
\n"
# markdown_to_html("[foo](http://foo.com)") #=> "foo"
def markdown_to_html(text)
  text
    .gsub(anything_inside(">", "\n\n"))  {|txt| "<q>#{txt.sub(/^>*/,"").tr("\n\n", "")}</q>" }
    .gsub(anything_inside("**")) {|txt| "#{txt.tr("**","")}"}
    .gsub(anything_inside("_")) {|txt| "#{txt.tr("_","")}"}
    .gsub(anything_inside("`"))  {|txt| "<code>#{txt.tr("`","")}"}
    .gsub(anything_inside("#", "\n")) {|txt| "
#{txt.tr("\n","").sub(/^\#*/,"")}
"}
    .gsub(anything_inside("\n")) {|txt| "\n
#{txt.tr("\n","")}
\n"}
    .gsub(/\ \ \ \ .*/) {|txt| "#{txt.strip}"}
    .gsub(/\[.*\]\(.*\)/) do |txt|
       to_show = txt.match(/(\[.*\])/)[1].tr("[","").tr("]","")
       url = txt.match(/(\(.*\))/)[1].tr("(","").tr(")","")
       "#{to_show}"
    end
end

if __FILE__ == $0
  arrow_test($0, true)
  File.write("example.html", markdown_to_html("""
# A nice example.

All the time, the site [example](www.example.com) amuses me with its beauty.

I felt a **strong attachment** to it, regardless of its simplicity.

The site is an  _example_ as few things can be, as Lapalisse said:

> What is an example, is an example.

Such beatiful a site may be used in examples such as:

**Python**

    import webbrowser
    webbrowser.open(\"www.example.com\")

And now, for something completely different, `inline code`.

> The great man may not have ideas, but will always write examples.

_And that is all,_ I hope you enjoyed reading this example, good day.

"""))
end


texts: Storing a version number in a Python project

texts:
If I have this simple structure:

$ tree
.
└── project
    ├── __init__.py
    └── my_script.py

where I want to define __version__ in __init__.py (this allows setup.py, in the parent directory, to import project.__version__):

$ cat __init__.py
# -*- coding: utf-8 -*-

__version__ = "0.1"

Now, I also want to use the value stored in __version__ from other scripts (possibly in subdirectories). I can write this in my_script.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __init__ import __version__

print(__version__)

It works, but looks so ugly. Is this really the way to do that?

EDIT:

The from . import __version__ unfortunately doesn't work:

$ ./my_script.py
Traceback (most recent call last):
  File "./my_script.py", line 4, in <module>
    from . import __version__
SystemError: Parent module '' not loaded, cannot perform relative import


texts: Longest words in dictionary that can be constructed from a list of letters

texts:
The problem is to find the longest words in a dictionary of legal words that can be constructed from a given list of letters.

For example:

$ ./scrabble dictionary.txt i g h l p r a
argil glair grail graph hilar laigh phial pilar ralph

More details here.

I've already solved this problem in Python (see this).

To brush up my C++ I decided to reproduce the exact same algorithm in C++. I learned C++ as "C with classes" and never learned to use the STL properly, so I usually end up writing more code than necessary to accomplish simple things.

This is what I came up with for this problem:

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

using namespace std;

bool can_make(string word, vector<char> letters);
int get_max_len(vector<string> words);

int main(int argc, char* argv[])
{
    // Grab the dictionary.
    fstream dict_file(argv[1]);
    string in;
    vector<string> dict_words;
    while(getline(dict_file, in)) dict_words.push_back(in);
    dict_file.close();

    // Get the list of input letters.
    vector<char> letters;
    for (int i = 2; i < argc; i++)
        letters.push_back(argv[i][0]);

    // Get all words.
    vector<string> all_words;
    vector<string>::iterator it;
    for (it = dict_words.begin(); it < dict_words.end(); it++)
        if (can_make(*it, letters))
            all_words.push_back(*it);

    // Get longest words.
    int max_len = get_max_len(all_words);
    vector<string> longest_words;
    for (it = all_words.begin(); it < all_words.end(); it++)
        if ((*it).length() == max_len)
            longest_words.push_back(*it);

    // Print the result.
    for (it = longest_words.begin(); it < longest_words.end(); it++)
        cout << *it << " ";
    cout << endl;

    return 0;
}

bool can_make(string word, vector<char> letters)
{
    /*
        Return true if the word <word> can be generated by all letters in <letters>
        and only the letters in <letters>.
    */

    if (word.length() > letters.size()) return false;

    vector<char> l(letters);
    vector<char> word_letters(word.c_str(), word.c_str()+word.length());
    vector<char>::iterator it, loc;

    // Iterate through <word_letters>. If a letter in <word_letters> also
    // appears in <letters>, remove it. Otherwise, return false.
    for (it = word_letters.begin(); it < word_letters.end(); it++) {
        loc = find(letters.begin(), letters.end(), *it);
        if (loc == letters.end()) return false;
        letters.erase(loc);
    }

    return true;
}

int get_max_len(vector<string> words)
{
    /*
        Return the length of the longest word(s) in <words>.
    */

    int max_len = 0;
    vector<string>::iterator it;
    for (it = words.begin(); it < words.end(); it++)
        if ((*it).length() > max_len)
            max_len = (*it).length();

    return max_len;
}

Is this idiomatic C++?
How can I make this code more concise?
How can I make it more correct?
What C++11 features can I use here to make the code even shorter?
What features have I used here that I should avoid?


texts:
Please review my Bash code to create an authenticated, all privileged MySQL user plus a DB with the same name, through the MySQL CLI:

read -sp "DB user password:" dbrootp_1       && echo
read -sp "DB user password again:" dbrootp_2 && echo
read -sp "DB user password:" dbuserp_1       && echo
read -sp "DB user password again:" dbuserp_2 && echo

if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched" && exit 1 fi
if [ "$dbuserp_1" != "$dbuserp_2" ]; then echo "Values unmatched" && exit 1 fi

cat <<-DBSTACK | mysql -u root -p"$dbrootp"
    CREATE USER "$domain"@"localhost" IDENTIFIED BY "$dbuserp";
    CREATE DATABASE "$domain";
    GRANT ALL PRIVILEGES ON "$domain".* TO "$domain"@"localhost";
DBSTACK


texts:
I wanted to implement a version of rambda's compose function in python. I also implemented some examples to show its working. However, I would like the community's input on my code:

These are the methods I use for testing

from functools import reduce, partial
import random
import math

def calcMean(iterable):
    return sum(iterable) / len(iterable)

def formatMean(mean):
    return round(float(mean), 2)

def adder(val, value):
    return val + value

def multiplier(val, value):
    return val * value

def isEven(val):
    return val % 2 == 0

The actual compose function

def compose(*fargs):
    def inner(arg):
        if not arg:
            raise ValueError("Invalid argument")
        if not all([callable(f) for f in fargs]):
            raise TypeError("Function is not callable")
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

The first exercise is something I came up with. In it I populate a list of length 10000 with random numbers from 0 to 10000, find the mean, round it to 2 decimal places, add 1 to it , then floor it and finally print out whether it is even or not.

if __name__ == '__main__':
    # Ex1
    rand_range = [random.randint(0, 10000) for x in range(0, 10000)]

    isRandIntEven = compose(calcMean, formatMean,
                            partial(adder, value=1), math.floor.__call__, isEven)

    print(isRandIntEven(rand_range))

The second exercise is taken from rambda's compose page. I tried to see if I could replicate the example (theirs is much more elegant)

    # Ex2
    classyGreeting = lambda firstName, lastName: "The name's " + \
        lastName + ", " + firstName + " " + lastName
    yellGreeting = compose(partial(
    classyGreeting, "James".upper()), str.upper.__call__)

    print(yellGreeting("Bond"))

The last example is also taken from rambda's compose page

# Ex3
    print(compose(
        partial(multiplier, value=2),
        partial(adder, value=1),
        math.fabs)(-4))


texts:
I have the following code to solve dinning philosophers problem using Go channels and am looking for review comments:

package main

import (
    "fmt"
    "time"
    "sync"
    "os"
    "bufio"
)

type diner struct {
    thinkTime time.Duration
    eatTime time.Duration
    free []chan bool
    done []chan bool
    n int
    c  *sync.Cond
    started chan int
}

func newDiner(n int,eatTime time.Duration,thinkTime time.Duration) *diner {

    d := new(diner)
    d.n = n
    // first create n fork channels and philo channels as communication between forks and philosophers
    d.free = make([]chan bool,n)
    d.done = make([]chan bool,n)

    d.c = sync.NewCond(&sync.Mutex {} )

    d.thinkTime = thinkTime
    d.eatTime = eatTime

    // make a buffered channel
    d.started = make(chan int,n)

    for i:=0;i<n;i++{
        d.free[i] = make(chan bool)
        d.done[i] = make(chan bool)
    }
    return d
}

func (d *diner) start() {

    for i:=0;i<d.n;i++ {
        go d.fork(i)
        go d.philo(i)
    }

}

func (d *diner) philo(p int) {

    for {
        // think time
        fmt.Printf("%d,think\n",p)
        time.Sleep(d.thinkTime)
        fmt.Printf("%d,hungry\n",p)

        left := false
        right := false
        // check if we can get the left fork
        select {
        case left = <- d.free[p]:
            break
        default:
            left = false
            break
        }

        if !left {
            continue
        }

        //try and get right one
        select {
        case right = <- d.free[((p+1)%d.n)]:
            break
        default:
            right = false
            break
        }

        if !right {
            // then free left as well
            d.done[p] <- true
        }

        if left && right {
            // eat and then release
            fmt.Printf("%d,eat\n",p)
            time.Sleep(d.eatTime)
            // indicate done
            d.done[p] <- true
            d.done[((p+1)%d.n)] <- true
        }

    }

}

func (d *diner) fork(f int) {

    for {

    // indicate that the fork is free
    d.free[f] <- true

    //fmt.Printf("Waiting for fork %d to be done\n",f)
    //wait for it to be used and then released
    select {
    case <- d.done[f]:
        break
    }
    }

}

func main() {

    d := newDiner(5,1*time.Second,4*time.Second)
    d.start()

    reader := bufio.NewReader(os.Stdin)
    //fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println(text)
}


texts:
I have some code where the purpose is the decide if a char is between quotes in an expression. For example, awk '{print $1}' has a { between quotes.

The function that I want to test is

int IBQplain(int pos, char *str, int offset);

int IBQdouble(int pos, char *str, int offset);

int IBQsingle(int pos, char *str, int offset) {
    int escaped = 0;
    for (; str[offset]; ++offset) {
        if (!escaped) {
            switch (str[offset]) {
                case '\\':
                    escaped = 1;
                case '\'':
                    return IBQplain(pos, str, offset + 1);
            }
        } else {
            escaped = 0;
        }
        if (pos == offset) {
            return 1;
        }
    }
    return 0;
}

int IBQdouble(int pos, char *str, int offset) {
    char ch;
    if (pos == offset)
        return 0;  /* Not within quotes */
    int escaped = 0;
    for (ch = str[offset]; ch; ch = str[++offset]) {
        if (!escaped) {
            switch (str[offset]) {
                case '\'':
                    return IBQsingle(pos, str, offset + 1);
                case '"':
                    return IBQdouble(pos, str, offset + 1);
                case '\\':
                    escaped = 1;
            }
        } else {
            escaped = 0;
        }
        if (pos == offset)
            return escaped;  /* Not within quotes, but may be single-escaped */
    }
    return 0; /* FIXME */
}

int IBQplain(int pos, char *str, int offset) {
    char ch;
    if (pos == offset)
        return 0;  /* Not within quotes */
    int escaped = 0;
    for (ch = str[offset]; ch; ch = str[++offset]) {
        if (!escaped) {
            switch (str[offset]) {
                case '\'':
                    return IBQsingle(pos, str, offset + 1);
                case '"':
                    return IBQdouble(pos, str, offset + 1);
                case '\\':
                    escaped = 1;
            }
        } else {
            escaped = 0;
        }
        if (pos == offset)
            return escaped;  /* Not within quotes, but may be single-escaped */
    }
    return 0; /* FIXME */
}

int isBetweenQuotes(int pos, char *str) {
    return IBQplain(pos, str, 0);
}

Write the test

#include "openshell.h"
#include "errors.h"
#test myQtest
fail_unless(isBetweenQuotes(11, "abc'asdqerfdsdxcvc'xc") == 1, "isBetweenQuotes function borked");
lm */

Compile it and run it

gcc -Wall -o bquotes-test util.c errors.c bquotes-test.c -lcheck -lsubunit -lrt -pthread -lm^C
dac@dac-Latitude-E7450:~/osh$ ./bquotes-test
Running suite(s): Core
100%: Checks: 1, Failures: 0, Errors: 0

It seems ok. I make more tests

#include "openshell.h"
#include "errors.h"
#test myQtest
fail_unless(isBetweenQuotes(11, "abc'asdqerfdsdxcvc'xc") == 1, "isBetweenQuotes function borked");
fail_unless(isBetweenQuotes(5, "abcasdqerfdsdxcvcxc") == 0, "isBetweenQuotes function borked");
fail_unless(isBetweenQuotes(11, "ab'c'as'dqerfdsdxcvc'xc") == 1, "isBetweenQuotes function borked");

Compile and run it

checkmk tst_bquotes.check > bquotes-test.c
dac@dac-Latitude-E7450:~/osh$ gcc -Wall -o bquotes-test util.c errors.c bquotes-test.c -lcheck -lsubunit -lrt -pthread -lm
dac@dac-Latitude-E7450:~/osh$ ./bquotes-test
Running suite(s): Core
100%: Checks: 1, Failures: 0, Errors: 0


texts:
I was recently solving a question on LeetCode platform to delete a node from a Binary Search Tree, I wrote the given below iterative solution, I was wondering if it was a good practice to add a return statement within every if else block, that way the control would never reach the end of the function, however doing that did improve the time to pass all test cases. Any help appreciated !

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
    if(!root)
        return NULL;
    if(root->val==key && !root->left && !root->right)
        return NULL;

    TreeNode* root1=root;
    TreeNode* parent=root;

    while(root1 && root1->val!=key){
        parent=root1;
        if(key<root1->val)
            root1=root1->left;
        else
            root1=root1->right;
    }

    TreeNode* delNode=root1;

    if(!root1)
        return root;

    if(!root1->left && !root1->right){
        if(parent->left==root1)
            parent->left=NULL;
        else
            parent->right=NULL;
        return root;
    }

    else if(root1->right){
        parent=root1;
        root1=root1->right;
        while(root1->left){
            parent=root1;
            root1=root1->left;
        }
        delNode->val=root1->val;
        if(parent==delNode)
            parent->right=root1->right;
        else
            parent->left=root1->right;

        return root;
    }
    else{
        if(parent==delNode)
            root=root->left;
        else
            if(parent->left==delNode)
            parent->left=delNode->left;
        else
            parent->right=delNode->left;

        return root;
    }
    return root;
}
};


texts: Optimal way to annihilate a list by removing items from the ends

texts:
I'm stuck with a contest problem.

Description:

What is the minimum number of moves to annihilate an int array where the possible moves are:

Remove both the first and last elements if they are equal to each other, or
Remove the first element, or
Remove the last element.

Input

The first line is the number of test cases (less than or equal to 200).

For any test case there is two lines.

Line 1 has 1 integer with the size of the vector. (The size never exceeds 1000)
Line 2 has n integers with the values of the vector. (Values never greater than 109)

Ouput

The output must show the test case number with the minimum value of remove steps.

Input Example:

3
5
1 3 1 3 2
5
1 2 3 2 1
7
1 1 2 3 3 4 2

Output Example:

Case #1: 4
Case #2: 3
Case #3: 5

My solution is brute-force and recursive, with memorization:

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

int minOf2(int x, int y){
    return (x < y) ? x : y;
}

int minOf3(int x, int y, int z){
    return minOf2(z,minOf2(x,y));
}

int memoization[1010][1010];

int recur(unsigned long long *arr,int i,int j){
    if(i > j){
        return 0;
    }
    int aux = INT_MAX;
    if(arr[i] == arr[j]){
        aux = recur(arr,i+1,j-1);
    }
    if(memoization[i][j])
        return memoization[i][j];
    else
        return memoization[i][j] = 1 + minOf3(aux,recur(arr,i+1,j),recur(arr,i,j-1));
}

int main()
{
    int t,n,i,j;
    unsigned long long arr[1010];
    scanf("%d",&t);
    for (i = 1; i <= t; i++) {
        memset(memoization,0,sizeof(memoization));
        scanf("%d",&n);
        for (j = 0; j < n; j++) {
            scanf("%llu",&arr[j]);
        }
        printf("Case #%d: %d\n",i,recur(arr, 0, n-1));
    }
    return 0;
}

This solution is still getting "Time Limit Exceeded".


texts: Validation of a couple of model classes using FluentValidator

texts:
A couple of model classes are doing the validation using FluentValidator. These model classes are used to Add and Edit the branch data and they are working well but I have no idea how to remove the code smell (duplication).

Problem: Notice the duplicate validations being written in BranchEditModel class as well. I have marked in the code itself what I think is being duplicated I thought it would be easier for you to read it.

BranchAddModel

using FluentValidation;
using FluentValidation.Attributes;

namespace Application //sample namespace
{
    [Validator(typeof(BranchAddModelValidator))]
    public class BranchAddModel
    {
        public string BranchName { get; set; }
        public byte ServiceTypeId { get; set; }
        public short TimezoneId { get; set; }
    }

    public class BranchAddModelValidator : AbstractValidator<BranchAddModel>
    {
        public BranchAddModelValidator()
        {
            RuleFor(x => x.BranchName)
                .NotEmpty()
                .Length(0, 128);  //up to 128 length of string is allowed.

            RuleFor(x => x.ServiceTypeId)
                .NotEmpty();  //mandatory

            RuleFor(x => x.TimezoneId)
                .NotEmpty();  //mandatory
        }
    }
}

BranchEditModel

BranchEditModel is inheriting the model from BranchAddModel. And, it has 2 extra properties.

namespace Application //sample namespace
{
    [Validator(typeof(BranchEditModelValidator))]
    public sealed class BranchEditModel : BranchAddModel
    {
        public int BranchId { get; set; }
        public bool IsActive { get; set; }
    }

    public class BranchEditModelValidator: AbstractValidator<BranchEditModel>
    {
        public BranchEditModelValidator()
        {
            RuleFor(x => x.BranchName) // code repeated
                .NotEmpty()
                .Length(0, 128);

            RuleFor(x => x.ServiceTypeId) // code repeated
                .NotEmpty();

            RuleFor(x => x.TimezoneId) // code repeated
                .NotEmpty();

            RuleFor(x => x.BranchId)
                .NotEmpty();

            RuleFor(x => x.IsActive)
                .NotEmpty();
        }
    }
}


texts: Reverse Polish Notation Evaluation in Java

texts:
I would like to hear feedback about my code both in term of improving efficiency if possible or using other data structures. Also go ahead and let me know about code styles/patterns.

/**
 * Created by mona on 5/26/16.
 */
import java.util.Arrays;
import java.util.Stack;
import java.util.HashSet;
public class EvaluateReversePolishNotation {
    //["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
    public static int evaluateReversePolishNotation(String[] tokens) throws ArithmeticException {
        Stack<Integer> stk = new Stack<>();
        HashSet<String> ops = new HashSet<>(Arrays.asList("+","-","*","/"));
        for (int i=0; i<tokens.length; i++) {
            if (!ops.contains(tokens[i])) {
                stk.push(Integer.parseInt(tokens[i]));
            }
            else {
                int secondOperand = stk.pop();
                int firstOperand = stk.pop();
                switch (tokens[i]) {
                    case "+":
                        stk.push(firstOperand+secondOperand);
                        break;
                    case "-":
                        stk.push(firstOperand-secondOperand);
                        break;
                    case "*":
                        stk.push(firstOperand*secondOperand);
                        break;
                    case "/":
                        if (secondOperand == 0) {
                            throw new ArithmeticException("Second operand can't be zero in division");
                        }
                        stk.push(firstOperand/secondOperand);
                        break;
                    default:
                        break;
                }
            }
        }
        return stk.pop();
    }

    public static void main(String[] args) {
      String[] revPolishNotations ={"2","1", "+", "3", "*"};
      System.out.println(evaluateReversePolishNotation(revPolishNotations));
    }
}


texts: Calculating numbers in the Collatz sequence

texts:
I have found two ways in which I can generate the Collatz sequence given a start number. I have looked briefly into their performance, but I'd like a more in depth/solid review into the difference in the two methods.

The main difference really is, one of them doesn't have if statements. But the down side to this method is there's a fair bit of math involved, which is where I'm concerned with performance.

The main questions I have are:

Do computers get slower when they have to make (slightly) complex calculations?
Do if statements actually have a significant affect on performance?
If we were generating the numbers in the Collatz sequence for large numbers (for example numbers > 1,000,000,000), would the performance difference actually be noticeable?

Here are the two methods I have created:

private static ArrayList<Integer> generateCollatz1(int n) {
    ArrayList<Integer> results = new ArrayList<>();
    while(n != 1) {
        if(n % 2 == 0) {
            n = n / 2;
            results.add(n);
        }else {
            n = ((n * 3) + 1);
            results.add(n);
        }
    }
    return results;
}

private static ArrayList<Integer> generateCollatz2(int n) {
    ArrayList<Integer> results = new ArrayList<>();
    while(n != 1) {
        n = (int) ( (7 * n + 2) - (Math.pow(-1, n)) * (5 * n + 2) ) / 4;
        results.add(n);
    }
    return results;
}

The math in the second method (generateCollatz2) is using the following formula:

$$ f(n) = \frac{7n + 2 - (-1)^n (5n + 2)}{4}$$


texts:
I have a database class that in __construct() initialize a PDO connection and insert the instance into a $db private var.
Now i'm working on a method that can be used to query in this way:

$db = new db;
$db->query(array(
 'select' => 1,
 'from' => 'table',
 'where' => array('id' => 1, 'name' => 'charlie'),
 'limit' => array(1, 5)
));

I did something that works pretty nicely long time ago while PDO was something unknown, but i was wondering:

How could i improve this code a bit
How can i end it? I mean how to use the PDO then to submit the query?

Here's the method query():

# Defining the type
     if (isset($array['select'])) { $type = 'SELECT'; $type_value = (is_int($array['select'])) ? '*' : $array['select']; }
     if (isset($array['update'])) { $type = 'UPDATE'; $type_value = $array['update']; }
     if (isset($array['delete'])) { $type = 'DELETE FROM'; $type_value = $array['delete']; }
     if (isset($array['insert'])) { $type = 'INSERT INTO'; $type_value = $array['insert']; }
     if (!isset($type)) { trigger_error("Database, 'type' not selected."); } // Error

     # From
     if (isset($array['from']))
     {
      $from = 'FROM';
      $from_value = mysql_real_escape_string($array['from']); // table cannot be pdoed
     }
     # Where
     if (isset($array['where']))
     {
      if (!is_array($array['where'])) { trigger_error("Database, 'where' key must be array."); }
      $where = 'WHERE'; $where_value = $array['where'];
      # Fixing the AND problem
      if (count($array['where']) > 1)
      {
       $list = $where_value;
       foreach ($list as $a => $b) { $w[] = "{$a} = {$b}"; }
       $and = implode(' AND ', $w);
       $where_value = $and;
      }
     }
     # Limit
     if (isset($array['limit']))
     {
      if (!is_array($array['limit'])) { trigger_error("Database, 'limit' key must be array."); }
      if (count($array['limit']) != 2) { trigger_error("Database, 'limit' array must be two-keys-long"); }
      $limit_first = $array['limit'][0];
      $limit_second = $array['limit'][1];
      $limit = 'LIMIT';
      $limit_value = "{$limit_first}, {$limit_second}";
     }

     # Set
     if (isset($array['set']))
     {
      if (!is_array($array['set'])) { trigger_error("Database, 'set' key must be array."); }
      $edits = $array['set'];
      foreach ($edits as $a => $b) { $e[] = "{$a} = {$b}"; }
      $set = 'SET';
      $set_value = implode(',', $e);
     }

     $vals = array('from', 'from_value', 'set', 'set_value', 'where', 'where_value');
     foreach ($vals as $v) { if (empty($$v)) { $$v = ''; } }

     $sql = "
      {$type} {$type_value}
      {$from} {$from_value}
      {$set} {$set_value}
      {$where} {$where_value}
     ";

# Here there would be something like mysql_query($sql), but i'd like PDO! PDO get me hornier.

And now? How to bind parameters? Is that possible to work it out?


texts: Building a task listing for a task manager

texts:
I'm super new to CodeIgniter 3 and I'm using it to build a task manager (Claritask.com). Also, I'm just starting to learn how to program, so forgive me beforehand if I'm not making sense and I'll try to clarify in comments.

As I'm building my specific Project page that lists specifc tasks, I was curious to know if I'm doing it right.

What I need on my view is: tasks belonging to a specific Project & the name of the project. I can get this to work fine, however I want to learn if my way of doing it correct.

I'm using two various methods

The first method I'm using, deals with having two functions on my Model, triggering two queries:

// Show project tasks
function get_tasks($project_id) {
    $this->db->from('tasks');
    $this->db->where('tasks.project_id', $project_id);
    $this->db->order_by('tasks.created_date', 'DESC');
    return $this->db->get()->result_array();
}

// Show single project name
function get_single_project($project_id) {
    $this->db->from('projects');
    $this->db->where('projects.id', $project_id);
    return $this->db->get()->row_array();
}

Then on my controller

$data['tasks'] = $this->project_model->get_tasks($project_id);
$data['project_name'] = $this->project_model->get_single_project($project_id)['project_name'];

This is working as expected, and producing an elegant array (especially on projects without tasks).

array (
  'tasks' =>
  array (
  ),
  'project_name' => 'Default name',
)

However I didn't like triggering two different queries, so I decided to JOIN projects with tasks and have one hit to the database, as such:

// Show project tasks
function get_project_tasks($project_id) {
    $this->db->select("tasks.*, projects.project_name");
    $this->db->from('projects');
    $this->db->where('projects.id', $project_id);
    $this->db->join('tasks', 'tasks.project_id = projects.id', "LEFT");
    $this->db->order_by('tasks.created_date', 'DESC');
    return $this->db->get()->result_array();
}

and then my controller:

$data['tasks'] = $this->project_model->get_project_tasks($project_id);
$data['project_name'] = $data['tasks'][0]['project_name'];

While the second approach is using one query only, It's also producing an "empty" array (below) on projects without any tasks and causing to print at least one empty line within a 'foreach'.

array (
  'tasks' =>
  array (
    0 =>
    array (
      'id' => NULL,
      'project_id' => NULL,
      'list_id' => NULL,
      'task_text' => NULL,
      'task_due_date' => NULL,
      'created_by' => NULL,
      'created_date' => NULL,
      'project_name' => 'Website design',
    ),
  ),
  'project_name' => 'Website design',
)

Even though, I'm mitigating that, with the following:

<?php foreach($tasks as $task) { ?>
    <?php if(isset($task['id'])): ?>

<?php echo $task['task_text']; ?>

    <?php endif; ?>
<?php } ?>

Even though there are thousands of ways to skin a cat, I would like to really know which approach is the correct one: Having a specific query for each element and printing an elegant output, or optimizing the outcome.


texts: naive suffix tree construction in Python

texts:
I'm not certain if my implementation is correct, it appears to be, but looking for any feedback as far as readability and efficiency goes. Obviously using dictionaries isn't particularly efficient space wise, but how else could you achieve O(1) lookup?

import os

def get_suffixes(string):
    return [string[i:] + "$" for i in range(len(string) + 1)]

def shared_prefix(string_a, string_b):
    return os.path.commonprefix([string_a, string_b])

def construct_suffix_tree(string):
    tree = {}
    for i in range(len(string) + 1):
        suffix = string[i:] + "$"
        insert_suffix(suffix, tree)
    return tree

def insert_suffix(string, suffix_tree):
    if len(suffix_tree) == 0:
        suffix_tree[string] = []
        return suffix_tree

    found_match = False
    for key in list(suffix_tree):
        prefix = shared_prefix(string, key)
        n = len(prefix)
        if len(prefix) > 0:
            found_match = True
            key_suffix = key[n:]
            string_suffix = string[n:]
            del suffix_tree[key]
            suffix_tree[prefix] = [key_suffix, string_suffix]

    if not found_match:
        suffix_tree[string] = []
    return suffix_tree

my_string = "banana"
print(construct_suffix_tree(my_string))


texts:
Homework:  Write a function to score a scrabble word.
values is a global dict formatted as values = {'a': 1, 'b': 3,...}
The docstring is supplied as part of the course, thus I'm only looking for feedback on the actual program logic.

I could have written a bunch of variables, iterated over the string word, looking up points from values, etc., but I've been reading about functional programming lately and this is my first attempt at something "non-procedural".

I feel like this code (while working) looks terrible, isn't easily understood, and has more than one code smell.  For example, I understand that breadth is generally preferred over depth (at least in python, right?), uses the much-hated python ternary, and is 89 chars wide (plus probably more significant smells I don't even recognize).

I'm trying to:

not declare pointless or temporary variables
be concise
avoid traditional loops
avoid changing variables' values

I considered rewriting with a nested recursive function, would this make more sense?
Also, if I'm using the term "functional" in the wrong way, or completely missing the point, please correct.

def getWordScore(word, n):
    """
    Returns the score for a word. Assumes the word is a valid word.

    The score for a word is the sum of the points for letters in the
    word, multiplied by the length of the word, PLUS 50 points if all n
    letters are used on the first turn.

    word: string (lowercase letters)
    n: integer (hand size required for additional points)
    returns: int >= 0
    """
    return len(word) * sum(map(lambda x: values[x], word)) + (50 if len(word)==n else 0)


texts:
I wanted to implement merge sort in a generic way. I was not sure whether I should use the iterator or the container for the template type. I did not find a way to infer the container type using iterator_traits, so I decided to use the templated type for the container. Please let me know what you think!

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
void printArray(const T& a) {
    for (auto i: a) {
        cout << i << " ";
    }
    cout << endl;
}

template<typename T>
T mergeSort(typename T::iterator begin, typename T::iterator end) {
    auto n = end - begin;
    if (n < 2) {
        return T(begin, end);
    }
    auto firstHalf  = mergeSort<T>(begin, begin + n/2);
    auto secondHalf = mergeSort<T>(begin + n/2, end);
    auto firstIt = firstHalf.begin();
    auto secondIt = secondHalf.begin();
    T merged;
    while (firstIt != firstHalf.end() && secondIt != secondHalf.end()) {
        if (*firstIt < *secondIt) {
            merged.push_back(*firstIt);
            ++firstIt;
        } else {
            merged.push_back(*secondIt);
            ++secondIt;
        }
    }
    while(firstIt != firstHalf.end()) {
        merged.push_back(*firstIt);
        ++firstIt;
    }
    while(secondIt != secondHalf.end()) {
        merged.push_back(*secondIt);
        ++secondIt;
    }
    return merged;
}

int main() {
    vector<int> a = {3, 0, 7, 5, 7, 8, 3, 1};
    printArray(mergeSort<vector<int>>(a.begin(), a.end()));
    return 0;
}