texts:
I would like to make (or improve my function) a function that returns an array of integers containing all the prime numbers from 2...n that can execute as quickly and efficiently as possible (ideally so that it will be able to execute n = 1,000,000,000 in a matter of seconds). I am using Swift 4.1 and Xcode 9.3.

Where I'm currently at

So far, I've used the Sieve of Eratosthenes to make this function that can calculate prime numbers under 1,000,000 in 0.28s, but when I try it with a number like 1 billion or 1 trillion, it takes too long.

func generatePrimes(to n: Int) -> [Int] {

    precondition(n > 5, "Input must be greater than 5")

    var arr : [Int] = Array<Int>(stride(from: 3, to: n, by: 2))

    for index in 0... {
        let num : Int = arr.remove(at: index)
        arr = arr.filter{ $0 % num != 0 }
        arr.insert(num, at: index)
        if arr[index + 1] >= Int(floor(sqrtf(Float(n)))) { break }
    }

    arr.insert(2, at: 0)

    //Print Statements
    print("Prime numbers under \(n):")
    _ = arr.enumerated().map { (index, element) in print("\t\(index + 1). \(element)") }

    return arr
}

Usage:

generatePrimes(to: 50)

Prints:

Prime numbers under 50:
    1. 2
    2. 3
    3. 5
    4. 7
    5. 11
    6. 13
    7. 17
    8. 19
    9. 23
    10. 29
    11. 31
    12. 37
    13. 41
    14. 43
    15. 47


texts:
This code takes the position of your mouse cursor, and it creates circles where the cursor is.

 strokeWeight(3);
 stroke(24, 0, 0);
 fill(245, 0, 0);
 background(255, 255, 255);
    draw = function() {
        ellipse(mouseX, mouseY, 30, 30)
    };

I would like to know:

If there is a way to shorten this code, but still keep it readable.
Or any suggestions to make it better.

You can see a live demo here.


texts:
In Dice Poker (or Yacht), a player rolls 5 standard dice (sides 1 - 6) and the resulting roll is given a score based on combinations:

Two matching dice only - pair
Three matching dice only - three
Four matching dice only - four
Five matching dice - yacht
two pairs, full house, small straight, large straight, you get the idea

A player rolls the dice and the input is in a space-delimited format e.g.

3 6 5 6 1 - pair
1 6 6 1 6 - full-house
2 4 3 5 1 - small-straight

I'm reading these results from column A on Sheet1 (we'll say). I'm not convinced I'm checking the hands for results very effectively. It works, but it seems incoherent.

First I have an Enum of the results as well as a function for getting the name of the result -

Option Explicit
Private Enum Combination
    none
    pair
    three
    four
    Yacht
    twopair
    fullhouse
    smallstraight
    bigstraight
End Enum

Private Function GetEnum(ByVal value As Combination) As String
    Select Case value
        Case 0
            GetEnum = "none"
        Case 1
            GetEnum = "pair"
        Case 2
            GetEnum = "three"
        Case 3
            GetEnum = "four"
        Case 4
            GetEnum = "yacht"
        Case 5
            GetEnum = "two-pairs"
        Case 6
            GetEnum = "full-house"
        Case 7
            GetEnum = "small-straight"
        Case 8
            GetEnum = "big-straight"
    End Select
End Function

The meat of it is here:

Sub YachtHands()
    Dim lastRow As Long
    Dim dice As Variant
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    Dim index As Long
    Dim result As String
    For index = 1 To lastRow
        dice = Split(Sheet1.Cells(index, 1), " ")
        result = result & EvaluateHand(dice)
    Next
    Debug.Print Trim$(result)
End Sub

Private Function EvaluateHand(ByVal dice As Variant) As String
    Dim score As Combination
    Dim bucket() As Long
    Dim threeFlag As Boolean
    Dim twoFlag As Boolean
    ReDim bucket(1 To 6)
    Dim i As Long
    For i = LBound(dice) To UBound(dice)
        bucket(dice(i)) = bucket(dice(i)) + 1
    Next
    For i = LBound(bucket) To UBound(bucket)
        If bucket(i) > 3 Then
            score = bucket(i) - 1
            GoTo Eval
        End If
        If bucket(i) = 3 Then
            If twoFlag Then
                score = fullhouse
                GoTo Eval
            Else
            threeFlag = True
            End If
        End If
        If bucket(i) = 2 Then
            If threeFlag Then
                score = fullhouse
                GoTo Eval
            ElseIf twoFlag Then
                score = twopair
                GoTo Eval
            Else
                twoFlag = True
            End If
        End If
    Next
    If threeFlag Then
        score = three
        GoTo Eval
    End If
    If twoFlag Then
        score = pair
        GoTo Eval
    End If
    score = CheckStraight(bucket)
Eval:
    EvaluateHand = GetEnum(score) & " "
End Function

Private Function CheckStraight(ByVal bucket As Variant) As Combination
    If bucket(1) = 1 And bucket(2) = 1 And bucket(3) = 1 And bucket(4) = 1 And bucket(5) = 1 Then CheckStraight = smallstraight
    If bucket(2) = 1 And bucket(3) = 1 And bucket(4) = 1 And bucket(5) = 1 And bucket(6) = 1 Then CheckStraight = bigstraight
End Function

I think my straight checking function is sort of ridiculous. My main evaluation also uses a lot of GoTo which in general should be avoided. It also suffers some arrow-code. I think this all stems from whatever algorithm I'm using.


texts:
I need to do pending methods invocation in Java (Android) in my game project. A method represents actions in a scene.

Maybe you're familiar with Context.startActivity in Android, which is not suddenly starting the activity, but statements below it is still executed before starting the requested activity. I've found 3 ways, but I'm not sure which one should I choose by considering the performance and PermGen issues (actually I don't know whether Android has PermGen issue if there are so many classes). These methods will not be called very frequent, may be once in 5 seconds, but may be they will be very many (there are so many scenes).

Please suggest the best way of doing this, by considering memory usage (maybe PermGen too), performance, ease of coding, and bug freedom.

Using switch-case

I need to add each method call in switch-case.

public class MethodContainer {

    public void invoke(int index) {
        switch (index) {
        case 0:
            method0();
            break;
        .
        .
        .
        case 100:
            method100();
            break;
        }
    }

    private void method0() {
        ...
    }

    .
    .
    .

    private void method100() {
        ...
    }
}

Using for-loop and annotation/reflection

Like the above, but make coding easier (except in defining constants).

public class MethodContainer {

    private static final int METHOD_0 = 0;
    ...
    private static final int METHOD_100 = 100;

    public void invoke(int index) {
        for (Method m : MethodContainer.class.getMethods()) {
            MyAnnotation annotation = m.getAnnotation(MyAnnotation.class);
            if (annotation != null && annotation.value() == index) {
                try {
                    m.invoke(this);
                    break;
                } catch (...) {
                    ...
                }
            }
        }
    }

    @MyAnnotation(METHOD_0)
    private void method0() {
        ...
    }

    .
    .
    .

    @MyAnnotation(METHOD_100)
    private void method100() {
        ...
    }
}

Using inner classes

There's no need to declare constants and no reflection, but too many classes.

public class MethodContainer {

    public void invoke(Runnable method) {
        method.run();
    }

    private Runnable method0 = new Runnable() {

        public void run() {
            ...
        }
    };

    .
    .
    .

    private Runnable method100 = new Runnable() {

        public void run() {
            ...
        }
    };
}


texts: Taking a list and using it to build columns

texts:
Say I have [1, 2, 3, 4, 5, 6, 7, 8, 9] and I want to spread it across - at most - 4 columns. The end result would be: [[1, 2, 3], [4, 5], [6, 7], [8, 9]]. So I made this:

item_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
item_count = len(item_list)
column_count = item_count if item_count <= 4 else 4
items_per_column = int(item_count / 4)
extra_items = item_count % 4

item_columns = []

for group in range(column_count):
    count = items_per_column
    if group < extra_items:
        count += 1

    item_columns.append(item_list[:count])
    item_list = item_list[count:]

Is there a nicer way of accomplishing this?


texts: Correct implementation of the factory pattern in php

texts:
All, during my vacation I am trying to learn myself the basic principles of OOP and the factory pattern in php. I read a lot of tutorials and websites (e.g. http://www.phptherightway.com) and began to write some classes.

Is the underlying implementation correct?

Additional information:
I have set up a singleton class for my MysqlConnection. Furthermore I created a MysqlQuery class to handle the queries to the database.

Thanks for the advice!

Factory class

This is the factory class with the different CRUD-operations and the queries for the database

class OrganisationFactory
{
    public function getOrganisations()
    {
        $r = [];
        $q = new MysqlQuery("SELECT ID, Name, Created FROM organisations;", [0], MysqlConnect::get('core'));
        $q->select('', []);
        foreach($q->getResult() as $r)
        {
            $r[] = new Organisation($q['ID'], $q['Name'], $q['Created']);
        }
        return $r;
    }

    public function getOrganisation($ID)
    {
        $r = 0;
        $q = new MysqlQuery("SELECT ID, Name, Created FROM organisations WHERE ID = ?;", [0], MysqlConnect::get('core'));
        $q->select('i', [$ID]);
        foreach($q->getResult() as $r)
        {
            $r = new Organisation($q['ID'], $q['Name'], $q['Created']);
        }
        return $r;
    }

    public function createOrganisation($obj)
    {
        /* @var $obj Organisation */
        $q = new mysqlQuery('INSERT INTO organisations (Name, Created) VALUES (?, ?);', [0], mysqlConnect::get('core'));
        $q->insert('ss', [$obj->getName(), $obj->getCreated()]);
        $obj->setID($q->getResult());
        return $obj;
    }

    public function updateOrganisation($obj)
    {
        /* @var $obj Organisation */
        $q = new mysqlQuery('UPDATE organisations SET Name = ?, Created = ? WHERE ID = ?;', [0], mysqlConnect::get('core'));
        $q->update('ssi', [$obj->getName(), $obj->getCreated(), $obj->getID()]);
        return $obj;
    }

    public function deleteOrganisation($obj)
    {
        /* @var $obj Organisation */
        $q = new mysqlQuery('DELETE FROM organisations WHERE ID = ?;', [0], mysqlConnect::get('core'));
        $q->delete('i', [$obj->getID()]);
        return $obj;
    }
}

Base Class

This is the base class of the object including the variables, constructor and the getters and setters

class Organisation
{
    //variablen
    private $_ID = 0;
    private $_Name = '';
    private $_Created = '';

    //constructor
    function __construct($ID, $Name, $Created) {
        $this->_ID = $ID;
        $this->_Name = $Name;
        $this->_Created = $Created;
    }

    //getter & setters
    public function getID() { return $this->_ID; }
    public function setID($ID) { $this->_ID = $ID; }

    public function getName() { return $this->_Name; }
    public function setName($Name) { $this->_Name = $Name; }

    public function getCreated() { return $this->_Created; }
    public function setCreated($Created) { $this->_Created = $Created; }
}


texts:
I'm learning Clojure, and decided to write a Conway's Game of Life clone as my starting project. I ended up dicking around for a bit before diving in, and came up with a few functions that I'd like looked over. Mainly, I'm concerned about writing them more concisely and idiomatically.

I'm planning on using a 1D vector to represent a 2D field. The typical equation to get the index of a vector corresponding to an (x,y) coordinate is y * width + x. Here are my first attempts:

; A 2D point representing a coordinate, or any pair of numbers
(defrecord Point [x y])

; Represents the Game of Life world.
; cells is a vector representing a 2D matrix of cells
; dims is the dimensions of the world as a Point
(defrecord Enviro [cells dims])

(defn index-of [width x y]
  (+ (* y width) x))

(defn enviro-index-of [enviro x y]
  (let [width (:x (:dims enviro))]
    (index-of width x y)))

(defn enviro-index-of-2 [enviro x y]
  (let [width (-> enviro :dims :x)]
    (index-of width x y)))

index-of is straight forward. My issue is the 2 convenience functions to get an index by supplying the Enviro instead of the width directly. I tried deconstructing the record directly in the argument list, but it complained that it didn't recognize the keyword record keys. The work-around was to just "navigate" the records manually, and bind "width" in a let. My first attempt was kind of naïve; using the accessor functions to get the Enviro, then the dimensions Point. Then I remembered the thread macro! For my second attempt, I used -> to find the width. It seems to be much cleaner, but is this as idiomatic as it gets?

Next, I decided to try writing a function that returns a vector containing all the points surrounding a given point. I can then check the cell at each neighboring point to see whether or not the center point should be dead or alive:

(defn generate-neighbor-points
  ([cx cy r]
   (let [start-x (- cx r)
         end-x (+ cx r 1) ; Adding 1 so it's inclusive
         start-y (- cy r)
         end-y (+ cy r 1)]
     (for [y (range start-y end-y)
           x (range start-x end-x)
           :when (and (not= x cx) (not= y cy))] ; Should actually be `or` instead of `and`
       (Point. x y))))

  ([center-point r]
   (let [cx (:x center-point)
         cy (:y center-point)]
     (generate-neighbor-points cx cy r))))

There's a couple things that I'm not happy about here:

The fact that this generates a list of cells, just so it can be checked. I might see if I can just make this a higher-order function that takes a callback that's executed on each Point surrounding the cell. That might be thinking too javascript-y though.
The fact that this requires the creation of 2 "range"s, which are really full lists. This seems to be the best way of "iterating" a range of numbers and returning a list. I'm open for suggestions on how to make this more efficient and idiomatic though.


texts: Using a thread to update a table automatically in Django

texts:
For my portfolio app using Django I made a thread that pulls out the usd exchange rates for various currencies every 6 hours and updates the database. The program kicks in as soon as the module module_stock.py is being imported.

Other than to make  the thread to start in a function call, should I be aware of any disadvantages if this runs in production environment for days, weeks on end? Or in other words is it ok to have this thread running at all time ?

Relevant pieces of code below.

module_stock.py:

import threading

UPDATE_INTERVAL = 21600

class WorldTradingData:
    ''' methods to handle trading data
        website: https://www.worldtradingdata.com
    '''
    @classmethod
    def setup(cls,):
        cls.api_token = config('API_token')
        cls.stock_url = 'https://api.worldtradingdata.com/api/v1/stock'
        cls.intraday_url = 'https://intraday.worldtradingdata.com/api/v1/intraday'
        cls.history_url = 'https://api.worldtradingdata.com/api/v1/history'
        cls.forex_url = 'https://api.worldtradingdata.com/api/v1/forex'

    @classmethod
    def update_currencies(cls):
        base_currency = 'USD'
        url = ''.join([cls.forex_url,
                       '?base=' + base_currency,
                       '&api_token=' + cls.api_token,
                       ])
        try:
            res = requests.get(url)
            forex_dict = json.loads(res.content).get('data', {})

        except requests.exceptions.ConnectionError:
            forex_dict = {}
            logger.info(f'connection error: {url}')

        for cur in Currency.objects.all().order_by('currency'):
            currency_key = cur.currency
            currency_object = Currency.objects.get(currency=currency_key)
            usd_exchange_rate = forex_dict.get(currency_key, '')

            if usd_exchange_rate:
                currency_object.usd_exchange_rate = usd_exchange_rate
                currency_object.save()

def update_currencies_at_interval(interval=UPDATE_INTERVAL):
    '''  update the currency depending on interval in seconds
         default value is 6 hours (21600 seconds)
    '''
    assert isinstance(interval, int), f'check interval setting {interval} must be an integer'

    wtd = WorldTradingData()
    wtd.setup()
    start_time = time.time()
    current_time = start_time
    elapsed_time = int(current_time - start_time)

    while True:
        if elapsed_time % interval == 0:
            wtd.update_currencies()

        current_time = time.time()
        elapsed_time = int(current_time - start_time)

thread_update_currencies = threading.Thread(
    target=update_currencies_at_interval, kwargs={'interval': UPDATE_INTERVAL})
thread_update_currencies.start()

models.py:

from django.db import models

class Currency(models.Model):
    currency = models.CharField(max_length=3, unique=True)
    usd_exchange_rate = models.CharField(max_length=20, default='1.0')

    def __str__(self):
        return self.currency
```


texts:
I made a little JavaScript app here that let people generate bitmap for generating characters. Currently it generate code of a dictionary. But I want to also generate a example that let them play like the Arduino samples, use it as starting point or use it as-is.

This is the code I wrote to enable someone to use 7-segment displays

I want some feedback on the code itself also things like suggestions for variable and function names, order of things, aesthetics etc...

//common cathode turns on with HIGH, and common anode turns on with LOW
const bool LED_P HIGH

const uint8_t myDisplayPins[8] = {3, 4, 5, 6, 7, 8, 9, 10}; //dp A B C D E F G

byte font[] = {
    B1111110,   // [0] => "0"
    B0110000,   // [1] => "1"
    B1101101,   // [2] => "2"
    B1111001,   // [3] => "3"
    B0110011,   // [4] => "4"
    B1011011,   // [5] => "5"
    B1011111,   // [6] => "6"
    B1110000,   // [7] => "7"
    B1111111,   // [8] => "8"
    B1111011,   // [9] => "9"
    B1110111,   // [10] => "A"
    B0000001,   // [11] => "dash"
};

void setup(){
    display7Setup(myDisplayPins); //configure myDisplayPins as outputs
}

void loop(){

  display7(myDisplayPins, font[0]); //display "0"
  delay(1000);
  display7(myDisplayPins, font[9]); //display "A"
  delay(1000);
  display7(myDisplayPins, font[11]); //display "-"
  delay(1000);
  display7(myDisplayPins, B00000000); //turn all segments OFF
  delay(1000);

  //count 0 to 9
  for(int i=0; i<=9; i++){
    display7(myDisplayPins, font[i]);
    delay(1000);
  }

}

/* Configure pins as outputs */
void display7Setup(const uint8_t displayPins[]){
  for(uint8_t i=0; i<8; ++i){
    pinMode(displayPins[i], OUTPUT);
  }
}

/* Function that writes a bitmap to a 7-segment display */
void display7(const uint8_t displayPins[], byte bitmap){
  for(uint8_t i=0; i<8; ++i){
    byte segment = bitmap & (0x1<<i); //apply a mask to select just the desired segment bit
    bool state = segment>>i;          //shift the bit to LSF (rightmost) to get a boolean value 0x1 or 0x0
    if(!LEDP) state = !state;         //invert level for common anode
    digitalWrite(displayPins[i], state);
  }
}


texts:
This is a classic problem with a classic solution and I've seen it a number of times on this site, but I wanted to know what people thought of this C# implementation, as opposed to the numerous C implementations.

Below you'll find the source code, the output of the code and then a link to repl.it, so you can run the code in your browser.

Source code

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass {
    // An array of valid words. Would normally contain way more words.
    private static string[] dictArray = new string[] {
        "trainee",
        "train"
    };

    public static void Main (string[] args) {
        Node dictTrie = CreateDictTrie(dictArray);
        Console.WriteLine(IsWord("Train", dictTrie)); // True
        Console.WriteLine(IsWord("Traine", dictTrie)); // False
        Console.WriteLine(IsWord("Trainee", dictTrie)); // True
    }

    // Create the trie to use for spell checking, based on an array of valid words.
    private static Node CreateDictTrie(string[] dictArray) {
        Node root = new Node();
        for (int i = 0; i < dictArray.Length; i++) {
            string word = dictArray[i];
            Node node = root;
            for (int j = 0; j < word.Length; j++) {
                char character = word[j];
                if (!node.Children.ContainsKey(character)) {
                    node.Children[character] = new Node();
                }
                node = node.Children[character];
            }
            node.IsWord = true;

        }
        return root;
    }

    // Check whether a string is a valid word.
    private static bool IsWord(string word, Node dictTrie) {
        word = word.ToLower();
        Node node = dictTrie;
        for (int i = 0; i < word.Length; i++) {
            char character = word[i];
            if (!node.Children.ContainsKey(character)) {
                return false;
            }
            node = node.Children[character];
        }
        return node.IsWord;
    }
}

// Class used for the trie structure.
public class Node {
    public bool IsWord;
    public Dictionary<char, Node> Children { get; set; }

    public Node() {
        Children = new Dictionary<char, Node>();
    }
}

Output

True
False
True

Repl.it link

https://repl.it/EOlt/14

I tried to make the code pretty readable, so if you wanted to really optimize the code, you could probably remove a few of the variable declarations and so on. But other than that, are there any overall performance problems with my approach? Anything else you think I could have done better? Feedback is much appreciated. Thanks!

Edit: I updated the code to use arrays and for loops instead of Lists and foreach loops, which should improve the performance a bit.


texts:
I'm testing Python 3 code to perform a Monte Carlo simulation based on the result of an statistical test.

I currently have the result of the statistical test in a pandas dataframe, like this.

Dataframe A
+-----+-------+
| id  | f_res |
+-----+-------+
|   1 | 4.22  |
|   2 | 5.25  |
|   3 | 3.3   |
|   4 | 2.5   |
|   5 | 1.9   |
|   6 | 9.3   |
+-----+-------+

So my idea is; for each row in f_res, pass that value to a function and extract multiple values from a Noncentral chi-squared distribution, ask how many of this extracted values are greater than the original and divide this by the total of values analyzed.

I'm working with numpy to generate the array of values, and I have this working code.

import numpy as np
import pandas as pd

total_sample = 100

def monte_carlo(x, tot_sample):
    gen_dist = np.random.noncentral_chisquare(df=1, nonc=x, size=tot_sample)
    compare = gen_dist > x
    return np.divide(np.sum(compare), tot_sample)

df = pd.DataFrame(np.random.randint(0,10, 625527), columns=[['A']])
b = np.array(df.values)
g = np.vectorize(monte_carlo)

x = g(b, total_sample)

I know that the use of np.vectorize is not good for speed, because behind curtains is a for loop, but currently I don't understand another method for applying a function element wise in numpy.

Currently analyzing a dataframe of 625.000 items and with a total sample of 100, it takes approx 20 s. line_profiler shows the following.

Total time: 19.909 s
File: test3.py
Function: test at line 6

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     6                                           @profile
     7                                           def monte_carlo(x, tot_sample):
     8    625528     33866564     54.1     58.2      gen_dist = np.random.noncentral_chisquare(df=1, nonc=x, size=tot_sample)
     9    625528      4621263      7.4      7.9      compare = gen_dist > x
    10    625528     19704575     31.5     33.9      return np.divide(np.sum(compare), tot_sample)

So, using numpy or pandas or both, is there any way I could improve this
in execution time and syntax?

The final idea is to return a numpy array with the simulated p-values to append it to the original dataframe.


texts: Task.Finally extension, good, bad, or ugly?

texts:
I wrote this, and it has helped to avoid the 'Some exception weren't handled' problem. Is there something glaringly wrong with this that I might have missed?

    /// <summary>
    /// Handles any exceptions on this task, and executes action on specified scheduler.
    /// </summary>
    /// <param name="task">The task.</param>
    /// <param name="exceptionHandler">The exception handler.</param>
    /// <param name="finalAction">The final action.</param>
    /// <param name="scheduler">The scheduler.</param>
    public static void Finally(this Task task, Action<Exception> exceptionHandler,
                                               Action finalAction, TaskScheduler scheduler)
    {
        task.ContinueWith(t =>
        {
            if(finalAction != null) finalAction();

            if(t.IsCanceled || !t.IsFaulted || exceptionHandler == null) return;
            var innerException = t.Exception.Flatten().InnerExceptions.FirstOrDefault();
            exceptionHandler(innerException ?? t.Exception);
        }, scheduler);
    }


texts: Eliminating repetitions of subsequent items in a list

texts:
I would like to convert a list A
A = {1, 12, 3, 3, 3, 8, 5, 5 }

into list B
B = {1, 12, 3, 8, 5 }

As you see, items 3 and 5 are repeated in A, and those repetitions are eliminated in B.
The code I've created to do that is the following:
public IEnumerable<int> FilterRepeatingElements(IEnumerable<int> source)
{
    return source
        .Select(x => (IEnumerable<int>)new[] { x })
        .Aggregate((a, b) => a.Last() != b.First() ? a.Concat(b) : a);
}

It works, but I wonder if there's a better more expressive way to do it using "LINQ", either with the classic .NET methods or the ones in a library like morelinq.
Thanks!
EDIT
I have found out that my solution has problem with uses case like this:
FilterRepeatingElements(MoreEnumerable.Random()).Take(10)

MoreEnumerable.Random() generates an infinite sequence.
Executing code like this, hangs the execution.


texts: Choose the right type for method GetById

texts:
I designed my repository class and I need some advice from you. Now I have a method GetByID that returns a generic type:

 public T GetById(object id)
 {
    return this.Entities.Find(id);
 }

I'm going to use OData to filter data, and for that (when I'm using $expand for single row) I need to do something like this:

SingleResult.Create(repository.GetByID(id));

But of course I received an error because SingleResult needs a type IQueryable<T>.

So, I decided to change my GetByID to:

public IQueryable<T> GetById(object id)
{
    return this.Entities.FirstOrDefault(p => p.ID == (int)id);
}

Could you please tell me if is it the right way? What type should be returned from GetByID?

I prefer to use T GetById because it is more correct in my opinion, but I don't know.


texts: Python program to calculate the sun angle

texts:
Given a string representing the hour and minute, where: 00:00 <= time <= 23:59, the program should output the number of angles the sun is above the horizon.

When time is "06:00" the sun angles are 0º
At "12:00" the sun is at 90º
At "18:00" the sun goes to 180º
After "18:00" and before "06:00" the program should output "I don't see the sun!"

Examples:

sun_angle("07:00") == 15
sun_angle("01:23") == "I don't see the sun!"
sun_angle("12:15") == 93.75

The code:

import datetime as dt

def check_you_dont_see_sun(time_dt, end_dt, start_dt):
    return ((time_dt > start_dt and time_dt < end_dt)
    or (time_dt > start_dt or time_dt < end_dt))

def calculate_sun_angle(time_dt, end_dt):
    difference = time_dt - end_dt
    hours_of_difference = (difference.seconds / 60) / 60
    angle_increase_each_hour = 15
    return hours_of_difference * angle_increase_each_hour

def sun_angle(time):

    start_dt = dt.datetime.strptime('18:00', '%H:%M')
    end_dt = dt.datetime.strptime('06:00', '%H:%M')
    time_dt = dt.datetime.strptime(time, '%H:%M')

    if check_you_dont_see_sun(time_dt,end_dt,start_dt):
        return "I don't see the sun!"
    else:
        return calculate_sun_angle(time_dt, end_dt)

What could we improve?


texts: Using Parent and Child in PyQt and Python

texts:
I've been searching the internet and cannot find a proper answer as when one should user "Parent" and "Child". I see these two used all over, I have not used them myself in my programs, and now I'm wondering if I have missed something in creating my software. I am wondering why and when should they be used. I've only gathered that they should be used when one class controls another. Only thing I have done in that sense is call another class/window, from a class. Example below.

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.doSomething

class Child(QtWidgets.QWidget)
    def __init__(self, Parent)
        super(Child, self).__init__(Parent)

        self.doSomething


texts:
I came up with this recursive pure-Python implementation of De Casteljau's algorithm for computing points on a Bézier curve:

def bezier_curve(control_points, number_of_curve_points):
    return [
        bezier_point(control_points, t)
        for t in (
            i / (number_of_curve_points - 1) for i in range(number_of_curve_points)
        )
    ]

def bezier_point(control_points, t):
    if len(control_points) == 1:
        result, = control_points
        return result
    control_linestring = zip(control_points[:-1], control_points[1:])
    return bezier_point([(1 - t) * p1 + t * p2 for p1, p2 in control_linestring], t)

Assumptions about control_points

The elements of control_points represent the control points of the Bézier curve. They must be of the same type of mutually compatible types fulfilling the following rules:

points shall all be of the same dimension.
Multiplying a point by a scalar shall result in a point of the same
dimension and with a value according to vector-scalar multiplication
(i.e., multiply each of the point's Cartesian coordinates with the scalar)
Adding two points shall result in a point of the same dimension and
with a value according to vector addition (i.e., component-wise
addition of the points' Cartesian coordinates)

Some examples that work as control_points:

list of turtle.Vec2D
list of complex
list of numpy.array with shape (2,)
numpy.array with shape (n, 2), where n is the number of control points

(tuples instead of lists work, too. Probably any sequencey container will work.)

Why pure Python?

Because I want this to be usable in a QGIS plugin, but SciPy, NumPy, etc. (usually) aren't available to QGIS plugins. As I'm unsure which Python libraries are available in QGIS (and the answer to that seems to be platform-dependent), I'd like to avoid external libraries (those that would have to be installed with pip or one of its alternatives) completely.

Using standard library functions should be fine, so if any part of the implementation could benefit from them, please point that out.

What I'd like to know in this review

Could / should the readability and comprehensibility of this implementation be improved?
Did I go foul of any performance (computation speed, memory usage, etc.) no gos? (It doesn't need to be super-fast, but it shouldn't be unnecessarily slow if I can avoid it.)

Performance for low degrees (e.g., degree 2, i.e. cubic Bézier with three control points per curve) will probably be more relevant than performance at high degrees (many control points per curve)
Performance for large outputs (large number_of_curve_points) might be relevant

About the destructuring assignment result, = control_points to unpack the single point while at the same time making sure it really is exactly one point

Is this idiomatic in Python (i.e. "pythonic")?
Is this readable and comprehensible enough or too obscure?
Is there any good alternative that's an expression, i.e. that could be used directly in the return statement without going through an assignment? (control_points[0] is an expression but doesn't fail when there's more than one element in control_points.)


texts: Typesetting A* in LaTeX using algorithm2e

texts:
(See the next iteration.)

The result looks like

and my code is:

\documentclass[10pt]{article}

\usepackage{amsmath}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}

\begin{document}

  \begin{algorithm}
    \SetKw{Nil}{nil}
    \SetKw{Is}{is}
    \SetKw{Not}{not}
    \SetKw{Mapped}{mapped}
    \SetKw{In}{in}
    \SetKw{ChildNode}{child node}
    \SetKw{Of}{of}
    \SetKw{Continue}{continue}
    $\text{OPEN} = \{ s \}$ \\
    $\text{CLOSED} = \emptyset$ \\
    $\pi = \{ (s \mapsto$ \Nil $)\}$ \\
    $g = \{ (s \mapsto 0) \}$ \\
    \While{$|\text{OPEN}| > 0$}{
      $u = \textsc{ExtractMinimum}(\text{OPEN})$ \\
      \If{$u$ \Is $t$}{
        \KwRet \textsc{TracebackPath}$(u, \pi)$ \\
      }
      $\text{CLOSED} = \text{CLOSED} \cup \{ u \}$ \\
      \ForEach{\ChildNode $v$ \Of $u$}{
        \If{$v \in \textsc{CLOSED}$}{
          \Continue \\
        }
        $c = g(u) + w(u, v)$ \\
        \If{$v$ \Is \Not \Mapped \In $g$}{
          $g(v) = c$ \\
          $\pi(v) = u$ \\
          \textsc{Insert}$(\text{OPEN}, v, c + h(v))$ \\
        }
        \ElseIf{$g(v) > c$}{
          $g(v) = c$ \\
          $\pi(v) = u$ \\
          \textsc{DecreaseKey}$(\text{OPEN}, v, c + h(v))$ \\
        }
      }
    }
    \KwRet $\langle \rangle$
    \caption{\textsc{AStarPathFinder}$(s, t, w, h)$}
  \end{algorithm}

  \begin{algorithm}
    \SetKw{Is}{is}
    \SetKw{Not}{not}
    \SetKw{Nil}{nil}
    $p = \langle \rangle$ \\
    \While{$u$ \Is \Not \Nil}{
      $p = u \circ p$ \\
      $u = \pi(u)$ \\
    }
    \KwRet $p$
  \caption{\textsc{TracebackPath}$(u, \pi)$}
  \end{algorithm}

\end{document}

Can I make my code better? For example, is there a way to defined custom keywords in a "global scope" so that I don't have to repeat myself?


texts:
I am creating a search filter using jQuery and implementing Array.prototype.filter().

What I have done is that I call the $("#dataList tr:first-child ~ tr").remove(); every time the user .keyup() on the input field. I would like to know if there will be a performance issue and also if there is any alternative workaround for this.

I am open for any feedback and suggestion on how I can enhance my code.

var arrayList = [
  { name: "Caty", data: 'Cat' },
  { name: "Doggy", data: 'Dog' },
  { name: "Fishy", data: 'Fish' },
  { name: "Piggy", data: 'Pig' }];

$("#search").keyup((e)=>{
  $("#dataList tr:first-child ~ tr").remove();
  if(e.key != "Backspace"){
    filterItem = $("#search").val().toLocaleLowerCase();
  }else{
    filterItem = "";
  }

  var filter = arrayList.filter(array => array.name.toLocaleLowerCase().indexOf(filterItem) !== -1);
  doFilter(filter);
});

doFilter(arrayList);
function doFilter(data){
  $.each(data, function( key, value ) {
    $("#dataList tr:last-child").after("
"+value.data+"	"+value.name+"
");
  });
}

html,body{
  margin:5px 20px;
  font-family: arial;
}

table{
  color:white;
  text-align:center;
}

table, td{
  margin:0;
  padding:0;
  width:200px;
}

th{
  background:#2c3e50;
  padding:5px 0px;
}

td{
  background:#2980b9;
  padding:5px 0px;
}

Search: <input id="search" type="text">

    Owner
    Pet


texts: Print the string equivalents of a phone number

texts:
Task

Old mobile phones had the ability to type characters by pressing a number. The letter a could be typed by pressing 2 once. The letter b could be typed by pressing 2 twice.

Given a sequence of numbers, give all possible letter combinations.

For example: The number 23 could give an output ad, ae, af, bd, be, bf, cd, ce, cf

My recursive solution to this problem is given below.

def num_to_char(value):
    if value == 2: return ["a","b","c"]
    if value == 3: return ["d","e","f"]
    if value == 4: return ["g","h","i"]
    if value == 5: return ["j","k","l"]
    if value == 6: return ["m","n","o"]
    if value == 7: return ["p","q","r","s"]
    if value == 8: return ["t","u","v"]
    if value == 9: return ["w","x","y","z"]

def convert_num(number, current_string = ""):
    if number == []:
        print(current_string)
        return
    get_list = num_to_char(int(number[0]))
    for character in get_list:
        current_string += character
        convert_num(number[1:], current_string)
        current_string = current_string[:-1]

num_to_covert = list("234")
convert_num(num_to_covert)


texts: Web API controller to get details of a travel plan or a leave request

texts:
My web API has 3 controllers for get, post and users CRUD. I named it as DetailsControllor, FormControllor and AuthControllor. In the details controllor, I used a switch case to find out which type of details needed, but I found that code is repeated in switch case. Can I use generics to minimize code or is there any other way to carry out these things?

 [HttpPost]
    [Route("details/{id}")]
    public async Task<HttpResponseMessage> GetDetails(string id)
    {

        try
        {
            var content = Request.Content.ReadAsStringAsync().Result;
            HttpResponseMessage response = Request.CreateResponse();
            switch (id)
            {
                case "leave":
                    RequestBase LeaveInput = jsonSerializer.Deserialize<RequestBase>(content);
                    Task<LeaveForm> LeaveOutput = repo.GetLeaveRequest(LeaveInput);
                    response.Content = new ObjectContent(typeof(object), LeaveOutput, jsonFormatter);
                    break;

                case "travel":
                    RequestBase travelInput = jsonSerializer.Deserialize<RequestBase>(content);
                    Task<BaseTravel> travelOutput = repo.GetTravel(travelInput);
                    response.Content = new ObjectContent(typeof(object), travelOutput, jsonFormatter);
                    break;

            }
            return response;
        }
        catch (Exception e)
        {

             HttpResponseMessage responseToClient = Request.CreateResponse((HttpStatusCode)422);
             responseToClient.Content = new StringContent(e.message, Encoding.Unicode);
         throw new HttpResponseException(responseToClient);
        }
    }


texts: Simplify Oracle SQL: Treat null date as 'N' and non-null date as 'Y'

texts:
This works, but nvl AND case seem redundant.
Basically, if null then 'N' else 'Y.

CHICKEN_HATCH_DATE is a DATE data type.

  select  stricken_chicken_id,
          case nvl(to_char(chicken_hatch_date),'N')
          when 'N' then 'N'
          else 'Y'
          end chicken_hatch_date
   from   stricken_chicken;


texts: Simple tkinter application that choose a random string

texts:
I am really new to programming, and I made this simple tkinter app in
python. Please tell me what can be improved and how to use classes
correctly in combination with tkinter.

Github to clone if you want

#!/usr/bin/env python

# ---------------------------------
# @author: apoc
# @version: 0.1
# ---------------------------------

# importing
from tkinter import *
import csv
from random import randint

class LRG(object):

    def __init__(self,master):

        # variables
        with open('data/champs.csv','r') as f:
            reader = csv.reader(f)
            self.champ_list = list(reader)

        # layout
        self.randombutton = Button(master,text='Random',command=self.scan)
        self.infofield = Text(master,height=20,width=50)

        # layout
        self.randombutton.grid(row=0,column=1,sticky=E,pady=2,padx=5)
        self.infofield.grid(row=1,columnspan=4,sticky=W,column=0,pady=4)

    def scan(self):

        self.infofield.delete('1.0',END)
        self.infofield.insert(END,self.champ_list[
            randint(0,len(self.champ_list))
            ])

if __name__ == "__main__":
    master = Tk()
    LRG(master)
    master.title("LRG")
    master.mainloop()


texts: Extension method to get results of type T from a cache

texts:
Are there issues of any kind with this extension method?

using System;
using System.Web;

namespace AccountingBackupWeb.CacheExtensions
{
    public static class Extensions
    {
        public static T Get<T>(this System.Web.Caching.Cache cache, string key, Func<T> f) where T : class
        {
            T results = HttpContext.Current.Cache[key] as T;

            if (results == null)
            {
                results = f();
                HttpContext.Current.Cache[key] = results;
            }

            return results;
        }
    }
}


texts: Database design for Instagram-like post/comments

texts:
I'd like a review of my design for an Instagram-like application where users can post and comment on pictures.

I just finished a freecodecamp crash course on database design and this is the first ERD I make. If you also have suggestions for readings on this topic I'd appreciate it.

This is my SQL code:

CREATE TABLE users
(
    id SERIAL PRIMARY KEY,
    username VARCHAR(30) UNIQUE NOT NULL,
    email TEXT UNIQUE NOT NULL,
    salted_password TEXT NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP
);

CREATE TABLE photos
(
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
    caption VARCHAR(150),
    latitude DECIMAL,
    longitude DECIMAL,
    src TEXT NOT NULL,
    size INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP,
    FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE TABLE avatars
(
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
    src TEXT NOT NULL,
    size INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP,
    FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE TABLE comments
(
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
    photo_id INTEGER NOT NULL,
    comment VARCHAR(300) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY(photo_id) REFERENCES photos(id) ON DELETE CASCADE
);
```


texts:
I made an animation of the Microsoft logo. It's available as a CodePen doodle, also. Would anyone be so kind as to check my style and say if there is anything I could've improved? (I am sure there is.)

$(document).ready(function(){
    $(".logo").click(function(){
      $(this).toggleClass("turnOffAnimation");
      $(".brand").toggleClass("turnOffAnimation");
    });
});
body {
  background: hsl(30, 20%, 20%);
  color: #fff;
  font-family: 'Open Sans', sans-serif;
}

.boxes {
  animation: logo 4s infinite;
  position: absolute;
}

.box {
  animation: scaling 1s infinite;
  height: 50px;
  width: 50px;
}

.brand {
  animation: fadein 2s ease 3s forwards;
  display: inline-block;
  font-size: 36px;
  left: 40%;
  margin: 30px 0 0 20px;
  opacity: 0;
  position: absolute;
  top: 40%;
  z-index: 0;
}

.intro {
  text-align: center;
}

.logo {
  animation: moveLeft .5s linear 3s forwards;
  display: inline-block;
  left: 50%;
  position: absolute;
  top: 40%;
  z-index: 1;
}

.turnOffAnimation {
  animation-name: none;
}

#red {background: #f65314;}
#green {background: #7cbb00;}
#yellow {background: #ffbb00;}
#blue {background: #00a1f1;}

#animateRed {animation-delay: 3s;}
#animateGreen {animation-delay: 2s;}
#animateYellow {animation-delay: 1s;}
#animateBlue {animation-delay: 0s;}

@keyframes fadein {
  from {opacity: 0; left: 40%}
  to {opacity: 1; left: 50%;}
}

@keyframes logo {
  0%, 100% {left: 0px; top: 0px; transform: rotate(0deg)}
  25% {left: 50px; top: 0px; transform: rotate(180deg)}
  50% {left: 50px; top: 50px; transform: rotate(0deg)}
  75% {left: 0px; top: 50px; transform: rotate(-180deg)}
}

@keyframes moveLeft {
  from {left: 50%}
  to {left: 40%}
}

@keyframes scaling {
  0%, 100% {transform: scale(1)}
  50% {transform: scale(.5)}
}

}

<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

  Microsoft


texts:
I've written the following sample program as a way to help improve my understanding of passing pointers to a function, and it currently works:
#include "stdio.h"

typedef struct Car {
    char*           name;
    unsigned int    price;
} Car;

void print_cars(Car* cars[]) {
    for (int i=0; cars[i] != NULL;i++) {
        printf("\n<Car: %s, Price: $%d>", car->name, car->price);
    }
}
void depreciate(Car* cars[]) {
    for (int i=0; cars[i] != NULL; i++) {
        cars[i]->price = cars[i]->price * 0.95;
    }
}

int main(int argc, char* argv[]) {

    Car chevy = {.name = "Chevy", .price = 45000};
    Car mazda = {.name = "Mazda", .price = 30000};
    Car ferrari = {.name = "Ferrari", .price = 200000};

    Car* my_cars[] = {&chevy, &mazda, &ferrari, NULL};
    print_cars(my_cars);
    printf("\n--------- Depreciating -----------");
    depreciate(my_cars); // <-- ignoring this
    print_cars(my_cars);

    return 1;

}

Ignoring the line that modifies the value of the struct, would it be possible to do the print_cars function without using a pointer? When I tried doing it I would receive the error:

new5.c:13:27: error: invalid operands to binary expression ('Car' (aka 'struct Car') and 'void *')

Which I think may be related to using the NULL in the my_cars array to signal the end of it, but wasn't positive. Additionally, is using NULL in a non-char array a common way to show that the end has been reached? Where else could this be improved?


texts: Code seems repeated, except for the callback function

texts:
I've written some JavaScript code:

  app.get('/offers/', function(req, res){
    var funcGetOffers = utils.funcGetOffers;
    var options = {top_sort: true};
    funcGetOffers(function(offers){
      res.render('offers', { offers:offers });
    }, options);
  });

  app.get('/api/get_offers', function(req, res){
    var funcGetOffers = utils.funcGetOffers;
    var options = {top_sort: true};
    funcGetOffers(function(offers){
      res.json(offers);
    }, options);
  });

The code is almost the same, and only the callback function is different.  I want to get rid of the repeat code, but didn't find a good way.

funcGetOffers is a long function which gets a list of items from the database:

var funcGetOffers = function(callback, opt) {
  var order = [['updatedAt', 'DESC']];
  var where = {};
  if (opt && opt.top_sort) {
    order.unshift(['flag_top', 'DESC']);
  }
  var Offer = models.offer;
  Offer.findAll({order:order}).success(function(offers){
    // some calc with offers
    // callback
    callback(offers);
  });
}

Thank @Flambino make me more clear, I did some change to funcGetOffers to make it promisily, now the code:

var options = {top_sort: true};

utils.funcGetOffers(options).then(function(offers){
  res.render('offers', { offers:offers });
});

utils.funcGetOffers(options).then(function(offers){
  res.json(offers);
});

changed the funcGetOffers signature, use a bluebird to make it promisily.

utils.funcGetOffers(options).then(res.json) didn't work by the promise, but looks much better now!


texts:
class Pool(type):
    pool = dict()
    def __new__(clas, *a, **k):
        def __del__(self):
            Pool.pool[self.__class__] = Pool.pool.get(self.__class__, []) + [self]
        a[-1]['__del__'] = __del__
        return type.__new__(clas, *a, **k)

    def __call__(clas, *a, **k):
        if Pool.pool.get(clas):
            print('Pool.pool is not empty: return an already allocated instance')
            r = Pool.pool[clas][0]
            Pool.pool[clas] = Pool.pool[clas][1:]
            return r
        else:
            print('Pool.pool is empty, allocate new instance')
            return type.__call__(clas, *a, **k)

class Foo(metaclass=Pool):
    def __init__(self):
        print('Foo > .', self)
    def foo(self):
        print('Foo > foo:', self)

f1 = Foo()
f1.foo()

print('## now deleting f1')
del f1

print('## now create f2')
f2 = Foo()
f2.foo()

print('## now create f3')
f3 = Foo()
f3.foo()

what do you think about this piece of code?


texts:
Here is my little snake game which I made in c++ using the SFML library. The game is very simple. I have also included a screenshot of how the GUI looks. The files which I am loading are 30x30 colored squares. Yellow is the background. Red represents the snake. White is the cherry/fruit/prize to increase the size of the snake

#include<SFML/graphics.hpp>
#include<windows.h>

using namespace sf;
struct position{
    int x;
    int y;
}snake[200];

char direction = 'r';
int length = 2;

void update(){
    for(int i = length-1;i > 0;i--){
        snake[i].x = snake[i-1].x;
        snake[i].y = snake[i-1].y;
    }
    if (direction == 'u') snake[0].y-=1;
    else if (direction == 'd') snake[0].y+=1;
    else if (direction == 'r') snake[0].x+=1;
    else if (direction == 'l') snake[0].x-=1;
}
int fruitx = 5;
int fruity = 5;

void genrand(){
    int rx = rand() % 20;
    int ry = rand() % 20;
    fruitx = rx;
    fruity = ry;
}
int main(){
    snake[0].x = 5;
    snake[0].y = 5;
    RenderWindow window(VideoMode(620,620),"Snake c++");
    Texture t;
    Texture t2;
    Texture t3;
    t3.loadFromFile("images/green.png");
    t2.loadFromFile("images/red.png");
    t.loadFromFile("images/yellow.png");
    Sprite bg(t);
    Sprite sn(t2);
    Sprite fruit(t3);
    const int size = 31;
    while(window.isOpen()){
        Event e;
        while(window.pollEvent(e)){
            if(e.type == Event::Closed)
                window.close();

            if(e.type == Event::KeyPressed){
                if(e.key.code == Keyboard::Key::Up && direction != 'd') direction = 'u';
                else if(e.key.code == Keyboard::Key::Down && direction != 'u') direction = 'd';
                else if(e.key.code == Keyboard::Key::Left && direction != 'r') direction = 'l';
                else if(e.key.code == Keyboard::Key::Right && direction != 'l') direction = 'r';
            }
        }
        Sleep(60);
        update();
        window.clear();
        for(int i = 0;i < 20;i++){
            for(int j = 0;j < 20;j++){
                bg.setPosition(i*size,j*size);
                window.draw(bg);
            }
        }

        for(int i = 0;i < length;i++) {
            if (snake[i].x < 0) snake[i].x+=20;
            if (snake[i].x > 19) snake[i].x-=20;
            if (snake[i].y < 0) snake[i].y+=20;
            if (snake[i].y > 19) snake[i].y-=20;

            sn.setPosition(snake[i].x*size,snake[i].y*size);
            if (i != 0){
                if(snake[i].x == snake[0].x && snake[i].y == snake[0].y)
                    length = 2;
            }
            if (snake[i].x == fruitx && snake[i].y == fruity){
                length+=1;
                genrand();
                fruit.setPosition(fruitx*size,fruity*size);
            }
            window.draw(sn);
        }
        window.draw(fruit);
        window.display();
    }

    return 0;
}

The snake is represented by an array of position objects.
When I detect any collision I just reset the length of the snake.


texts: Replace anchor tags and force create new tag with custom attributes

texts:
I'm just use the add_filter('the_content', function($content){}); for filtering anchor tags in a post.

Basically, I want filter anchor tags to appropriate format. I want to add custom attributes like rel="nofollow noopener" and target="_blank" if the anchor tag linked to external of my WordPress site.

Instead checking and replace if rel or target is already exists in the anchor tag, I just need to retrieve the value of href and the value of the anchor tag itself (value). So I can force create an anchor tags with my preferred custom attributes.

Here's my current working function:

add_filter('the_content', function($content) {
    $internal = get_home_url();

    return preg_replace_callback('#([^>]*)#i', function($match) use ($internal) {
        if(stripos($match[1], $internal) || strpos($match[1], "#") == 0) {
            return "$match[2]";
        } else {
            return "$match[2]";
        }
    }, $content);
});

I'm worried about performance because this function run each user read a post. Any suggestions are welcome.


texts:
I'm using this C# function to generate random coupons for a system. How can I improve it?

public static string GenerateCoupon(int length)
{
    string result = string.Empty;
    Random random = new Random((int)DateTime.Now.Ticks);
    List<string> characters = new List<string>() { };
    for (int i = 48; i < 58; i++)
    {
        characters.Add(((char)i).ToString());
    }
    for (int i = 65; i < 91; i++)
    {
        characters.Add(((char)i).ToString());
    }
    for (int i = 97; i < 123; i++)
    {
        characters.Add(((char)i).ToString());
    }
    for (int i = 0; i < length; i++)
    {
        result += characters[random.Next(0, characters.Count)];
        Thread.Sleep(1);
    }
    return result;
}

Business requirements are:

The length of coupons are not fixed and static
Coupons can contain A-Z, a-z and 0-9 (case sensitive alphanumeric)
Coupons should be unique (which means that we store them as key in a table in database, and for each coupon, we check its uniqueness)


texts:
Please bear in mind, I've only started learning c++ this week, and as such, would love topic suggestions for which I should master, to become better at C++.

Below, is my code for a singly linkedlist. It doesn't have complete functionality, just the ability to print, append, and add a node at a specified index.

Currently I'm aware that each node is created on the Heap. I have no idea how to delete the nodes in a LinkedList once the LinkedList itself is deleted. I'm also not sure how to create a linkedlist without pointers.

#include<iostream>

template <typename T>
struct Node {
    Node(T value);
    T data;
    Node<T> *next;
};

template <typename T>
Node<T>::Node(T value){
    this->data = value;
    this->next = nullptr;
}

template <typename T>
class LinkedList {
public:
    Node<T> *head;
    LinkedList<T>();
    void push_back(T data);
    void push_back(int index, T data);
    void print();
};

template <typename T>
LinkedList<T>::LinkedList(){
    this->head = nullptr;
}

template <typename T>
void LinkedList<T>::push_back(T data){
    Node<T> *n = new Node<T>(data);
    if (this->head == nullptr){
        this->head = n;
    } else {
        Node<T> *cursor = this->head;
        while(cursor->next != nullptr){
            cursor = cursor->next;
        }
        cursor->next = n;
    }
}

template <typename T>
void LinkedList<T>::push_back(int index, T data){
    Node<T> *cursor = this->head;
    unsigned const position = index - 1;
    int i = 0;
    while (i < position && cursor->next != nullptr){
        cursor = cursor->next;
        i++;
    }
    Node<T> *nodeToInsert = new Node<T>(data);
    Node<T> *temp = cursor->next;
    cursor->next = nodeToInsert;
    nodeToInsert->next = temp;
}

template <typename T>
void LinkedList<T>::print(){
    Node<T> *cursor = this->head;
    while(cursor != nullptr){
        std::cout << cursor->data << '\n';
        cursor = cursor->next;
    }
}

int main(){

    LinkedList<int> intL;
    intL.push_back(1);
    intL.push_back(2);
    intL.push_back(3);
    intL.print();

    LinkedList<std::string> sL;
    sL.push_back("one");
    sL.push_back("two");
    sL.push_back("three");
    sL.push_back(2, "two point five");
    sL.print();
}

Also, should I potentially add an abstract class/or a c++ version of an interface for my LinkedList to follow, and then I could use this same abstraction for, say, a stack?


texts:
Question: Take an input string and output the "encoded" string by using the following rules:

 [1] vowels are replaced with number: a->1, e->2, etc
 [2] consonants are replaced with previous letter b->a, c->b, etc
 [3] y goes to space
 [4] space goes to y
 [5] numbers are reversed
 [6] other characters remain unchanged(punctuation, etc.)
 [7] all output should be lower case
 E.g.: Hello World! => g2kk4yv4qkc!

My Solution:

  /// pre processed conversions for letters
  private static Dictionary<char, char> Convert;

  public static string encode(string stringToEncode) {

     // approach: pre process a mapping (dictionary) for letter conversions
     // use a Dict for fastest look ups.  The first run, will take a little
     // extra time, subsequent usage will perform even better
     if (Convert == null || Convert.Count == 0) BuildConversionMappings();

     // our return val (efficient Appends)
     StringBuilder sb = new StringBuilder();

     // used for reversing the numbers
     Stack<char> nums = new Stack<char>();

     // iterate the input string
     for(int i = 0; i < stringToEncode.Length; i++) {

        char c = stringToEncode[i];

        // we have 3 cases:
        // 1) is alpha ==> convert using mapping
        // 2) is number ==> peek ahead to complete the number
        // 3) is special char / punctunation ==> ignore

        if(Convert.ContainsKey(c)) {
           sb.Append(Convert[c]);
           continue;
        }

        if(Char.IsDigit(c)) {
           nums.Push(c);

           // we've reached the end of the input string OR
           // we've reached the end of the number
           if (i == stringToEncode.Length - 1
              || !Char.IsDigit(stringToEncode[i + 1])) {
              while (nums.Count > 0) {
                 sb.Append(nums.Pop());
              }
           }

           continue;
        }

        // not letter, not digit
        sb.Append(c);
     }
     return sb.ToString();
  }

  // create our mappings for letters
  private static void BuildConversionMappings() {

     Convert = new Dictionary<char, char>();

     // only loop once for both
     for(char c = 'B'; c<='Z'; c++) {
        // add capitals version
        char val = (char)(c - 1);
        val = Char.ToLower(val);
        Convert.Add(c, val);
        // add lower case version
        Convert.Add(Char.ToLower(c),val);
     }

     // special cases
     Convert['y'] = ' ';
     Convert['Y'] = ' ';
     Convert.Add(' ', 'y');

     // vowels
     char[] vowels = new char[] { 'a', 'e', 'i', 'o', 'u' };
     for(int i = 0;i < vowels.Length;i++) {
        var letter = vowels[i];
        var value = (i+1).ToString()[0];
        Convert[letter] = value;
        Convert[Char.ToUpper(letter)] = value;
     }
  }

I was asked this question for an interview and the only feedback I received was building a dictionary was a very poor choice and they were no longer interested in continuing the application process.  I was surprised and disappointed, but I want to improve for the next time.  What should I do better?


texts:
Please let me know if the MVVM pattern I followed in this is correct or not.

Here is the code for ViewModel

public class LoginViewModel
{
    public string Email { get; set; } = "";
    public string Password { get; set; } = "";

    public ProgressBar ProgressBar { get; set; }
    public Label StatusLabel { get; set; }

    public Command LoginCommand
    {
        get
        {
            return new Command(async()=> {
                ProgressBar.IsVisible = true;
                ProgressBar.Progress = 0;
                await ProgressBar.ProgressTo(0.2, 250, Easing.BounceOut);

                if(Email.Length>0 && Password.Length > 0)
                {
                    ApiServices apiServices = new ApiServices();
                    var isSuccess = await apiServices.LoginAsync(Email, Password);
                    if (isSuccess)
                    {
                        await ProgressBar.ProgressTo(1, 250, Easing.Linear);
                        Application.Current.MainPage = new FirstMasterDetailPage();
                    }
                    else
                    {
                        await ProgressBar.ProgressTo(1, 250, Easing.Linear);
                        StatusLabel.IsVisible = true;
                        StatusLabel.Text = "Failed to login.";
                    }
                }
                else
                {
                    await ProgressBar.ProgressTo(1, 250, Easing.Linear);
                    StatusLabel.IsVisible = true;
                    StatusLabel.Text = "Username and Password is required to login.";
                }
                ProgressBar.IsVisible = false;
            });
        }
    }

    public Command RegisterCommand
    {
        get
        {
            return new Command(()=> {
                Application.Current.MainPage = new RegisterPage();
            });
        }
    }
}

this is code behind page

public LoginPage ()
    {
        InitializeComponent ();

        var current = BindingContext as LoginViewModel;
        current.ProgressBar = progressBar;
        current.StatusLabel = lblStatus;
    }


texts: Looping through an array of strings containing approximately 3 million elements

texts:
I have a function that loops through an array of strings containing approximately 3 million lines of strings.  My problem is this loop is running too slowly and I want to know how to make it faster.

string[] words = { "Hello", "world", "!", "My", "name", "is", "Something", "."};
    List<MyClass> result = new List<MyClass>();

    for (int i = 0; i < words.Length; i++)
    {
        if (words[i] == "&&&")
        { }
        else if (words.Length > i + 2 && FileContains(words[i] + " " + words[i + 1] + " " + words[i + 2]))
        {
            result.Add(new MyClass(words[i] + " " + words[i + 1] + " " + words[i + 2]));
            words[i + 1] = "&&&";
            words[i + 2] = "&&&";
        }
        else if (words.Length > i + 1 && FileContains(words[i] + " " + words[i + 1]))
        {
            result.Add(new MyClass(words[i] + " " + words[i + 1]));
            words[i + 1] = "&&&";
        }
        else
            result.Add(new MyClass(words[i], Parent));

    }

And my FileContains function which loops through the array of strings:

public static bool FileContains(string Text)
{
    foreach (string line in ARRAYOFWORDS)  // Approximately 3 million strings
    {
        if (Text.ToLower() == line.Substring(0, line.LastIndexOf('|')))
        {
            return true;
        }
    }
    return false;
}


texts: Weighting mysql full-text search results by date

texts:
I'm using innodb full-text search to return a set of results where the newest posts are more relevant.  Just wanted to check that this the best method:

SELECT *, (MATCH(note) AGAINST ('$search' IN BOOLEAN MODE))/SQRT(GREATEST(1, DATEDIFF(NOW(), date))) AS score FROM notes WHERE userid = '$userid' HAVING score > 0 ORDER BY score DESC


texts: Summing durations associated with each MAC address in a MongoDB result

texts:
I have a script which get data from MongoDB in the form of array and show the result. The array has a number of records in the thousands. A sample array is as follows:

array(2) {   ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478199995) ["duration"]=> int(5) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478203338) ["duration"]=> int(3) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478201111) ["duration"]=> int(7) }

array(2) {   ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478206709) ["duration"]=> int(7) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478202821) ["duration"]=> int(6) }

array(2) {   ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478202366) ["duration"]=> int(4) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478205023) ["duration"]=> int(2) }

I am showing record with respect mac address like in above array MAC address "2c:33:7a:10:f8:39" has three records and "38:0b:40:ad:03:53" has four, so I will add duration of each record and show on browser like this

2c:33:7a:10:f8:39          16sec
38:0b:40:ad:03:53          18sec

I am doing this by following logic which I think is too slow for 5000 to 6000 records.

I first get the MAC address in an array and remove duplication and then run a for loop on that array and add all duration for specific MAC my code is as below.

<?php
 foreach ($cursor as $document) {
 array_push($arr,$document["mac"]);
 }
 $arr=array_unique($arr);
 $duration=0;

 for($i=0;$i<count($arr);$i++){

foreach ($cursor as $document) {

if($document["mac"]==$arr[$i])
{

$duration+=$document['assoc_time'];

}

echo $arr[$i]."      ".$duration;
}

?>

How I can make this process fast and how to perform this task in only one foreach loop.


texts: minimum window subsequence leetcode dynamic programming solution

texts:
Given strings S and T, find the minimum (contiguous) substring W
  of S, so that T is a subsequence of W.

  If there is no such window in S that covers all characters in T,
  return the empty string "". If there are multiple such minimum-length
  windows, return the one with the left-most starting index.

Solution:

Concept is almost inspired from \$O(N log N)\$ solution for longest increasing sequence in a integer array presented here.
Let DP[i] represent longest increasing sequence in T which matches [0:i] subsequence of S. So,

DP[j] = i if S[j] == T[i] and j == 0

DP[j] = DP[j-1] if S[j] == T[i]

And then we are looking for DP[len(T)-1].

class Solution:
    def minWindow(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: str
        """
        dp = [-1] * (len(T)+1)
        dic = {}
        for i, t in enumerate(T):
            dic.setdefault(t, []).append(i)
        global_index, starting_index, global_count = -1, -1, 1 << 31
        for i in range(len(S)):
            if S[i] in dic:
                for j in dic[S[i]][::-1]:
                    if j == 0:
                        dp[j] = i
                    else:
                        dp[j] = dp[j-1]
                if dp[len(T)-1] != -1 and (i - dp[len(T)-1] + 1) < global_count:
                    starting_index, global_count = dp[len(T)-1], i - dp[len(T)-1] + 1
        if starting_index == -1:
            return ""
        return S[starting_index:starting_index + global_count]


texts:
Please review the code.

document.addEventListener("keydown", function(e) { // shortcuts
  if (e.ctrlKey) { // Ctrl+
    if (/^(82|79|83|66|191)$/.test(e.keyCode)) {
      e.preventDefault();
    }
    switch (e.keyCode) {
      case 82: // R
        newDoc();
        break;
      case 79: // O
        openDoc();
        break;
      case 83: // S
        saveDoc();
        break;
      case 66: // B
        showHideStatusBar(statusBarOn ? false : true); // toggle
        break;
      case 191: // /
        alert("Welcome to " + appname + "!");
        break;
    }
  }
  if (e.keyCode == 9) { // tab
    e.preventDefault();
    var sStart = textarea.selectionStart,
      text = textarea.value;
    textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd);
    textarea.selectionEnd = sStart + 1;
  }
});


texts: Compressing time series by removing repeated samples

texts:
I work on a project with time series data. So there are samples (\$y\$), and each sample has a timestamp (\$x\$). The data will be visualized, but often there are time series which contain samples that do not change over several timestamps. In a visualization (a \$y(x)\$ plot) those repeated samples can be removed, since the visualization will just show a horizontal line. (For example, if a constant value 3.14 is sampled 1 million times in one second, the plot would have the same visual appearance as if the value had been sampled just twice in that period.) I wrote an algorithm that removes those repeated samples in the order to reduce the amount of data and speed up visualization. My algorithm works, but I know that it can be done better.

Here is the algorithm (in the file compress_2D_signal.py):

def compress_2D_signal(x, y):
    end = len(x)
    end_1 = len(x) - 1
    x1 = []
    y1 = []

    x1append = x1.append
    y1append = y1.append

    for ind, elements in enumerate(zip(x, y)):
        if ind == end or ind >= end_1 or y[ind - 1] != y[ind] or y[ind + 1]     != y[ind] or ind == 0:
        x1append(elements[0])
        y1append(elements[1])
    return x1, y1

and here are the tests:

from unittest import TestCase
import time
from compress_2D_signal import compress_2D_signal

class Test2DSignal(TestCase):
    def test_store_sample_array_one_signal_parameter_returns_same_when_each_sample_different(self):
        x = [1, 2, 3, 4]
        y = [0, 1, 2, 3]
        x1, y1 = compress_2D_signal(x, y)
        self.assertEqual(x, x1)
        self.assertEqual(y, y1)

    def test_store_sample_array_one_signal_parameter(self):
        x = [1, 2, 3, 4, 5]
        y = [0, 2, 2, 2, 0]
        x1, y1 = compress_2D_signal(x, y)
        self.assertEqual([1, 2, 4, 5], x1)
        self.assertEqual([0, 2, 2, 0], y1)

    def test_store_sample_array_one_signal_parameter_2(self):
        x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        y = [0, 2, 2, 2, 0, 0, 1, 1, 1]
        x1, y1 = compress_2D_signal(x, y)
        self.assertEqual([1, 2, 4, 5, 6, 7, 9], x1)
        self.assertEqual([0, 2, 2, 0, 0, 1, 1], y1)

    def test_time_self(self):
        length = int(1e6)
        x = range(length)
        y = range(length)
        start = time.time()
        compress_2D_signal(x, y)
        stop = time.time()
        print('Time elapsed for %s points : %s this are %s points/second' % (length, stop - start, length / (stop - start)))


texts: Kotlin function which counts standard deviation

texts:
Here is the code. The code should counts the standard deviation for double array, but also for Int arrays.

fun calculateSD(numArray: DoubleArray): Double {
var sum = 0.0
var standardDeviation = 0.0

for (num in numArray) {
    sum += num
}

val mean = sum / numArray.size

for (num in numArray) {
    standardDeviation += Math.pow(num - mean, 2.0)
}

val divider = numArray.size - 1

return Math.sqrt(standardDeviation / divider )
}


texts:
Currently I'm displaying a news feed from an XML file and using a counter to limit the number of news articles that are displayed. But I'm unsure if this is the best way to do it.

Here is my code.

<?php
function get_news($feed) {

$xml = new SimpleXmlElement(uwe_get_file($feed));
$counter = 0;
foreach ($xml->channel->item as $item) {
    echo 'link . '" target="_blank">' . $item->title . '
' . '' . $item->description . '' . '' . $item->pubDate . '' . '
' . '
';
    ++$counter;
    if ($counter == 5) {
        break;
    }
}
}

?>

Any suggestions on how I could improve this counter?


texts: HackerEarth Girlfriend's Demand challenge, solved two ways

texts:
I solved the Girlfriend's Demand challenge on HackerEarth.  In summary:

  Input: First line of the input contains a string S. Next line contains an integer Q, the number of queries.  Each of the next Q lines contains a test case consisting of 2 integers, a and b.

  Output: If S is repeated infinitely, would string positions a and b contain the same character (using 1-based indexing)?  For each query, print “Yes” or “No”.

  Constraints:

  1 ≤ |S| ≤ 105
  1 ≤ Q ≤ 105
  1 ≤ a, b ≤ 1018

  Sample Input:

vgxgp
3
2 4
2 5
7 14

  Sample Output:

Yes
No
Yes

My first solution:

public static void main(String args[] ) throws Exception {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String item=br.readLine();

        StringBuffer sb=new StringBuffer();
        int len = item.length();
        int inputs = Integer.parseInt(br.readLine());

        while(inputs-->0)
        {
            String strarr[] =null;

                strarr = br.readLine().split(" ");

            long a=Long.parseLong(strarr[0]);
            long b=Long.parseLong(strarr[1]);
            a=a-1;
            b=b-1;
            a=a%len;
            b=b%len;

            if(item.charAt((int)a)==item.charAt((int)b))
                sb.append("Yes\n");
            else
                sb.append("No\n");

        }

        System.out.println(sb);

    }

While this gave me an output in almost 5.2954 seconds for various inputs, when I tried the same inputs on this version of the code that I wrote:

public static void main(String args[] ) throws Exception {
      BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
        String demanded=reader.readLine();
        int length = demanded.length();
        int T=Integer.parseInt(reader.readLine());
        for(int i = 0;i < T; i++){
            String[] pairedAAndB=reader.readLine().split(" ");
                long a = ((Long.parseLong(pairedAAndB[0]) - 1) % length);
                long b = ((Long.parseLong(pairedAAndB[1]) -1) %length);
            System.out.println((demanded.charAt((int)a)==demanded.charAt((int)b)) ? "Yes" : "No");

    }

}

It took around 15.7819 seconds. What is the best way to convert long to int optimally? What I'm not able to understand is why the second code snippet is taking so much time when the second version is almost similar. There must be something about the second version that I'm not able to understand.


texts: Project Euler #5 - Lowest Multiple of 1 through 20

texts:
I was trying to solve problem 5 of Project Euler, and this was I needed to do:

  2520 is the smallest number that can be divided by each of the numbers
  from 1 to 10 without any remainder.

  What is the smallest positive number that is evenly divisible by all
  of the numbers from 1 to 20?

I came up with a solution, and I get the correct answer in about 7 minutes, but my question is, how could I make it faster? Calculation speeds are incredibly slow, how could I optimize it?

        for (long x = 1; x < 1000000000; x++) {

            bool dividable = true;

            for (int y = 20; y > 0; y--) {
                if (x % y != 0) {
                    dividable = false;
                }

            }
            if (dividable == true) {
                Console.WriteLine (x);
            }
        }
    }


texts:
I have some code which aligns the sequence of two strings, I am doing numbers just for my implementation.

I was wondering whether there are any performance enhancements I could make as the code itself is \$O(n^2)\$ which isn't ideal in terms of scalability, here's the code:

        int[] goal = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 0};
        int[] test = {1, 5, 9, 11, 2, 10, 0, 6, 8, 14, 15, 12, 7, 4, 3, 13};
        int gap = 1;
        // The penalties to apply
        int substitution = 1, match = 0;

        int[][] opt = new int[goal.length + 1][goal.length + 1];

        // First of all, compute insertions and deletions at 1st row/column
        for (int i = 1; i <= goal.length; i++) {
            opt[i][0] = opt[i - 1][0] + gap;
        }
        for (int j = 1; j <= test.length; j++) {
            opt[0][j] = opt[0][j - 1] + gap;
        }

        for (int i = 1; i <= goal.length; i++) {
            for (int j = 1; j <= test.length; j++) {
                int scoreDiag = opt[i - 1][j - 1] + (goal[i - 1] == test[j - 1] ? match : substitution); // different symbol
                int scoreLeft = opt[i][j - 1] + gap; // insertion
                int scoreUp = opt[i - 1][j] + gap; // deletion
                // we take the minimum
                opt[i][j] = Math.min(Math.min(scoreDiag, scoreLeft), scoreUp);
            }
        }

        for (int i = 0; i <= goal.length; i++) {
            for (int j = 0; j <= test.length; j++) {
                System.out.print(opt[i][j] + "\t");
            }
            System.out.println();
        }

The value that I actually need from the code is opt[goal.length][test.length]


texts: Retrieve all parents, all possible children, sorted and with their "depth"

texts:
I have a model section with a column parent_id - the only thing identifying a parent/child relationship. I wrote a helper method to output all sections, all their possible subsections and include their "depth".

This is the helper method:

# Calls itself for each section recursively to fetch all possible children
def fetch_all_sections(standard, section = nil, depth = 0)
  all_sections = []
  if section.nil?
    rootsections = roots(standard.sections.sorted)
    if ! rootsections.nil?
      rootsections.each do |section|
        all_sections.push(fetch_all_sections(standard, section))
      end
    end
  else
    all_sections.push({:id => section.id, :sortlabel => section.sortlabel, :title => section.title, :depth => depth})
    section.children.sorted.each_with_index do |section, index|
      all_sections.push(fetch_all_sections(standard, section, (depth += 1) - index))
    end
  end
  return all_sections
end

sorted is a module method which sorts based on the sort_key column using regular expressions. The output of debug(fetch_all_sections(@standard)) is:

- - "1 Collaborase Test Document depth: 0"
  - - "1.1 Section One Dot One depth: 1"
  - - "1.a Testing 123 depth: 1"
  - - "1.b Section One dot B depth: 1"
    - - "1.b.1 Testing One B One depth: 2"
- - "2 Identify Project GHG Sources, Sinks, and Reservoirs (SSRs) depth: 0"
  - - "2.a Section Two dot A depth: 1"
- - "3 Identify the Baseline depth: 0"
- - "4 Identify the Baseline GHGs depth: 0"
- - "5 Identify SSRs Relevant for Quantification depth: 0"
  - - "5.1 Section Five Dot One depth: 1"
- - "6 GHG Quantification depth: 0"
- - "7 Monitoring depth: 0"
- - "8 Data and Information Retention depth: 0"
- - "9 QA/QC depth: 0"

My questions is this:

In this loop:

<% fetch_all_sections(@standard).each do |section| %>
  <%= debug section %>
<% end %>

I want each section and all their children to be separated. Instead, each section in the above loop contains their children.

Instead of this:

---
- - :id: 122
    :sortlabel: "5"
    :title: Identify SSRs Relevant for Quantification
    :depth: 0
- - - :id: 412
      :sortlabel: "5.1"
      :title: Section Five Dot One
      :depth: 1

I want this:

---
- - :id: 122
    :sortlabel: "5"
    :title: Identify SSRs Relevant for Quantification
    :depth: 0
---
- - :id: 412
    :sortlabel: "5.1"
    :title: Section Five Dot One
      :depth: 1


texts: Opinions on my Command pattern design - is it extensible?

texts:
I am implementing a program that takes commands from a user and based on those commands, drives a Robot on a grid. To implement this program I have used the Command pattern. I have used this pattern because, most importantly, I want to be able to add to the list of possible commands in the future.

The program takes a string of commands from the user, and executes those commands, e.g. FFRFLF (forward x 2, turn right, forward, turn left, forward).

Can anyone give me their opinion on the quality of my design?

Robot Controller class:

    public void control(){

do{
    process();
}while(tru);
}

public String process(){

    // 1. Get user input
    String cmds = get user input from console

    // 2. Populate command list
    populateCommandList(cmds);

    // 3. Execute commands
    executeCommands();

       // 4. Display current location of robot
}

public void populateCommandList(String cmds) {

    Command r = new TurnRightCommand(robot);
    Command l = new TurnLeftCommand(robot);
    Command f = new ForwardCommand(robot);

    commands = new ArrayList<Command>();

        for(int i=0; i<cmds.length(); i++){

            char cmd = cmds.charAt(i);
            switch(cmd){
                case 'F':
                    commands.add(f);
                    break;
                case 'R':
                    commands.add(r);
                    break;
                case 'L':
                    commands.add(l);
                    break;
            }
        }
}

private void executeCommands() {
    if(commands!=null && commands.size()>0){
        for(Command cmd : commands){
            cmd.execute();
        }
    }
}

Main class:

public class Main {
    public static void main(String[] args) {

        RobotController r = new RobotController();
        r.control();
    }
}

Is this a good design? I need to know if the deign is good and that I can easily add new commands with minimal rework.


texts: Is there a better SQLite update / insert pattern than this?

texts:
I've got a function which updates an existing record or inserts a new one, but it looks very clunky to me.

using (SQLiteConnection db = new SQLiteConnection(AppSettings.DbPath))
{
    db.RunInTransaction(() =>
    {
        var y = db.Table<MyClass>().Where(x => x.GUID == this.GUID && x.VersionNumber == this.VersionNumber).FirstOrDefault();

        bool insert = false;

        if (y == null)
        {
            y = new MyClass();
            y.GUID = this.GUID;
            insert = true;
        }

        y.VersionNumber = this.VersionNumber;
        y.WordCount = this.WordCount;
        y.Updated = DateTime.Now;
        y.Checksum = this.Checksum;
        y.Deleted = this.Deleted;
        y.Source = this.Source;

        if (insert)
        {
            db.Insert(y);
        }
        else
        {
            db.Update(y);
        }
    });
}

The only alternative I can see is a bigger if else, which looks neater but has some argument repitition

using (SQLiteConnection db = new SQLiteConnection(AppSettings.DbPath))
{
    db.RunInTransaction(() =>
    {
        var y = db.Table<PoeFileVersion>().Where(x => x.GUID == this.GUID && x.VersionNumber == this.VersionNumber).FirstOrDefault();

        if (y == null)
        {
            y = new PoeFileVersion();
            y.GUID = this.GUID;

            y.VersionNumber = this.VersionNumber;
            y.WordCount = this.WordCount;
            y.Updated = DateTime.Now;
            y.Checksum = this.Checksum;
            y.Deleted = this.Deleted;
            y.Source = this.Source;

            db.Insert(y);
        }
        else
        {
            y.VersionNumber = this.VersionNumber;
            y.WordCount = this.WordCount;
            y.Updated = DateTime.Now;
            y.Checksum = this.Checksum;
            y.Deleted = this.Deleted;
            y.Source = this.Source;

            db.Update(y);
        }
    });
}

This is not unique to SQLite of course - I've come up against the same ugly code in Linq-to-SQL. Is there a better pattern?


texts:
A hashmap is a data structure that implements an associative array abstract data type using keys and values and has a hash function to compute an index into an array, from which the desired value can be set and get [reference].

Based on some tutorial, I wrote this hashmap class:

class HashMap():
    def __init__(self):
        self.hahsmap_size = 32
        self.hashmap_data = [None] * self.hahsmap_size

    def __get_hash_mod_size(self, key):
        hash_key_var = hash(key+str(self.hahsmap_size*0.01))
        return hash_key_var % self.hahsmap_size

    def set_key_value(self, key, value):
        key_var = self.__get_hash_mod_size(key)
        key_value_list = [key, value]

        if self.hashmap_data[key_var] is None:
            self.hashmap_data[key_var] = list([key_value_list])
            return True
        else:
            for pair in self.hashmap_data[key_var]:
                print(pair)
                if pair[0] == key:
                    pair[1] = value
                    return True
            self.hashmap_data[key_var].append(key_value_list)
            return True

    def get_key(self, key):
        key_var = self.__get_hash_mod_size(key)
        if self.hashmap_data[key_var] is not None:
            for pair in self.hashmap_data[key_var]:
                if pair[0] == key:
                    return pair[1]
            return None

    def remove_key(self, key):
        key_var = self.__get_hash_mod_size(key)

        if self.hashmap_data[key_var] is not None:
            return False
        for i in range(len(self.hashmap_data[key_var])):
            if self.hashmap_data[key_var][i][0] == key:
                self.hashmap_data[key_var].pop(i)
                return True
    def print_hashmap(self):
        for item in self.hashmap_data:
            if item is not None:
                print(item)

hm = HashMap()
hm.set_key_value('A', '1')
hm.set_key_value('A', '2')
hm.set_key_value('B', '1')
hm.set_key_value('A', '3')
hm.set_key_value('A', '4')
hm.set_key_value('C', '1')
hm.set_key_value('D', '1')
hm.set_key_value('E', '1')
hm.set_key_value('E', '2')
hm.remove_key('A')
hm.remove_key('B')
hm.remove_key('B')
hm.print_hashmap()

If you had time, I'd appreciate a review.


texts:
After thoroughly profiling my program, I have been able to pinpoint that it is being slowed down by the vectorizer.

I am working on text data, and two lines of simple tfidf unigram vectorization is taking up 99.2% of the total time the code takes to execute. I am extending the default TfidfVectorizer to add a stemmer.

Here is a runnable example (this will download a 3mb training file to your disk, omit the urllib parts to run on your own sample):

#####################################
# Loading Data
#####################################
import urllib
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk.stem
raw = urllib.urlopen("https://s3.amazonaws.com/hr-testcases/597/assets/trainingdata.txt").read()
file = open("to_delete.txt","w").write(raw)
###
def extract_training():
    f = open("to_delete.txt")
    N = int(f.readline())
    X = []
    y = []
    for i in xrange(N):
        line  = f.readline()
        label,text =  int(line[0]), line[2:]
        X.append(text)
        y.append(label)
    return X,y
X_train, y_train =  extract_training()
#############################################
# Extending Tfidf to have only stemmed features
#############################################
english_stemmer = nltk.stem.SnowballStemmer('english')

class StemmedTfidfVectorizer(TfidfVectorizer):
    def build_analyzer(self):
        analyzer = super(TfidfVectorizer, self).build_analyzer()
        return lambda doc: (english_stemmer.stem(w) for w in analyzer(doc))

tfidf = StemmedTfidfVectorizer(min_df=1, stop_words='english', analyzer='word', ngram_range=(1,1))
#############################################
# Line below takes 6-7 seconds on my machine
#############################################
Xv = tfidf.fit_transform(X_train)

I tried converting the list X_train into an np.array but there was no difference in performance.


texts:
I'm a beginning C programmer. I need a function that will take a string and determine if it's a number. The data is coming from files created by different people and the number formats WILL vary. So the function needs to decide if it was Supposed to be a number and if so, I will call the right conversion function (atoi/strtoi, atol/strtol etc etc.) So it needs to consider ints and floats, some with dollar signs, some with commas, some not. If a human would recognize it as a number the function should too.

The function works exactly as I want it to, and I haven't been able to break it no matter what I throw at it, but I'm sure there are better ways to do the job, and I'm equally sure there are problems with the way I'm doing it that I just am too inexperienced to know about yet. So Please, take a look and let me know of any potential pitfalls I may encounter with this function, feel free to suggest alternative ways if you're inclined.

Here's what I have come up with. As I've said it works, the example takes one or more command line args to simplify testing and there is no error checking yet, I will add that to the working program, but for function testing in a controlled setting I'm looking purely for functionality and problems that I might not know about with the way I'm handling the function.

Since the $ is significant to the shell it has to be enclosed in quotes but that won't be a problem when implemented because the data won't be coming from the command line.

Anything I should be aware of, or should consider with this code? More efficient mechanisms for accomplishing this would be appreciated. If there is a library function for this it has escaped my detection but would love to pointed in the right direction.

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

int check_is_numeric(const char *arr)
{
    //define valid characters for any numeric value
    char numdig[] = {'0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', ',', '.', '$'};
    int j=0;
    int notnum = 0;
    int hasdec = 0;

    while (arr[j] != '\0')  {
        for(int b = 0; b < 13;b++){
            //use hasdec to indicate a decimal in the string
            //but don't allow more than one.
            if( arr[j] == numdig[b] && hasdec < 2) {
                if (b == 11) {++hasdec;}
                notnum =0;
                break;
            } else {
                notnum =1;
            }
        }
        if(notnum){break;}
        ++j;
    }
    if(!notnum) {
        if(!hasdec){return 1;}
        else {return 2;}
    } else {
        return 0;
    }
}

int main(int argc, char *argv[])
{

    char *argvarray[argc];
    for(int j=0; j< argc; j++){
        argvarray[j] = malloc(strlen(argv[j] + 1));
        strcpy(argvarray[j], argv[j]);
    }

    int i = 0;
    for(int j=1; j< argc; j++){
        //pass each arg to the function
        //function should accept anything a human would recognize as a number
        //and return 0 for non number, 1 for int and 2 for float
        i = check_is_numeric(argvarray[j]);
        switch(i) {
            case 0:
                printf("%s is not a number.\n", argvarray[j]);
                break;
            case 1:
                printf("%s is an integer.\n", argvarray[j]);
                break;
            case 2:
                printf("%s is a floating point number.\n", argvarray[j]);
                break;
        }
    }
    return 0;
}


texts:
I'm posting an sliding window problem of LeetCode (Minimum Window Substring) with C++. If you have time and would like to review the code, please do so, I appreciate that.
On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).
Problem

Given a string base_string and a string target, find the minimum window
in base_string which will contain all the characters in target in
complexity O(n).
Example:
Input: base_string = "ADOBECODEBANC", target = "ABC" Output: "BANC"
Note:
If there is no such window in base_string that covers all characters in
target, return the empty string "". If there is such window, you are
guaranteed that there will always be only one unique minimum window in
base_string.

C++
class Solution {
public:
    string minWindow(string base_string, string target) {
        vector<int> count_map(128, 0);

        for (auto character : target)
            count_map[character]++;

        int left = 0, right = 0;
        int min_left = 0, min_right = INT_MAX;
        int target_length = target.size();

        while (right < base_string.size()) {
            if (count_map[base_string[right++]]-- > 0)
                target_length--;

            while (target_length == 0) {
                if (right - left < min_right)
                    min_right = right - (min_left = left);

                if (count_map[base_string[left++]]++ == 0)
                    target_length++;

            }
        }

        return min_right == INT_MAX ? "" : base_string.substr(min_left, min_right);
    }
};

Reference

Question

Solution

Discussion


texts:
For project Euler, I need quite often to test things like is x*y*z < 1e18. Since BigInteger is usually too slow, long overflows, and double may return incorrect result due to rounding, I wanted to use long with appropriate checks. As Guava's LongMath.checkedMultiply throws, it can't be used as exception handling is too slow, too. So I decided to write a saturated arithmetic class.

As usual, feel free to ignore my slightly deviating coding conventions. The code has been optimized, so it's a bit hacky. There should be no bugs as it's thoroughly tested. Simplifications and optimizations are most welcome.

@UtilityClass public class SaturatedMath {
    public static long pow(long base, int exp) {
        if (exp==0) return 1;
        checkArgument(exp>=0);

        // Handle small bases and also Long.MIN_VALUE
        if (Math.abs(base) <= 2) return powSpecial(base, exp);

        switch (exp) {
            case 1: return base;
            case 2: return square(base);
            case 3: return cube(base);
        }

        // Now base is at least 3, so the exponent can't be big.
        if (exp >= FLOOR_ROOTS_MAX_LONG.length) return saturate(base < 0 && (exp&1) != 0);

        final long limit = FLOOR_ROOTS_MAX_LONG[exp];
        if (base > +limit) return Long.MAX_VALUE;
        if (base < -limit) return saturate((exp&1) != 0);

        // No more overflow.
        return powUnsaturated(base, exp);
    }

    private static long powSpecial(long base, int exp) {
        assert -2 <= base && base <= 2 || base == Long.MIN_VALUE;
        final long sign = 1 - ((exp&1) << 1);

        switch ((int) base) {
            case -2: return exp>=63 ? saturate(sign) : sign << exp;
            case -1: return sign;
            case 0: return base<0 ? saturate(sign) : 0;
            case 1: return base;
            case 2: return exp>=63 ? Long.MAX_VALUE : 1L << exp;
        }

        throw new RuntimeException("impossible");
    }

    private static long powUnsaturated(long base, int exp) {
        long result = 1;
        for (long x=base; exp>0; exp>>=1) {
            if ((exp&1) != 0) result *= x;
            x *= x;
        }
        return result;
    }

    public static long mul(long x, long y) {
        final long result = x * y;
        // See https://goo.gl/ZMEZEa
        final int nlz = Long.numberOfLeadingZeros(x) + Long.numberOfLeadingZeros(~x)
                + Long.numberOfLeadingZeros(y) + Long.numberOfLeadingZeros(~y);
        if (nlz > 65) return result;
        if (nlz < 64) return saturate(x^y);
        if (x==Long.MIN_VALUE & y<0) return Long.MAX_VALUE;
        if (y != 0 && result / y != x) return saturate(x^y);
        return result;
    }

    public static long square(long x) {
        if (x > +FLOOR_SQRT_MAX_LONG) return Long.MAX_VALUE;
        if (x < -FLOOR_SQRT_MAX_LONG) return Long.MAX_VALUE;
        return x * x;
    }

    public static long cube(long x) {
        if (x > +FLOOR_CBRT_MAX_LONG) return Long.MAX_VALUE;
        if (x < -FLOOR_CBRT_MAX_LONG) return Long.MIN_VALUE;
        return x * x * x;
    }

    private static long saturate(long sign) {
        return saturate(sign < 0);
    }

    private static long saturate(boolean negative) {
        return negative ? Long.MIN_VALUE : Long.MAX_VALUE;
    }

    // (long) Math.sqrt(Long.MAX_VALUE)
    private static final long FLOOR_SQRT_MAX_LONG = 3037000499L;
    // (long) Math.cbrt(Long.MAX_VALUE)
    private static final long FLOOR_CBRT_MAX_LONG = (1L << 21) - 1;

    // For n>=3, the n-th item is the n-th root of Long.MAX_VALUE.
    // The first three values are unused.
    private static final int[] FLOOR_ROOTS_MAX_LONG = {
        0, 0, 0, 2097151, 55108, 6208, 1448, 511,
        234, 127, 78, 52, 38, 28, 22, 18,
        15, 13, 11, 9, 8, 7, 7, 6,
        6, 5, 5, 5, 4, 4, 4, 4,
        3, 3, 3, 3, 3, 3, 3, 3,
        // The next value would be 2, so we stop here.
    };
}


texts: Tiny function to write array or string to a file for testing with MVC, Ajax, etc

texts:
This might not even warrant posting here, but I"m enjoying it and thought I would share.

//For Testing
function write_to_file($message){
        $handle = fopen("/path/to/logs/a_log_file.php", "a+");
        if (is_array($message)):
            fwrite($handle, "\nMessage is array.\t ");
            fclose($handle);
            file_put_contents('/path/to/logs/a_log_file.php', print_r($message, true),
                              FILE_APPEND | LOCK_EX);
        else:
            fwrite($handle, "\nMessage:\t " . $message);
            fclose($handle);
        endif;

        }

Haven't actually tested with multidimensional array yet and might be a good opportunity for some recursion.

Comments, suggestions and criticism are of course welcome.


texts: Class for measuring distance as feet and inches

texts:
My homework question states:

  Develop a class to measure distance as feet (should be int), inches (should
  be float).  Include member functions to set and get attributes.  Include
  constructors.  Develop functions to add two distances.

  The prototype of the sum function is:

Distance Sum(Distance d);

Please check out my coding style and other aspects that can make this program better.

#include <iostream>
using namespace std;
class Distance
{
        private:
                int feet;
                float inch;
        public:
        Distance();
        Distance(int a,float b);
        void setDistance();
        int getFeet();
        float getInch();
        void distanceSum(Distance d);
};
int main()
{
        Distance D1,D2;
        D1.setDistance();
        D2.setDistance();
        D1.distanceSum(D2);
        return 0;
}
/*Function Definitions*/
Distance::Distance()
{
        inch=feet=0;
}
Distance::Distance(int a,float b)
{
        feet=a;
        inch=b;
}
void Distance::setDistance()
{
        cout<<"Enter distance in feet";
        cin>>feet;
        cout<<endl<<"Enter inches:";
        cin>>inch;
}
int Distance::getFeet()
{
        return feet;
}
float Distance::getInch()
{
        return inch;
}
void Distance::distanceSum(Distance d)
{
        cout<<"feet="<<d.feet+feet<<endl;
        cout<<"inches="<<d.inch+inch<<endl;
}