texts:
I have a review request about this part of the code:

let private startReading (client:TcpClient) (bus:IBus) =
    //TODO check if that can be changed to rec parameter
    let frameNumber = ref 0
    let rec StartReading (client:TcpClient) =
        async{
            match client with
            | null -> async { return 0 } |> Async.StartAsTask |> ignore
            | _ ->
                match (client.IsConnectionEstablished()) with
                | true ->
                    incr frameNumber
                    DeployService.DeployCabninetService
                    let! messange = MessagingHandler.ReadMessage client

                    match(messange) with
                        | Some data ->
                            let frameNumber = uint32 frameNumber.Value
                            logger.Info(sprintf "Received message with Frame Number: %i" frameNumber)

                        | None ->
                            _logger.Info(sprintf "Client disconnected : %O" client.Client.RemoteEndPoint)
                            return! DisconnectClient client None

                    return! StartReading client
                | false ->
                    _logger.Info(sprintf "Client disconnected : %O" client.Client.RemoteEndPoint)
                    return! DisconnectClient client None
        }

    StartReading client |> Async.StartAsTask

It is simple reading message procedure from tcp client in f#, but I feel this can be written more gracefully, especially todo part with frame number incrementation using ref in f# feels wrong.

Any suggestions?


texts: Given a polygon with weighted vertices, calculate a value for an interior point

texts:
I want to be able to find out the value of a point inside a polygon if I have assigned weights to its vertices.

In the figure below, some weights have been applied to the green dots.  For some red interior point, I need to calculate

I have use the inverse of the distance from the point to a vertex as my correction factor.

This is my code so far to get the weighted value at one red point:

def add_weights(poly, weights):
    poly.weights = [float(w) for w in weights]+[weights[0]] #need to add the first weight
                                                          # at the end to account for
                                                          # the first point being added to close the loop

def distance(a,b):
    dist = ( (b.x - a.x)**2 + (b.y - a.y)**2 )**0.5
    if dist == 0: dist = 0.000000001
    return dist

def get_weighted_sum(poly, point):
    return sum([poly.weights[n]/distance(point,p) for n,p in enumerate(poly.points_shapely) if poly.weights[n] != 'nan'])

def get_weighted_dist(poly, point):
    return sum([1/distance(point,p) for n,p in enumerate(poly.points_shapely) if poly.weights[n] != 'nan'])

def get_point_weighted_value(poly, point):
    return get_weighted_sum(poly,point)/get_weighted_dist(poly,point)

Note that my polygon can be irregular. Also, not all the vertices might have a weight, in which case the vertex is skipped for the calculation: in the example above it would mean that the value of the weight would only be calculated using two vertices rather than three.

And this is a test code sample:

import shapely.geometry as shapely

class MyPoly(shapely.Polygon):
    def __init__(self,points):
        closed_path = list(points)+[points[0]]
        super(MyPoly,self).__init__(closed_path)
        self.points = closed_path
        self.points_shapely = [shapely.Point(p[0],p[1]) for p in closed_path]

def convert_to_shapely_poly(poly):
    poly_shapely = MyPoly(poly)
    return poly_shapely

#inputs
poly = [[0,0],[5,10],[10,0]]

#conversion to shapely format
mypoly = convert_to_shapely_poly(poly)

#adding weights to the vertices of the polygone
add_weights(mypoly,[2,11,5])

#calculate the weighted value of a point inside the polygon:
get_point_weighted_value(mypoly,shapely.Point(7,2))

Any suggestion on improving this code would be welcome!


texts:
Peter wants to generate some prime numbers for his cryptosystem. Help
him! Your task is to generate all prime numbers between two given
numbers!
Input
The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5

Output:
2
3
5
7

3
5

My code
x = raw_input()

for i in range(int(x)):
    a = map(int, raw_input().split())
    if a[0] == 1:
        a[0] = 2
    for num in range(a[0],a[1]+1):
        if num == 2:
            print num
        for j in range( 2, num):
            if num%j == 0:
                break
            elif j == num - 1:
                print num
    print " "
    i = i + 1


texts: Construct binary tree from inorder and preorder traversal

texts:
console.clear();

function cons(inorder, preorder) {
  if (isEmpty(inorder) || isEmpty(preorder)) return null

  if (size(inorder) === 1 && size(preorder) === 1)
    return {val: inorder[0], l: null, r: null};

  var leftSize = inorder.indexOf(head(preorder));

  return {
    val: preorder[0],
    l: cons(take(inorder, leftSize), take(tail(preorder), leftSize)),
    r: cons(drop(inorder, leftSize + 1), drop(tail(preorder), leftSize))
  };
}

function head(xs) {
  return xs[0];
}

function size(xs) {
  return xs.length;
}

function isEmpty(xs) {
  return xs.length === 0;
}

function take(xs, i) {
  return xs.slice(0, i);
}

function drop(xs, i) {
  return xs.slice(i);
}

function tail(xs) {
  return xs.slice(1);
}

var inorder  = [1, 2, 3, 4, 5, 6];
var preorder = [4, 2, 1, 3, 5, 6];

var tree = cons(inorder, preorder);
console.log(tree.r.val === 5);
console.log(tree.l.val === 2);
console.log(tree.r.r.val === 6);
console.log(tree.l.l.val === 1);
console.log(tree.l.r.val === 3);


texts: Caliburn Micro communication between list and edit viewmodels

texts:
I'm new at Caliburn Micro and the MVVM pattern.

I have 3 views (with its corresponding viewmodels):

AppView
ClientsView
EditClientView

AppView is my main page with a TabControl inside. The child views (WPF UserControls) are loaded in new tabs.

In ClientsView I have a grid with filtered clients. I select one, and when the Modify button is clicked I need to load a new tab with the editClientView and load its data. Here is my code:

public class EventAggregationProvider
{
    static EventAggregator _eventAggregator = null;
    public static EventAggregator EventAggregator
    {
        get
        {
            if (_eventAggregator == null)
                _eventAggregator = new EventAggregator();

            return _eventAggregator;
        }
    }
}

Function on ClientsViewModel:

public void ModificarCliente()
    {
        AppViewModel myParent = (AppViewModel)this.Parent;
        myParent.OpenTab(typeof(modClienteViewModel));
        EventAggregationProvider.EventAggregator.Publish(_selectedclient);
    }

MainViewModel OpenTab function:

public void OpenTab(Type TipoVista)
{
    bool bFound = false;
    if (TipoVista != null)
    {
        Screen myScreen = (Screen)Activator.CreateInstance(TipoVista as Type);
        myScreen.DisplayName = myScreen.ToString();
        foreach (Screen miItem in Items)
        {
            if (miItem.ToString() == myScreen.ToString())
            {
                bFound = true;
                ActivateItem(miItem);
            }
        }
        if (!bFound) ActivateItem(myScreen);
    }
}

EditClientViewModel:

class modClienteViewModel : Screen, IHandle<vw_ClientesFull>
{
    private OhmioService.OhmioServiceClient serviceClient =
        new OhmioService.OhmioServiceClient();

    public Clientes Cliente { get; set; }

    public modClienteViewModel()
    {
        EventAggregationProvider.EventAggregator.Subscribe(this);
        Cliente = new Clientes();
    }

    public void Handle(vw_ClientesFull myClient)
    {
        Cliente = serviceClient.Cliente_GetById(myClient.ID_Cliente);
        NotifyOfPropertyChange("Cliente");
    }
}

So what's your opinion on this? Especially about how I open the edit view (ClientsView becomes aware of the existence of MainWindowViewmodel and EditClientViewModel) from clients' viewmodel, and how I use eventaggregator to exchange the selected client between clientsViewModel and EditClientViewModel.


texts: Python - A Regex Text File Searcher by Content Project

texts:
I would like some advice on efficiency and ways to further remove redundant code.
Regex Text File Search:

enter a valid directory path, and a string to search for

makes a list containing all the matched paths, and a dictionary with the matches of the matched paths

get a list of all the text files and go through them

for each text file, search for a match, line by line

if a match is found, then the path is appended to the matched_paths list

update the matched_dict to include the lines and the start index and end index for each match in the matched path

format the output into an appropriate form and display the results of the find

from pathlib import Path
from pyinputplus import inputCustom, inputStr
import re

# 2)
def check_path(path):
    """
    returns the directory if the path is a directory, and it exists otherwise asks to input again
    """
    directory = Path(path)
    if directory.is_dir():
        return directory
    else:
        raise Exception('Path is not a valid directory')

def format_output(matched_paths, matched_dict):
    """
    - outputs the directories and matches for the string to be searched, only outputs the matched text files
    Formats the output into this template:

        file1.txt
        >>> --------------------------- <<<
              ------ Line 280 ------
             (start_index, end_index) # match 1
             (start_index, end_index) # match 2 if it exists

        <<< --------------------------- >>>

        file2.txt
        ...

    """
    for path in matched_paths:
            print()
            print(path.name)
            print('>>> --------------------------- <<<')
            for line, matches in matched_dict[path].items():
                print(f'      ------ Line {line} ------')
                for match in matched_dict[path][line]:
                    print('             ', match)
                print()
            print('<<< --------------------------- >>>')

def search_for_string(path, string):
    """
    1) opens the string

    2) makes a check on if a match exists in the file

    3) if it does, goes line by line

    4) appending all the matches (start_index, end_index) to the line number in the dict of path

    returns True if match was found, so it will be appended to the matched_paths list
        matched_paths = [path1, path2, path3]

        matched_dict = {path1: {line1: [(s1, e1), (s2, e2)] }, path2: ... }
    """
    global matched_dict
    with open(path, 'r') as text_file:
        if re.search(string, path.read_text()):
            matched_dict[path] = dict()
            for i, line in enumerate(text_file.readlines()): # i refers to line number
                matches = list(re.finditer(string, line))
                if matches:
                    matched_dict[path][i] = []

                    for m in matches:
                        matched_dict[path][i].append(m.span())
            return True
        return False

# 1)
path = inputCustom(check_path, prompt='Enter Path: ')
string = inputStr(prompt='Enter string: ')

# 2)
matched_paths = []
matched_dict = dict()

# 3)
for text_file in path.glob('*.txt'):

    # 4) and 6)
    if search_for_string(text_file, string):

        # 5)
        matched_paths.append(text_file)
# 7)
format_output(matched_paths, matched_dict)


texts: Read and convert binary files to ASCII text

texts:
This is my code which receives a file to read and converts binary values to ASCII text.

The code works fine, so I am looking for a review on what I have written, and suggestions on how I could do it better, perhaps without the use of a StringBuffer.

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author Tumpi
 */
public class DN6 {

public static void main(String[] args)
        throws Exception {

    File file = new File("sporocilo.txt");

    Scanner sc = new Scanner(file);
    String lastString = "";

    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        lastString = lastString + line;
    }
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < lastString.length(); i += 8) {
            result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));
        }
        System.out.println(result);
    }

}


texts: Amplitude and Frequencies of sound Analyser

texts:
As I'm beginner with mobile/OO programming, I reached a situation that confused me and made me wonder if I was coding correctly...

The main class:

    class ViewController: UIViewController, SoundAnalyserDelegate{

        lazy var fontSize : SoundAnalyser = {
            return SoundAnalyser(delegate: self)
        }()

        @IBOutlet var frequencyLabel: UILabel!
        @IBOutlet var amplitudeLabel: UILabel!
        @IBOutlet var note: UILabel!

        override func viewDidLoad() {
            super.viewDidLoad()
            soundAnalyser.start()

        }

        func setLabelAmp (_ text:String) {

            frequencyLabel.text = text

        }

        func setLabelFreq (_ text:String) {

            frequencyLabel.text = text

        }

        func setLabelNote (_ text:String) {

            frequencyLabel.text = text

        }

And the Second class:

    class SoundAnalyser {

        var delegate:SoundAnalyserDelegate?

        let minimum = Double(160)
        let maximum = Double(1400)

        var mic: AKMicrophone
        var tracker: AKFrequencyTracker
        fileprivate var silence: AKBooster
        fileprivate var timer: Timer?
        fileprivate var notesArray: [(String, Double)]?

        init(delegate: SoundAnalyserDelegate){
            mic = AKMicrophone()
            tracker = AKFrequencyTracker(mic, hopSize: minimum, peakCount: maximum)
            silence = AKBooster(tracker, gain:0)
            notesArray = self.getNotesFrequencies()
            self.delegate = delegate

        }

        func tick(){
            let amp = tracker.amplitude
            let freq = tracker.frequency

            if amp > 0.05 && freq > minimum && freq < maximum{
                let readNote = notesArray![analyseCapturedSound()]

                delegate?.setLabelAmp(String(format:"%f", amp)) //Setting the text of a label from the UI

                delegate?.setLabelFreq(String(format:"%f", freq))

    //            delegate?.setLabelNote(String(format:"%f", readNote))

                print("freq:", freq," amp:", amp," NOTE: \(readNote)")
            }
        }

I just included the most important code to express what I am trying to ask.

Summary:
Class ViewController initiates SoundAnalyser.
Under SoundAnalyser, there's a function that executes a function from ViewController ("delegate?.setLabel..."). I've made it with a delegate class using protocol, but I don't know why I feel that something is wrong.. I mean, executing a method of its creator... is it right? If not, what's the most 'good citizen' way to implement something with the same result?


texts: Regex to select the last components of a file path

texts:
I have a regex sequence that will take the end of a file path and select it for me:

  resources/services/dealerInfoRequest/V5-0/dealerInfoRequestManager.cfc

In this, the regex would select:

  /V5-0/dealerInfoRequestManager.cfc`

In some cases there is no V5-0 and it's just the file name and extension. My regex is working as shown but I was wanting to see if there was any optimization I could do, if it could be cleaned up, or if I should just leave it in the order it is now.

Regex is as shown:

((\/)(\w\d-?\d)(\/)\w.+)|(\/)(\w+\.\w+)

It's used in JavaScript and in Sublime Text 3.


texts: Making the same amount from different combinations of coins (top-down approach)

texts:
I was reading a typical interview question found here. Given an amount and a list of denominations, count the number of possible ways to break the amount into different combinations of coins. For example, if amount = 4 and denominations=[1, 2, 3], there are 4 possibilities. Here's my Python solution.

def _get_num_of_changes(amount, denominations, i=0):
    if amount == 0:
        return 1
    elif amount < 0:
        return None
    else:
        s = 0
        for i in range(i, len(denominations)):
            coin = denominations[i]
            if amount - coin < coin:
                c = _get_num_of_changes(amount - coin, denominations, i+1)
            else:
                c = _get_num_of_changes(amount - coin, denominations, i)

            if c:
                s += c
        return s

def get_num_of_changes(amount, denominations):
    return _get_num_of_changes(amount, denominations)

print(get_num_of_changes(4, [1, 2, 3]))

This is a top-down solution in the sense that I subtract from the starting amount and not try to add coins starting at zero to get to amount (which would be a bottom-up solution). Given this difference, I am really interested to see if my solution is good enough, too.


texts: Nth Fibonacci number (Bottom-up with dict)

texts:
This is an algorithm that I wrote to get the nth Fibonacci number using bottom-up dictionary. How can I make this better/more efficient?

memo={1:1,2:1}
f=0

def Fib(n):
    for i in range(3,n+1):
        memo[i]=memo[i-1]+memo[i-2]

    f=memo[n]
    print(f)
    return f

Fib(15)


texts:
What do you think about this?

#include <alloca.h>

#include <setjmp.h>

#include <cassert>

#include <functional>

template <::std::size_t N = 4096>
class coroutine
{
  jmp_buf env_in_;
  jmp_buf env_out_;

  bool running_{};

  char stack_[N];

public:
  coroutine() = default;

  auto running() const noexcept
  {
    return running_;
  }

  template <typename F, typename ...A>
  void run(F&& f, A&& ...a)
  {
    if (setjmp(env_in_))
    {
      return;
    }
    // else do nothing

    auto top(reinterpret_cast<char*>(&top));
    alloca(top - (stack_ + N));

    running_ = true;

    [this, f = ::std::forward<F>(f)](A&& ...a) __attribute__ ((noinline))
    {
      f(::std::ref(*this), ::std::forward<A>(a)...);

      running_ = false;

      yield();
    }(::std::forward<A>(a)...);
  }

  void yield() noexcept
  {
    if (setjmp(env_out_))
    {
      return;
    }
    else
    {
      longjmp(env_in_, 1);
    }
  }

  void resume()
  {
    assert(running_);
    if (setjmp(env_in_))
    {
      return;
    }
    else
    {
      longjmp(env_out_, 1);
    }
  }
};

Usage:

#include <iostream>

#include "coroutine.hpp"

int main()
{
  coroutine<> c;

  c.run([](decltype(c)& c)
    {
      for (int i{}; i != 3; ++i)
      {
        ::std::cout << i << ::std::endl;

        c.yield();
      }
    }
  );

  while (c.running())
  {
    c.resume();
  }

  return 0;
}

EDIT

Change

auto top(reinterpret_cast<char*>(&top));

to

char* top;
top = reinterpret_cast<char*>(&top);

Also check out an updated version of the code.


texts:
I just built a function to merge a set of List[A]s into a single scalaz.Tree[A].

Specifically, if I have the following three List[Int]s as input:

List[Int](1,3,5,10,20)
List[Int](1,3,5,700,701)
List[Int](1,800)

My output should be:

1
|
+- 3
|  |
|  `- 5
|     |
|     +- 700
|     |  |
|     |  `- 701
|     |
|     `- 10
|        |
|        `- 20
|
`- 800

I got the code working exactly as expected, but I was wondering if there is a way to improve it. Specifically, I'd like to make it more:

Functional (as a primary priority)
Performant (as a secondary priority)

Most importantly, I don't like the long chain of if statements.

However, general feedback would also be very appreciated, as I'm still getting warmed up to Scala.

This is the code for the merge:

object TreeBuilder {
  private def mergeAtJunction[A](coreLoc: TreeLoc[A], currentLoc: TreeLoc[A])(currentLevel: Int, maxLevels: Int): TreeLoc[A] = {
    if (currentLevel > maxLevels) {
      if (currentLoc.hasChildren) {
        coreLoc.insertDownFirst(currentLoc.firstChild.get.tree)
      } else {
        coreLoc
      }
    } else if (coreLoc.getLabel == currentLoc.getLabel) {
      if (coreLoc.hasChildren && currentLoc.hasChildren) {
        mergeAtJunction(coreLoc.firstChild.get, currentLoc.firstChild.get)(currentLevel + 1, maxLevels)
      } else if (!coreLoc.hasChildren && currentLoc.hasChildren) {
        coreLoc.insertDownFirst(currentLoc.firstChild.get.tree)
      } else {
        coreLoc
      }
    } else {
      if (coreLoc.rights.nonEmpty) {
        mergeAtJunction(coreLoc.right.get, currentLoc)(currentLevel + 1, maxLevels)
      } else {
        coreLoc.insertRight(currentLoc.tree)
      }
    }
  }

  def buildTreeFromLists[A](lists: List[A]*) = {
    val treeLists =
      lists
        .par
        .map(list => list.reverse.tail.foldLeft(list.reverse.head.node())((acc, next) => next.node(acc)) -> list.length)
        .toList
        .sortBy(_._2)
        .reverse
        .map(_._1)

    treeLists.tail.foldLeft(treeLists.head.loc.root)((coreTreeLoc, currentTree) => {
      mergeAtJunction(coreTreeLoc, currentTree.loc.root)(1, (treeLists.head.levels.length :: currentTree.levels.length :: Nil) max).root
    })
  }
}

Usage:

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> TreeBuilder.buildTreeFromLists(List(1,3,5,10,20), List(1,3,5,700,701), List(1,800)).toTree.drawTree
res0: String =
"1
|
+- 3
|  |
|  `- 5
|     |
|     +- 700
|     |  |
|     |  `- 701
|     |
|     `- 10
|        |
|        `- 20
|
`- 800
"


texts:
I have been attempting to implement a cache which caches the results of an asynchronous method, with the restriction that I only want that method to run once for any particular item in the cache. Many other implementations I have seen allow the method to run multiple times. Although only the first returned value is actually stored, if this is a long running method, this is not desirable for me.

Storing Task<T> (instead of T) in the cache, as recommended by most implementers, is a good idea, but I still could not work out how to prevent the method that fetches the value (the valueFactory) from running more than once for any given item. The solution I came up with was to use TaskCompletionSource instead of Task for the items in the cache.

This is what I came up with:

public class AsyncCache<TKey, TValue>
  {
    private readonly Func<TKey, Task<TValue>> valueFactory;

    private readonly ConcurrentDictionary<TKey, TaskCompletionSource<TValue>> completionSourceCache =
      new ConcurrentDictionary<TKey, TaskCompletionSource<TValue>>();

    public AsyncCache(Func<TKey, Task<TValue>> valueFactory)
    {
      this.valueFactory = valueFactory;
    }

    public async Task<TValue> GetItem(TKey key)
    {
      if (!completionSourceCache.TryAdd(key, new TaskCompletionSource<TValue>()))
      {
        return await completionSourceCache[key].Task;
      }

      TaskCompletionSource<TValue> taskSource = completionSourceCache[key];

      try
      {
        var result = await valueFactory(key);
        taskSource.SetResult(result);
      }
      catch (Exception e)
      {
        taskSource.SetException(e);
      }

      return await taskSource.Task;
    }
  }

The idea was that a key is associated with a TaskCompletionSource. The first time a particular item is requested, the TaskCompletionSource will be added to the dictionary for that key. Any subsequent (potentially reentrant) callers would be returned the Task associated with the TaskCompletionSource.

The first caller would then go on to actually call the method, and once the value was determined, this would be associated with the TaskCompletionSource, and anyone waiting on that Task would be able to view the result.

This is my first use of TaskCompletionSource, so please tell me if you think I've missed anything, or done anything wrong.

Note: I am aware of the ParallelExtensionsExtras AsyncCache here: https://blogs.msdn.microsoft.com/pfxteam/2010/04/23/parallelextensionsextras-tour-12-asynccache/

but I only found this after I'd written the above! This is the only other implementation I've found with the semantics described, but since it uses Lazy, it does not await the result of the value factory. I'm not sure if this makes any difference though, i.e. does this mean it is not truly asynchronous, are new threads created, etc.


texts:
I'm a 16 year old who has picked up coding recently using the codecademy course on Python. I completed the last of the lessons yesterday and decided to start on a simple Hangman game. As this is my first free-form project, it took me around 7h to finish it (a number i'm not proud of, i admit).

Here is the main body:

import string
import Hidden_word

try_again = 'y'

while try_again == 'y':
    word = Hidden_word.HiddenWord()
    hidden_word = word.hide_word()
    shown_word = word.show_word()
    chances_left = int(len(shown_word) / 2 + 1)
    misses = 0
    used_letters = []

    print("Here is the hidden word:", ' '.join(hidden_word))
    print("You have %d tries" % chances_left)

    while chances_left > 0:
        letter = input("Choose a letter: ").lower()
        while True:
            if not letter in string.ascii_lowercase or letter == '':
                letter = input("Please provide a valid answer: ").lower()
            elif letter in used_letters:
                letter = input("You've already used this letter, try another one: ").lower()
            else:
                used_letters.append(letter)
                break

        if letter in shown_word:
            print("Bingo!")
            for x in range(len(shown_word)):
                if shown_word[x] == letter:
                    hidden_word[x] = letter
            print(' '.join(hidden_word))
        else:
            chances_left -= 1
            if chances_left > 0:
                print ("Whoops, there is no '%s' in this word, try again! (%d chance(s) left)" % (letter, chances_left))
                print(' '.join(hidden_word))
                misses += 1

        if ''.join(hidden_word) == shown_word:
            if misses == 0:
                print("Congratulations! You did it without missing a single time!")
            else:
                print("Congratulations! You did it! But you've missed %d time(s)" % misses)
            break
        elif chances_left == 0:
            print("There's no '%s' in this word. You've got no tries left" % letter)
            print("The word was:", shown_word)

    try_again = input("Would you like to try again ? (y/n)").lower()

    while not try_again.lower() in ('y', 'n'):
        try_again = input("Please provide a valid answer: ")
print("Good bye!")

and here is the hidden_word class:

import linecache
import random

def number_lines ():
    with open("Words.txt", 'r') as file:
        for i, l in enumerate(file):
            pass
        return i + 1

class HiddenWord(object):
    hidden_word = []

    def __init__(self):
        self.shown_word = linecache.getline("Words.txt", random.randint(1, number_lines()))[:-1]

    def show_word (self):
        return self.shown_word

    def hide_word(self):
        self.hidden_word = []
        for x in self.shown_word:
            if x == ' ':
                self.hidden_word.append(' ')
            else:
                self.hidden_word.append('*')
        return self.hidden_word

I made sure to check all the possible cases, and it works perfectly without a hitch.


texts: Partition a singly linked list using Java

texts:
This is my attempted solution to exercise 2.4 in Cracking the Coding Interview.

The problem statement is:

  Write code to partition a linked list around a value x such that all nodes less than x come before all nodes greater than or equal to x.

  Example:

  Input: \$ 3 \rightarrow 5 \rightarrow 8 \rightarrow 5 \rightarrow 10 \rightarrow 2 \rightarrow 1 \$

  Output: \$ 3 \rightarrow 1 \rightarrow 2 \rightarrow 10 \rightarrow 5 \rightarrow 5 \rightarrow 8\$

I used the template code for a singly linked list from the book to write the Node class and I wrote the method partition and a JUnit test case for the method.  I would appreciate any feedback on the algorithm for partition and the code overall.

Node.java

package practice_cracking_code_interview;

public class Node {
    Node next = null;
    int data;

    public Node(int d){
        data = d;
    }

    void appendToTail(int d){
        Node end = new Node(d);
        Node n = this;
        while(n.next != null ){
            n = n.next;
        }
        n.next = end;
    }

    Node partition(Node head, int x){
        Node pRunner = head;
        Node pHead = head;
        Node pTemp = null;

        while(pRunner != null && pRunner.next != null){
            if(pRunner.next.data < x){
                pTemp = pRunner.next.next;
                pRunner.next.next = pHead;
                pHead = pRunner.next;
                pRunner.next = pTemp;
            }
            else{
                pRunner = pRunner.next;
            }
        }
        return pHead;
    }
}

TestNode.java

package practice_cracking_code_interview;

import junit.framework.TestCase;

public class TestNode extends TestCase {

    public void testAppendToTail(){
        Node head = new Node(5);
        head.appendToTail(10);
        assertEquals(head.next.data, 10);
    }

    public void testPartitionOne(){
        Node head = new Node(3);
        head.appendToTail(5);
        head.appendToTail(8);
        head.appendToTail(5);
        head.appendToTail(10);
        head.appendToTail(2);
        head.appendToTail(1);
        Node n = head.partition(head, 5);

        int[] expected = new int[]{1, 2, 3, 5, 8, 5, 10};
        int i = 0;

        while(n != null){
            assertEquals(n.data, expected[i]);
            i++;
            n = n.next;
        }
    }

    public void testPartitionTwo(){
        Node head = new Node(3);
        head.appendToTail(5);
        head.appendToTail(8);
        head.appendToTail(5);
        head.appendToTail(10);
        head.appendToTail(2);
        head.appendToTail(1);
        Node n = head.partition(head, 11);

        int[] expected = new int[]{1, 2, 10, 5, 8, 5, 3};
        int i = 0;

        while(n != null){
            assertEquals(n.data, expected[i]);
            i++;
            n = n.next;
        }
    }
}


texts: Java class: for getOrder, getData, updateData operation

texts:
Problem Statement :

Design a class for three operations for given set of integers :

int getOrder(int data) /* order meaning rank in list */
int getData(int order)
void updateData(int oldData, int newData) /* [Most used operation] */

My solution

class App {

    Set<Integer> appData;

    public App(List<Integer> data) {
        this.appData = new TreeSet<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if(o1 > o2) {
                    return -1;
                } else if (o1 < o2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        appData.addAll(data);
    }

    public int getOrder(int m) {
        int counter = 1;
        for(Integer i : this.appData) {
            if(i == m) {
                return counter;
            }
            counter ++ ;
        }
        return -1;
    }

    public int getdata(int order) {
        int counter = 1;
        for(Integer data : this.appData) {
            if(counter == order) {
                return data;
            }
            counter++;
        }
        return -1;
    }

    public void updatedata(int olddata, int newdata) {
        if(appData.contains(olddata)) {
            this.appData.remove(olddata);
        }
        this.appData.add(newdata);
    }
}


texts: List Any vs Count, which one is better for readability?

texts:
Resharper thinks I should change this

while (dockPanel.Contents.Count() > 0)

to the following:

while (dockPanel.Contents.Any())

Without thinking twice about it, I switched to the any version because .Any() is more readable for me. But a coworker of mine sees the change and asked why I did it. I explained that this improves readability but his objection was the following:

Any is an ambiguous word.
People may not be familiar with LINQ, so they might not be aware of what Any does at first glance.
Count > 0 is universal. You don't have to know C# to find out what you're trying to do.

The confusion is probably compounded by the fact that I'm working overseas. People here speak little to no English here.

Which method should I stick with?


texts: Most intuitive way to register "commands" in an extensible IRC bot in Go

texts:
I'm writing an IRC bot as a toy project, and one of the goals is to be easy and straight-forward to implement and register new commands.

As I'm new to Go, I don't know which would be the "Go way" for doing it.

This is a working "hello world" command:

package example

import (
    "fmt"
    "github.com/fabioxgn/go-bot"
)

func hello(command *bot.Cmd) (msg string, err error) {
    msg = fmt.Sprintf("Hello %s", command.Nick)
    return
}

func init() {
    bot.RegisterCommand(&bot.CustomCommand{
        Cmd:         "hello",
        CmdFunc:     hello,
        Description: "Sends a 'Hello' message to you on the channel.",
    })
}

Would an interface make it easier for the user to figure out how to write a new command? In this case, instead of a struct with a CmdFunc, an interface like:

type CustomCommand interface {
    Cmd() string
    CmdFunc(cmd *Cmd) (string, error)
    Description() string
    Usage() string
}

Or maybe the RegisterCommand function receive several args, like this Google example?

func registerDemo(name, scope string, main func(c *http.Client, argv []string)) {
    if demoFunc[name] != nil {
        panic(name + " already registered")
    }
    demoFunc[name] = main
    demoScope[name] = scope
}

I personally don't like the interface idea. For me one of the best things about Go is the freedom you get to just implementa a little func and make magic happen, but I don't know what would be idiomatic Go and intuitive for the fellow Gophers. :)


texts:
I have created this fake API just because I want to learn how to use JWT. It is a simple unsigned token exchange with two methods call: login and adminPassword.

I've used https://github.com/lcobucci/jwt as a JWT implementation.

This is the server code (index.php):

<?php
// https://github.com/lcobucci/jwt
require_once 'vendor/autoload.php';

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;

define('USERNAME', 'admin');
define('PASSWORD', 'p4ssw0rd');

function login($username, $password) {
  if ($username == USERNAME && $password == PASSWORD) {
    $token = (new Builder())->setIssuer('JWT Example')
      ->setAudience('JWT Example')
      ->setIssuedAt(time())
      ->setExpiration(time() + 3600)
      ->getToken();
    return json_encode(['result' => 1, 'message' => 'Token generated successfully', 'token' => '' . $token,]);
  } else {
    return json_encode(['result' => 0, 'message' => 'Invalid username and/or password']);
  }
}

function validateToken($token) {
  try {
    $token = (new Parser())->parse($token);
  } catch (Exception $exception) {
    return false;
  }

  $validationData = new ValidationData();
  $validationData->setIssuer('JWT Example');
  $validationData->setAudience('JWT Example');

  return $token->validate($validationData);
}

function adminPassword($token) {
  if (validateToken($token)) {
    return json_encode(['result' => 1, 'message' => 'The admin\'s password is: ' . PASSWORD]);
  } else {
    return json_encode(['result' => 0, 'message' => 'Invalid token']);
  }
}

$requestUri = trim($_SERVER['REQUEST_URI'], '/');
if ($requestUri == 'users/login') {
  echo login($_POST['username'], $_POST['password']);
} else if ($requestUri == 'users/admin-password') {
  echo adminPassword($_SERVER['HTTP_AUTHORIZATION']);
}

And the following is the client code:

<?php
// https://github.com/lcobucci/jwt
define('SERVER_URL', 'http://localhost:9999/');

function httpPost($url, $data = [], $headers = []) {
  $options = [
    'http' => [
      'method'  => 'POST',
      'header'  => array_merge(['Content-type: application/x-www-form-urlencoded'], $headers),
      'content' => http_build_query($data),
    ],
  ];
  $context  = stream_context_create($options);
  return file_get_contents($url, false, $context);
}

$url = SERVER_URL . 'users/login';
$response = httpPost($url, ['username' => 'admin', 'password' => 'p4ssw0rd']);
$response = json_decode($response);

$url = SERVER_URL . 'users/admin-password';
echo httpPost($url, [], ["Authorization: Bearer <{$response->token}>",]);

Dependencies (composer.json):

{
    "name": "ns/jwtexampleapp",
    "require": {
        "lcobucci/jwt": "^3.1"
    },
    "authors": [
        {
            "name": "Author name",
            "email": "autho@email.com"
        }
    ]
}

The next step is to learn about token signatures.

I know the code could be better. Actually I'm focused on the JWT concepts. Please analyse the code with that in mind ...

Am I following the right path? Is it a good representation about the JWT concepts?


texts: How would I name these types in a way that's accurate and not redundant?

texts:
I have a component that shows the status of a customer's billing plan. There are about seven different states it can be in, with about six props each (I've simplified it down to two for this example). I'm trying to create an enum that I can get the props from, to be used like this:
<PlanCard {...PlanCardProps.TrialPlan} />

But I'm trying to give it proper typing. The names just feel wonky here though. I hate using "type" as part of the name of a type, but given that the enum is called PlanCardProps, I just didn't know what to call the typing for the object literal and for its values.
Is there a better way of naming this?
export type PlanCardPropsType = {
  header: string;
  ctaText: string;
};

type PlanCardPropsEnum = {
  [key: string]: PlanCardPropsType;
};

export const PlanCardProps: PlanCardPropsEnum = {
  TrialPlan: {
    header: 'x',
    ctaText: 'click here'
  },
  NoPlan: {
    header: 'y',
    ctaText: 'cancel'
  }
};


texts:
I was working on a react hooks project.
I was making a form
In the form, I noticed myself writing a very wet code
Here is my code
const FormInvite = (props) => {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [country, setCountry] = useState("")
  const [email, setEmai] = useState("")

  const changeSelectedCountry = (event) => {
    setCountry(event.target.value)
  }

  const changeFirstName = (event) => {
    setFirstName(event.target.value)
  }

  const changeLastName = (event) => {
    setLastName(event.target.value)
  }

  const changeEmail = (event) => {
    setEmail(event.target.value)
  }

Can someone help me/give recommendation so that I don't write those one liner, kind of representative code?


texts:
Interview question from the interwebz

  You have a set of envelopes of different widths and heights.  One
  envelope can fit into another if and only if both the width and height
  of one envelope is greater than the width and height of the other
  envelope. What is the maximum number of envelopes can you russian
  doll?

My implementation:

# assuming no dups
def max_russian_doll(enve):
    if not enve: return 0
    enve.sort()
    max_global = 1
    for j in xrange(len(enve) - 1):
        max_local = 1
        for i in xrange(j, len(enve) - 1):
            if enve[i][1] < enve[i + 1][1] and enve[i][0] != enve[i + 1][0]: # @comment
                max_local += 1
        max_global = max(max_global, max_local)
    return max_global

envelopes = [(4,5), (6,7), (2,3)]
max_russian_doll(envelopes)

obviously this is \$O(n^2)\$. Right now I'm trying to figure out faster solution. Any tips?


texts: String compression algorithm using functional JavaScript

texts:
I've written an algo to compress a string

eg. aabcbbba to a2bcb3a

I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not.

I'm wondering how I can make this code cleaner and more functional.

I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters

const signature = `aabcbbba`;

const compressString = signature => {
  return compressCharacters(groupCharacters(signature));
}

const groupCharacters = signature => {
  let newSignature = "", arr = [];

  // convert signature to an array
  let result = [...signature].reduce((accumulator, element, index) => {

    // check if last letter in accumulator matches the current element
    if (accumulator[accumulator.length -1] !== element) {
      // add the accumulator string into an array
      arr.push(accumulator);
      // clear the newSignature string and set it to current element
      newSignature = element;
    } else {
      // if it doesn't match, add it to the accumulator
      newSignature = accumulator += element;
    }

    // check if it's the last item - add to array
    if (index === signature.length - 1) arr.push(element);

    // return newSignature to accumulator
    return newSignature;
  })

  return arr;
}

const compressCharacters = arr => {
  let newArray = [];

  let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

  return newArray.join("");
}

compressString(signature);


texts:
This is a view as part of a RESTful image handler module, written for Flask, I am sure there is a better/more pythonic way of doing parts of this, maybe using List Comprehensions or Generator Functions. But I am a bit of a Python newbie and cannot spot it. Can any experienced pythonistas take a look?

@__mod__.route('/', methods=['GET'])
@__mod__.route('/<filename>', methods=['GET'])
def get(filename=None):
    """ Get a list of all Images or a single Image """

    couchdb.init_app(current_app)
    image = Image()

    if filename is None:
        results = image.view('images/all')
        filenames = []
        for result in results.all():

            if result._attachments:
                for attachment in result._attachments.keys():
                    filenames.append(url_for('.get', filename=attachment))
        response = make_response(simplejson.dumps(filenames), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        results = image.view('images/all', key=filename)

        if results.first() is not None:
            try:
                image_file = image.get_db().fetch_attachment(results.first(), filename)
                image_doc = results.first()._attachments[filename]
                response = make_response(image_file, 200)
                response.headers['Content-Type'] = image_doc['content_type']
                return response
            except ResourceNotFound:
                abort(404)

        else:
            abort(404)

I've managed this on my own, using a list comprehension instead of the ugly for-if structures:

if filename is None:
    results = image.view('images/all')
    filenames = [url_for('.get', filename=attachment)
                 for result in results
                 if result._attachments
                 for attachment in result._attachments]
    response = make_response(simplejson.dumps(filenames), 200)
    response.headers['Content-Type'] = 'application/json'
    return response
else:
    results = image.view('images/all', key=filename)

    if results.first():
        try:
            image_file = image.get_db().fetch_attachment(results.first(), filename)
            image_doc = results.first()._attachments[filename]
            response = make_response(image_file, 200)
            response.headers['Content-Type'] = image_doc['content_type']
            return response
        except ResourceNotFound:
            abort(404)
    else:
        abort(404)


texts:
Monitors DB2 for changes in table data. It doesn't take any actions with the data just yet, only checks to see if new data is available every 2 seconds.

const { dbconn, dbstmt } = require('idb-connector');// require idb-connector

// global for storing row data in
var data = ''

async function queryDB() {
    const sSql = `SELECT * FROM LIBNAME.TABLE`;

    // create new promise
    let promise = new Promise ( function(resolve, reject) {
        // create new connection
        const connection = new dbconn();
        connection.conn("*LOCAL");
        const statement = new dbstmt(connection);
        statement.exec(sSql, (rows, err) => {
          if (err) {
            throw err;
          }

          // check if data is new
          if (data === rows) {
            resolve('no new data')
          } else {
            data = rows;
            resolve('new data arrived');
          };

          // close DB connections
          statement.close();
          connection.disconn();
          connection.close();
        })
    });

    let result = await promise;// await promise
    return result;
};

async function checkDB2() {
    const status = await queryDB();// check for new data

    if (status === 'new data arrived') {
        // new data action
    };

    setTimeout(checkDB2, 2000);// check again in 2 seconds
};


texts: Error-checking macro to jump to specified label given a failing statement

texts:
I'm starting a new C projet and I want to have the cleanest and shortest error checking code possible.

To that aim, I often use two things :

functions return 0, false or NULL on error
I try to use small functions with one cleanup label "fail" or "error"

So I thought about using a macro to simplify the code even more. If I choose to use it, this pattern will appear in almost every function so I expect that people reading the code will become accustomed to it very quickly.

So, is it a viable solution ? Here is an example snippet :

#define try( stmt , error_label ) if (!(stmt)) { goto error_label; }

// this function creates a new image database
ImageDatabase*
db_create(uint32_t max_images,
          struct resolution resolutions[NB_RESOLUTIONS])
{
    ImageDatabase* db;
    try( db = allocate_empty_db(), error);
    memcpy(db->resolutions, resolutions, NB_RESOLUTIONS * sizeof(struct resolution));
    db->max_nb_images = max_images;
    try( db->metadatas = calloc(max_images, sizeof(struct metadata)) , error);
    try( finalize_creation(db) , error);
    return db;

error:
    free(db->metadatas);
    free(db);
    return NULL;
}

EDIT: Here is an alternative without the try macro... but it's not as pretty. Also note that in this example the code is simple enough to avoid a goto, but it's not always the case.

ImageDatabase*
db_create(uint32_t max_images,
          struct resolution resolutions[NB_RESOLUTIONS])
{
    ImageDatabase* db = allocate_empty_db();
    if (db) {
        memcpy(db->resolutions, resolutions, NB_RESOLUTIONS * sizeof(struct resolution));
        db->max_nb_images = max_images;
        db->metadatas = calloc(max_images, sizeof(struct metadata)) , error);
        if (db->metadata == NULL
           || !finalize_creation(db))
        {
            free(db->metadatas);
            free(db);
            db = NULL;
        }
    }
    return db;
}


texts: Loading an animation with an Ajax request

texts:
I am not sure if this is the correct way to make an Ajax request and do the typical loading/processing GIF/animation while processing is happening and displaying the response.

HTML:

Photo Name : <input type='text' placeholder='Photo Name' name='photo-name' title='Photo Name' value='Untitled'>

                <img src="<?php echo 'tmp/' . $imgUpload->getFileName() . $imgUpload->getType() ?>" alt='photo'>

                Photo Tags : <input type='text' placeholder='Tags e.g. (#beach #park #dog)'>

                SaveCancel

CSS:

img { border: none; }
input { padding: 0.30em; }

.photo-setup {
    width: 600px;
    height: auto;
    margin: 0 auto;
    font-weight: 200;
    font-size: 0.9em;
    letter-spacing: 1px;
}

.setup-head {
    border-left: 1px solid #cacece;
    border-right: 1px solid #cacece;
    border-top: 1px solid #cacece;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    padding: 1em;
    overflow: hidden;
}

.photo-name { float: left; }

.photo-section {
    border: 1px solid #cacece;
    text-align: center;
}

.tag-section {
    padding: 1em 0 1em 1em;
}

.tag-section input {
    width: 81%;
    display: inline-block;
}

.ajax-loading {
    text-align: center;
    margin: 1em;
    display: none;
}

.response {
    display: none;
    text-align: center;
}

.commit-section {
    text-align: center;
}

.commit-section a {
    margin-left: 1em;
}

jQuery:

$(document).ready(function() {

    $('.save').on('click', function(e) {
        e.preventDefault();
        save();
    });

    $(document).ajaxStart(function() {
        $('.commit-section .save').hide();
        $('.ajax-loading').fadeIn();
    });

    $(document).ajaxComplete(function() {
        setTimeout(function() {
            $('.ajax-loading, .commit-section').hide();
            $('.response').fadeIn();
        }, 500);
    });

});

// collect all photo data and send to php for database storage
function save() {

    // regex to parse hashtags
    var regex = /[#]+[A-Za-z0-9-_]+/g;
    var name = $.trim($('.photo-name input').val());
    var tags = $.trim($('.tag-section input').val()).match(regex);
    var photo = $.trim($('.photo-section img').attr('src'));

    $.ajax({

        url: 'save_photo.php',
        method: 'POST',
        dataType: 'html',
        data: {
            title: name,
            hash_tags: tags,
            filename: photo
        }

    })
    .done(function(response) {
        $('.response').html(response);
    })
    .fail(function() {
        alert('Something went wrong!')
    });
}


texts:
I have written code that gets the reputation badge from given score like this:

I use an if-else statement here:

func GetReputationBadge2(score int) string {

    badge := "badges-off.jpg"
    if score >= 50001 { // Diamond
        badge = "diamond-1.gif"
        if score >= 500001 {
            badge = "diamond-5.gif"
        } else if score >= 200001 {
            badge = "diamond-4.gif"
        } else if score >= 150001 {
            badge = "diamond-3.gif"
        } else if score >= 100001 {
            badge = "diamond-2.gif"
        }
    } else if score >= 4501 { // Gold
        badge = "gold-1.gif"
        if score >= 45001 {
            badge = "gold-5.gif"
        } else if score >= 30001 {
            badge = "gold-4.gif"
        } else if score >= 15001 {
            badge = "gold-3.gif"
        } else if score >= 10001 {
            badge = "gold-4.gif"
        }
    }

    return badge
}

I was kinda thinking that I could make it better using a switch-case statement:

func GetReputationBadge(score int) string {

    badge := "badges-off.jpg"
    caseSwitch := true
    switch caseSwitch {
    case score >= 50001:
        badge = "diamond-1.gif"

        switch caseSwitch {
        case score >= 500001:
            badge = "diamond-5.gif"
        case score >= 200001:
            badge = "diamond-4.gif"
        case score >= 150001:
            badge = "diamond-3.gif"
        case score >= 100001:
            badge = "diamond-2.gif"

        }

    case score >= 4501:
        badge = "gold-1.gif"

        switch caseSwitch {
        case score >= 45001:
            badge = "gold-5.gif"
        case score >= 30001:
            badge = "gold-4.gif"
        case score >= 15001:
            badge = "gold-3.gif"
        case score >= 10001:
            badge = "gold-2.gif"

        }

    default:
        return badge
    }

    return badge
}

Notice that I'm comparing boolean in the switch-case statement. Which are better for performance: using if-else or switch-case statement in this case?


texts: Building Weather Forecast from JSON with optionals

texts:
I am looking for the best way of parsing JSON in Swift 2.0.

I have this JSON

{
  "latitude": 37.8267,
  "longitude": -122.423,
  "currently": {
    "time": 1440110395,
    "summary": "Clear"
  }
}

and field summary is NOT always visible in response.

My model object and parsing method:

enum JSONErrorType: ErrorType {
  case InvalidJson
}

struct WeatherForecast {
  let date: NSDate
  let summary: String?
  let latitude: Double
  let longitude: Double

  init(date: NSDate, summary: String?, latitude: Double, longitude: Double) {
    self.latitude = latitude
    self.longitude = longitude
    self.date = date
    self.summary = summary
  }

  static func fromJSON(json: AnyObject) throws -> WeatherForecast {
    guard let dict = json as? NSDictionary,
      let latitude = dict["latitude"] as? Double,
      let longitude = dict["longitude"] as? Double,
      let curr_dict = dict["currently"] as? NSDictionary,
      let timestamp = curr_dict["time"] as? NSTimeInterval else {
      throw JSONErrorType.InvalidJson
    }
    let date = NSDate(timeIntervalSince1970: timestamp)
    if let summary = curr_dict["summary"] as? String {
      return WeatherForecast(date: date, summary: summary, latitude: latitude, longitude: longitude)
    } else {
      return WeatherForecast(date: date, summary: nil, latitude: latitude, longitude: longitude)

    }
  }
}

I can't use guard because the summary property is optional. if let works here but I have two returns which doesn't look very good. Also if I will have more optionals fields, the code gets messy.


texts:
I'm computing the gradient of an image manually (without using built in functions) and I want to make it faster but keeping the same performance.
I'm very open to any suggestions.. currently learning c++ optimzation and STL lib in recent c++.

Here is my code, my main concern is gradiantAndDirection function that I need to optimize. The TimerAvrg struct is how I compute the running time of that function:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <chrono>

struct   TimerAvrg
{
    std::vector<double> times;
    size_t curr=0,n;
    std::chrono::high_resolution_clock::time_point begin,end;
    TimerAvrg(int _n=30)
    {
        n=_n;
        times.reserve(n);
    }

    inline void start()
    {
        begin= std::chrono::high_resolution_clock::now();
    }

    inline void stop()
    {
        end= std::chrono::high_resolution_clock::now();
        double duration=double(std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count())*1e-6;
        if ( times.size()<n)
            times.push_back(duration);
        else{
            times[curr]=duration;
            curr++;
            if (curr>=times.size()) curr=0;}
    }

    double getAvrg()
    {
        double sum=0;
        for(auto t:times)
            sum+=t;
        return sum/double(times.size());
    }
};

//Those variables will be in a class with gradiantAndDirection
uchar *dirImg;
int gradThresh = 20;

void gradiantAndDirection(cv::Mat& GxGy, const cv::Mat &grey)
{
    cv::Mat smoothImage;
    GaussianBlur(grey, smoothImage, cv::Size(5, 5), 1.0);
    uchar *smoothImg = smoothImage.data;

    GxGy.create( grey.size(),CV_16SC1);
    short* gradImg = (short*)GxGy.data;

    dirImg = new unsigned char[grey.cols*grey.rows];

    //Initialization of row = 0, row = height-1, column=0, column=width-1
    for (int j = 0; j<grey.cols; j++)
        gradImg[j] = gradImg[(grey.rows - 1)*grey.cols + j] = gradThresh - 1;

    for (int i = 1; i<grey.rows - 1; i++)
        gradImg[i*grey.cols] = gradImg[(i + 1)*grey.cols - 1] = gradThresh - 1;

    for (int i = 1; i<grey.rows - 1; i++) {
        for (int j = 1; j<grey.cols - 1; j++) {
            int com1 = smoothImg[(i + 1)*grey.cols + j + 1] - smoothImg[(i - 1)*grey.cols + j - 1];
            int com2 = smoothImg[(i - 1)*grey.cols + j + 1] - smoothImg[(i + 1)*grey.cols + j - 1];
            int gx;
            int gy;
            gx = abs(com1 + com2 +  (smoothImg[i*grey.cols + j + 1] - smoothImg[i*grey.cols + j - 1]));
            gy = abs(com1 - com2 +  (smoothImg[(i + 1)*grey.cols + j] - smoothImg[(i - 1)*grey.cols + j]));
            int sum;
            if(0)
                sum = gx + gy;
            else
                sum = (int)sqrt((double)gx*gx + gy*gy);

            int index = i*grey.cols + j;
            gradImg[index] = sum;
            if (sum >= gradThresh) {
                if (gx >= gy) dirImg[index] = 1;//1 vertical
                else      dirImg[index] = 2;//2 Horizontal
            }
        }
    }
}

int main( int argc, char** argv )
{
    cv::Mat image;
    image = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);

    float sum=0;
    cv::Mat GxGy;
    for(int alpha = 0; alpha <20 ; alpha++)
    {
        TimerAvrg Fps;
        Fps.start();
        gradiantAndDirection(GxGy, image);
        Fps.stop();
        sum = sum + Fps.getAvrg()*1000;
    }

    std::cout << "\rTime detection=" << sum/19 << " milliseconds" << std::endl;
    cv::resize(GxGy,GxGy,cv::Size(image.cols/2,image.rows/2));
    cv::Mat result8UC1;
    cv::convertScaleAbs(GxGy, result8UC1);
    cv::imshow( "Display window",result8UC1);
    cv::waitKey(0);

    return 0;
}

I compile my code under Ubuntu 16.04 gcc 8.1.0

g++ -std=c++1z -fomit-frame-pointer -O3 -ffast-math -mmmx -msse -msse2 -msse3 -DNDEBUG -Wall improve_code.cpp -o improve_code -fopenmp `pkg-config --cflags --libs opencv`


texts:
I've written a script in VBA in combination with selenium which is able to scrape all the 1000 links from a lazy-loading webpage which displays it's content 20 at a time and doesn't display the full content until it reaches the bottom of that page. However, my script can make this webpage scroll to the end. After collecting all the links from main page, it then follows each individual link to scrape the Name of CEO and Web address of that organization. It is working perfectly now. I tried to make the whole thing flawless. Here is the full code:

Sub Fortune_parser()

Dim driver As New WebDriver
Dim posts As Object, post As Object, items As Object, item As Object

driver.Start "chrome", "http://fortune.com/fortune500"
driver.get "/list/"

driver.Wait 500

For y = 0 To 200

    driver.ExecuteScript ("window.scrollTo(0, document.body.scrollHeight);")
    driver.Wait 500

Next y

Set posts = driver.FindElementsByXPath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]")

For Each post In posts

    i = i + 1
    item_links = post.FindElementByXPath(".//a").Attribute("href")

    driver.Start "chrome", ""
    driver.get item_links

    driver.Wait 500

    Set items = driver.FindElementsByXPath("//div[contains(@class,'company-info-card-table')]")

    For Each item In items
        x = x + 1
        Cells(x, 1) = item.FindElementByXPath(".//div[contains(@class,'small-7')]/p[@class='remove-bottom-margin']").Text
        Cells(x, 2) = item.FindElementByXPath(".//div[contains(@class,'small-9')]/a").Attribute("href")
        driver.Quit
    Next item
Next post

End Sub


texts: Create one function instead of two bootstrap modal

texts:
I have a form that reads a JSON file for default wrong answers to be applied to a 'summary div' at the end of the form.

I wondered if I could make these two functions one somehow?

It is a bootstrap modal, that I am using data-attributes to get the right answers which populate the text in the modal body, then when I click 'save changes' button I am repeating myself but wondered if I could make this more efficient.

$('#ncModal').on('show.bs.modal', function(e) {
    var btn = $(e.relatedTarget);
    var reciepient = btn.data('whatever');

    if (reciepient === "@mdo") {
        console.log(reciepient);
        $.getJSON('./NCText/solar-nc.json', function (data) {
            //console.log(data);
            //console.log(data[0]);
            var output = '
';
            $.each(data[0], function(key, val) {
                output += '
' + val + '
';
            });

            output += '
';
            $('#modalbody').html(output); // replace all existing content
        });
    }

    // get Action Improvement text clicked to add
    // to summary box.
    $('.modal-body').on('click', function () {
        var text = $(event.target).text();
        console.log(text);
        $('#summary').append(text).append('\n');
    });

    // Add Action Improvement textarea to summary
    $('#saveModalNc').on('click', function () {
        var txt = $('#nc_textarea').val();
        console.log(txt);
        $('#summary').append(txt);
    });
});


texts: Check whether a list of list of string fits a regex efficiently

texts:
I have the following structure for my object:

Word (Object)

Word (String)
List<Symbol>

Symbol (Object)

Symbol (String)
List<SymbolChoice>

SymbolChoice (Object)

Symbol (String)

The background of this is that this is processed OCR output and I want to force a word to match a certain regex. If it cannot find a match, it should return an empty List<SymbolChoice>, otherwise it should return all List<SymbolChoice> that match the specified regex.

Example:

Found word: "1o0"
Symbols: "1", "o" and "0"
Choices of "1": "1"
Choices of "o": "o", "0"
Choices of "0": "0"

When forcing this word to abide regex "\\d{3}", it has to return [["1", "0", "0"]], here I am denoting the SymbolChoice objects as strings.

I have a solution, however it is not fast enough, more details after the method:

public List<List<SymbolChoice>> forceFitRegex(final String regex) {
    Objects.requireNonNull(regex, "regex");

    if (getSymbols().size() <= 1) {
        return new ArrayList<List<SymbolChoice>>();
    }

    int combinations = 1;
    for (Symbol symbol : getSymbols()) {
        combinations *= symbol.getSymbolChoices().size();
    }
    System.out.println("Combinations: " + combinations);

    List<List<SymbolChoice>> listOfSymbolChoices = new ArrayList<List<SymbolChoice>>();
    for (SymbolChoice symbolChoice : getSymbols().get(0).getSymbolChoices()) {
        List<SymbolChoice> symbolChoices = new ArrayList<SymbolChoice>();
        symbolChoices.add(symbolChoice);
        listOfSymbolChoices.add(symbolChoices);
    }

    int i = 1;
    while (i < getSymbols().size()) {
        List<List<SymbolChoice>> listOfSymbolChoicesCopy = new ArrayList<List<SymbolChoice>>(listOfSymbolChoices);
        for (SymbolChoice symbolChoice : getSymbols().get(i).getSymbolChoices()) {
            for (List<SymbolChoice> symbolChoicesCopy : listOfSymbolChoicesCopy) {
                List<SymbolChoice> symbolChoices = new ArrayList<SymbolChoice>(symbolChoicesCopy);
                symbolChoices.add(symbolChoice);
                listOfSymbolChoices.add(symbolChoices);
            }
        }
        i++;
    }

    Pattern pattern = Pattern.compile(regex);
    ListIterator<List<SymbolChoice>> symbolChoicesListIterator = listOfSymbolChoices.listIterator();
    while (symbolChoicesListIterator.hasNext()) {
        List<SymbolChoice> symbolChoices = symbolChoicesListIterator.next();
        StringBuilder stringBuilder = new StringBuilder();
        for (SymbolChoice symbolChoice : symbolChoices) {
            stringBuilder.append(symbolChoice.getSymbol());
        }
        if (!pattern.matcher(stringBuilder.toString()).matches()) {
            symbolChoicesListIterator.remove();
        }
    }
    return listOfSymbolChoices;
}

Let n be the number of combinations possible, calculated as the product of the size of all symbol choices. In my example that would be 1 * 2 * 1 = 2.

For n <= 288 I observe it to run very quick, however with for example n = 5760 it takes a few minutes to process. I also spot here another case of n = 311040 and have a feeling that it will never finish.

What can I do to solve my problem efficiently? I need to stick to Java 6 for Android compatibility.

(Bonus points if someone can calculate the asymptotic time my algorithm takes)


texts:
I have the following code that allows easy creation, pulling, and deletion of Tickets in a CakePHP application.

App::uses('Component', 'Controller');
App::uses('Ticket', 'Model');
App::import(array('Security'));

class TicketComponent extends Component
{
    public $name = 'Ticket';

    // Create a new ticket by providing the data to be stored in the ticket.
    function set($info = null)
    {
        $this->garbage();
        if ($info)
        {
            $ticketObj = new Ticket();
            $data['Ticket']['hash'] = md5(time());
            $data['Ticket']['data'] = $info;

            if ($ticketObj->save($data))
            {
                return $data['Ticket']['hash'];
            }
        }
        return false;
    }

    // Return the value stored or false if the ticket can not be found.
    function get($ticket = null)
    {
        $this->garbage();
        if ($ticket)
        {
            $ticketObj = new Ticket();
            $data = $ticketObj->findByHash($ticket);
            if (is_array($data) && is_array($data['Ticket']))
            {
                // optionally auto-delete the ticket -> this->del($ticket);
                return $data['Ticket']['data'];
            }
        }
        return false;
    }

    // Delete a used ticket
    function del($ticket = null)
    {
        $this->garbage();
        if ($ticket)
        {
            $ticketObj = new Ticket();
            $data = $ticketObj->findByHash($ticket);
            if ( is_array($data) && is_array($data['Ticket']) )
            {
                return $data = $ticketObj->delete($data['Ticket']['id']);
            }
        }
        return false;
    }

    // Remove old tickets
    function garbage()
    {
        $deadline = date('Y-m-d H:i:s', time() - (24 * 60 * 60)); // keep tickets for 24h.
        $ticketObj = new Ticket();
        $data = $ticketObj->query('DELETE from tickets WHERE created < \''.$deadline.'\'');
    }
}

It feels a little old now (not sure how old the code is) but wondered if certain things could be improved and if there was any parts that were considered 'bad code'.

Some observations of my own:

Do I need to keep creating the $ticketObj? And is using new Ticket() correct for CakePHP conventions?
The garbage function runs when anything ticket related is called, and makes sure that expired tickets cannot be used... But requires that it be called at the beginning of all other functions. Could this be better? Not necessarily a CRON job, but more code efficient.


texts: Simple code that finds number of factors crashes my computer. Is there a workaround for a large number?

texts:
This is my attempt at problem 12 from Project Euler. However, my code freezes my old, linux computer when I run it. I've only got 512MB of RAM and an old Intel Core 2 Duo processor on my machine which, I assume, is why it can't run the code.

Is there a way to optimize this code without using up too much resources?

#!/bin/python

def nth_triangle_number(nth):
    """ Sequence of triangle numbers is generated by adding the natural numbers.
        So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. """
    return sum([i for i in range(nth+1)])

def get_number_of_factors(num):
    quantity = 0
    for i in range(1, int(num/2)+1):     # I think the problem lies here in range()
        if not num % i:                  # BTW, using math.sqrt() produces the wrong
            quantity += 1                # answer for smaller numbers. I don't know why.
    return quantity + 1     # Added 1 to count for num (as in 1 * num)

def get_triangle_number(divisors):
    """ Find the triangle number with the given amount of divisors """
    i = 1
    while get_number_of_factors(nth_triangle_number(i)) <= divisors:
        i += 1

    return nth_triangle_number(i)

if __name__ == '__main__':
    number_of_divisors = 500
    print "Answer found: ", get_triangle_number(number_of_divisors)

I've tried initializing get_triangle_number(), i, at higher values, but it didn't seem to help. I believe the problem is with get_number_of_factors(). I had originally stored all the factors of a given integer into a list then compared its length to number_of_divisors. I figured counting each integer that satisfied the condition would save some resources.

The code does run properly and produces the correct answer when I tested the example provided on Project Euler and the following values:

    number_of_divisors = 5      # Runs properly and produces correct answer
    number_of_divisors = 50     # Runs properly and         "    "
    number_of_divisors = 150    # Runs properly and         "    "
    number_of_divisors = 200    # Crash


texts:
I'm re-implementing the common core functions that work on list as a learning exercise. I'm new to Haskell and often find myself staring at what I've written trying to determine the simpler or more elegant solution I'm certain exists. I'm also unsure about my naming conventions, since there are some things the style guides I've read don't really cover. I'd appreciate any advice or criticism.

foldl

foldl' :: (b -> a -> b) -> b -> [a] -> b
foldl' f accumulator [] = accumulator
foldl' f accumulator (x:xs) =
  seq accumulator' $ foldl' f accumulator' xs
  where accumulator' = f accumulator x

I wrote this for the ListOps https://exercism.io challenge, which had a requirement about strictness.

foldr

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f accumulator []     = accumulator
foldr f accumulator (x:xs) = f x (foldr f accumulator xs)

length

length :: [a] -> Int  -- Deliberately not using a fold
length = length' 0

length' :: Int -> [a] -> Int
length' accumulator [x]    = 1
length' accumulator (x:xs) = 1 + length' accumulator xs
length' accumulator []

map

map :: (a -> b) -> [a] -> [b]
map f []     = []
map f [x]    = [f x]
map f (x:xs) = f x:map f xs

filter

filter :: (a -> Bool) -> [a] -> [a]
filter _ []    = []
filter f (x:xs)
  | f x         = x : filter f xs
  | otherwise   = filter f xs

(++)

(++) :: [a] -> [a] -> [a]
xs ++ [] = xs
xs ++ ys = foldr (:) ys xs


texts: ExitCode class and derived Status class able to return a value

texts:
I was thinking about an ExitCode concept in a strict nothrow environment and came up with the following two classes and would like to get some peer review on what flaws they have.
They are very simple in terms of inner complexity but are quite complicated in terms of language features (at least for me :) )

ExitCode is a class encapsulating an arbitrary state and a status message.

#include <string>

class ExitCode
{
public:
    enum class TState
    {
        OK,
        FAILED,
        CORRECTED
    };

    /**
    * Default failing exit code, can be created from a simple string
    */
    ExitCode(const std::string& msg = "", const TState state = TState::FAILED)
        : m_sMessage(msg), m_state(state)
    {
    }

    ExitCode(const TState state) : m_state(state)
    {
    }

    /**
    * Uses nested exit code message and adds it to the outer message
    */
    ExitCode(const std::string& msg, const TState state, const ExitCode& nested) :
        m_sMessage(msg + ": " + nested.m_sMessage), m_state(state)
    {
    }

    ExitCode(ExitCode&& other) // Note: VS 2012 has no noexcept
    {
        m_state = other.m_state;
        m_sMessage = std::move(other.m_sMessage);
    }

    ExitCode& operator=(ExitCode&& other) // Note: VS 2012 has no noexcept
    {
        if (this != &other)
        {
            m_state = other.m_state;
            m_sMessage = std::move(other.m_sMessage);
        }

        return *this;
    }

    const std::string& GetMessage() const
    {
        return m_sMessage;
    }

    TState GetState() const
    {
        return m_state;
    }

private:

    std::string m_sMessage;
    TState m_state;
};

Simple cases could be

ExitCode foo1("All failed");

ExitCode foo2("All good", ExitCode::TState::OK);

ExitCode root("All good, but was", ExitCode::TState::OK, foo);

And a derived Status<T> class which is also able to provide some return value. The idea is that some method X may or may not return a valid output but at the same time may or may not return an error (which should not be propagated via exceptions)

template <typename TResult>
class Status : public ExitCode
{
public:

    // Converting
    Status( const TResult& result, const std::string & msg = "", const TState state = TState::OK )
        : ExitCode( msg, state ), m_result( result )
    {
    }

    // Converting move
    Status( TResult&& result, const std::string & msg = "", const TState state = TState::OK )
        : ExitCode( msg, state ), m_result( std::move( result ) )
    {
    }

    // Converting
    Status( const std::string& msg = "", const TState state = TState::FAILED )
        : ExitCode( msg, state )
    {
    }

    TResult& GetResult() const
    {
        return m_result;
    }

private:

    TResult m_result;
};

Some usage could be

Status<int> s1 = 23;

Status<int> corrected( 1, "Failed to produce valid output, but corrected something", ExitCode::TState::CORRECTED );

Status<int> s2 = "This was bad";

Are there any obvious bad design decisions in such an implementation?

I am currently aware of one: Multiple implicit string conversion when I write code like that:

Status<std::string> status = "Which constructor to use?";


texts: Folktale 2 skeleton workflow for resetting a forgotten password

texts:
I am learning more about functional programming via loop recur's online book Mostly Adequate Guide to Functional Programming, and Brian Londorf's video series on egg head.

I started using curry more (from lodash), and my last foray was actually installing folktale and trying it out for a spin.

My basic task here, is to provide a skeleton for a forgot password workflow. There are a few places where I've skipped over the details, or left things out, but these are pieces of real code I want to ship in a product. I'm hoping that the smaller functions will yield more reusable parts as time goes on, but I'm having trouble with the Result and Task types (result's are, more generally, the Either type).

Here's some nodejs javascript code for Node.js 8.5.x:

const crypto = require('crypto');
const util = require('util');
const curry = require('lodash/curry');
const moment = require('moment');
const Result = require('folktale/result');
const { task, fromPromised, waitAll, of } = require('folktale/concurrency/task');
const compose = require('folktale/core/lambda/compose');

// isValidForgotPasswordRequest :: ForgotPasswordInput -> boolean
const isValidForgotPasswordRequest = data =>
  data != null
  && data.usernameOrEmail != null
  && typeof data.usernameOrEmail == 'string'
  && data.usernameOrEmail.length > 0;

// usernameOrEmailExists :: ForgotPasswordInput -> Result string
const usernameOrEmailExists = data => isValidForgotPasswordRequest(data)
  ? Result.Ok(data.usernameOrEmail)
  : Result.Error('No username or email');

// toHex :: Buffer -> string
const toHex = b => b.toString('hex');

// getRandomBytes :: () -> Promise Buffer
const getRandomBytes = util.promisify(crypto.randomBytes);

// genToken :: () -> Task string
const genToken = fromPromised(() => getRandomBytes(40).then(toHex));

// TODO ?? Task Result, could I traverse this?

// simulate db query that returns a promise
// fetchUser :: string -> Task Result User
const fetchUser = fromPromised(un => Promise.resolve(Result.of({
    id: 1,
    email: 'test@test.com',
    username: un,
    resetToken: null,
    resetTokenExpiration: null
})));

// run fetching user and generating token in parallel,
//  to test that out / learn how to use tasks better
// getUsernameAndToken :: (getUser) -> (getToken) ->
//  Result string -> Result Task [ Result User, string ]
const getUsernameAndToken = curry((getUser, getToken, res_un) =>
  res_un.map(un =>
    waitAll([ getUser(un), getToken() ])));

// TODO validate getUser returns correctly (so add an extra Result in there)

// TODO come back to this....
// chainTokenAssign :: Result Task [ Result User, string ] ->
const chainTokenAssign = res =>
  res.map(jobs =>
    jobs.chain(([ res_user, token ]) =>
      of(res_user.map(usr => {
        usr.resetToken = token;
        usr.resetTokenExpiration = 'tmrw';

        return usr;
    }))
  )
);

// TODO after successful chainTokenAssign, we can
//  email user (call microservice)

// toPromise :: Result a -> Promise a
const toPromise = res =>
  res.matchWith({
    Ok: ({ value }) => value.run().promise(),
    Error: ({ value }) => Promise.reject(value)
  });

// compose it all together!
// f :: ForgotPasswordInput -> (string eventually, for now it is whatever object)
let f = compose.all(
  toPromise,
  chainTokenAssign,
  getUsernameAndToken(fetchUser, genToken),
  usernameOrEmailExists);

f({ usernameOrEmail: 'admin' })
  .then(console.log)
  .catch(console.error);

Note the above was written against Node version 8.5.

Specific questions:

Are those type signatures correct?
Am I wielding Result and Task properly?
Is there a way to avoid chainTokenAssign's deep nesting? (Result mapped over a task chained with a new task, which is further mapped over an inner Result)
Related to above, could traverse help combine some of these types?
Are there any general improvements or style guidelines?


texts: Finding all neighbours of a node sliding tile

texts:
So I have some code which finds neighbours of a given State. So the positions the blank tile (which is represented as 0 in my code) can be moved.

I am doing the 3x3 tile puzzle. The goal state is represented like this :

1 2 3
4 5 6
7 8 0

Say I have a problem state which is:

8 5 1
3 4 7
0 6 2

I would call the findNeighbours() method on this State and it should return two states like this .

8 5 1                             8 5 1
3 4 7   (This is a right move)    0 4 7  (This is an up move)
6 0 2                             3 6 2

The reason I'm posting here is because I'm not getting the performance I'd hoped for and I'm assuming this findNeighbours() is the issue as the code is clunky to say the least! I should also point out that state is an array which looks something like state = {1,2,3,4,5,6,7,8,0} and neighbours is an ArrayList which I am adding every State to

   public void findNeighbours() {
        for (int i = 0; i < state.length; i++) {
            if (state[i] == 0) {
                if (i % 3 != 0) {
                    int[] left = new int[9];
                    System.arraycopy(state, 0, left, 0, left.length);
                    int temp = left[i];
                    left[i] = left[i - 1];
                    left[i - 1] = temp;
                    State newState = new State(left,this, "left");
                    this.neighbours.add(newState);

                }
                if (i % 3 != 2) {
                    int[] right = new int[9];
                    System.arraycopy(state, 0, right, 0, right.length);
                    int temp = right[i];
                    right[i] = right[i + 1];
                    right[i + 1] = temp;
                    State newState = new State(right, this, "right");
                    this.neighbours.add(newState);
                }
                if (i > 3) {
                    int[] up = new int[9];
                    System.arraycopy(state, 0, up, 0, up.length);

                    int temp = up[i];
                    up[i] = up[i - 3];
                    up[i - 3] = temp;
                    State newState = new State(up, this, "up");
                    this.neighbours.add(newState);
                }
                if (i < 6) {
                    int[] down = new int[9];
                    System.arraycopy(state, 0, down, 0, down.length);
                    int temp = down[i];
                    down[i] = down[i + 3];
                    down[i + 3] = temp;
                    State newState = new State(down,  this, "down");
                    this.neighbours.add(newState);
                }
                break;
            }
        }
    }


texts: Persist relation to a class (and not a class instance) in Ruby on Rails with Mongoid

texts:
Assume my users can subscribe to several plan_types. I want to define those plans as classes, and be able to keep, for each user, a reference to a subscription_plan and also a presubscription_plan. This is like a State pattern :

class Payment::SubscriptionPlan
  def self.max_subscription_quantity
    120
  end
end

class Payment::ConcretePlan1 < Payment::SubscriptionPlan
  def self.commitment_period
    2.months
  end
end

class Payment::ConcretePlan2 < Payment::SubscriptionPlan
  def self.max_subscription_quantity
    50
  end
end

What is the best way to "persist" the relation to a class in the database ? Currently I was doing the following using the as_enum gem

class Settings
  setting :subscription_plans, type: Array, default: [
    Payment::ConcretePlan1,
    Payment::ConcretePlan2
  ]
end

class User
  as_enum :subscription_plan, Settings.subscription_plans, map: :string
  as_enum :presubscription_plan, Settings.subscription_plans, map: :string

  def subscription_plan
    return nil if super.nil?
    Payment.const_get(super.to_s.demodulize)
  end

  def presubscription_plan
    return nil if super.nil?
    Payment.const_get(super.to_s.demodulize)
  end
end

The current implementation works but I'm not sure this is the best way to tackle the problem


texts:
I have class House and module Lockable.  Locking and unlocking House should reflect the real world, so you can't lock twice.

Do you think this is a good approach to using a module and raising an exception?

module Lockable
  attr_reader :locked

  def lock!
    raise StandardError, "Already locked" if @locked == true
    @locked = true
  end

  def unlock!
    raise StandardError, "Already unlocked" if @locked == false
    @locked = false
  end
end

class House
  include Lockable
end

Usage:

house = House.new
house.lock!
house.unlock!
house.unlock! # raise an exception


texts: Finding the positive numbers count in an ECMAScipt array

texts:
All I am trying to achieve is better use of built-in ES functions.

var arr = [0, 1, 2, 3, -1, -2, -3];

function countPositiv(p, c, i, a)
{
  if(c > 0){
    return p+1;
  } else {
    return p;
  }
}

var positiv = arr.reduce(countPositiv, 0);

console.log(positiv);


texts: Removing whitespace and space in list that contains different types of elements

texts:
My goal is to remove whitespaces from string elements of my list, and to remove empty string elements altogether. My code:

def modifylist(lst):
        lst = [elt.strip() if type(elt) is str else elt for elt in lst]
        while '' in lst:
                lst.remove('')
        return lst

Is there any other method that python provides? more elegant and hopefully more fast than using this while loop?


texts:
The task:

  You are given an array of length n + 1 whose elements belong to the
  set {1, 2, ..., n}. By the pigeonhole principle, there must be a
  duplicate. Find it in linear time and space.

const lst = [1,2,3,4,5,6,7,8,7];

My functional solution:

const findDuplicate = lst => {
  const set = new Set();
  let ret;
  lst.some(x => set.has(x) ?
           !Boolean(ret = x) :
           !Boolean(set.add(x))
  );
  return ret;
};

console.log(findDuplicate(lst));

My imperative solutions:

function findDuplicate2(lst) {
  const set = new Set();
  let i = 0;
  while(!set.has(lst[i])) { set.add(lst[i++]); }
  return lst[i];
}

console.log(findDuplicate2(lst));

function findDuplicate3(lst) {
  for (let i = 0, len = lst.length; i < len; i++) {
    if (lst[Math.abs(lst[i])] >= 0)  {
      lst[Math.abs(lst[i])] = -lst[Math.abs(lst[i])];
    } else {
      return Math.abs(lst[i]);
    }
  }
}

console.log(findDuplicate3(lst));


texts: Algorithm to remove duplicates array leaving at most 2 elements

texts:
My interview question was that I need to return the length of an array that removed duplicates but we can leave at most 2 duplicates.

For example, [1, 1, 1, 2, 2, 3] the new array would be [1, 1, 2, 2, 3]. So the new length would be 5. I came up with an algorithm with \$O(2n)\$ I believe.

def removeDuplicates(nums):
    if nums is None:
        return 0

    if len(nums) == 0:
        return 0

    if len(nums) == 1:
        return 1

    new_array = {}
    for num in nums:
        new_array[num] = new_array.get(num, 0) + 1

    new_length = 0
    for key in new_array:
        if new_array[key] > 2:
            new_length = new_length + 2
        else:
            new_length = new_length + new_array[key]

    return new_length

new_length = removeDuplicates([1, 1, 1, 2, 2, 3])
assert new_length == 5

Can I improve this code to be any faster?


texts: Find size for elements to fit in certain width

texts:
This is a follow-up on Change size of elements until parent reaches certain height

The goal of the function is to find a size for the elements inside a parent, so they all fit in a single row. I tried it with a loop (check previous question), and now I changed it to if statements. However I would like to simplify it, but I can't find how. The Size of the elements don't have to be exactly how they are now. The default size is width: 10px; height: 10px; margin: 5px 7px, which is a total of 24px wide.

function _AdjustHeightOwlDots(id) {
    const thisElementId = `owl-carousel-${id}`;
    const dotRowWidth = $(`#${thisElementId} .owl-dots`).width();
    const amountOfDots = document.querySelector(`#${thisElementId} .owl-dots`).childElementCount;
    const singleDotWidth = $(`#${thisElementId} .owl-dots > button`).width();

    if ( (singleDotWidth * amountOfDots) < dotRowWidth ) { // dots fit in single row
      return;
    }
      let maxDotWidth = Math.floor(dotRowWidth / amountOfDots);
      const setNewStyle = function(hw, margin) {
        $(`#${thisElementId} div.owl-dots > button > span`).css('width', `${hw}px`);
        $(`#${thisElementId} div.owl-dots > button > span`).css('height', `${hw}px`);
        $(`#${thisElementId} div.owl-dots > button > span`).css('margin', `5px ${margin}px`);
      }
      if (maxDotWidth % 2 === 1) {
        maxDotWidth -= 1;
      }

      // A/B
      // width = Apx
      // height = Apx
      // margin = 5px Bpx

      if (maxDotWidth <= 3) {
        // set to 1/1
        setNewStyle(1, 1);
      } else if (maxDotWidth === 4) {
        // set to 2/1
        setNewStyle(2, 1);

      } else if (maxDotWidth === 6) {
        // set to 2/2
        setNewStyle(2, 2);

      } else if (maxDotWidth === 8) {
        // set to 4/2
        setNewStyle(4, 2);

      } else if (maxDotWidth === 10) {
        // set to 4/3
        setNewStyle(4, 3);

      } else if (maxDotWidth === 12) {
        // set to 6/3
        setNewStyle(6, 3);

      } else if (maxDotWidth === 14) {
        // set to 6/4
        setNewStyle(6, 4);

      } else if (maxDotWidth === 16) {
        // set to 8/4
        setNewStyle(8, 4);

      } else if (maxDotWidth === 18) {
        // set to 8/5
        setNewStyle(8, 5);

      } else if (maxDotWidth === 20) {
        // set to 10/5
        setNewStyle(10, 5);

      } else if (maxDotWidth === 22) {
        // set to 10/6
        setNewStyle(10, 6);
      }
  };


texts: Is this a good Ruby implementation of Prime Factorization?

texts:
I'm doing some practice problems on Khan Academy. The current one is Prime factorization. I came up with this:

require 'prime'

def prime_factorization(n, primes = nil)
  return [n] if Prime.prime? n

  primes ||= Prime.take_while { |p| p < n/2 }
  factorization = []
  prime = primes.detect { |p| n % p == 0 }
  factor = n / prime
  factorization << prime

  if Prime.prime? factor
    factorization << factor
  else
    factorization += prime_factorization factor, primes
  end

  factorization
end

The benchmarks for this are:

                            user       system     total       real
prime factorization of 75:  0.000000   0.000000   0.000000 (  0.000129)
prime factorization of 750:  0.000000   0.000000   0.000000 (  0.000241)
prime factorization of 4202:  0.000000   0.000000   0.000000 (  0.000498)
prime factorization of 39450:  0.010000   0.000000   0.010000 (  0.003061)
prime factorization of 460522:  0.050000   0.000000   0.050000 (  0.057704)

What is the big O notation for this method?
How does this algorithm compare to optimal prime factor algorithms in terms of complexity/performance?
Is recursion a good way to solve this problem?
How could it be improved?
Is this a stupid question?


texts: Automating easy-rsa cert creation with Bash script

texts:
In order to make cert creation with easy-rsa as practical for others, this script was created and it works so far.  The questions are:

where can it be improved?
are there flaws that are not obvious to the author?

The commentary is a bit extensive, but whomever will come across this in the future should be able to understand what's being done no matter how advanced.

#!/bin/bash
##
## This script automates the complete process of creating new easy-rsa  client certificates.
## It includes:     1. Mounting a block device.
##          2. Generating certificates using individual timestamps.
##          3. Copying the created certs to the mounted block device.
##
##
#
# First we look for the usb device at sdc1 and mount it. If not present tell the pebcac the it should insert one.

# all the predifined variables will end up beneath

myself=auto_rsa_gen.sh # tells the script who it is

export easy_rsa=../rsa_testing # tells the script where it is and exports this information for use in child processes

now=$(date +"%F")

##
# Show a list of available drives and ask the user for the dev he wants to mount
echo "These \n$(ls /dev | grep sd) \nare the drives available. Please tell me which one you want to mount \n(hint: its usually the one having just the  one additional entry. Like sdc1):"

# read user input (blkdev is the variable that will hold the user inuput for further processing)
read blkdev

##
# I. Mount
# check if de given device exists
if [ -b /dev/"$blkdev" ]
        then # if it exists mount it to /media
            sudo mount /dev/$blkdev /media
            echo "\nDevice $blkdev has been mounted!"
        else # if it doesn't exist
            echo "Device doesn't appear to exist! Restarting"
            sh "$myself" # restart the script
        fi

# Ask for an identifier to be used in the wrapper for easy-rsa cert creation
echo "\nPlease provide an identifier for the certs that will be created \n(The identifier will be appended to the current date of the machine):"

# read user input (ident is the variable that will hold the user input for further processing)
read ident

# Ask for ne number of certs to be created
echo "\nHow many certificates do you want me to create?"
# read user input (cnum is the variable that will hold the user input for further processing)
read cnum

##
# II. Wrapper for easy-rsa cert creation
#

# this is a while loop in case there was no input for ident. It only stop when the user hast put in something other than nothing
while [ -z $ident ]
    do
    echo "\nYou did not supply an identifier. Please do so or i will terminate."
    read ident # read user input again
done

# change directory to the easy-rsa directory
cd $easy_rsa

# tell user what you are going to do
echo "\nCreating $cnum certificates with ${now}_$ident."

# load vars file
. ./vars

##
# II.a Generation
# for loop that creates $cnum certificates and appends an incrementing number to the end of every
# file name

for i in $(seq -f %03g $cnum)
    do
        ${easy_rsa}/./build-batch ${now}_${ident}_$i

done

##
# II.b Copying
# for loop that searches for all certs created with this run and copies them to /media where $blkdev is mounted
find ${easy_rsa}/keys/ -name ${now}_${ident}*.crt -o -name ${now}_${ident}*.key > /media/${now}_${ident}
for f in $(find ${easy_rsa}/keys/ -name ${now}_${ident}*.crt -o -name ${now}_${ident}*.key )
    do
        cp $f /media

done
echo "\nCopied \n$(find ${easy_rsa}/keys/ -name ${now}_${ident}*.crt -o -name ${now}_${ident}*.key) \nto /media"

# unmounting $blkdev at /media
umount /media
echo "\nUmounted $blkdev at /media. Exiting! Bye!"ere


texts:
I have solved the LeetCode Remove Duplicates From Sorted Array problem:

  Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. It doesn't matter what you leave beyond the new length.

I was able to come up with a approach but only when I submitted this solution and got it accepted I found that my solution ranked somewhere around 60%, ranked by run-time. i.e) My solution was only faster that 40% of other contestants solution for the same language.

  int removeDuplicates(vector<int>& nums) {
    if (nums.size() == 0)
    {
        return 0;
    }
    auto start = nums.begin(), end = nums.end();
    int last_value = *(nums.end() - 1);
    for (auto it = nums.begin(); it != end;)
    {
        int find_value = *it;
        auto upper = upper_bound(start, end, find_value); //Find the last occurring index of this number
        iter_swap(start, it);
        ++start;
        if ((upper != end) || ((upper == end) && (find_value == last_value)))
        {
            it = upper;
        }
        else
        {
            ++it;
        }
    }
    return distance(nums.begin(), start);
}

Could you please suggest any performance improvements to this code. And also please go easy on the naming convention and code formatting. This was written for a programming challenge :)

Edit.

The worst case time complexity i believe is O(n Log n) which happens when the entire array is unique. And the best case run time should be O(log n) when the entire array contains duplicates.


texts: Get every information about the Reservation

texts:
I'm developing a plugin for Revit (a software to make 3D buildings).

The goal is simple to understand. When there is an intersection between a Wall and a Duct I create an object called Reservation at this location. I need to extract the Curve of the Ducts and the Faces of the Walls in order to calculate this intersection.

My algorithm is working fine and fast with a small building (3 Ducts, 10 Walls and 8 intersections) But when I want to launch it on a real project (around 10 000 Ducts) the code is way too slow due to many ForEach loops. Here is the sample which cause the issue:

foreach (Duct d in ducts)
            {
                Curve ductCurve = FindDuctCurve(d);
                curves.Add(ductCurve);

                foreach (Wall w in walls)
                {
                    wallFaces = FindWallFace(w);
                    foreach (Curve c in curves)
                    {
                        foreach (Face f in wallFaces)
                        {
                            foreach (KeyValuePair<XYZ, Wall> pair in FindInterWalls(c, f, walls))
                            {
                                Reservation.Res res = new Reservation.Res();
                                res.RoundCenter = new XYZ(Math.Round(pair.Key.X), Math.Round(pair.Key.Y), Math.Round(pair.Key.Z));
                                res.WallWidth = pair.Value.Width;
                                bool containsItemX = resList.Any(itemX => itemX.RoundCenter.DistanceTo(res.RoundCenter) < res.WallWidth + 1);

                                if (containsItemX == false)
                                {
                                    res.AssociatedWall = pair.Value;
                                    res.Radius = 1;
                                    res.AssociatedDuct = d;

                                    res.Center = pair.Key;
                                    resList.Add(res);
                                    model.Reservations.Add(new Reservation { ResList = resList });
                                }
                            }
                        }
                    }
                }
            }

The custom methods I'm using also contain loops. I wonder if a LINQ would be faster but I don't really know how to use it.

In a nutshell i want to get all the information about Reservations without loosing so much time stuck in so many foreach loops.

Here is my Reservation Class :

public sealed class Reservation
{

    public List<Res> ResList { get; set; }

    public class Res
    {
        public XYZ Center { get; set; }
        public XYZ RoundCenter { get; set; }
        public Duct AssociatedDuct { get; set; }
        public Wall AssociatedWall { get; set; }
        public double WallWidth { get; set; }
        public int Radius { get; set; }
    }

    public Reservation()
    {
        ResList = new List<Res>();

    }

}

A Curve is a right in the center of a Duct (each Duct contains one Curve). And a Face is a side of a Wall (each Wall contains 6 Faces)


texts:
This is my sample code to check if a given pair of strings are anagram or not.

      static bool AreAnagram(string s1, string s2)
      {

        if (s1.Length != s2.Length)
            return false;

        foreach (char c in s1)
        {
            int ix = s2.IndexOf(c);

            if (ix == -1)
                return false;
        }

        return true;
    }

The complexity of this approach is \$O(n)\$.

What boundary conditions am I missing? Can it be made better?