texts:
I watched this live coding of Sokoban in Haskell and thought I'd take a crack at writing it using State and lenses, since I've never tried that before. My problem is that the control flow seems to be complicated by isWall and friends now being monadic values that I need to unwrap, so I can't use the otherwise obvious approach of guards etc. Any suggestions? I did not focus very much on not making partial functions or handling IO properly, what interests me is how to manage the data and control flow cleanly. Note that I should have also not set default values for _wWorker and _wMax.

The worst culprits are move, toChar and setMaxCoords.

EDIT: Because of the way values are in State, I have a series of functions:

isWall :: MonadState World m => Coord -> m Bool
isWall    c = use $ wWalls.contains c

isCrate :: MonadState World m => Coord -> m Bool
isCrate   c = use $ wCrates.contains c

isStorage :: MonadState World m => Coord -> m Bool
isStorage c = use $ wStorage.contains c

isWorker :: MonadState World m => Coord -> m Bool
isWorker  c = uses wWorker (==c)

These, I feel, are all fine, but they end up being less than useful in practice, because of the fact that the Bool is wrapped. The unwrapping process becomes very tedious in several functions:

move :: MonadState World m => Direction -> m ()
move dir = do
    newCoord  <- uses wWorker (moveCoord dir)
    let newCoord' = moveCoord dir newCoord
    wall      <- isWall  newCoord
    wall'     <- isWall  newCoord'
    crate     <- isCrate newCoord

    case () of
        () | wall  -> return ()
           | crate -> if wall' then return () else
                        do
                            wWorker ^= newCoord
                            wCrates %= delete newCoord
                            wCrates %= insert newCoord'
           | otherwise -> wWorker ^= newCoord

toChar :: MonadState World m => Coord -> m Char
toChar c = do
    wall    <- isWall    c
    crate   <- isCrate   c
    storage <- isStorage c
    worker  <- isWorker  c
    return $ case () of
        () | wall      -> '#'
           | worker    -> '@'
           | crate     -> 'o'
           | storage   -> '.'
           | otherwise -> ' '

The lenses themself also come with a certain cost

setMaxCoords :: StateT World IO ()
setMaxCoords = do
    xMaxWall           <- uses wWalls   $ fold (max . fst) 0
    yMaxWall           <- uses wWalls   $ fold (max . snd) 0
    xMaxCrate          <- uses wCrates  $ fold (max . fst) 0
    yMaxCrate          <- uses wCrates  $ fold (max . snd) 0
    xMaxStorage        <- uses wStorage $ fold (max . fst) 0
    yMaxStorage        <- uses wStorage $ fold (max . snd) 0
    (xWorker, yWorker) <- use wWorker
    wMax ^= (
        maximum [xMaxWall, xMaxCrate, xMaxStorage, xWorker],
        maximum [yMaxWall, yMaxCrate, yMaxStorage, yWorker]
            )

I feel like I must be missing some obvious abstractions, because all these operations seem trivial and necessary, but the wrapping adds a lot of boilerplate.

The full code is here: http://hpaste.org/73124


texts: Cross Thread Access to Object in ViewModel

texts:
This is a fairly straight forward question. I have a C# WPF MVVM application that call a C++ DLL to do some compilation/crunching. To update the UI C# application for progress updates I am using callback delegates.

public static class Callbacks
{
    public static ConsoleCallback ConsoleOutputCallback { get; set; }

    [UnmanagedFunctionPointer(CallingConvention.StdCall)]
    public delegate void ConsoleCallback(string message);
}

where the implementation is

Callbacks.ConsoleOutputCallback = (message) =>
    {
        console.Document.Text += message;
    };

where Document is of type TextDocument. I am then passing this object into the C++ to be able to invoke it and update the UI. This works great, however, for one control I am getting a standard

  A first chance exception of type 'System.InvalidOperationException' ... TextDocument can be accessed only from the thread that owns it.

Now, I understand this error. To get around it I have done the following

TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
Callbacks.ConsoleOutputCallback = (message) =>
    {
        Task.Factory.StartNew(() =>
        {
            console.Document.Text += message;
        }, CancellationToken.None,
           TaskCreationOptions.None,
           scheduler);
    };

which works. However, it would be nicer to look at if I could do a similar thing that I could do with a Control (which TextDocument Document is not) like

public static void PerformSafely<T>(this Control target, Action<T> action, T parameter)
{
    if (target.InvokeRequired)
        target.Invoke(action, parameter);
    else
        action(parameter);
}

but I cannot do this with TextDocument as it does not inherit from Control. Is there a nicer way to do what I am doing?


texts: PHP - Importing columns from uploaded CSV file to SQL database (Laravel 5.7)

texts:
The goal is to upload the columns from the csv into the SQL Pro database. I am able to select the column names that have been uploaded from the csv file, the columns from the csv file are then uploaded into the option dropdown.  In return I need to submit the selections that have been selected from the options dropdown, into the database. I am writing this in PHP. What I have is definitely not correct.

PHP

public function csvProcess(Request $request)
    {

        $contact = newContact();
        $contact->first_name = $rowProperties[$mapping['column_first_name']];
        $contact->last_name = $rowProperties[$mapping['column_last_name']];
        //$contact->newContact()->attach($first_name[$mapping['column_first_name']]);
        store(newContact()->where->$columnNames=$firstrow());
        $result = create($this(newContact()));

        $contact->save();
}

HTML

 Contact Fields

    {{field}}
    <select :id="field" :name="field" v-model="mapping[field]"required>
      <option value="">Please Select</option>
      <option v-for="columnName in columnNames" :name="columnName" :value="columnName"  value="">{{columnName}}</option>
    </select>

Javascript

     submitFiles()
        {
          //Form validation that will not allow a user to submit the form by upon the @click event
          if(!this.$refs.csvFile.checkValidity())
          {
            return null;
          }
          let formData = new FormData();
          formData.append('file', this.file);
          axios.post('http://localhost:8080/api/contacts/upload-csv',
          formData,
          {
          headers:
            {
              'Content-Type': 'multipart/form-data'
            }
          }
          )
          .then(function(response){
            console.log('SUCCESS!!');
            console.log(response);

          })
          .catch(function(response){
            console.log('FAILURE!!');
            console.log(response);

          })
        }

      }
    }
    </script>


texts: Perfect Number usage in higher order function

texts:
I am new to Scala.

I have been trying to complete an exercise where the ask was as follows:

// Write a function isPerfectNumber which takes integer input and returns String output.

// It finds if a number is perfect, and returns true if perfect, else returns false

// Write a higher order function myHigherOrderFunction which takes isPerfectNumber and intList as input, and returns a List of Strings which contain the output if the number is perfect or not using map.

Perfect Number :

https://rosettacode.org/wiki/Perfect_numbers#Scala

My Code :

object ListMapHigherOrder{
def main(args:Array[String])
{

val intRes = args.toList
val intList: List[Int] = intRes.map(_.toInt).toList

 def isPerfectNumber(input: Int) :String  =
 {
 var check_sum = ( (2 to math.sqrt(input).toInt).collect  { case x if input % x == 0 => x + input / x}  ).sum
 if ( check_sum == input - 1 )
      return "true"
      else
      return "false"
      }

def myHigherOrderFunction(argFn: Int => String, argVal:List[Int]): List[String] = { argVal.map(argFn) }

println(myHigherOrderFunction(isPerfectNumber, intList))

}
}

Code execution : scala ScalaExcercise12.scala 1 6 13

Expected Output : List(false , true , false)

the code gives expected output, am not sure how the backend testing is being done.... it just dosent pass the test.

Is there any issue with the code? - i did like to fix it , but cant i see anything wrong/missing

any help or direction is greatly appreciated.


texts:
This file manager has a code snippet that handles an argument of the "cd" console command. It converts the argument to a valid path, expands ~ and environment variables into the corresponding values:

std::vector<unicode_t> ConvertCDArgToPath( const unicode_t* p )
{
    std::vector<unicode_t> Out;

    std::vector<unicode_t> Temp;

    while ( p && *p )
    {
        unicode_t Ch = 0;

        if ( *p == '~' )
        {
            if ( LookAhead( p, &Ch ) )
            {
                if ( ( IsPathSeparator(Ch) || Ch == 0 ) && ApplyEnvVariable( "HOME", &Temp ) )
                {
                    // replace ~ with the HOME path
                    Out.insert( Out.end(), Temp.begin(), Temp.end() );
                    PopLastNull( &Out );
                }
            }
        }
        else if ( *p == '$' )
        {
            // skip `$`
            std::vector<char> EnvVarName = unicode_to_utf8( p+1 );
            for ( auto i = EnvVarName.begin(); i != EnvVarName.end(); i++ )
            {
                if ( IsPathSeparator( *i ) )
                {
                    *i = 0;
                    break;
                }
            }

            if ( ApplyEnvVariable( EnvVarName.data( ), &Temp ) )
            {
                // replace the var name with its value
                Out.insert( Out.end(), Temp.begin(), Temp.end() );
                PopLastNull( &Out );
                // skip var name
                p += strlen( EnvVarName.data() );
            }
        }
        else if ( IsPathSeparator(*p) )
        {
            if ( !LastCharEquals( Out, '/' ) && !LastCharEquals( Out, '\\' ) ) Out.push_back( DIR_SPLITTER );
        }
        else
        {
            Out.push_back( *p );
        }
        p++;
    }

    Out.push_back( 0 );

    return Out;
}

bool LookAhead( const unicode_t* p, unicode_t* OutNextChar )
{
    if ( !p ) return false;
    if ( !*p ) return false;
    if ( OutNextChar ) *OutNextChar = *(p+1);
    return true;
}

Is this code secure?
What is missing?
How can I deal with the duplicate code around the ApplyEnvVariable() calls?


texts: Determining if a word is an anagram of another

texts:
The question was to see if a word is an anagram of another word.

How would you improve this? It returns True if an anagram, or False otherwise.

# write the function is_anagram
def is_anagram(test, original):
    if len(test) != len(original):
        return False
    for letter in test.lower():
        if letter not in original.lower():
            return False
    for letter in original.lower():
        if letter not in test.lower():
            return False
    return True


texts: Finding the most common DNA patterns of some given length

texts:
I'm working on an algorithm to search through 100,000+ lines of dna sequencing, with the fastest time possible. Here is my current code, I was wondering if there's any ways to make this run faster:

public static void mostCommonKmer(String s, int k) {
    // your code here
    HashMap<String, Integer> m = new HashMap<>();
    int l = 0, g;
    String n = "", ss;
    for (int i = 0; i < s.length() - k; i++) {
        ss = s.substring(i, i+k);
        g = m.getOrDefault(ss, 1);
        m.put(ss, g + 1);
        if (l < g) {
            l = g;
            n = ss;
        }
    }
    System.out.println("Most Frequent " + k + "-mer = " + n);
    System.out.println("frequency = " + l);
}

s is the 100,000+ character string passed to the method and k is the length of pattern to look for

To be clear, it runs fast (0.08s for 100,000 chars), but I want to see how fast I can get it to go.


texts: How can I simplify these checkbox onClicks?

texts:
I know there is a way to simplify these checkbox onClick functions.  I'm just not sure how to make it happen.
Upon checking the checkAllProfiles checkbox, all of the profileCheckboxes are checked:
$('#checkAllProfiles').on('click', function()
{
  $(".profileCheckbox").prop('checked', $(this).prop('checked'));
});

Then, if one of the profileCheckboxes are checked, it unchecks the checkAllProfiles checkbox:
$(".profileCheckbox").on('click', function()
{
  $(".checkAllProfiles").prop("checked", false );
});

Now here is another set of checkboxes that require the same functionality:
$('#checkAllRegions').on('click', function()
{
  $('.regionCheckbox').prop('checked', $(this).prop('checked'));
});

$(".regionCheckbox").on('click', function()
{
  $(".checkAllRegions").prop("checked", false );
});

I want to be able to simplify this code.  How can I do it?


texts:
I have a list of candidates which looks like this:

candidates = [
    {
        'name': 'John',
        'rank': 13
    },
    {
        'name': 'Joe',
        'rank': 8
    },
    {
        'name': 'Averell',
        'rank': 5
    },
    {
        'name': 'William',
        'rank': 2
    }
]

What I want to do is semi-randomly pick one of these candidates, based on its squared rank. So that a candidate A having a rank twice as big as B, will have 4 times more chances to be picked than B.

Here is a naive implementation of the idea I had to solve this problem:

def pick_candidate(candidates):
    # initiates a global probability space
    prob_space = []

    # bring the max rank to 20
    # to avoid useless CPU burning
    # while keeping a good granularity -
    # basically, just bring the top rank to 20
    # and the rest will be divided proportionally
    rate = candidates[0]['rank'] / 20

    # fills the probability space with the indexes
    # of 'candidates', so that prob_space looks like:
    # [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
    # if candidates[0] has rank 3 and candidates[1] has rank 2
    for i, c in enumerate(candidates):
        rank = c['rank'] / rate
        for j in range(int(rank*rank)):
            prob_space.append(i)

    # picks a random index from the probability space
    picked_prob_space_index = random.randint(0, len(prob_space)-1)

    # retrieves the matching candidate
    picked_candidate_index = prob_space[picked_prob_space_index]

    return candidates[picked_candidate_index]

The questions I'm thinking of, concerning the above code, are:

Concept: Is the core principle of the algorithm (the idea of building prob_space, etc) overkill and solvable more easily in other ways or with builtins
Implementation: This core principle put aside, what do you think of the implementation? Would you think of a better, cleaner way to write it?


texts: Extending DOM elements with prototype for easier function execution

texts:
I've creating a small library of JavaScript functions that I will be using. Some are for UI functions others are to return something.

I am wondering if this method is ok and not a bad move before going any further with this library. Also, please do not mention jQuery as this is all JavaScript!

HTMLElement.prototype.drag = function(bool) {
var self = this;
self.classList.add('draggable');
    event.stopPropagation();
    event.preventDefault();
    var origLeft= parseInt(self.offsetLeft,10);
    var origTop = parseInt(self.offsetTop,10);
    var mdX = event.clientX;
    var mdY = event.clientY;
    var elements = [];
    if(bool === true){
      var j = window.localStorage.getItem('userSettings');
      if(j){
        self.style.left= j.left;
        self.style.top = j.top;
      }
    }
      function drag(bool) {
        self.style.position="absolute";
        self.style.zIndex=999;
        self.style.left = origLeft + event.clientX - mdX + "px";
        self.style.top = origTop + event.clientY - mdY + "px";
        event.stopPropagation();
      }
      function stop(bool){
        self.classList.remove('draggable');
        self.style.zIndex=0;
        document.removeEventListener('mousemove',drag,true);
        document.removeEventListener('mouseup',stop,true);
           if(bool === true){
            var settings = {
              left: self.style.left,
              top: self.style.top
            };
            var b = JSON.stringify(settings);
            window.localStorage.setItem('userSettings',b);
            console.log(b);
            }
        event.stopPropagation();
      }
       document.addEventListener('mousemove',drag,true);
       document.addEventListener('mouseup',stop,true);
};

The above code is of course for a draggable function. Here is a getClientRects() sort of function but better:

HTMLElement.prototype.getRect = function(){
     var a = this.offsetLeft;
     var b = this.offsetTop;
     var c = this.offsetHeight + b;
     var d = this.offsetWidth + a;
     var f = this.offsetHeight;
     var g = this.offsetWidth;
     var obj = { };
     obj.left = a;
     obj.right=d;
     obj.top=b;
     obj.bottom=c;
     obj.width = g;
     obj.height=f;
  return obj;
};

The purpose of showing you all this is to get your thoughts and maybe advise about prototype or should I not do it this way. I just like the method execution like this:

document.getElementById('div').getRect();

instead of doing it with a function getRect('div');.

The problem is for one not sure what enumerable is as I've self taught everything, and never really read on the terminology. I know what one of the users means when he says iterating them using a for in loop though not sure how to make it non-enumerable. Nor how to go about this any better way as I don't want my users (who use jQuery a lot) though the library is huge and honestly I'd rather them use a vanilla JavaScript library in the sense that is minimized for purposes of what I am doing (making a huge plug-in with a library and other coding options they can have their hands on).


texts:
I was trying to create the selenium web element object repository in python. I have come up with three ways to do so. However, I am new to python so I am not sure which one is better than other.

Note: I am using Page object pattern for writing my tests, however just for understanding and simplicity I have put all the function in one file (class).

First: Using Decorator

def FindBy(by, value):
    def decorator(func):
        def wrapper(self):
            return self.driver.find_element(by, value)
        return wrapper
    return decorator

class TestGoogle(object):

    @FindBy(By.NAME, "q")
    def search_input(self): pass

    def test_search(self):
        self.driver = webdriver.Firefox()
        self.driver.get("https://google.com")
        self.search_input().send_keys("selenium python")

Second & Third: using Lambda and Method

class TestGoogle(object):

    def find_element(self, by, value):
        return self.driver.find_element(by, value)

    def search_input(self): return self.find_element(By.NAME, "q")

    search_input_1 = lambda self: self.find_element(By.NAME, "q")

    def test_search(self):
        self.driver = webdriver.Firefox()
        self.driver.get("https://google.com")
        self.search_input().send_keys("selenium python")
        self.search_input_1().clear()


texts: Suggestions for a Profiler class in Python

texts:
Here's what I've right now:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import functools
import math
import time

class Timer(object):
    def __init__(self):
        self.__values = []

    def start(self):
        self.__start = time.time()

        return self

    def stop(self):
        self.__values.append(int(round((time.time() - self.__start) * 1000)))
        self.__start = None

        return self

    @property
    def average(self):
        return sum(self.__values) / len(self.__values)

    @property
    def deviation(self):
        if self.average:
            return math.sqrt(sum((v - self.average) ** 2 for v in self.__values) / self.runs)

        return 0

    @property
    def elapsed(self):
        return sum(self.__values)

    @property
    def runs(self):
        return len(self.__values)

class Profiler(object):
    __timers = {}

    @staticmethod
    def info(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        return Profiler.__timers[timer_id]

    @staticmethod
    def profile(f):
        @functools.wraps(f)
        def wrap(self=None, *args, **kwargs):
            method = self.__class__.__name__ + '.' + f.func_name if self \
                     else f.func_name

            Profiler.start(method)
            r = f(self, *args, **kwargs) if self else f(*args, **kwargs)
            Profiler.stop(method)

            return r

        return wrap

    @staticmethod
    def reset(timer_id):
        Profiler.__timers[timer_id] = Timer()

    @staticmethod
    def start(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            Profiler.reset(timer_id)

        Profiler.__timers[timer_id].start()

    @staticmethod
    def stop(timer_id):
        if not Profiler.__timers.has_key(timer_id):
            raise Exception('Timer not started')

        Profiler.__timers[timer_id].stop()

if __name__ == '__main__':
    class Test(object):
        def isPrime(self, n):
            if n < 2 or (n % 2) == 0:
                return n == 2

            f = 3

            while (f * f) <= n:
                if (n % f) == 0:
                    return False

                f += 2

            return True

        @Profiler.profile
        def run(self):
            return filter(self.isPrime, range(1, 1000001))

    test = Test()

    for x in range(5):
        test.run()

    p = Profiler.info('Test.run')
    print 'runs = %d' % p.runs
    print 'elapsed = %d ms' % p.elapsed
    print 'average = %d ms' % p.average
    print 'deviation = %d ms' % p.deviation

I'm looking for suggestions to improve it and you're welcome to suggest. :)

The Profiler.profile decorator supports both functions and class methods. I've written a small test to demonstrate my profiler.


texts: Checking whether a number is a power of 10

texts:
Is there a better way to check whether a number is a power of 10? This is what I've implemented:

    public class PowersOfTen {

    public static boolean isPowerOfTen(long input) {

        if (input % 10 != 0 || input == 0) {
            return false;
        }

        if (input == 10) {
            return true;
        }

        return isPowerOfTen(input/10);
    }

    public static void main(String[] args) {

        System.out.println("1000: " + isPowerOfTen(1000));
        System.out.println("4: " + isPowerOfTen(4));
        System.out.println("0: " + isPowerOfTen(0));
        System.out.println("10: " + isPowerOfTen(10));
        System.out.println("100: " + isPowerOfTen(100));
    }
}


texts:
I am tracking trains and trying to identify individual trains seen multiple times at different points through the IDs of the wagons on them when spotted.

// create a lookup of all tracked trains for each wagon
IEnumerable<Train> trains = GetTrains();

var wagonTrains = new Dictionary<int, List<Train>>();
foreach (Train t in trains)
{
  foreach (int w in t.WagonsInTrain)
  {
    if (!wagonTrains.ContainsKey(w))
    {
      wagonTrains.Add(w, new List<Train>());
    }
    wagonTrains[w].Add(t);
  }
}

Is there a better way do to what I am doing in this code segment? Perhaps some chained linq operations? Is there a particular name for the kind of operation I am using here?


texts: Bash script to install zsh on different distributions

texts:
Extreme script newbie here, so please go easy on me!
I wrote a script to install zsh on a number of different Linux distributions. But since I'm so new at this, I'm piecing a lot of different things together and I doubt it's as efficient and tight as possible. Any suggestions are welcome. Thank you!
#!/bin/bash

export ZSHUSER=$USER

if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
elif type lsb_release >/dev/null 2>&1; then
    OS=$(lsb_release -si)
    VER=$(lsb_release -sr)
fi

echo "Creating fonts directory"
cd /tmp && mkdir fonts && cd $_

echo "Downloading fonts"
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Regular.ttf
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold.ttf
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Italic.ttf
wget https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold%20Italic.ttf

echo "Entering sudo mode to copy fonts"

if [[ $NAME = "Fedora" ]]; then
sudo su - <<EOF
dnf install -y git zsh zsh-autosuggestions zsh-syntax-highlighting
cd /usr/share/fonts/ && mkdir MesloMGS
cp /tmp/fonts/*.ttf /usr/share/fonts/MesloMGS
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/$NAME/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
su $USER
EOF

elif [[ $NAME = "void" ]]; then
sudo su - <<EOF
xbps-install -y git zsh zsh-autosuggestions zsh-syntax-highlighting
cp /tmp/fonts/*.ttf /usr/share/fonts/TTF
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/$NAME/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
su $USER
EOF

elif [[ $NAME = "Debian" ]] || [[ $NAME = "Ubuntu" ]] || [[ $NAME = "Linux Mint" ]]; then
sudo su - <<EOF
apt install -y git zsh zsh-autosuggestions zsh-syntax-highlighting
cd /usr/share/fonts/truetype && mkdir MesloMGS
cp /tmp/fonts/*.ttf /usr/share/fonts/truetype/MesloMGS
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/Debian/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
su $USER
EOF

elif [[ $NAME = "CentOS Linux" ]]; then
sudo su - <<EOF
yum install -y git zsh zsh-syntax-highlighting
cd /usr/share/fonts/ && mkdir MesloMGS
cp /tmp/fonts/*.ttf /usr/share/fonts/MesloMGS
fc-cache
rm -r /tmp/fonts
scp -v /mnt/E/Linux/zsh/CentOS/aliasrc $HOME
chown $USER:$USER $HOME/aliasrc
git clone https://github.com/zsh-users/zsh-autosuggestions /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh
su $USER
EOF

else
echo "Operating system not identified"
pause
fi

mkdir ~/powerlevel10k && cd ~/powerlevel10k
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k
echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >> ~/.zshrc

echo "opening terminal to configure zsh"
if [[ $NAME = "Ubuntu" ]] || [[ $NAME = "CentOS Linux" ]] || [[ $NAME = "Linux Mint" ]]; then
    gnome-terminal -q -- zsh
    read -p "press enter to resume"
elif [[ $NAME = "Fedora" ]]; then
    mate-terminal -e zsh
elif [[ $NAME = void ]]; then
    qterminal -e zsh
elif [[ $NAME = Debian ]]; then
    xfce4-terminal -e zsh
fi

sudo su - <<EOF
echo "copying .zshrc file"
scp -v /mnt/E/Linux/zsh/.zshrc $HOME
chown $USER:$USER $HOME/.zshrc
su $USER
EOF

```


texts: Find two numbers in a sorted array whose sum is closest to a given number

texts:
Given a sorted array and a number x, find a pair in array whose sum is closest to x.

Here's my solution:

import Data.List (minimumBy)
import Data.Ord (comparing)

closestPairSum :: (Num a, Ord a) => [a] -> a -> (a, a)
closestPairSum xs n = snd $ minimumBy (comparing fst) pairs
  where
    pairs = sums xs (reverse xs)
    sums xxs@(x:xs) yys@(y:ys) = let sum = x + y in
      if n < sum
      then (sum - n, (x, y)) : sums xxs ys
      else (n - sum, (x, y)) : sums xs yys
    sums _ _ = []

I'm mostly self-taught, so I would love to know in which ways my code is not according to common practice. More specifically:

How can I more clearly align my let-in and if-then-else expressions?
I use an intermediate list of (a, (a, a)) tuples, which I'm not thrilled about. Is there a more elegant way to do this, without sacrificing performance?
I'm on the fence about sum xs (reverse xs) vs sum xs $ reverse xs. Is this just considered nitpicking, or do people have a strong opinion about this?
Would it make more sense to swap the parameters of this function? I have the feeling that a would usually precede [a] with pointfree style in mind, but I'm not sure about this one.
Anything else that I might not have thought of :)


texts:
I have an array of number objects, which can be selected only if the orderable quantity is greater than 0.

I have a select all checkbox that is checked or unchecked accordingly with this function:

self.allSelected = function () {
  return self.shownNumbers().filter(function (number) {
    return number.isSelected();
  }).length === self.shownNumbers().filter(function (number) {
    return number.orderableQty > 0;
  }).length;
}

I can also iterate over the array and return the result:

self.allSelected = function () {
  var s = 0, o = 0;
  for (var i = 0; i < self.shownNumbers().length; i += 1) {
    if (self.shownNumbers()[i].isSelected()) s ++;
    if (self.shownNumbers()[i].orderableQty > 0) o ++;
  }
  return s === o;
}

The second one seems more readable and probably is more efficient since it iterates the array only once. Is there a way to use a single filter, map or other Array.prototype built-in function in order to reduce the code and make it more readable or should I keep the single loop option?


texts: Web Component prevent multiple API fetches

texts:
I work on a small Web Component that converts an amount of money to another currency. For that, I use an API that returns the exchange rates.
I want to use the component multiple times on a page and thought that it would be a waste of traffic if every component fetches the same exchange rates. So I wrote some logic that only the first handled component fetches it, stores the results in a window variable. The other components notice that some already loads the data and store a callback in that window variable. When the fetching is done all callbacks will be resolved.
This works great but I wonder if this is a bad practice or whether this is even unnecessary because maybe it is cached etc.
Code (the described part is in the "connectedCallback" function):
const template = document.createElement('template');
template.innerHTML = `

  `;

class CurrencyConverter extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }

  async fetchApi() {
    return new Promise((resolve, reject) => {
      fetch(`https://api.exchangeratesapi.io/latest?base=${this.baseCurrency}`)
        .then((response) => response.json())
        .then((data) => resolve(data))
        .catch((err) => reject(err));
    });
  }

  renderData() {
    const browserLocale = navigator.language;
    const originFormat = new Intl.NumberFormat(browserLocale, {
      style: 'currency',
      currency: this.baseCurrency,
    });
    const conversionFormat = new Intl.NumberFormat(browserLocale, {
      style: 'currency',
      currency: this.conversionCurrency,
    });

    const originAmount = originFormat.format(this.value);

    this.convertedAmount =
      this.value *
      window.rates[this.baseCurrency].data.rates[this.conversionCurrency];

    const conversionAmount = conversionFormat.format(this.convertedAmount);

    this.shadowRoot.querySelector(
      '.curr-shell'
    ).innerText = `${originAmount} | ${conversionAmount}`;
  }

  async connectedCallback() {
    this.baseCurrency = this.getAttribute('base-currency');
    this.value = parseFloat(this.getAttribute('value'));
    this.conversionCurrency = this.getAttribute('conversion-currency');

    if (!window.rates) window.rates = {};

    if (!window.rates[this.baseCurrency]) {
      // first one -> fetch api
      window.rates[this.baseCurrency] = {
        status: 'fetching',
        data: null,
        callbacks: [],
      };

      window.rates[this.baseCurrency].data = await this.fetchApi();
      window.rates[this.baseCurrency].status = 'loaded';
      this.renderData();
      // resolve all callbacks from the waiting ones
      window.rates[this.baseCurrency].callbacks.forEach((cb) => cb());
    } else if (window.rates[this.baseCurrency].status === 'fetching') {
      // currently some else is fetching -> add callback to be called when done
      window.rates[this.baseCurrency].callbacks.push(() => this.renderData());
    } else {
      // all data loaded
      this.renderData();
    }
  }
}

window.customElements.define('currency-converter', CurrencyConverter);

Demo: https://phartenfeller.github.io/currency-converter-wc/demo/


texts: Execute a command repeatedly until a stop message is received

texts:
I'm trying to create a script that receive command from other script, and based on the command received it will execute a method with a while loop or stop it. I manage to make it works with the code below:

import rospy
import threading
from std_msgs.msg import String

class MonitoringInterrupt(Exception): pass

def cbCmd(nData):
    """Call back function when receive command from a topic"""
    cmd=nData.data
    print("Received cmd: ", cmd)
    global is_monitoring
    global t
    try:
        if cmd=='1':
            is_monitoring = False
            raise MonitoringInterrupt
        elif cmd=='0':
            is_monitoring = True
            t = threading.Thread(target=do_something)
            t.start()
        else:
            print("Unknown cmd")
    except MonitoringInterrupt:
        pass

def do_something():
    try:
        while is_monitoring:
             print(str(rospy.get_time()))
             rate.sleep()
    except MonitoringInterrupt:
        pass

def talker():
    while not rospy.is_shutdown():
        rate.sleep()

if __name__ == '__main__':
    global is_monitoring
    is_monitoring = False
    global t
    rospy.init_node('Testing_command', anonymous=True)
    rospy.Subscriber('cmd', String, cbCmd)
    rate = rospy.Rate(20)
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

But it look a little bit messy. And I read in the forum that we shouldn't use exception to interrupt method. So is there any other cleaner way to do this? Some people recommend using thread.Event but I haven't success to implement that with is one. Also, when should I call t.join()? I want to call the method multiple times, and as I understand you can only start a thread once.


texts: Generate next available filename based on current date

texts:
I have a bit of code that I would like your collective opinions on. Currently, my working code has two return statements. I'm not sure how I feel about having multiple points of exit, however, the alternative introduces the inclusion of else, which looks like it will eventually be harder to maintain if more logic is added to the code later on.

My current code (Feel free to comment on other aspects as well):

function generateFileName() {
    var k = 0;
    var today = new Date();
    today = (today.getMonth() + 1).toString() + '-' + today.getDate().toString()
            + '-' + today.getFullYear().toString();
    while (true) {
        if (!fs.existsSync('./'+ today + '.pdf')) {
            return './' + today + '.pdf';
        }

        if (!fs.existsSync('./' + today + '(' + k + ').pdf')) {
            return './' + today + '(' + k + ').pdf';
        }

        k++;
    }
}

As you see, here there are two different return statements. If the file does not exist in the system, a file will be generated with the name 5-19-2017.pdf, i.e., the current date. If there is already a file named that, the file will be named 5-19-2017 (0).pdf, then 5-19-2017(1).pdf, and so on...

This code works just fine, however - I am wondering if maybe a single point of exit might be better, such as :

function generateFileName() {
    var k = 0;
    var today = new Date();
    today = (today.getMonth() + 1).toString() + '-' + today.getDate().toString() + '-' +today.getFullYear().toString();
    var result = today;
    var stop = false;
    while (!stop) {
        if (fs.existsSync('./'+ today + '.pdf')) {
            if (fs.existsSync('./' + today + '( ' + k + ' ).pdf')){
                k++;
            } else {
                result = today + '( ' + k + ' )';
                stop = true;
            }
        }
        else {
            stop = true;
        }
    }
    return result;
}

Now, the code has a single point of exit, however the added else statements make the code unbearable to read, in my opinion.

Thoughts?


texts:
I wrote a little program that recognises poker hand combinations and compares hands if the ranks of both hands are the same. I had tested my program on possible combinations for each rank and the outcomes were correct. I would like to know how it is possible to improve the design of my code and maybe cut a few steps.

I am also planning on expanding the whole program a bit further e.g. recognising the best combination from two initial cards and five cards on the table, so making code programmer-friendly is a priority for me.

vector<string> cards{"6H", "7H", "8H", "9H", "TH"}; //Or any other hand

char rank = 0;
vector<char> vals;

//Extracting values of each card without a suit
for(vector<string>::iterator it = cards.begin(); it != cards.end(); ++it)
{
    if((*it)[0] == 'T')vals.push_back(58);
    else if ((*it)[0] == 'J')vals.push_back(59);
    else if ((*it)[0] == 'Q')vals.push_back(60);
    else if ((*it)[0] == 'K')vals.push_back(61);
    else if ((*it)[0] == 'A')vals.push_back(62);
    else vals.push_back((*it)[0]);
}

// Checking for pairs, triples and quadruples
sort(vals.begin(), vals.end(), greater<char>());
for(vector<char>::iterator it = vals.begin(); it != vals.end(); it)
{
    int counter = 0;
    auto nx = next(it);
    while(*it == *nx && nx != vals.end())
    {
        ++counter;
        ++nx;
    }
    switch(counter)
    {
        case 1:
            if(rank == 0)
            {
                rank = 1;
                rotate(vals.begin(), it, nx); //Pairs are compared first
            }
            else if(rank == 1)
            {
                rank = 2;
                rotate(vals.begin()+2, it, nx); //2nd pairs are compare after 1st pairs
            }
            else if(rank == 3)rank = 6;
            break;
        case 2:
            if(it != vals.begin())rotate(vals.begin(), it, nx); //Tripples are always compared first
            if(rank == 0) rank = 3;
            else if(rank == 1)rank = 6; //Full House
            break;
        case 3:
            rank = 7;
            if(it != vals.begin())rotate(vals.begin(), it, nx);
    }
    it = nx;
}

//Checking for flash and street
if(cards[0][1] == cards[1][1] && cards[1][1] == cards[2][1] && cards[2][1] == cards[3][1] && cards[3][1] == cards[4][1])rank = 5;
if(vals[0] == vals[1]+1 && vals[1] == vals[2]+1 && vals[2] == vals[3]+1 && vals[3] == vals[4]+1)
{
    if(rank == 0)rank = 4;
    else rank = 8;
}
cout << "RANK: " << static_cast<int>(rank) << endl;


texts: Getting hexagonal arrays of dots arranged in this spiral pattern

texts:
Answers to this explain why I can't reliably get int type arrays. While there are some workarounds I have a hunch there's a better, cleaner or otherwise "less tricky" way to get these hexagonal arrays of dots arranged in this spiral pattern than the way I've done it by using several conditions.

Is my hunch correct?

Note: hexit_60() and get_points() are used in different ways in other places so I don't want to combine them.

Context: This is used in a simulation and plotting routine for points in reciprocal space of a hexagonal lattice as part of a diffraction calculator.

import numpy as np
import matplotlib.pyplot as plt

def hexit_60(n_max):
    pairs = []
    if n_max >= 0:
        pairs.append(np.zeros(2, dtype=int)[:, None])
    if n_max >= 1:  # https://stackoverflow.com/q/61382568/3904031 trap 0*[n] because casts to float
        seq = [1, 0, -1]
        p0  = np.hstack((seq, seq[::-1]))
        N   = len(p0)
        p1  = np.hstack((p0[N-2:], p0[:N-2]))
        pairs.append(np.stack((p0, p1), axis=0))
    for n in range(2, n_max+1):
        seq = np.arange(n, -n-1, -1, dtype=int)
        p0  = np.hstack((seq, (n-1)*[-n], seq[::-1], (n-1)*[n]))
        N   = len(p0)
        p1  = np.hstack((p0[N-2*n:], p0[:N-2*n]))
        pairs.append(np.stack((p0, p1), axis=0))
    if len(pairs) > 0:
        pairs = np.hstack(pairs)
    else:
        pairs = None
    return pairs

def get_points(a, n_max):
    vecs = a * np.array([[1.0, 0.0], [0.5, 0.5*np.sqrt(3)]])
    pairs = hexit_60(n_max = n_max)
    if isinstance(pairs, np.ndarray):
        points = (pairs[:, None]*vecs[..., None]).sum(axis=0)
    else:
        points = None
    return points

fig = plt.figure()
for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):
    ax = fig.add_subplot(2, 3, i+1)
    # plt.subplot(2, 3, i+1)
    ax.set_title('n_max: ' + str(n_max))
    points = get_points(a=1.0, n_max=n_max)
    if isinstance(points, np.ndarray):
        x, y = points
        ax.scatter(x, y)
        ax.plot(x, y, '-k', linewidth=0.5)
    ax.set_xlim(-4.2, 4.2)
    ax.set_ylim(-4.2, 4.2)
    ax.set_aspect('equal')
plt.show()


texts: HTML and CSS markup to achieve desired result

texts:
I am new to HTML and CSS. I was wondering if anyone could give me some advice on my use of markup and CSS to achieve this result. I am trying to get a fixed full height sidebar with a list with sprite image for each item.

This is the code I have which achieves this.

HTML

User

Vacancies

Company

Create New

Title

Create new list

        <form name="input">
            <input type="text" name="Title">
            <input type="text" name="Location">
            <input type="text" name="Description">
            <input type="text" name="Closing date">
            <input type="submit" value="Add">
        </form>

CSS

* {
    margin: 0px;
    padding: 0px;
}
li {
    list-style-type: none;
}
.container {
    display: block;
    position:absolute;
    height:auto;
    bottom:0;
    top:0;
    left:0;
    right:0;
    background-color:white;
}
.column_wrap {
    position:relative;
}
.col_left {
    background-color:#f2f2f2;
    width:250px;
    position:absolute;
    left:0;
    top:0;
    bottom:0;
    height:auto;
    display: block;
}
.col_left img {
    float:right;
    display: block;
    line-height:40px;
    margin-left: auto;
    margin-right: auto;
}
.col_left li a {
    color: gray;
    display: block;
    line-height: 26x;
}
.col_left li a:hover {
    color: green;
}
.col_right {
    margin-left:250px;
}
.col_right li {
    float: right;
}
.col_right a {
    float: right;
    background: green;
    padding: 10px;
    color: white;
    font-weight:bold;
}
.col_right a:hover {
    background: blue;
}
input {
    display: block;
    border: 2px solid gray;
    padding: 10px;
    margin: 10px
}
input:hover {
    border: 2px solid blue;
}
input:focus {
    border: 2px solid blue;
}
.navimg {
    background:url('http://www.otlayi.com/web_images/content/free-doc-type-sprite-icons.jpg');
width: 0px;
    height: 20px;
    padding-left: 30px;
}
#user {
    background-position: -10px -6px;
}
#vacancy {
    background-position: -48px -6px;
}
#company {
    background-position: -88px -6px;
}

However, I think there might be some areas where my code is inefficient, messy or non symantic. Can anyone give me any advice please? I would really appreciate it.


texts: Filter string depending on filtered & unfiltered keywords

texts:
I have worked on a small script where I check if the given string is a filtered or unfiltered keyword. Basically if its filtered then we want to add a additional key to dict. with value True, if its not filtered then its False. Once that is done we want to return True if its filtered else False.
Right now I have done something like this:
import re

payload = {"test_string": "hello World"}

def test(payload):
    def check_all(sentence, words):
        return all(re.search(r'\b{}\b'.format(word), sentence) for word in words)

    filtered_keywords = ["hello+world", "testing"]
    unfiltered_keywords = ["bad+word", "naughty+word"]

    if not any(check_all(payload["test_string"].lower(), word.split("+")) for word in filtered_keywords) or any(check_all(payload["test_string"].lower(), word.split("+")) for word in unfiltered_keywords):

        payload["keyword"] = False

        # Thread to send to discord
        # Thread(
        #     target=discord.create_embed,
        #     args=(
        #         payload,
        #     )
        # ).start()

        return False

    else:
        payload["keyword"] = True

        # Thread(
        #     target=discord.create_embed,
        #     args=(
        #         payload,
        #     )
        # ).start()

        return True

print(test(payload))

The part with Thread is where I post to discord and then return either True or False depending on if-else statement.
The point of this script is that I will later on send a payload with random string in the future so it will not be static.
If there is any more question or missing info needed, please feel free to comment :)


texts: Running code snippets in a background thread

texts:
I'm working on a dataset from a MOOC.  I have a lot of python3 code snippets that I need to run and get the results from.  To do this I've written a python script that loops over each snippet.  For each snippet I:

Create new StringIO objects
Set sys.stdout and sys.stderr to my stringIO buffers
Execute the code snippet in a threading.thread object
Join the thread
Log the results in the stringIO buffers
Restore stdout and stderr

This works fine for "correct" code, but this has undesired side effects in other cases:

When the code has an infinite loop, thread.join doesn't kill the thread.  The thread itself is a daemon thread, so it runs quietly in the background until my loop finishes.
When the code has an infinite loop with a print(), the thread starts overwriting my actual stdout when I set it back to the default (away from the StringIO buffer).  This pollutes my reporting.

Here is my current code:
def execCode(code, testScript=None):
    # create file-like string to capture output
    codeOut = io.StringIO()
    codeErr = io.StringIO()

    # capture output and errors
    sys.stdout = codeOut
    sys.stderr = codeErr

    def worker():
        exec(code, globals())

        if testScript:
            # flush stdout/stderror
            sys.stdout.truncate(0)
            sys.stdout.seek(0)
            # sys.stderr.truncate(0)
            # sys.stderr.seek(0)
            exec(testScript)

    thread = threading.Thread(target=worker, daemon=True)
    # thread = Process(target=worker) #, stdout=codeOut, stderr=codeErr)
    thread.start()
    thread.join(0.5)  # 500ms

    execError = codeErr.getvalue().strip()
    execOutput = codeOut.getvalue().strip()

    if thread.is_alive():
        thread.terminate()
        execError = "TimeError: run time exceeded"

    codeOut.close()
    codeErr.close()

    # restore stdout and stderr
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__

    # restore any overridden functions
    restoreBuiltinFunctions()

    if execError:
        return False, stripOuterException(execError)
    else:
        return True, execOutput

To handle the undesirable cases, I've tried to use multithreading.Process and/or contextlib.redirect_stdout to run the code in a process (then I can call process.terminate()), but I'm not having any success capturing stdout/stderr.
So my question is:  What can I do to make this better/more robust to handle bad code snippets?
(And yes, I know this is a bad idea in general; I'm running it in a virtual machine just in case there is malicious code in there somewhere)
Python version is 3.5.3

Update
It occurs to me that there is a little more flexibility in this situation.  I have a function, preprocess(code) that accepts a the code submission as a string and alters it.  Mostly I've been using it to swap out the value of some variables using regular expressions.
Here is an example implementation:
def preprocess(code):
    import re
    rx = re.compile('earlier_date\s*=\s*.+')
    code = re.sub(rx, "earlier_date = date(2016, 5, 3)", code)
    rx = re.compile('later_date\s*=\s*.+')
    code = re.sub(rx, "later_date = date(2016, 5, 24)", code)
    return code

I could use the preprocess function to help redirect STDOUT


texts:
This is a calculator I created. It can take all basic operators, including brackets. I am a beginner with Python so I want to know what can I do better next time I write something similar.

def eval(expression):
    current = 0
    while current < len(expression):
        x = expression[current]
        if x == '(':
            levels = 1
            inside = ''
            while levels:
                current+=1
                x = expression[current]
                if x == ')':
                    levels -= 1
                    if not levels:
                        expression = expression.replace('('+inside+')',str(eval(inside)))
                        current -= (len(inside)+2)
                    else:
                        inside+=')'
                elif x == '(':
                    levels+=1
                    inside+=x
                else:
                    inside+=x
        current+=1
    expressions = list(filter(None,expression.replace('+-','-').replace('-','+-').split('+')))
    ret = 0
    for exp in expressions:
        if exp.find('*') == -1 and exp.find('/') == -1:
            ret+=int(exp)
            continue
        op = '*'
        expret = 1
        exp +='*1'
        while exp.find('*') > -1 or  exp.find('/') > -1:
            next_mult = exp.find('*')
            next_div = exp.find('/')
            if next_mult > -1 and (next_mult < next_div or next_div==-1):
                expret = multdiv(expret,op,float(exp[:next_mult]))
                op = '*'
                exp = exp[next_mult+1:]
            elif next_div < next_mult:
                expret = multdiv(expret,op,float(exp[:next_div]))
                op = '/'
                exp = exp[next_div+1:]
        ret += expret
    return ret
def multdiv(num1,op,num2):
    if op == '*':
        return num1*num2
    return num1/num2

print(eval(input()))


texts:
I'm implementing a method which has the purpose of waiting for a message (boolean value). Works, but can it be improved?
Code:
public class Waiter {
    private ExecutorService executor;

    public Waiter(ExecutorService executor){
        this.executor = executor;
    }

    public void waitFor(Supplier<Boolean> condition, long maxTimeSeconds, long pooligTimeMiliseconds)
            throws TimeoutException
             {
                 try{
                     executor.submit(() -> {
                        while (true){
                            if (condition.get())
                                return;
                            try {
                                Thread.sleep(pooligTimeMiliseconds);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                return;
                            }
                        }
                     }).get(maxTimeSeconds, TimeUnit.SECONDS);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 } catch (ExecutionException e) {
                     e.printStackTrace();
                 }
             }
    }

For short, waitFor runs a thread in an Executor object - wait for a message (as a lambda supplied by Supplier). Wait maxTimeSeconds time in poolingTimeMiliseconds intervals. get method check if the thread finish execution in it's the first argument (maxTimeSeconds here) time.


texts:
I would like to get some advice on WAI-ARIA markup I have added to my paginated post navigation.

Does this look correct, am I missing anything?

Should anything be added/removed to the current page link (#2)?

Also, curious on my "Page Count" and "View All" sections what if anything can be added to make it more ARIA-friendly.

        Page 2 of 4

                «

            1

            2

            3

            4

                »

            View All


texts:
I am using node.js with express. There is a button that the user can click, and doing so calls this method on the server:

app.get('/getTime', function(req, res) {

    var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
    http.get(url + '?key=' + apikey, function(resp) {

        var xml = '';
        resp.on('data', function(chunk) {
            xml += chunk;
        });

    resp.on('end', function() {
            console.log(xml);
            res.send(xml);
        });

    });

});

This works, strictly speaking, in that the client side does receive the XML data. What bothers me is that there are two response objects that I have only dealt with by calling one "res" and the other "resp". I have a feeling I am handling the callbacks the wrong way, or that the entire structure of this task is done incorrectly.

I would appreciate some guidance about the "right way" to do this, as I am sure this is not it.


texts:
I've been experimenting with the Express Node.js framework. On the face of it, the approach of passing functions to app.VERB methods seems unusual. In other frameworks I've used (in languages other than javascript), you create a single handler class for each url pattern, with methods representing different HTTP verbs. One advantage is the ability to bundle common functionality in methods of superclasses.

I've tried to replicate this in node, but I'm interested in feedback on whether this seem like a good approach.

(I realise that the naming of "as_view" doesn't make much sense - I just named it that way because I'm used to django, where the term "view" is used to refer to something akin to a controller rather than a template.)

function Controller(verbs) {
    for (verb in verbs) {
        this[verb] = verbs[verb];
    }
}
Controller.prototype.as_view = function() {
    var dispatcher = function(req, res) {
        var verb = req.method.toLowerCase();
        this[verb](req, res);
    };
    return dispatcher.bind(this);
};

var pageone = new Controller({

    get: function(req, res) {
        res.send("Get request");
    },

    post: function(req, res) {
        res.send("Post request");
    }
});

....

app.all('/pageone', pageone.as_view());
....


texts:
I wrote this together for a test I'm doing that parses the Heroku access log. What I'm mainly interested is if this code follow common best practices and if there are any improvements I can make in terms of memory efficiency.

Here is a line from the Heroku from their docs:

  2010-09-16T15:13:46.723498+00:00 heroku[router]: at=info method=GET
  path="/posts" host=myapp.herokuapp.com" fwd="204.204.204.204"
  dyno=web.1 connect=1ms service=18ms status=200 bytes=975

And an endpoint is a line that looks like this:

  GET /api/users/{user_id}/count_pending_messages

class FileReader

  def initialize(filename, start_at = nil, end_at = nil, endpoints = nil)
    @filename = filename
    @start_at = start_at
    @end_at = end_at
    @endpoints = endpoints
  end

  def read
    File.foreach(@filename).map { |l|
      # saving some memory here by only loading data into memory that we need
      unless @start_at.nil? or @end_at.nil?
        start = l.index(@start_at)
        finish = l.index(@end_at) - 2
        l[start..finish]
      else
        l
      end
    }
  end

  def endpoints
    File.foreach(@endpoints).map { |line| line.split }
  end

end

require 'forwardable'

class AccessParser
  extend Forwardable

  def_delegators :@reader, :read, :endpoints

  REGEX_MATCH_DIGITS = /\d+/
  PLACEHOLDER = '{user_id}'

  Uris = Struct.new(:method, :uri, :stats)
  Stats = Struct.new(:dyno, :response_time)

  def initialize(reader)
    @reader = reader
  end

  def parse

    uris = endpoints_to_uris

    read.each.map { |line|

      data = line_to_hash line

      method = data['method']
      uri = data['path'].sub(REGEX_MATCH_DIGITS, PLACEHOLDER)

      uris.each.map { |e|
        if uri == e.uri.to_s and method == e.method
          (e.stats.dyno ||= []) << data['dyno']
          response_time = data['connect'].to_i + data['service'].to_i
          (e.stats.response_time ||= []) << response_time
        end
      }
    }
    uris

  end

  private

  def endpoints_to_uris
    # using structs because it's faster than hashes
    endpoints.each.map { |e| Uris.new(*e, Stats.new) }
  end

  def line_to_hash(line)
    # using split because it's faster than regex
    Hash[line.split.each.map { |a| a.split('=') }]
  end

end

module Enumerable

  def sum
    inject(0.0) { |result, el| result + el }
  end

  def mean
    sum / size
  end

  def median
    len = sort.length
    (sort[(len - 1) / 2] + sort[len / 2]) / 2.0
  end

  def mode
    counter = Hash.new(0)
    entries.each.map { |i| counter[i] += 1 }
    mode_array = []
    counter.each.map { |k, v|  mode_array << k if v == counter.values.max }
    mode_array.sort.first
  end
end

class AccessConsoleWriter
  extend Forwardable

  def_delegators :@parser, :parse

  def initialize(parser)
    @parser = parser
  end

  def call
    parse.each do |d|
      puts "# #{d.method} #{d.uri}"
      puts "# " + "-" * (d.uri.length + d.method.length + 1)
      if d.stats.dyno.nil?
        puts "# Calls: 0"
      else
        puts "# Calls: #{d.stats.dyno.count}"
        puts "# Mean: #{d.stats.response_time.mean.round(2)}"
        puts "# Median: #{d.stats.response_time.median.round(2)}"
        puts "# Mode: #{d.stats.response_time.mode}"
        puts "# Dyno: #{d.stats.dyno.mode}"
      end
      puts ""

    end
  end

end

reader = FileReader.new('sample.log', 'method=', 'status=', 'endpoints.txt')
parser = AccessParser.new(reader)
AccessConsoleWriter.new(parser).call


texts: Implementing ShowDialog() style functionality without disabling any other windows

texts:
I need a simple prompt window to ask the user to do something with an OK/Cancel return. But I also need all Windows to remain functional, so a xx.ShowDialog isn't appropriate.

This is my attempt. DialogWindow takes a Delegate in the constructor and calls it when OK or Cancel is clicked with a True/False parameter respectively. The Window is coded to take top Z priority.

It seems to work but I'm not very knowledgeable on await usage. Is there an easier way?

        bool result;
        ManualResetEvent manualReset = new ManualResetEvent(false);
        DialogWindow myDialog = new DialogWindow((dialogResult) =>
        {
            result = dialogResult;
            manualReset.Set();
        });
        myDialog.Show();
        await Task.Factory.StartNew(() =>
        {
            manualReset.WaitOne();
        });
        //Do something with result


texts: Create one class to perform all type orm functionalities

texts:
I'm trying to create a separate package in a monorepo to handle TypeORM functions. So if I have two APIs (User API, Admin API), both can refer to the same package to talk to the database. I have written a class which takes all the TypeORM entities, create a connection and export them. Please let me know whether I can further refactor this:

import { createConnection, Connection, Repository, getConnectionOptions } from 'typeorm';
import { User } from './entity/User';

class Store {
  private dbConnection: Connection | undefined;

  private userRepository: Repository<User> | undefined;

  /**
   * Create a new DB connection and set repositories
   */
  createDBConnection = async (): Promise<void> => {
    const connectionOptions = await getConnectionOptions();

    this.dbConnection = await createConnection({
      ...connectionOptions,
      entities: [User],
    });

    this.userRepository = await this.dbConnection.getRepository(User);
  };

  /**
   * Throw an error if the repository is not available
   */
  private connectionNotCreatedError = (): never => {
    throw new Error('Repository not available. Please check whether you created the connection first.');
  };

  /**
   * Get the user repository
   */
  getUserRepository = (): Repository<User> => {
    return this.userRepository || this.connectionNotCreatedError();
  };
}

export const store = new Store();


texts:
How can I shorten and optimize this code which displays then hides a DIV?

setTimeout(function () {
    $('.updateNotification').show().addClass('heightener');
    callback();
},2000)

function callback() {
  setTimeout(function() {
    $( '.updateNotification' ).fadeOut();
  }, 10000 );
};

My first thought was to combine the functions. However, I would like them to remain separate because at a later date I will additionally incorporate a button which will trigger callback() in addition to the timer.


texts: Hunchentoot first steps - good ways of pulling out parenscript from an easy-handler

texts:
In the following hunchentoot easy-handler definition:

(define-easy-handler (new-game :uri "/new-game") ()
  (standard-page (:title "Add a new game"
                 :script (ps
                           (defvar add-form nil)
                           (defun validate-game-name (evt)
                             (when (= (@ add-form name value) "")
                               (chain evt (prevent-default))
                               (alert "Please enter a name.")))
                           (defun init ()
                             (setf add-form (chain document
                                                   (get-element-by-id "addform")))
                             (chain add-form
                                    (add-event-listener "submit"
                                                validate-game-name false)))
                           (setf (chain window onload) init)))
    (:h1 "Add a new game to the chart")
    (:form :action "/game-added" :method "post" :id "addform"
      (:p "What is the name of the game?" (:br)
          (:input :type "text" :name "name" :class "txt"))
      (:p (:input :type "submit" :value "Add" :class "btn")))))

What is the most straightforward and architecturally sensible way to pull out the parenscript (lines 3-15)?

Is it really nothing more than creating a lisp function like so

(define-easy-handler (new-game :uri "/new-game") ()
  (standard-page (:title "Add a new game"
                 :script (separate-js))   ; <- just call the new fn below here
    (:h1 "Add a new game to the chart")
    (:form :action "/game-added" :method "post" :id "addform"
      (:p "What is the name of the game?" (:br)
          (:input :type "text" :name "name" :class "txt"))
      (:p (:input :type "submit" :value "Add" :class "btn")))))

;; Just pulled out the parenscript into a separate function, super simple:
(defun separate-js ()
  (ps
    (defvar add-form nil)
    (defun validate-game-name (evt)
     (when (= (@ add-form name value) "")
       (chain evt (prevent-default))
       (alert "Please enter a name.")))
    (defun init ()
     (setf add-form (chain document
                           (get-element-by-id "addform")))
     (chain add-form
            (add-event-listener "submit"
                        validate-game-name false)))
    (setf (chain window onload) init)))

It's interesting finding that in lisp we are getting by without models, views, or controllers; just using lisp functions & macros. However, these are important steps and concepts here so I wanted to proceed with caution, hence seeking comment & discussion.

The general context of the question here is how to structure a web application. These are my first baby steps doing this in lisp, in contrast to plenty of experience with a more run of the mill MVC. Hence, any illumination of differences in thinking required would be excellent.

The first code block is from the leanpub book "Lisp for the Web".
The second is my own super simple modification of that.

For information: In my opinion the book "Lisp for the Web" seems great so long as you get past the introduction and first few pages, which have terrible sentence structure and seem not to have been proof read before being published. The rest of the book is much better quality! I nearly binned it and am glad I didn't.


texts:
I currently have a sorting script that will check line by line for a certain string. If the string matches, then that line will be copied to that worksheet and the line will be deleted. However, sometimes I need to sort tens of thousands of rows and it can take a long time or will crash Excel. Is there a way to rewrite it to be able to sort more efficiently?

In my code, I have the With ws2 block copied multiple times with different sheet names

Dim ws1 As Worksheet, ws2 As Worksheet
Dim firstRowWs1 As Long
Dim lastRowWs1 As Long
Dim lastRowWs2 As Long
Dim searchColumnWs1 As Integer
Dim i As Integer
Dim check As Variant
Dim strSearch As Variant
Dim foundMatches As Boolean
Dim sDate As String
sDate = Format(Now(), "mm/dd/yyyy")
Set ws1 = Worksheets("Sort")
Set ws3 = Worksheets("Overview")

Set ws2 = Worksheets("sheet2")
With ws2
lastRowWs1 = ws1.UsedRange.Rows.Count
lastRowWs2 = ws2.UsedRange.Rows.Count
firstRowWs1 = 1
searchColumnWs1 = 10
strSearch = Array("john")

For i = firstRowWs1 To lastRowWs1
    For Each check In strSearch
        If check = ws1.Cells(i, searchColumnWs1).Value Then
            ws1.Rows(i).Copy (ws2.Rows(lastRowWs2 + 1))
            ws2.Rows(lastRowWs2 + 1).Columns("A:B").Insert xlToRight
            lastRowWs2 = lastRowWs2 + 1
            ws1.Rows(i).Delete shift:=xlUp
            i = i - 1
            Exit For
        End If
    Next check
Next i
End With


texts: Smallest job first algorithm implementation

texts:
I have implemented smallest job first algorithm using javascript. It was part of a coding challenge. I would like to ask for evaluation of my script. I would like to get suggestions to improve my code performance. Which parts of the code I can improve. Is there an alternative to for loops?

Function takes jobs array with transaction time and index. Returns the clock cycles of the process/job at specific index. Function Call with sample input, sjf([10, 3, 15, 8, 7], 3).

Here is the code.

function sjf(jobs, index) {

// declare waiting time array
var waitingTime = [];
// set waiting time for first task to zero
waitingTime[0] = 0;

// declare total time array
var totalTimeArray = [];

var processArray = [];
// add job value and index as an object to process array
for (i=0; i < jobs.length; i++) {
    processArray.push({
        id: i,
        value: jobs[i]
    })
}

// sort the array in ascending order
function sortArray(a, b) {
    return a.value - b.value;
}

// calculate waiting time for each process except first process
// waiting time for first process is zero so we start to calculate from index 1
function calculateWaitingTime(sortedArray, waitingTime) {
    for (i=1; i < sortedArray.length; i++) {
        waitingTime.push(sortedArray[i-1].value + waitingTime[i-1]);
    }
}

// total time taken to complete each task
function calculateTimeForEachTask(sortedArray, totalTimeArray) {
    for (i=0; i < sortedArray.length; i++) {
        totalTimeArray.push({
            id: sortedArray[i].id,
            time: sortedArray[i].value + waitingTime[i]
        });
    }
}

// find clock cycles
function findClockCycles(totalTimeArray, index) {
    for (i = 0; i < totalTimeArray.length; i++) {
        if (totalTimeArray[i].id === index) {
            return totalTimeArray[i].time;
        }
    }
}

// First of all sort the process array in ascending order of their value
var sortedArray = processArray.sort(sortArray);

// calculate waiting time for the rest of the processes
calculateWaitingTime(sortedArray, waitingTime);

// calculate total time for each task
calculateTimeForEachTask(sortedArray, totalTimeArray);

// return clock cycles for the task
return findClockCycles(totalTimeArray, index);
}


texts: A better way to read text files into html?

texts:
Currently I'm making a website that has a to-do list that will probably become quite long to write in html. So I decided to make a shorter version for me to write that I find more comfortable to read.

What I am currently doing is using ajax to read the text file from the server. Once the file has been stored into a string, it's sent to a function which formats it correctly for html. After that, it's returned into a variable that is now stored into a container div using jquery div.

This is my javascript code:

var todoListMake = function( reading ){
        var wanted =reading.split("\n");
        var newString = "";
        for( var i = 0; i < wanted.length; i ++ )
        {
            if( wanted[i] === "\n" )
                continue;
            /* Place text formatting code below */
            wanted[i] = wanted[i].replace("","");
            wanted[i] = wanted[i].replace("","");
            wanted[i] = wanted[i].replace("<c>","");
            wanted[i] = wanted[i].replace("</c>","");

            if( wanted[i].search("[X]") != -1 )
            {
                wanted[i] = "" + wanted[i].replace("[X]","") + "";
            }

            if( wanted[i].search("<ul") === -1 && wanted[i].search("</ul") === -1 )
                wanted[i] = "
" + wanted[i]; // Open the list if no ul tags

            if (i === (wanted.length-1) )
            {
                newString += wanted[i];
                break;
            }// Break early because the rest cannot be processed correctly

            if( wanted[i].search("</ul") != -1 )
                wanted[i] += "
"; // Close the list at the end of each ul

            if ( wanted[i + 1].search("</ul") != -1 )
                wanted[i] += "
";// Close the list of regular data

            //alert(wanted[i]);
            newString += wanted[i];
        }
        return newString;

};

window.onload = function(){
        $.get("textData/todoData.txt", function(data) {

 var compiledData = todoListMake( data );
            $("#todoList").append( compiledData );
        });
    };

And then read from the text file like this:

Release 1:
  Completed

Release 2:  Current Version

            Core Additions

                [X] Save Progress
                [X] <c>14</c> 9 New Levels

            Programmers Check List

                    [X] Add functionality to Level Restart
                    [X] Add checkpoint floater

            Bug Fixes

                    [X] Hanging on Slopes teleport you
                    [X] Hanging on Slopes froze the game
                    [X] Fixed Menu overlay problem


texts:
I'd like to check if the user submitted adress ip is a valid public IPv4 (non loopback, non local, non reserved).

For that purpose, I came up with that method, but I was wondering if this was enough or if I was missing some tests.

private boolean isValidPublicIp(String ip) {
    try
    {
        Inet4Address address = (Inet4Address) InetAddress.getByAddress(ip.getBytes());
        if (!address.isSiteLocalAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress() && !address.isLoopbackAddress() && !address.isMulticastAddress()) {
            return true;
        }
    }
    catch (UnknownHostException exception) {}

    return false;
}


texts:
I'm curious what people think about this little bit of logging code.  It seems to work ok.  Is there anything I'm missing?

public static class Logger
{
    private static readonly object Locker = new object();
    private static readonly StreamWriter Writer =
                        new StreamWriter("c:\\temp\\logtester.log", true) ;

    public static void Log(string message)
    {
        Action<string> action = MessageWriter;
        action.BeginInvoke(message, null, null);
    }

    private static void MessageWriter(string message)
    {
        lock(Locker)
        {
            Writer.WriteLine(message);
        }
    }
}

Using Jesse's code, but with QueueUserWorkItem instead of BeginInvoke.

public sealed class Logger : IDisposable
{
    private static readonly object Locker = new object();
    private static readonly StreamWriter Writer = new StreamWriter("c:\\temp\\logtester.log", true);
    private static bool _disposed;

    public static void Log(string message)
    {
        ThreadPool.QueueUserWorkItem(MessageWriter, message);
    }

    private static void MessageWriter(object message)
    {
        if (!(message is string)) return;
        lock (Locker)
        {
            Writer.WriteLine(message);
        }
    }

    ~Logger()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        lock (Locker)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                if (Writer != null)
                    Writer.Dispose();
            }

            _disposed = true;
        }
    }
}


texts:
I'm new to Clojure, and would appreciate feedback on this short program. The problem I set out to solve was selected at random from Project Euler, and is described in the comments. The part that I'm least happy about is the repeated series for the product, which I think could be replaced with a reduce call somehow.

; An irrational decimal fraction is created by concatenating the positive integers:
; 0.123456789101112131415161718192021...
;              ^
; It can be seen that the 12th digit of the fractional part is 1.
; If dn represents the nth digit of the fractional part,
; find the value of the following expression:
;    d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

(def d (apply str (map str (range 1 1000001)))) ; generate Champernowne's contant
(defn get-digit [x k] (read-string (.substring x k (+ k 1)))) ; get digit at position
(* (get-digit d 0)
   (get-digit d 9)
   (get-digit d 99)
   (get-digit d 999)
   (get-digit d 9999)
   (get-digit d 99999)
   (get-digit d 999999)
) ; product from problem statement


texts: Functional, recursive algorithm for flattening a tree

texts:
My goals for the algorithm were to use recursion, to avoid mutation, and to decouple the tree walking from the action that we take on each node. My sense is that the result uses mode code is reasonably readable but that it might be unconventional.

Test

Test Data

const nestedPaths: TreeNode = {
  path: '/',
  children:
    [
      {
        path: '/one',
        children: [
          {
            path: '/two',
            children: [
              {
                path: '/three',
              }
            ]
          }
        ]
      },
      {
        path: '/four',
        children: [
          {
            path: '/five',
          },
          {
            path: '/six'
          }
        ],
      }
    ]
};

Test Output

The ... represents the unchanged path and children properties of the original node.

const expected = [
  { fullPath: '/four/six', ... },
  { fullPath: '/four/five', ... },
  { fullPath: '/four', ... },
  { fullPath: '/one/two/three', ... },
  { fullPath: '/one/two', ... },
  { fullPath: '/one', ... },
];

Algorithm

Types

type TreeNode = {
  path: string;
  children?: TreeNode[];
};

type FlatTreeNode = TreeNode & {
  fullPath: string;
};

type FlattenTreeNodeState = {
  previousNode: FlatTreeNode;
  flattenedTree: FlatTreeNode[];
};

Walk Tree Depth First

const walkTreeDepthFirst = <TState>(
  node: TreeNode,
  action: (parent: TreeNode, nextChild: TreeNode, state?: TState) => TState,
  state?: TState): TState | undefined => {

  // Use $state to avoid naming collisions while maintaining a functional approach.
  const traverseChildren = ($state?: TState, next = 0): TState | undefined => {

    // base cases:
    // there is no node
    // the node has no children
    // the node has children, but no next child
    if (!node || !node.children || !node.children[next]) {
      return $state;
    }

    const nextChild = node.children[next];

    $state = action(node, nextChild, $state);

    const $updatedState = walkTreeDepthFirst(nextChild, action, $state);
    return traverseChildren($updatedState, next + 1);
  };

  return traverseChildren(state);
};

Flatten Tree Node

const flattenTreeNode = (
    parentNode: TreeNode,
    currentNode: TreeNode,
    state?: FlattenTreeNodeState) : FlattenTreeNodeState => {

  const defaultState = {
    previousNode: {
      path: '/',
      fullPath: '/',
    },
    flattenedTree: []
  };

  const { previousNode, flattenedTree } = state || defaultState;

  const fullPathToParentNode = parentNode.path === previousNode.path
    ? previousNode.fullPath
    : parentNode.path;

  const fullPathToCurrentNode = fullPathToParentNode === '/'
    ? currentNode.path
    : fullPathToParentNode + currentNode.path;

  const currentNodeWithFullPath = {
    ...currentNode,
    fullPath: fullPathToCurrentNode,
  };

  return {
    previousNode: currentNodeWithFullPath,
    flattenedTree: [...flattenedTree, currentNodeWithFullPath],
  }
}

Flatten Tree

const flattenTree = (node: TreeNode) => walkTreeDepthFirst(node, flattenTreeNode);


texts:
Autodidact and inspired by David Beazley code (to improve my skills in Python) i would like to get your feed back on this Parser code.
NB: The lazy property let the code be computed only one time if used (https://github.com/dabeaz/python-cookbook/blob/master/src/8/lazily_computed_attributes/example1.py)

class lazyproperty:
    def __init__(self, func):
        self.func = func
    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            value = self.func(instance)
            setattr(instance, self.func.__name__, value)
            return value

class PDFParser():
    """

    """
    def __init__(self,filepath,page_num=0):
        self.filepath = filepath
        try:
            self._doc = fitz.open(filepath)
            self.page_num = page_num
            self._page = self._doc[page_num]
        except Exception as e:
            print("Lecture PDF impossible. {}".format(e))

    @lazyproperty
    def text(self):
        return self._page.getText()

    @lazyproperty
    def _pixs(self):
        imgs = self._doc.getPageImageList(self.page_num)
        pixs =[]
        for img in imgs:
            xref = img[0]
            pix = fitz.Pixmap(self._doc, xref)
            pixs.append(pix)
        return pixs

    @lazyproperty
    def _pixpage(self):
        pix = self._page.getPixmap(colorspace=fitz.csGRAY)
        return pix

    @property
    def img(self):
        return self.imgs[0]

    @lazyproperty
    def imgs(self):
        pixs = self._pixs
        imgsarray = []
        for pix in pixs:
            img = self.pix2np(pix)
            imgsarray.append(img)
        return imgsarray

    def write(self,outputdir,fullpage=False):
        filename = os.path.basename(self.filepath).split('.pdf')[0]
        def writePNG(pix,filepath):
            # This is GRAY or RGB
            try:
                pix.writePNG(filepath)
            # CMYK: convert to RGB first
            except:
                pix = fitz.Pixmap(fitz.csRGB, pix)
                pix.writePNG(filepath)
                pix = None
        if fullpage:
            filepath = os.path.join(outputdir,'{}_p{}.png'.format(filename,self.page_num))
            pix = self._pixpage
            writePNG(pix,filepath)
            return
        pixs = self._pixs
        for i,pix in enumerate(pixs):
            filepath = os.path.join(outputdir,'{}_p{}_i{}.png'.format(filename,self.page_num,i))
            writePNG(pix,filepath)
        return

    @staticmethod
    def pix2np(pix):
        """
        Convert pixmap to image np.ndarray
        https://stackoverflow.com/questions/53059007/python-opencv
        param pix: pixmap
        """
        import numpy as np
        #https://stackoverflow.com/questions/22236749/numpy-what-is-the-difference-between-frombuffer-and-fromstring
        im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
        try:
            im = np.ascontiguousarray(im[..., [2, 1, 0]])  # rgb to bgr
        except IndexError:
            #Trick to convert Gray rto BGR, (im.reshape)
            logger.warning("Shape of image array is {}".format(im.shape))
            im = cv2.cvtColor(im,cv2.COLOR_GRAY2RGB)
            im = np.ascontiguousarray(im[..., [2, 1, 0]])
        return im


texts:
I've got a rather long function that will take the size of a triangle print it with stars and give the user the option of whether or not they want stars printed inside the triangle, and the orientation (point up or down).  I was hoping for some general refactoring methodologies I could apply.

Every permutation is possible for inverted/filled, inverted/not filled, etc.  What are some good general methods I can apply here to get some more code reuse?

void Triangle::Print(string direction, string fill)
{
    string starWithSpace = "* ";

    for (int i = leg1 - 1, j = 1; i >= 0; i--, j++, j < i)
    {
        if (direction == "vertical")
        {
            cout << string(i, ' ');

            if (fill == "yes")
            {
                int repeat = 0;
                while (repeat < j)
                {
                    cout<< starWithSpace;
                    repeat++;
                }
            }
            else if (fill == "no")
            {
                if (j * 2 - 3 < 0)
                {
                    cout << "*";
                }

                if ( j > 1 && i >= 1)
                {
                    cout << "*";
                    cout << string(((j * 2 - 3) < 0) ? 1 : j * 2 - 3, ' ');
                    cout << "*";

                }
                if (i == 0)
                {
                    int repeat = 0;
                    while (repeat < leg1)
                    {
                        cout << starWithSpace;
                        repeat++;
                    }
                }

            }
            cout << "\n";
        }
        else if (direction == "inverted")
        {
            //print bottom line
            if (j == 1)
            {
                int repeat = 0;
                while (repeat < leg1)
                {
                    cout << starWithSpace;
                    repeat++;
                }
            }
            cout << string(j - 1, ' ');
            if (j != 1 && fill == "yes")
            {
                int repeat = 0;
                while (j >1 && repeat < i +1)
                {
                    cout << starWithSpace;
                    repeat++;
                }
            }
            else if (fill == "no" && j!= 1)
            {
                int skipFactor = i * 2 - 1;
                cout << "*";
                cout << string(skipFactor > 0 ? skipFactor: 1, ' ');
                if (i != 0)
                {
                    cout << "*";
                }
            }
            cout << "\n";
        }
    }
    cout << "\n";
}


texts:
After getting comments on my previous implementation, I have tried to implement with DP. But without using matrix. I am not doing any boundary checks on the string just wanted to see if I am missing anything in this implementation.

Approach
I am using Set to store existing palindromes. First I add all letters which are palindrome by itself and then i add palindromes of size 2. Then I start with size 3. I check if the substring of current size is already been tested as palindrome or not, if it is, then i check the beginning and end character of the current string if they matches, i add them to the set and move on

My main aim was to get \$O(n^2)\$ by thinking and coding myself rather than looking at existing solutions. Normally, a 2D matrix is used when programming a DP but I used a set because to me it looked more intuitive and less complex.

public static String lpsMap(String str) {
    int maxSize = 0;
    String longestP = null;
    Set<String> map = new HashSet<>();

    for (char ch : str.toCharArray()) {
        map.add(String.valueOf(ch));
    }

    for (int i = 0; i < str.length() - 1; i++) {
        if (str.charAt(i) == str.charAt(i + 1)) {
            map.add(str.substring(i, i + 2));
        }
    }

    for (int len = 3; len <= str.length(); len++) {
        for (int index = 0; index < str.length() - len + 1; index++) {
            int endIndex = index + len;
            String existingP = str.substring(index + 1, endIndex - 1);
            if (map.contains(existingP)) {
                if (str.charAt(index) == str.charAt(endIndex - 1)) {
                    String currentP = str.substring(index, endIndex);
                    map.add(currentP);
                    if (currentP.length() > maxSize) {
                        maxSize = currentP.length();
                        longestP = currentP;
                    }
                }
            }
        }
    }

    return longestP;
}


texts:
I have written my very first Haskell module and I feel that the code can be improved based on the simplicity of the problem I am solving. Do you have any suggestions?

Problem statement:

You are given a String code containing a message composed entirely of decimal digits ('0'-'9'). Each digit consists of some number of dashes (see diagram below). A "check function" of a message is defined as the total number of dashes in the message. Return the value of the check function for the message represented in code.

Definition

Class:  CheckFunction
Method: newFunction
Parameters: String
Returns:    int
Method signature:   int newFunction(String code)
(be sure your method is public)

Notes
-   0 consists of 6 dashes, 1 consists of 2 dashes, 2 consists of 5 dashes, 3 consists of 5 dashes, 4 consists of 4 dashes, 5 consists of 5 dashes, 6 consists of 6 dashes, 7 consists of 3 dashes, 8 consists of 7 dashes, 9 consists of 6 dashes.

Constraints
-   code will contain between 1 and 50 characters, inclusive.
-   Each character in code will be a digit ('0'-'9').

Solution:

module Main where

import System.IO()
import Data.Char

-- Problem statement: https://community.topcoder.com/stat?c=problem_statement&pm=4788
-- Method signature: int newFunction(String code)

newFunction :: String -> Int
newFunction input =
    let arr = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
        x = [arr !! digitToInt (input !! x) | x <- [0..length input - 1]]
        in sum x

assert :: String -> Int -> String
assert s i = if newFunction s == i
then "test passed" else "test failed"

main :: IO()
main = do
  putStrLn $ show $ assert "13579" 21
  putStrLn $ show $ assert "868177" 28
  putStrLn $ show $ assert "8571" 17
  putStrLn $ show $ assert "3" 5
  putStrLn $ show $ assert "73254370932875002027963295052175" 157


texts:
I am writing a search indexer for a site I built. It counts the number of times a word is used in a given story allowing one use of the word per chapter. I have also attempt to weight words in the titles and the descriptions more heavily by including them in every chapter that is indexed.

I would like to know if I am handling transactions properly for this, and preventing dead-locks while the update is performed on the database. I would also like to know if I can clarify the sql statements any or if there is a better way of concatenating the columns.

#!/usr/bin/python
# Generates the search index for the writersite
import mysql.connector
import re
from sets import Set
from collections import Counter

MIN_WORD_LENGTH = 3

SQL_GET_REINDEXABLE = """
SELECT id,title
FROM Stories
WHERE Stories.needsReindex = TRUE
"""

SQL_GET_CHAPTER_BY_STORY_ID = """
SELECT id FROM Chapters WHERE StoryId = %s;
"""

SQL_GET_CHAPTER_SAMPLE_BY_ID = """
SELECT
  Chapters.id,
  CONCAT(Stories.title, ' ', IFNULL(Chapters.title, ' '), ' ',
    IFNULL(Stories.description, ' '), ' ', text) as text
FROM Chapters, Stories
WHERE Chapters.StoryId = Stories.id AND Chapters.id = %s;
"""

SQL_FREQ_UPSERT = """
REPLACE INTO FreqIdx(word, StoryId, weight) VALUES
    (%s, %s, %s)
"""

SQL_DELETE_OLD_INDEX = """
DELETE FROM FreqIdx WHERE StoryId = %s;
"""

SQL_UPDATE_STORY_INDEX_STATUS = """
UPDATE Stories SET needsReindex = FALSE WHERE id = %s
"""

def deleteStoryIndexByStoryId(db, StoryId):
    # delete the old index
    print("Deleting Index of Story {}".format(StoryId))
    cursor = db.cursor()
    cursor.execute(SQL_DELETE_OLD_INDEX, (StoryId,))
    cursor.close()
    db.commit()

def indexText(wordDict, text):
    text = re.sub(r"[^A-Za-z' ]", ' ', text).lower()
    words = Set()
    for word in text.split():
        words.add(word)
    for word in words:
        wordDict[word] = wordDict[word] + 1
    return wordDict

def processChapterById(db, chapterId, wordDict):
    cur = db.cursor()
    cur.execute(SQL_GET_CHAPTER_SAMPLE_BY_ID, (chapterId,))
    for (chid, text) in cur:
        wordDict = indexText(wordDict, text)
        print("Chapter: {}, length {}, wordDict {}".format(
            chid, len(text.split()), len(wordDict)))
    cur.close()
    return wordDict

def markStoryAsIndexedById(db, StoryId):
    cur = db.cursor()
    cur.execute(SQL_UPDATE_STORY_INDEX_STATUS, (StoryId,))
    cur.close()
    db.commit()

def processStoryById(db, StoryId):
    deleteStoryIndexByStoryId(db, StoryId)
    # word dict to store the new index temporary
    wordDict = Counter()
    # get the chapters
    cur = db.cursor(buffered=True)
    cur.execute(SQL_GET_CHAPTER_BY_STORY_ID, (StoryId,))
    for (ChapterId,) in cur:
        wordDict = processChapterById(db, ChapterId, wordDict)
    cur.close()
    # replace the index
    for word in wordDict:
        cur = db.cursor()
        cur.execute(SQL_FREQ_UPSERT, (word, StoryId, wordDict[word],))
        cur.close()
    db.commit()
    markStoryAsIndexedById(db, StoryId)

def main():
    # Open Db connection
    db = mysql.connector.connect(
            host="localhost",
            user="writersite",
            passwd="password",
            db="writersite")
    cur = db.cursor(buffered=True)
    cur.execute(SQL_GET_REINDEXABLE)

    for (StoryId, Title) in cur:
        print("processing Story {} - {}".format(StoryId, Title))
        processStoryById(db, StoryId)

    db.close()

# main sentinel
if __name__ == "__main__":
    main()

The table containing the index looks like the following:

CREATE TABLE FreqIdx (
    word VARCHAR(255) NOT NULL,
    weight INT(11) DEFAULT '0',
    StoryId INT(11),
    CONSTRAINT FreqIdx_ibfk_1 FOREIGN KEY (StoryId) REFERENCES Stories (id)
);
CREATE UNIQUE INDEX freq_idx_word__story_id ON FreqIdx (word, StoryId);
CREATE INDEX StoryId ON FreqIdx (StoryId);

The relevant relations are shown below:


texts:
I'm drawing a pixel by pixel image with the following code:

coord = np.where(np.all(imagen == (0, 0, 0), axis=-1))
cv2.imshow('imagen', imagen)

a = coord[0]
b = coord[1]

for x,y in zip(a,b):
    rectObs.append(pygame.Rect((y,x),(1,1)))

for rect in rectObs:
    pygame.draw.rect(screen, black, rect,20)

This code detects all the black pixels of an image and draws them in another window with the same coordinate. The problem is that there are so many black pixels that the processing is very very slow.

Any idea to improve performance or to graph in a more optimal (other than pixel by pixel)?


texts: Taking advantage of the falsey and ineffective "" empty string

texts:
The following code snippets are academic. I was required to make a PHP generated HTML interface for a MySQL database of a movie rental store, and the requirement was filtering the displayed movies by category.

The approach for having the filter persist across all form actions (without using a session) was to have the hidden form input inserted into all the other forms on the page.  And my first approach to this was testing if $_POST['category'] is set, and if so echoing the HTML tag for the hidden input to carry the category variable to the next page.

This was still the method, but, I tinkered with it and decided that instead of testing if a category was selected at every form I could test once, and if not leave the string variable for the HTML tag empty and echo it regardless.

This worked nicely but I'm curious if if in a larger/co-operative project if the possible confusion for the outputting of a variable that is sometimes empty (i.e. ineffectual) and sometimes not will be more confusing than the lines of code and processing time saved.

<?php
$categorySelected = '';
$hiddenCategory = '';

////....................
//conect to databes
//create mysqli object

if( isset($_POST['category']) &&  $_POST['category'] != $Allcats ){
  //<check that catagory still has entries>

  //if there are entries for category filter, set local variable, and html tag for form input
  //hidden input tag is inserted to all forms to carry category selection to next page reload
  if(<videos of that category exist>){
    $categorySelected = $_POST['category'];
    $hiddenCategory = "<input type='hidden' name='category' value='$categorySelected'>";
  } //else //<display message that there are no videos of that category>

}

//database manipulations completed
//html header

//in all forms in html $hiddenCategory is echod
//to add category k/v pair to post
//or '' is echoed with no consequence if category not set
?>
<form id='addvideo' action = <?php echo $SELF; ?> method ='post'>
    <?php echo $hiddenCategory; ?>
    <input type='hidden' name='ACTION' value='addvideo'>
    <input type="submit" value="ADD VIDEO">
    Name:<input type="text" name="name">
    <!--  more fields.... -->
</form>

<?php
//prepare statement for all entries of category filtered
if(!$categorySelected){
  $vidStmt = $mysqli->prepare("SELECT * FROM records");
}else{
  $vidStmt = $mysqli->prepare("SELECT * FROM records WHERE category=?");
  $vidStmt->bind_param("s",$categorySelected);
}

//iterate over all videos in database query, creating <tr> for each
while($vidStmt->fetch()){
echo "<tr>
<td> $name <td> $category <td> $length <td>
<form class='rent' action = $SELF method ='post'>
  $hiddenCategory
  <input type='hidden' name='ACTION' value='rent'>
  .... more fields ..
</form>
";
}
$vidStmt->close();
?>


texts: Find the sum of the digits in factorial of 100 in Erlang

texts:
This is a problem in poject Euler:

  n! means n × (n − 1) × ... × 3 × 2 × 1

  For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of
  the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

  Find the sum of the digits in the number 100!

I decided to solve it using erlang.
This is what I've come up with.

-module(fact).
-compile(export_all).

fact(1) -> 1;
fact(N) -> N*fact(N-1).

tolist(N) when N < 10 -> [N];
tolist(N) when N >= 10 -> tolist(N div 10)++[N rem 10].

sum(List) -> sum(List, 0).
sum([H|T], C) -> sum(T, C + H);
sum([], C) -> C.

factfinds the factorial of the number. toList converts it to a list of integers and sum gets the sum of the integers in the list. I run this program like this:

fact:sum(fact:tolist(fact:fact(100))).

Do I have to use 3 functions? Is there a problem with me doing so?

Should I make another function that calls all 3 functions?


texts: Calculating Chinese zodiac signs based on birthdays

texts:
I am attempting to write a function to calculate a user's Chinese zodiac sign based on his or her birthday for Drupal.

I originally had a function for calculating based on the Gregorian calendar (1924 = Rat, 1925 = Ox).  This was easy to write, but several of my users have complained that the Chinese zodiac is actually based on the lunar calendar, and a list of relevant start and end dates can be found here.

I started writing the code as follows.  The big problem is that I have an if, else if, and else per year, and at this rate I will have to manually code 100 years worth of birthdays.  On the other hand, I'm unsure of how to use a loop to iterate over this, because the day the lunar year starts and ends each year is different.  Any insight on how to make this more efficient would be highly appreciated.

function mymodule_calculate_chinese_zodiac($birthdate) {
  // Drupal MySQL data looks like this: 1981-07-30 00:00:00
  $year = substr($birthdate, 0, 4);
  $month = substr($birthdate, 5, 2);
  $day = substr($birthdate, 8, 2);

  if ($year == 1924) {
    if ($month > 2) {
      // Rat
      $sign = "1";
    }
    else if (($month == 2) && ($day > 4) {
      $sign = "1";
    }
    else {
      // Pig
      $sign = "12";
    }
  }
  else if ($year == 1925) {
    if ($month > 1) {
      // Ox
      $sign = "2";
    }
    else if (($month == 1) && ($day > 23)) {
      $sign = "2";
    }
    else {
      $sign = "1";
    }
  }
  else if ($year == 1926) {
    if ($month > 2) {
      // Tiger
      $sign = "3";
    }
    else if ($month == 2) && ($day > 12) {
      $sign = "3";
    }
    else {
      $sign = "2";
    }
  }
  //All years until 2020
  return $sign;
}


texts: C-Style unsigned char parsing and manipulation

texts:
Note that I'm using a C++ compiler ( hence, the cast on the calloc function calls) to do this, but the code is essentially C.

Basically, I have a typedef to an unsigned char known as viByte, which I'm using to create a string buffer to parse a file from binary (a TGA file, to be exact - but, that's irrelevant).

I'm writing basic functions for it right now; append, prepend, new, etc.

The problem is that, on the first iteration of the first loop in viByteBuf_Prepend, I get a segmentation fault. I need to know why, exactly, as this is something which could keep me up all night without some pointers (pun intended).

I also would like to know if my algorithms are correct in terms of how the buffer is pre-pending the viByte string. For example, I have a feeling that using memset too much might be a bad idea, and whether or not my printf format for the unsigned char is correct (I have a feeling it isn't, as nothing is getting output to my console).

Compiling on GCC, Linux.

#ifdef VI_BYTEBUF_DEBUG
void viByteBuf_TestPrepend( void )
{
    viByteBuf* buf = viByteBuf_New( 4 );

    buf->str = ( viByte* ) 0x1;

    printf(" Before viByteBuf_Prepend => %uc ", buf->str);

    viByteBuf_Prepend( buf, 3, ( viByte* ) 0x2 );

    printf(" After viByteBuf_Prepend => %uc ", buf->str);
}
#endif

viByteBuf* viByteBuf_New( unsigned int len )
{
    viByteBuf* buf = ( viByteBuf* ) calloc( sizeof( viByteBuf ), 1 );

    const int buflen = len + 1;

    buf->str = ( viByte* ) calloc( sizeof( viByte ), buflen );
    buf->len = buflen;

    buf->str[ buflen ] = '\0';

    return buf;
}

void viByteBuf_Prepend( viByteBuf* buf, unsigned int len, viByte* str )
{
    unsigned int pos, i;
    const unsigned int totallen = buf->len + len;
    viByteBuf* tmp = viByteBuf_New( totallen );
    viByte* strpos = buf->str;

    memset( tmp->str, 0, tmp->len );

    int index;

    for( i = 0; i < buf->len; ++i )
    {

       index = ( buf->len - i ) - 1;

       *strpos = buf->str[ 0 ];
       ++strpos;
    }

    memset( buf->str, 0, buf->len );

    printf( "%uc\n", buf->str );

    i = totallen;

    for ( pos = 0; pos < len; ++pos )
    {
        tmp->str[ pos ] = str[ pos ];
        tmp->str[ i ]   = buf->str[ i ];

        --i;
    }

    memset( buf->str, 0, buf->len );

    buf->len = tmp->len;

    memcpy( buf->str, tmp->str, tmp->len );

    viByteBuf_Free( tmp );

    //memset(  )
    //realloc( ( viByteBuf* ) buf, sizeof( viByteBuf ) * tmp->len );
}