texts: Re-arranging an matrix of numbers to a numeric list

texts:
If I have an array of numbers like this:

1  3  4  6  7
1  2
2  4  5  9
5  7
1  2  3  5

Is there a quick way to take all of the unique numbers and arrange them into a single column, like this?

1
2
3
4
5
6
7
9

The approach I have works, but takes a very long time for large matrix:

Sub Test1
Call RecordArrange
Call RemoveDuplicates2
End Sub

Private Sub RecordArrange()
Worksheets("List").Activate
Dim Rng As Range
Dim i As Long
i = 1
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlManual
Application.DisplayStatusBar = False
Application.EnableEvents = False

Dim lastRow As Long
lastRow = Range("A1").End(xlDown).row

While i <= lastRow

Set Rng = Range("A" & i)

If IsEmpty(Rng.Offset(0, 1).Value) = False Then
Rng.Offset(0, 1).Copy
Rng.Offset(1, 0).Insert Shift:=xlDown
Rng.Offset(0, 1).Delete Shift:=xlToLeft

Else: i = i + 1

End If
Wend
Columns("A:A").Select
    ActiveWorkbook.Worksheets("List").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("List").Sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("List").Sort
        .SetRange Range("A1:A8000")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Application.EnableEvents = True
Application.Calculation = xlAutomatic
Application.DisplayStatusBar = True
Application.EnableEvents = True
End Sub

Private Sub RemoveDuplicates2()

Dim Rng As Range
Dim i As Long
i = 1
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlManual
Application.DisplayStatusBar = False
Application.EnableEvents = False
Dim lastRow As Long
lastRow = Range("A1").End(xlDown).row

While i <= lastRow
Set Rng = Range("A" & i)

If Rng = Rng.Offset(1, 0) And IsEmpty(Rng.Value) = False Then
Rng.Delete Shift:=xlUp

ElseIf Rng <> Rng.Offset(1, 0) And IsEmpty(Rng.Value) = False Then
i = i + 1
ElseIf Application.WorksheetFunction.CountA(Rng) = 0 Then
i = i + 1
Else: i = i + 1

End If

Wend
    Application.EnableEvents = True
Application.Calculation = xlAutomatic
Application.DisplayStatusBar = True
Application.EnableEvents = True
End Sub

This does work, but it seems like a very roundabout approach. Is there a better way?


texts: Project Euler #14 solution takes quite a long time

texts:
Can anybody give me suggestions for making it faster? (Project Euler #14)

import time
start = time.clock()

def collatzChain(n):
    count = 1
    while n != 1:
        if n % 2 != 0:
            count += 1
            n = (n * 3) + 1

        if n % 2 == 0:
            count += 1
            n = n / 2

    return count

chainLengths = []
startNum = 999999
while startNum > 1:
    chainLength = collatzChain(startNum)
    chainLengths.append(chainLength)
    startNum -= 1

print(999999 - chainLengths.index(max(chainLengths)))
elapsed = time.clock() - start
print("This program took " + str(elapsed) + " seconds.")


texts:
To make a long story short, I must revive my Forth. It is rusty; last time I did anything serious in Forth was 30 years ago (man, I am old). As an exercise, I translated an STL-like implementation of qsort. It works (if you want to test it, install gforth). It performs well comparing to SDCC-compiled native C (I don't have Keil license). I know where my bottlenecks are.

I am mostly interested in how readable the code is; how much did I sin against Forth spirit; if there are modern Forth coding conventions, how does this code fare.

-1 cells constant -cell
: cell- -cell + ;

: xchg ( a0 a1 -- ) 2dup @ >r @ swap ! r> swap ! ;

: unguarded_linear_insert ( last val -- )
    >r
    begin cell- dup @ dup r@ > while over cell+ ! repeat
    drop r> swap cell+ !
;

: unguarded_insertion_sort ( first last -- )
    >r
    begin dup r@ <> while dup dup @ unguarded_linear_insert cell+ repeat
    drop rdrop
;

: linear_insert ( first last val -- )
    >r over @ r@ swap <
    if
        begin 2dup <> while cell- dup @ over cell+ ! repeat
        drop r> swap !
    else
        r> unguarded_linear_insert drop
    then
;

: insertion_sort ( first last -- )
    2dup <>
    if
        >r
        dup begin cell+ dup r@ <> while 2dup dup @ linear_insert repeat
        rdrop
    then
    2drop
;

: unguarded_partition ( l f p -- cut )
    >r swap cell-
    begin dup @ r@ > while cell- repeat swap
    begin dup @ r@ < while cell+ repeat swap
    begin 2dup < while
        2dup xchg cell- swap cell+ swap
        begin dup @ r@ > while cell- repeat swap
        begin dup @ r@ < while cell+ repeat swap
    repeat
    swap drop begin dup @ r@ < while cell+ repeat
    rdrop
;

: median_of_3 ( n0 n1 n2 -- n )
    >r 2dup > if swap then
    r> 2dup > if swap then drop
       2dup < if swap then drop
;

: pivot ( l f len -- l f p )
    2 / -cell and over +          ( l f m )
    @ >r over cell- @ over @ r>
    median_of_3
;

: quicksort_loop ( l f t -- )
    begin dup >r -rot 2dup - dup r@ > while
        pivot
        >r 2dup r> unguarded_partition
        >r 2dup + r@ swap r> 2 * < if
            rot over r> recurse swap else
            dup -rot swap r> recurse then
        rot
    repeat
    rdrop 2drop 2drop
;

: quicksort ( l f )
    2dup 2 cells quicksort_loop
    dup 2 cells + dup -rot insertion_sort
    swap unguarded_insertion_sort
;

\ Testing and benchmarking

include random.fs
0 random

: shuffle ( n a -- )
    >r dup
    begin ?dup while 1- 2dup cells r@ + swap rnd swap mod cells r@ + xchg repeat
    rdrop 2drop
;

: fill-i ( n a -- )
    >r
    begin ?dup while 1- dup dup cells r@ + ! repeat
    rdrop
;

: fill-ir ( n a )
    begin 2dup ! cell+ swap 1- ?dup while swap repeat drop
;

1024 1024 * constant total-size
variable data total-size cells allocate throw data !
total-size data @ fill-i
total-size data @ shuffle
variable ssrt total-size cells allocate throw ssrt !

: exetime  utime 2>r quicksort execute  utime 2r> d- ." dtime " . cr ;

variable size 16 size !
variable logs  4 logs !

: run ( fp )
    >r
    begin total-size size @ >= while
        data @ ssrt @ size @ cells move
        ssrt @ size @ cells + ssrt @
        size @ . cr
        .s cr
        r@ hex. cr
        r@ exetime
        size @ . size @ m*/
        size @ 2 * size !
    repeat
    rdrop
;

' quicksort run
bye


texts: Write the HTML markup for several of (profile picture + message heading + message)

texts:
I was asked to write the HTML markup and CSS like the following:

User's profile picture on the left
his message heading
his message content

I was so concerned with how to correctly make it displayed (with JavaScript data and render it into HTML, and the HTML would result as:

heading

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

heading

content...

heading

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

with CSS

.comment-section { width: 400px; font: 13px Arial, sans-serif; }
.comment-section .comment { margin: 10px 0; }
.comment-section img, .comment-section .comment-text { display: inline-block; }
.comment-section img { width: 50px; height: 50px; margin-right: 5px; }
.comment-section .comment-text { vertical-align: top; width: 340px; }
.comment-section h4 { margin: 0 0 2px; }

Example at: https://jsfiddle.net/zayquc9q/2/

Should I actually have used
 and
:

heading

content...

Or
 and
 instead?

heading

content...

So although what I did looked pretty good in the real webpage, I don't know whether it was that it wasn't semantic markup that they disqualified me (for a JavaScript / React / Redux position), after this phone interview.


texts: Class to create HTML heading tags in React

texts:
I have a class which is part of my page layout. It is creating header tag elements (h1 - h5). Could someone tell me how I could improve it (I know it should be improved, but don't know how)? I have problem with rewriting almost the same code in switch cases. Would rather to create some kind of <h{type}></h{type}> code, but couldn't.

import React, {Component} from 'react';
import PropTypes from 'prop-types';

export class TypographyHeader extends Component {
    createHeader() {
        let txt        = this.props.text;
        let spaceIndex = txt.indexOf(' ');
        let p2         = txt.substr(spaceIndex);

        txt =

                {txt.substr(0, spaceIndex)}
            ;

        switch(this.props.headerType) {
            case 1:
                return
{txt} {p2}
;
            case 2:
                return
{txt} {p2}
;
            case 3:
                return
{txt} {p2}
;
            case 4:
                return
{txt} {p2}
;
            case 5:
                return
{txt} {p2}
;
        }

        return
{txt} {p2}
;
    }

    render() {
        return (

                {this.createHeader()}

        );
    }
}

TypographyHeader.propTypes = {
    headerType: PropTypes.oneOf([1, 2, 3, 4, 5]).isRequired,
    text: PropTypes.string.isRequired,
};


texts: Word counter using a word list and some text files

texts:
My program works with two types of files.
File 1 contains 500,000 distinct words.
File set 2 contains 173 text files, each containing 500 paragraphs, that I scraped from Wikipedia.
The program counts how many times each word from the first file appears in the second set of files.

The main problem I have is that it's taking around 4 seconds per word to process so it will take around 24 days to complete all 500k words in a core5 7th gen 8gb ram laptop. Is it possible to make it more process efficient?

I am still learning Java so my knowledge is not that vast.  I am using Java 8, with IntelliJ as my IDE.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class Main {

public static void main(String[] args) {

    //This is the map that will contain each word
    Map<String, Integer> map = new HashMap<>();
    //int that will count how manny times the word is in the File set 2
    int wordCounter = 0;
    //List that contain arround 500k unrepeted words
    List<String> list = new ArrayList<>();
    //List that contains the current file words
    List<String> list1 = new ArrayList<>();

    try {
        //scans the file that contains the 500k unrepeted words
        Scanner s = new Scanner(new File("C:\\Users\\filepath"));
        //while loop that add the words to a list so it can manipulate it latter on
        while (s.hasNext()) {
            list.add(s.next());
        }
        //random output to see the Set size
        System.out.println(list.size());

        //main loop that will cheek each word in the 500k file
        for (int i = 0; i < list.size(); i++) {
            //loop to se each file of words
            for (int j = 0; j < 100; j++) {
                try {
                    //read each file
                    Scanner d = new Scanner(new File("C:\\Users\\filepath" + j));
                    //add the information of each file
                    while (d.hasNext()) {
                        list1.add(d.next());
                    }
                    d.close();
                    //this code counts the number of words in all the files a
                    wordCounter = wordCounter + Collections.frequency(list1, list.get(i).toLowerCase());
                    //clears the list so it has more space and not run out of it
                    list1.clear();

                } catch (IOException k) {
                    k.printStackTrace();
                }
            }
            //adds the information to the map
            map.put(list.get(i), wordCounter);
            //this sorts the information and discard the words that only has 1 or less matches
            if (wordCounter > 1) {
                try {
                    FileWriter fw = new FileWriter("C:\\Users\\filePath", true);
                    PrintWriter pw = new PrintWriter(fw);
                    pw.append("\n");
                    pw.append(map.toString());
                    pw.close();

                } catch (IOException f) {
                    f.printStackTrace();
                }
            }
            //this clean the map so it doesnt run out of memory
                map.clear();
            //resets the counter to 0
                wordCounter = 0;
                //simple display so it seems nice
            System.out.println(i);

        }
    } catch (IOException f){
            f.printStackTrace();
        }

        }

    }

Somewhere I read that because of Java using a virtual machine it makes the processing of data much slower. Would that be something to consider?


texts:
I have created my own personal data structure libraries for C and I've re-engineered it about two times now and I've added alot of preprocessor checks and defines concerning OS type and compiler type.

One thing I've wanted to add to my personal libraries is having an informal "standard" fixed-size floating-point types.

#ifndef __float32_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __float32_t_defined
        typedef float float32_t TYPE_MODE(__SF__);
#   elif FLT_MANT_DIG==24
#       define __float32_t_defined
        typedef float float32_t;
#   elif DBL_MANT_DIG==24
#       define __float32_t_defined
        typedef double float32_t;
#   endif
#endif

#ifndef __float64_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __float64_t_defined
        typedef float float64_t TYPE_MODE(__DF__);
#   elif FLT_MANT_DIG==53
#       define __float64_t_defined
        typedef float float64_t;
#   elif DBL_MANT_DIG==53
#       define __float64_t_defined
        typedef double float64_t;
#   elif LDBL_MANT_DIG==53
#       define __float64_t_defined
        typedef long double float64_t;
#   endif
#endif

#ifndef __floatmax_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __floatmax_t_defined
        typedef double floatmax_t TYPE_MODE(__XF__);
#   elif LDBL_MANT_DIG>=64
#       define __floatmax_t_defined
        typedef long double floatmax_t;
#   elif DBL_MANT_DIG>=64
#       define __floatmax_t_defined
        typedef double floatmax_t;
#   else
#       define __floatmax_t_defined
        typedef float floatmax_t;
#   endif
#endif

For Clang and GCC, I use the compiler extension that checks machine mode and sets the type definition to the largest width of the floating point type. I added further type definition checks in the event Clang or GCC are not used.

my main question is that, given the macros in float.h, is checking float size by its mantissa a wise/safe thing to do? If not, what alternative can I take?


texts:
To work around the XmlSerializer memory leak thing I created this:

public static class XmlSerializerCache
{
    public static XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute xmlRoot)
    {
        var cache = System.AppDomain.CurrentDomain;
        var key = String.Format(CultureInfo.InvariantCulture, "CachedXmlSerializer:{0}:{1}", type, xmlRoot.ElementName);

        var serializer = cache.GetData(key) as XmlSerializer;
        if (serializer == null)
        {
            serializer = new XmlSerializer(type, xmlRoot);
            cache.SetData(key, serializer);
        }
        return serializer;
    }
}

As far as I understood, the generated assemblies get unloaded as soon as the AppDomain gets unloaded. So I thought I can use the AppDomain Cache to cache my serializers.

Is this approach a good one? Or at least a "Leak-Safe" one?


texts:
I run into this often.  I have two functions very similar, that if I combine would be more DRY but if I didn't would be easier to read and make more sense.

In this case I have two implementations of fade, one using setInterval and one using setTimeout.

How do I not get stuck deciding between Dry vs. readability.  I hope this is not an opinion question that is not answerable.

   /*fade
    **  d:none
    **  n:uses setTimeout
    **
    */
    NS.prototype.fade = function (direction, max_time) {
        var statics = {},
            elements = this;
        statics.elapsed = 0;
        statics.granularity = 10;
        if (statics.timeout_id) {
            clearTimeout(statics.timeout_id);
        }
        (function next() {
            var kindex,
                opacity;
            statics.elapsed += statics.granularity;
            if (direction === 'up') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        opacity = statics.elapsed / max_time;
                        elements[kindex].style.opacity = opacity;
                    }
                }
            } else if (direction === 'down') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
                    }
                }
            }
            if (statics.elapsed < max_time) {
                statics.timeout_id = setTimeout(next, statics.granularity);
            }
        }());
    };

    /*fadeL
    **  d:none
    **  n:(L)inear. Uses setInterval. Better for short animations.
    **
    */
    NS.prototype.fadeL = function (direction, max_time) {
        var statics = {},
            elements = this;
        statics.elapsed = 0;
        statics.granularity = 10;
        if (statics.timeout_id) {
            clearInterval(statics.timeout_id);
        }
        (function next() {
            var kindex,
                opacity;
            statics.elapsed += statics.granularity;
            if (!statics.timeout_id) {
                statics.timeout_id = setInterval(next, statics.granularity);
            }
            if (direction === 'up') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        opacity = statics.elapsed / max_time;
                        elements[kindex].style.opacity = opacity;
                    }
                }
            } else if (direction === 'down') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
                    }
                }
            }
            if (statics.elapsed > max_time) {
                clearInterval(statics.timeout_id);
            }
        }());
    };


texts:
This is my solution to this question from Hackerrank.

  Given N (<= 100000), find the largest N-digit number such that:

  The number has only 3 and 5 as its digits.
  Number of times 3 appears is divisible by 5.
  Number of times 5 appears is divisible by 3.

  If no such number exists, produce -1.

Please guide me. Is there any optimization or improvement that can be done to the code?

a=0
items=[]

a=int(raw_input(''))
for i in range(0,a):
    items.append(int(raw_input('')))

def Sherlock_and_The_Beast(items):
    for i in items:

        if i<3:
            print -1
        elif i%3==0:
            print int(str(5)*i)
        elif i==5:
            print int(str(3)*i)

        else:
            flag=False
            for j in range(i/3,-1,-1):
                if (i-(3*j))%5==0:
                    flag=True
                    print int(str(5)*(3*j)+str(3)*(i-(3*j)))
                    break
            if not flag:
                print -1

Sherlock_and_The_Beast(items)


texts: Switching article states using state pattern

texts:
The Article model supports a bunch of transitions. Only two are shown below: star()/unstar().
Is this a valid implementation of the state pattern?
interface ArticleState {
  star(): ArticleState;
  unstar(): ArticleState;
  // other transitions ...
}

export class InitialArticleState implements ArticleState {
  star   = () => new StarredArticleState();
  unstar = () => this;
  // other transitions ...
}

export class StarredArticleState implements ArticleState {
  star   = () => this;
  unstar = () => new InitialArticleState();
  // other transitions ...
}

export class Article {
  state: ArticleState = new InitialArticleState();
  star() { this.state = this.state.star(); }
  unstar() { this.state = this.state.unstar(); }
}

The Article state operations are wrapped by the service which updates the feed:
@Injectable()
export class ArticlesFeedService {

  private feed$: Subject<Article[]> = new BehaviorSubject<Article[]>([]);
  private store: Article[] = [];

  private publishChanges() {
    this.feed$.next(this.store);
  }

  starArticle(article: Article): void {
    article.star();
    // update the store then publish changes...
  }
}

There's a component subscribed to get starred articles:
getStarredArticles(): Observable<Article[]> {
  return this.getArticles().pipe(
    map((articles: Article[]) =>
      articles.filter((article: Article) =>
        article.state instanceof StarredArticleState
      )
    )
  );
}

My motivation behind using the state pattern is that it helps reduce branching (decision making) in the feed service methods (e.g. starred article can't be blacklisted, only unstarred / initial).

Is it okay to use state as public property of the Article? I thought about marking the article's state property as private and introducing a readonly string tag to each state (to ArticleState interface), so I could subscribe/filter using the tag. But it's a string and I'm tottally not sure if it's better.
How can I improve the design?
Are there any TypeScript features that could be used instead?


texts: Faster copying of images to change their PixelFormat

texts:
I have the following code below that creates a new Bitmap object the same as the original but to ensure that its PixelFormat is 24bppRgb. Does anyone know if there is a faster way to do this:

using (Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
    }

    //...


texts:
I wrote this without much thought:

(defn- tail-cmd
  "Construct a tail cmd"
  [file n & ignore-patterns]
  (clojure.string/join
   " | "
   (flatten [(format "tail -n %s -f %s" (or n 200) file)
             (map #(format "grep --line-buffered -v \"%s\"" %)
                  ignore-patterns)])))

On further thought, I'm not sure if it can simplified further. Can it be?


texts:
I am writing my first programs in Python and want to be sure my code is good and not too C++-like. Consider the problem of finding all common 'associations' for set of 'keys'.

Data format is

first line: integer N
N lines: key: association 1 ... association P_1
N+2th line: integer K
K lines: key 1 ... key T_1

For each line after K, the program should output all common associations for all keys listed.

For example, the correct output for input

10
0: even
1: odd
2: even prime
3: odd prime
4: even composite notprime
5: odd prime
6: even composite notprime
7: odd prime
8: even composite notprime
9: odd composite notprime
2
8 4
2 3

is

composite even notprime
prime

My code is

f = open('input.txt', 'r') #input file
d = {} #associations
uni = set() #set of all associations

for i in range(int(f.readline())):
  t = f.readline().strip().split(': ') #split into list ('key', 'assoc1 ... assoc P_1')
  d[t[0]] = s = set(t[1].split(' ')) #d : key -> set('assoc1', ..., 'assoc P_1')
  uni |= s #add to uni

for i in range(int(f.readline())):
  #read keys as list and intersect uni and list's associations
  print reduce(lambda assoc, key: assoc & d[key], set(f.readline().strip().split(' ')), uni.copy())

How good is my code from the viewpoint of experienced Python programmers?


texts: Remove the parent element when user clicks on the remove icon

texts:
X
form 0

X
form 1

X
form 2

X
form 3

I would like to hide the parent div, when it clicks on the remove element.

   $(".remove-form-0").on("click", function(){
          $("#form-0").css("display", "none");
  });

I do not want to duplicate this for 4 times. What is the best solution for this ?

Any helps would be highly appreciated.


texts:
I'm starting to learn Python and am trying to optimize this bisection search game.

high = 100
low = 0
guess = (high + low)/2

print('Please think of a number between 0 and 100!')

guessing = True
while guessing:
    print('Is your secret number ' + str(guess) + '?')
    pointer = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l'   to   indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
    if pointer == 'h':
        high = guess
        guess = (low + guess)/2

    elif pointer == 'l':
        low = guess
        guess = (high + guess)/2

    elif pointer == 'c':
        guessing = False

    else:
        print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: ' + str(guess))


texts: F# InitInfinite(Async) functions in C# without disabling ReSharper warnings

texts:
When coding in C# I often miss some functions from the F# world.

One of them is Seq.initInfinite, others are its counterparts with the AsyncSeq library:

AsyncSeq.initInfiniteAsync
AsyncSeq.initInfinite

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;

public static class Enumerable
{
    public static IEnumerable<T> InitInfinite<T>(Func<T> itemFactory)
    {
        while (true)
        {
            yield return itemFactory();
        }
        // ReSharper disable once IteratorNeverReturns
    }
    public static IEnumerable<T> InitInfinite<T>(Func<BigInteger, T> itemFactory)
    {
        var index = BigInteger.Zero;
        while (true)
        {
            yield return itemFactory(index);
            index++;
        }
        // ReSharper disable once IteratorNeverReturns
    }
}
public static class AsyncEnumerable
{
#pragma warning disable 1998
    public static async IAsyncEnumerable<T> InitInfinite<T>(Func<T> itemFactory)
#pragma warning restore 1998
    {
        while (true)
        {
            yield return itemFactory();
        }
        // ReSharper disable once IteratorNeverReturns
    }
#pragma warning disable 1998
    public static async IAsyncEnumerable<T> InitInfinite<T>(Func<BigInteger, T> itemFactory)
#pragma warning restore 1998
    {
        var index = BigInteger.Zero;
        while (true)
        {
            yield return itemFactory(index);
            index++;
        }
        // ReSharper disable once IteratorNeverReturns
    }
    public static async IAsyncEnumerable<T> InitInfiniteAsync<T>(Func<Task<T>> asyncItemFactory)
    {
        while (true)
        {
            yield return await asyncItemFactory();
        }
        // ReSharper disable once IteratorNeverReturns
    }
    public static async IAsyncEnumerable<T> InitInfiniteAsync<T>(Func<BigInteger, Task<T>> asyncItemFactory)
    {
        var index = BigInteger.Zero;
        while (true)
        {
            yield return await asyncItemFactory(index);
            index++;
        }
        // ReSharper disable once IteratorNeverReturns
    }
}

My code is working as expected, like in the example below:

public static class Program
{
    public static async Task Main()
    {
        var asyncResultWithIntegers = await AsyncEnumerable
            .InitInfiniteAsync(i => Task.FromResult(i))
            .Take(4)
            .ToArrayAsync();

        var asyncResultWithoutIntegers = await AsyncEnumerable
            .InitInfiniteAsync(() => Task.FromResult("Hi there!"))
            .Take(4)
            .ToArrayAsync();

        var resultWithIntegers = await AsyncEnumerable
            .InitInfinite(i => i)
            .Take(4)
            .ToArrayAsync();

        var resultWithoutIntegers = await AsyncEnumerable
            .InitInfinite(() => "Hi there!")
            .Take(4)
            .ToArrayAsync();

        Console.ReadKey();
    }
}

I am wondering if there is a better way to implement those. In particular, is there a way to implement those methods without disabling the ReSharper warnings?


texts: Inline Sum() vs query Sum() vs Where on a List object

texts:
Just after a bit of feed back or peoples ideas on which practice is best.

I currently have a method but am unsure of the best way to approach it from a readability point of view or even from best practices point of view.  Or perhaps it doesn't really matter at all and they are all fine?

My three options I explored were:

1)

function double GetObjectArea(CustomObject obj, CustomEnum source)
{
   return obj.ListOfApplications.Sum(p => p.Source == source ? object.Area : 0);
}

2)

function double GetObjectArea(CustomObject obj, CustomEnum source)
{
   var query = from record in obj.ListOfApplications
               where record.Source == source
               select object.Area

   return query.Sum();
}

3)

function double GetObjectArea(CustomObject obj, CustomEnum source)
{
   return obj.ListOfApplications.Where(p.Source == source).Sum(object.Area);
}


texts:
I've just started writing asynchronous methods for the first time having watched some tutorials.

I have a method where I run two tasks in parallel (notifySales, insertDownload):

Task insertDownload = _downloadService.InsertDownloadRequestAsync(model, Request.UserAgent);

if (product.NotifySalesByEmail)
{
    Task notifySales = _downloadService.EmailDownloadRequestAsync(model);
    await Task.WhenAll(insertDownload, notifySales);
}
else
{
    await insertDownload;
}

As you can see, the task notifySales only gets run if product.NotifySalesByEmail is true. This task, as well as task insertDownload can be run in parallel.

I'm not sure I like the way in which I have said 'if true await both else just await one'.

Would a better way to be to create a Task[] array, add the tasks that are required to run and then await the array?


texts:
I've recently used this block of code from a quiz app where I check an array for the correct answer that was received from the browser and sent to the mobile device/application.

private void setCorrectAnswer() {
    //iterates till it finds the string that is equal to qAnswer(Correct Answer) in answerArray
    for (int i = 0; i < allButton.length; i++) {
        if (questionAns.equals(answerArray[i])) {
            viewAnswer = allButton[i];
            Log.i(TAG_INFO, "Correct Answer: " + answerArray[i]);
            i = allButton.length;
        }
    }
}

Another method to set the participant's answer:

private void setParticipantAnswer(View v) {
    try {
        studentViewAnswer = (Button)v;
        studentAnswer = studentViewAnswer.getText().toString();
        //iterates till it finds the string that is equal to studentAnswer in answerArray
        for (int i=0; i < allButton.length; i++) {
            if (studentAnswer.equals(answerArray[i])) {
                studentViewAnswer = allButton[i];
                Log.i(TAG_INFO, "Student Answer: " + answerArray[i]);
                i = allButton.length;
            }
        }
    } catch (NullPointerException e) {
        studentAnswer = null;
    }
}

Both of these methods set the button color to red (i.e. wrong) / green (i.e. right), which is triggered by another method.

My problem with this code is that it returns null when the user doesn't have an answer and every time the browser sends the choices I have to reset the last answer to null again. I've already caught the null with a nullexception. Would there be any problem if I continue doing this? If so, what's the better approach to this?


texts:
I'm back with a Python solution for Project Euler 35. Any help would be appreciated; I generate the numbers by observing that all circular primes can only have digits 1, 3, 7, and 9. Then I use the Cartesian product built into itertools. I also have a local primes test from Wikipedia.

from primes import test as is_prime
from itertools import product # cartesian product
from timeit import default_timer as timer

def find_circular_primes_under(limit):
    def is_circular(digits):
        digits = list(digits)
        for digit in digits:
            if not is_prime(int(''.join(map(str, digits)))):
                return False
            else:
                digits.append(digits.pop(0))
        return True

    if type(limit) != int or limit <= 2:
        return "Error: primes are positive integers greater than 1."
    elif limit <= 11:
        sum = 0
        for k in range(limit):
            if is_prime(k):
                sum += 1
        return sum

    else:
        sum = 4
        for k in range(2, len(str(limit))):
            for combo in product([1, 3, 7, 9], repeat = k):
                if is_circular(combo):
                    sum += 1
        return sum

start = timer()
ans = find_circular_primes_under(10**6)
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts:
I am a beginner in Python, I want to know if this code can be improved. Is it possible to make it work without the if/else?

number1=int(input('Enter first number: '))
number2=int(input('Enter Second number: '))
operation=input("Enter operation\n[+,-,*,/]")
if operation == '+':
    sum=number1+number2
elif operation == '-':
    sum =number1-number2
elif operation == '*':
    sum =number1*number2
else:
    sum =number1//number2
print(sum)


texts: Recreating Google homepage for learning purposes

texts:
Like other posters, I'm currently working on recreating Google's Homepage for The Odin Project.

I'm new to HTML and CSS but I'm eager to learn and have been looking around for an answer, testing different code, and pacing back & forth - I'm still stuck.

I'm having an issue with positioning things on my project. I've read through W3School's documentation on CSS but the method in which I used to position my buttons "Google Search" & "I'm feeling lucky" seems like a in-this-case-solution that may not work with all browsers or especially responsive design.

This is the area I'm trying to duplicate:

I was able to center the logo and the search bar with:

{margin-left: auto;
margin-right: auto;
display: block;}

I was able to center the buttons with:

#googleSearch {display: inline-block; margin-left: 520px;
margin-right: auto;}
#feelingLucky {display: inline-block;}

All of my code is below but my questions is: is there a better way to position the buttons and if so, what? Playing with the margin-left until it looks right seems to me like the equivalent of using a bunch of line breaks instead of changing the margin or padding.

li {font-family: arial,sans-serif;
font-size: 13px; list-style: none; display: inline-block;}

nav {text-align: right; padding-right: 160px; word-spacing: 10px;}

#userName {opacity: .55;}

a, a:visited {color: black; text-decoration: none;}

a:hover {text-decoration: underline;}

img, #searchBox {display: block;
margin-left: auto;
margin-right: auto;}

img {margin-top: 200px}

#googleSearch {display: inline-block; margin-left: 520px;
margin-right: auto;}
#feelingLucky {display: inline-block;}
<!DOCTYPE HTML>

<link rel="stylesheet" href="index.css">
<meta charset="UTF-8">
<title>Google</title>
<link rel="shortcut icon" type="image/x-icon" href="http://www.google.com/favicon.ico">

Jarod

Gmail

Images

    <form action="#" method="get" name="searchForm">
    <input id="searchBox" type="text" name="searchBox">

    <input id="two" type="submit" value="Google Search">
            <input id="feelingLucky" type="submit" value="I'm Feeling Lucky">

    </form>

Is there a better way to position my buttons?


texts:
I want to "canonicalize" URLs for my static (files and folders) website.

The 'Aims' describes what I want to accomplish. The 'Code' gives my current .htaccess.

Everything works right now, but I wonder if the code could be improved:

any changes for better performance?
can some rules be removed?
can some rules be merged?
can something be shortened?
are some explaining comments wrong?

In my .htaccess there shouldn't be anything else as what is described in 'Aims' and my examples. So if there should be something that has nothing to do with it, it is probably unneeded (if I don't miss an important part right now).

Aims

Strip the file ending .html (but keep all other endings).
if the file is index.html, strip "index", too, and don't keep a (folder) trailing slash
no trailing slashs for files or folders

if someone adds a trailing slash, redirect to variant without

Example 1

Physical file: example.com/foo/bar.html
Desired URL: example.com/foo/bar
URLs that should redirect (301) to desired URL:

example.com/foo/bar.html
example.com/foo/bar/

Example 2 (if index.html)

Physical file: example.com/foo/index.html
Desired URL: example.com/foo
URLs that should redirect (301) to desired URL:

example.com/foo/index.html
example.com/foo/index
example.com/foo/
example.com/foo.html

Example 3 (if non-HTML file)

Physical file: example.com/foo/bar.png
Desired URL: example.com/foo/bar.png (= same as physical)
URLs that should redirect (301) to desired URL:

none

Code (.htaccess)

# Turn MultiViews off. (MultiViews on causes /abc to go to /abc.ext.)
Options +FollowSymLinks -MultiViews

# It stops DirectorySlash from being processed if mod_rewrite isn't.
<IfModule mod_rewrite.c>

  # Disable mod_dir adding missing trailing slashes to directory requests.
  DirectorySlash Off

  RewriteEngine On

  # If it's a request to index(.html)
  RewriteCond %{THE_REQUEST} \ /(.+/)?index(\.html)?(\?.*)?\  [NC]
  # Remove it.
  RewriteRule ^(.+/)?index(\.html)?$ /%1 [R=301,L]

  # if request has a trailing slash
  RewriteCond %{REQUEST_URI} ^/(.*)/$
  # but it isn't a directory
  RewriteCond %{DOCUMENT_ROOT}/%1 !-d
  # and if the trailing slash is removed and a .html appended to the end, it IS a file
  RewriteCond %{DOCUMENT_ROOT}/%1.html -f
  # redirect without trailing slash
  RewriteRule ^ /%1 [L,R=301]

  # Add missing trailing slashes to directories if a matching .html does not exist.
  # If it's a request to a directory.
  RewriteCond %{REQUEST_FILENAME}/ -d
  # And a HTML file does not (!) exist.
  RewriteCond %{REQUEST_FILENAME}/index.html !-f
  # And there is not trailing slash redirect to add it.
  RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

  RewriteCond %{REQUEST_FILENAME} -d
  # And a HTML file exists.
  RewriteCond %{REQUEST_FILENAME}/index.html -f
  # And there is a trailing slash redirect to remove it.
  RewriteRule ^(.*?)/$ /$1 [R=301,L]

  RewriteCond %{REQUEST_FILENAME} -d
  # And a HTML file exists.
  RewriteCond %{REQUEST_FILENAME}/index.html -f
  # And there is no trailing slash show the index.html.
  RewriteRule [^/]$ %{REQUEST_URI}/index.html [L]

  # Remove HTML extensions.
  # If it's a request from a browser, not an internal request by Apache/mod_rewrite.
  RewriteCond %{ENV:REDIRECT_STATUS} ^$
  # And the request has a HTML extension. Redirect to remove it.
  RewriteRule ^(.+)\.html$ /$1 [R=301,L]

  # If the request exists with a .html extension.
  RewriteCond %{SCRIPT_FILENAME}.html -f
  # And there is no trailing slash, rewrite to add the .html extension.
  RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]

</IfModule>

(some parts of this file are by Jon Lin over at Stack Overflow)


texts: Increase performance for this keyup function?

texts:
I have a keyup function that expands an input field as text is added. There are a lot of fields where this code will be applied, what is the best way to write this for best performance?

Here is a working demo: http://jsfiddle.net/J9Ner/

$('input.name','#bakery').live('keyup', function() {
    var el = $(this);
    var len = el.val().length;

    if (len < 20) {
        el.width('200px');
        return;
    } else if (len > 56) {
        return;
    }

    el.width((len * 10) + 'px');
});


texts: improving speed of this numpy-based diffraction calculator

texts:
I'm going to simulate diffraction patterns of a normal incident gaussian profile beam from a 2D array of point scatterers with a distribution in heights.

The 2D array of scatterer positions X, Y and Z each have size N x N and these are summed-over in each call to E_ab(a, b, positions, w_beam). This is done M x M times to build up the diffraction pattern.

If I estimate ten floating point operations per scatter site per pixel and a nanosecond per flop (what my laptop does for small numpy arrays) I'd expect the time to be 10 M^2 N^2 1E-09 seconds. For small N this runs a factor of 50 or 100 slower than that, and for large N (larger than say 2000) it slows down even further. I am guessing these have something to do with the paging of the large arrays in memory.

What can I do to increase the speed for large N?

note: Right now the height variation Z is random, in the future I plan to include an additional systematic height variation term as well, so even though purely gaussian variation might have an analytical solution, I need to do this numerically.

Since I'm distributing Z height randomly here, plots will look a little different each time. My output (run on a laptop) is as follows, and I can not even begin to understand why it takes longer (~ 16 seconds) when w_beam is small than when it is large (~6 seconds). (When I run this on an older Python 2 that came with IDLE all four are between 10 and 10.5 seconds)

My estimator 10 M^2 N^2 1E-09 suggests 0.25 seconds, these are roughly 50 times slower so there may be room for substantial improvement.

1 16.460583925247192
2 14.861294031143188
4 8.405776023864746
8 6.4988932609558105

Total time: about 46 seconds on 2012 MacBook and recent Anaconda Python 3 installation.

Python script:

import numpy as np
import matplotlib.pyplot as plt
import time

def E_ab(a, b, positions, w_beam, k0):
    X, Y, Z = positions
    Rsq = X**2 + Y**2
    phases = k0 * (a*X + b*Y + (1 + np.sqrt(1 - a**2 - b**2))*Z)
    E = np.exp(-Rsq/w_beam**2)  * np.exp(-j*phases)
    return E.sum() / w_beam**2 # rough normalization

twopi, j = 2*np.pi, np.complex(0, 1)

wavelength = 0.08
k0  = twopi/wavelength

z_noise = 0.05 * wavelength

N, M = 100, 50
x = np.arange(-N, N+1)
X, Y = np.meshgrid(x, x)
Z = z_noise * np.random.normal(size=X.shape) # use random Z noise for now
positions = [X, Y, Z]

A = np.linspace(0, 0.2, M)

answers = []
for w_beam in (1, 2, 4, 8):
    E = []
    tstart = time.time()
    for i, a in enumerate(A):
        EE = []
        for b in A:
            e = E_ab(a, b, positions, w_beam, k0)
            EE.append(e)
        E.append(EE)
    print(w_beam, time.time() - tstart)
    answers.append(np.array(E))

if True:
    plt.figure()
    for i, E in enumerate(answers):
        plt.subplot(2, 2, i+1)
        plt.imshow(np.log10(np.abs(E)), vmin=0.0001)
        plt.colorbar()
    plt.show()


texts: Given an input string and a pattern, implement wildcard pattern matching

texts:
I have been trying to solve "Wildcard Matching" on leetcode. I know there are more "manual" ways to solve this without using the RE library. But I would like to know if passing the time limit is possible without having to manually create a pattern finder from scratch.

Currently this code times out at test case 1708 (out of 1800 or so). I will put the question, leet code examples and my try in the code block below. The case that exceeds the time limit has been included in the 'inps' list of test cases (it is the last one). Can anyone think of a way to make this faster?

"""Given an input string (s) and a pattern (p), implement wildcard pattern matching with
support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).

Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:
Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:
Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:
Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*'
matches the substring "dce".

Example 5:
Input:
s = "acdcb"
p = "a*c?b"
Output: false
"""

class Solution:
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        import re
        from itertools import groupby

        grps = groupby(p)
        l = [(x, len(list(y))) for x, y in grps]

        new_p = ''
        for c, cnt in l:
            if c == '*':
                new_p = ''.join([new_p, '.*'])
            elif c == '?':
                new_p = ''.join([new_p, '.{', str(cnt), '}'])
            else:
                new_p = ''.join([new_p, c * cnt])

        p = '^' + new_p + '$'
        MY_RE = re.compile(p)
        return True if MY_RE.match(s) else False

# string, patter, expected
inps = [
    ("aa", "a", False),
    ("aa", "*", True),
    ("cb", "?a", False),
    ("adceb", "*a*b", True),
    ("acdcb", "a*c?b", False),
    ("abcdef", "", False),
    ("abcdef", "*", True),
    ("abcdef", "??????", True),
    ("abcdef", "a?c?e?", True),
    ("abcdef", "a?c?e?", True),
    ("abcdef", "********************", True),
    ("abcdef", "*****abcdef*****", True),
    ("abcdef", "?abcdef?", False),
    ("", "", True),
    ("", "*", True),
    ("", "*****", True),
    ("", "?", False),
    ("a", "*********?********", True),
    ("a", "?", True),
    ("abc", "?*?", True),
    (
        "aaaabaaaabbbbaabbbaabbaababbabbaaaababaaabbbbbbaabbbabababbaaabaabaaaaaabbaabbbbaababbababaabbbaababbbba",
        "*****b*aba***babaa*bbaba***a*aaba*b*aa**a*b**ba***a*a*",
        True,
    ),
    (
        "abbabaaabbabbaababbabbbbbabbbabbbabaaaaababababbbabababaabbababaabbbbbbaaaabababbbaabbbbaabbbbababababbaabbaababaabbbababababbbbaaabbbbbabaaaabbababbbbaababaabbababbbbbababbbabaaaaaaaabbbbbaabaaababaaaabb",
        "**aa*****ba*a*bb**aa*ab****a*aaaaaa***a*aaaa**bbabb*b*b**aaaaaaaaa*a********ba*bbb***a*ba*bb*bb**a*b*bb",
        False,
    ),
]

sol = Solution()
for s, p, exp in inps:
    #print(f"Doing string[{s}] with pattern[{p}] and asserting...")
    assert sol.isMatch(s, p) == exp


texts: LINQ method to create objects of different types

texts:
I have the following code inside a method:

var addresses = new List<MutateAddressData>();

var yearsDB = (from tr in this.uow.TaxReturns
                where taxReturnIds.Contains(tr.Id)
                select new { Year = tr.TaxYear, TaxReturnTypeId = tr.TaxReturnType.Id }).ToList();

var ibAndVpb = yearsDB.Where(y => y.TaxReturnTypeId == (decimal)TaxReturnType.IB ||
                                  y.TaxReturnTypeId == (decimal)TaxReturnType.VpB);
if (ibAndVpb.Any())
{
    var address = new MutateAddressData
                    {
                    AddressType = AddressType.TaxReturn,
                    CityId = customer.PaCity.Id,
                    CountryId = customer.PaCity.Country.Id,
                    HouseNumber = customer.PaHouseNumber,
                    HouseNumberPostfix = customer.PaHouseNumberPostfix,
                    Street = customer.PaStreet,
                    ZipCode = customer.PaZipCode,
                    Years = string.Join(", ", ibAndVpb.Select(t => t.Year.ToString())),
                    TaxReturnType = (TaxReturnType)ibAndVpb.First().TaxReturnTypeId,
                    };

    addresses.Add(address);
}

var averaging = yearsDB.Except(ibAndVpb);
if (averaging.Any())
{
    var address = new MutateAddressData
                    {
                    AddressType = AddressType.TaxReturn,
                    CityId = customer.PaCity.Id,
                    CountryId = customer.PaCity.Country.Id,
                    HouseNumber = customer.PaHouseNumber,
                    HouseNumberPostfix = customer.PaHouseNumberPostfix,
                    Street = customer.PaStreet,
                    ZipCode = customer.PaZipCode,
                    Years = string.Join(", ", averaging.Select(t => t.Year.ToString())),
                    TaxReturnType = (TaxReturnType)averaging.First().TaxReturnTypeId,
                    };

    addresses.Add(address);
}

return addresses.ToArray();

I want to create max two different objects here. One object for types that er Ib or Vpb and the other object is for all other types.

My senses tell me that I can achieve the same more easily, but I can't figure out how. What do you think?


texts: Converting HashMap data to a Response object

texts:
I have a HashMap and I want to convert data in it to a Response object. Is it possible to achieve this code that parses the string in a better and optimized and cleaner way, maybe by using streams?

class Converter{

   public static void main(String[] args) {

      Map<String, Long> map = new HashMap<String, Long>();
      map.put("111", 80) // first
      map.put("1A9-ppp", 190) // second
      map.put("98U-6765", 900) // third
      map.put("999-aa-local", 95) // fourth

      List<FinalProduct> products = new ArrayList<>();
      for(String key : map.keySet()){
        FinalProduct response = new FinalProduct();
        String[] str  = key.split("\\-");
        response.id = str[0] //id is always present in key i.e 111, 1A9, 98U,999
        if(str.length == 2) {
             if(str.matches("-?\\d+(\\.\\d+)?")){ // check if is numeric
                  response.code = str[1]; // 6765
             }
             else{
                  response.city = str[1]; //ppp
             }
        }
         if(str.length == 3){
                  response.client = str[1]; //aa
                  response.type = str[2];   // local
         }
        response.qty = map.get[key];
        products.add(response);
      }
   }
}

class FinalProduct{

String id;
String city;
Long code;
String client;
String type;
Long qty;
// getters and setters
}


texts:
Learn You a Haskell shows the delete function.

  delete: deletes first occurrence of item

ghci> delete 'h' "hey there ghang!"
"ey there ghang!"

Please critique my implementation.

delete' :: (Eq a) => a -> [a] -> [a]
delete' y xs = delete'' y xs []
                 where delete'' _ [] _ = []
                       delete'' d (a:as) acc
                         | a == d    = reverse acc ++ as
                         | otherwise = delete'' d as (a:acc)

I don't like the fact that I'm using the : operator, but then calling reverse and acc ++ as.

Also, I don't know how to capture the first pattern match of delete'' with a single pattern match and guards alone.


texts: Removing a header and footer from text output with PDFminer

texts:
I use PDFminer to extract text from a PDF, then I reopen the output file to remove an 8 line header and 8 line footer. Is there a more efficient way to remove the header/footer, either in place or without re-opening/closing the file? Please mention general best practices I did not follow.

# convert PDF to text
def write_txt(pdf):
    outfile = pdf.split("_")[4] + "_" + pdf.split("_")[1] + "_" + \
        pdf.split("_")[0] + ".txt"
    pagenos = set([2,3])

    codec = 'utf-8'
    caching = True
    laparams = LAParams()

    rsrcmgr = PDFResourceManager(caching=caching)
    outfp = file(outfile, 'w+')
    device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)
    fp = file(pdf, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.get_pages(fp, pagenos):
        interpreter.process_page(page)
    fp.close()
    device.close()
    outfp.close()

    # remove header/footer
    with open(outfile, 'r') as txtin:
        lines = txtin.read().splitlines(True)
    with open(outfile, 'w') as txtout:
        txtout.writelines(lines[8:-8])

    return outfile


texts:
I am attempting to solve the Minimum Path Sum algorithm problem and I have a working solution, however there was an unwritten requirement that the algorithm not exceed an unspecified amount of time for any given matrix of size (m x n).

  Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

  Note: You can only move either down or right at any point in time.

I know that this is one of these problems perfectly suited to Dynamic Programming, however my brain turns to mush when I start reading up on it.  This is supposed to be possible with two different state arrays capturing sums, but I am not comprehending how to do this accurate such that I am sure I am going the right direction.

public class Solution {

    int width = 0;
    int height = 0;
    HashMap<Point, Integer> previousStates = new HashMap<Point, Integer>();

    public int minPathSum(int[][] grid) {
        previousStates = new HashMap<Point, Integer>();
        height = grid.length;
        width = grid[0].length;
        return func(grid, new Point(0, 0));
    }

    int func(int[][] grid, Point p) {
        if (p.x == (width - 1) && p.y == (height - 1)) {
            return grid[p.y][p.x];
        }

        Point rightMostPoint = new Point(p.x + 1, p.y);
        Point downMostPoint = new Point(p.x, p.y + 1);
        boolean existingRightPreviousState = previousStates.containsKey(rightMostPoint);
        boolean existingDownPreviousState = previousStates.containsKey(downMostPoint);
        int rightLowestCost = (existingRightPreviousState) ? previousStates.get(rightMostPoint) : Integer.MAX_VALUE;
        int downLowestCost = (existingDownPreviousState) ? previousStates.get(downMostPoint) : Integer.MAX_VALUE;
        if (rightMostPoint.x < width && !existingRightPreviousState) {
            rightLowestCost = func(grid, rightMostPoint) + grid[p.y][p.x];
            previousStates.put(rightMostPoint, rightLowestCost);
        }
        if (downMostPoint.y < height && !existingDownPreviousState) {
            downLowestCost = func(grid, downMostPoint) + grid[p.y][p.x];
            previousStates.put(downMostPoint, downLowestCost);
        }

        return (rightLowestCost <= downLowestCost) ? rightLowestCost : downLowestCost;

    }
}

class Point {
    int x; int y;
    public Point(int x, int y) { this.x = x; this.y = y; }
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Point))
            return false;
        Point p = (Point)obj;
        return this.x == p.x && this.y == p.y;
    }
    public int hashCode() {
        return this.x ^ this.y;
    }
}

I start at the top left and recursively work either down or right based on which one returns the lowest sum.  For a given cell in the matrix if I have already encountered it then I already know which Point has the lowest cost in relation to that so I don't have to re-evaluate it.  In a way I am capturing state and using it but it still doesn't seem to meet the performance requirements of this problem.  I am guessing the unspoken requirement is \$O(n)\$ complexity and I am unsure in my recursive approach if that is possible.

Do you have any suggestions for improvement here so that I can reduce the operational complexity of this algorithm or at least offer me a better explanation of how dynamic programming can be used to solve this?


texts:
Here is the general goal of this exercise:

  For each string, print whether or not the string of brackets is balanced on a new line. If the brackets are balanced, print YES; otherwise, print NO.

Please comment as this was a job interview and I had 30 mins to give something working and the best performance wise.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            List<string> list = new List<string> {"({[]})", "][(]}})("};

            foreach (var barcketsList in list)

            {
                string expression = barcketsList;
                Stack<char> stack = new Stack<char>();
                char[] symbols = expression.ToCharArray();
                if (symbols.Length == 0)
                {
                    break;
                }
                bool flagPrint = false;
                for (int start = 0; start < symbols.Count(); start++)
                {
                    char temp = symbols[start];
                    if (temp == '[' || temp == '{' || temp == '(')
                    {
                        stack.Push(temp);
                    }
                    else
                    {
                        if (stack.Count == 0) //only closer no opening
                        {
                            Console.WriteLine("NO");
                            flagPrint = true;
                            break;

                        }
                        char top = stack.Peek();
                        if (temp == ']')
                        {
                            if (top != '[')
                            {
                                break;
                            }
                            stack.Pop();
                        }
                        else if (temp == '}')
                        {
                            if (top != '{')
                            {

                                break;
                            }
                            stack.Pop();
                        }
                        else // temp == ')'
                        {
                            if (top != '(')
                            {

                                break;
                            }
                            stack.Pop();
                        }
                    }
                }
                if (!stack.Any() && !flagPrint)
                {
                    Console.WriteLine("YES");
                }
                else if (!flagPrint)
                {
                    Console.WriteLine("NO");
                }
            }
        }
    }
}


texts: (Leetcode) Longest consecutive sequence in Python

texts:
This is a Leetcode problem -

  Given an unsorted array of integers, find the length of the longest
  consecutive elements' sequence.

  Your algorithm should run in \$O(n)\$ complexity.

  Example -

Input: [100, 4, 200, 1, 3, 2]
Output: 4

# Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Here is my solution to this challenge -

def longestConsecutive(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    if not nums:
        return 0

    nums = list(dict.fromkeys(nums))
    nums.sort()
    count = 1
    longest_streak = []

    for index, value in enumerate(nums):
        if index + 1 >= len(nums):
            break

        if nums[index + 1] == value + 1:
            count += 1
            longest_streak.append(count)
        else:
            count = 1

    if not longest_streak:
        return count

    return max(longest_streak)

Here is my Leetcode result -

So, I would like to know whether I could make this program faster and more efficient.

NOTE - Though my solution got accepted, I really have no idea about the time complexity of my program. Maybe someone could cover that too?


texts:
Here's what I have:

require('../../src/utils/date-object-to-yyyymmdd');
var eighteenYearsAgo = new Date();
eighteenYearsAgo.setTime(eighteenYearsAgo.valueOf() - 18 * 365 * 24 * 60 * 60 * 1000);
eighteenYearsAgo = eighteenYearsAgo.yyyymmdd();

Basically, I am generate a date, setting it to 18 years ago (from today), and then converting it to yyyy-mm-dd format via an external function. I feel like this is quite verbose as is, but can't quite wrap my head around how to do it in a shorter way.


texts: Python: Find pairs of numeric palindromes that sum up to another palindrome

texts:
I am trying to identify and print pairs of 4 digit palindromes that sum up to a 5 digit palindrome.

This is what I have so far

def isPalindrome(x):
    return str(x)==str(x)[::-1]

palindrome = [x for x in range(1000, 10000) if isPalindrome(x)]

for x in palindrome:
    for y in palindrome:
        if (9999 < x+y < 100000) and isPalindrome(x+y):
            print(x, y, x+y)

I am estimating the time complexity for this to be O(n^2),because I am traversing the list twice. Is it possible to improve on this?


texts: Advent of Code 2020 Day 2 in Clojurescript

texts:
This is a Clojurescript solution to parts 1 and 2 of Day 2 of Advent of Code 2020.
This code is written in Clojurescript to run on Node.js. It can be run simply using lumo and this command: lumo filename.cljs.
Here's a short version of the problem statement:
Part 1. Given a file in the format
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc

Each line gives a "password policy" and then the password. The policy indicates the lowest and highest number of times the given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. How many passwords in the list are valid?
(require '[clojure.string :as str])

(def fs (js/require "fs"))

(def lines
  (str/split-lines
   (.readFileSync fs "puzzle.input" "utf8")))

(def split-lines (map #(str/split % #" ") lines))

(defn valid? [mini maxi freqs letter]
  (let [occurances (get freqs letter 0)]
    (and (>= occurances mini) (<= occurances maxi))))

(defn process-line [line]
  (let [[nums letter pass] line
        [mini maxi] (map js/parseInt (str/split nums #"-"))]
    (valid? mini maxi (frequencies pass) (subs letter 0 1))))

(println (count (filter true? (map process-line split-lines))))

Part 2: Given the same list, each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. Exactly one of these positions must contain the given letter. How many passwords are valid?
;; Same boilerplate

(defn valid? [index-1 index-2 letter pass]
  (let [spot-1 (subs pass (- index-1 1) index-1)
        spot-2 (subs pass (- index-2 1) index-2)]
    (or
     (and (= spot-1 letter) (not= spot-2 letter))
     (and (not= spot-1 letter) (= spot-2 letter)))))

(defn process-line [line]
  (let [[nums letter pass] line
        [index-1 index-2] (map js/parseInt (str/split nums #"-"))]
    (valid? index-1 index-2 (subs letter 0 1) pass)))

(println (count (filter true? (map process-line split-lines))))


texts: Circular dependency in utility functions

texts:
Some Background

I've been developing an ESLint plugin to catch Protractor/Jasmine specific code style violations.

In Protractor, there are two important notations: ElementFinder and ElementArrayFinder.

ElementFinder is a special object that corresponds to a single element

is typically defined via element(by.smth("")) or $("css selector").

ElementArrayFinder is a special object that corresponds to an array of elements

is typically defined via element.all(by.smth("")) or $$("css selector")

And, all of these notations can be chained. ElementFinder can also be retrieved from an ElementArrayFinder via get(), first() or last() methods, e.g.:

element.all(by.className("someClass")).element(by.tagName("td"));

The Task

In multiple ESLint rules I've been developing so far, I needed to locate the ESLint Call Expressions that are either ElementFinder or ElementArrayFinder.

Currently, I've come up with two utility functions that are circularly dependent on each other:

is-element-finder.js:

'use strict'

/**
 * Checks if a given node is an ElementFinder instance.
 *
 * @fileoverview Utility function to determine if a node is an ElementFinder
 * @author Alexander Afanasyev
 */

var elementArrayFinderGetMethods = [
  'get',
  'last',
  'first'
]
var elementFinderConstructors = [
  '$',
  'element'
]

module.exports = function (node) {
  var callee = node.callee
  if (!callee) {
    return false
  }

  // handling raw $ and element
  if (elementFinderConstructors.indexOf(callee.name) > -1) {
    return true
  }

  // handling $ and element chaining
  if (callee.type === 'MemberExpression' && callee.property) {
    if (elementFinderConstructors.indexOf(callee.property.name) > -1) {
      return true
    }

    // got element finder from element array finder
    var isElementArrayFinderMethod = elementArrayFinderGetMethods.indexOf(callee.property.name) > -1
    if (isElementArrayFinderMethod && callee.object && isElementArrayFinder(callee.object)) {
      return true
    }
  }

  return false
}
var isElementArrayFinder = require('./is-element-array-finder')

is-element-array-finder.js:

'use strict'

/**
 * Checks a given CallExpression node is an ElementArrayFinder instance.
 *
 * @fileoverview Utility function to determine if a node is an ElementArrayFinder
 * @author Alexander Afanasyev
 */

module.exports = function isElementArrayFinder (node) {
  var callee = node.callee

  if (callee) {
    // handling $$ shortcut
    if (callee.name === '$$') {
      return true
    }

    // handling element.all() and nested .all()
    if (callee.property && (callee.property.name === 'all' || callee.property.name === '$$')) {
      if (callee.object) {
        if (callee.object.type === 'Identifier') {
          return callee.object.name === 'element'
        }

        if (callee.object.type === 'CallExpression') {
          return isElementFinder(callee.object) || isElementArrayFinder(callee.object)
        }
      }
    }
  }

  return false
}
var isElementFinder = require('./is-element-finder')

The argument node here is a CallExpression ESLint object.

The Problem

These two functions successfully pass all of my tests and locate ElementFinder and ElementArrayFinder instances.

But, because they both can be chained, each of the functions need to call another, which leads to a circular dependency. How would you approach removing the circular dependency? I would also appreciate any comments about the code style and readability.

Note: using Standard JS style.

I understand that there is a bit of a context in order to understand the problem, but I am open to elaborate more or add any additional information.


texts: Selection sort review. Does it look good?

texts:
I always wanted to ask this but couldn't for some reason.

I had written this chunk of code about 3 months ago when one of my teacher explained what selection sort was using flow chart. I had a basic understanding of what arrays were. So I sat down and wrote this:

#include <stdio.h>

#define MAX_NUMBER 10

void selection_sort(int [], int []);

void selection_sort(int num[], int sorted[])
{
    int i, high = 0, k, j = 9, store;

    for(k = 0; k < MAX_NUMBER; k++)
    {
      for(i = 0; i < MAX_NUMBER; i++)
      {
         if(num[i] > high)
         {
             high = num[i];
             store = i;
         }
      }

      sorted[j] = high; // Place the highest number in the end of array and decrement array
      j--;
      num[store] = 0; // Place 0 in the place of maximum number that was in the array
      high = 0; // again make high as zero, so as to compare zerpo again with all the numbers that are in the array
    }
}

int main()
{
    int num[MAX_NUMBER], sorted[MAX_NUMBER];
    int i;

    printf("Enter %d numbers: ", MAX_NUMBER);

    for(i = 0; i < MAX_NUMBER; i++)
    {
        scanf("%d", &num[i]);
    }

    selection_sort(num, sorted);

    for(i = 0; i < MAX_NUMBER; i++)
      printf("%d ", sorted[i]);

    return 0;
}

and I took almost 30 minutes to write this. But as you know the program in text books are a lot faster and smaller.

Can you please tell me what kind of programmer I can become? I have been programming for a good 6 months now.

This code review monster got into my head after reading Steve McConnell: Code Complete. Still I have a lot of pages to go through.


texts: Mixing controlled/uncontrolled behaviour with `getDerivedStateFromProps`

texts:
I have a component that displays a bunch of selectable options in a single row. It takes a pageSize prop from the parent component due to responsiveness requirements.
If the pageSize prop ever changes, I need to reset the currentPage (currently active page), which is held in state, to 0.
class OptionsRow extends React.PureComponent {
    state = {
        currentPage: 0
    }
    ...
    static getDerivedStateFromProps(props, state) {
        // Reset page on pageSize change
        return {
            currentPage: props.pageSize === state.prevPageSize
                ? state.currentPage
                : 0,
            prevPageSize: props.pageSize
        }
    }
    ...
}

This code works as intended.
The reason I'm asking for a review is that React in it's documentation warns against getDerivedStateFromProps so I'm not sure if this is a correct usage. In order to avoid derived state, it recommends making the component completely controlled/uncontrolled, so I should lift the currentPage up to the parent component. But is this really necessary? Is something wrong with my solution except for "verbose code"?
Thank you!


texts:
Problem URL

This is the solution I came up with the minimax problem stated above. I did a top-down recursive approach with memoization, and I think this should be \$O(n)\$, since we are filling out a memoization table with \$n\$ elements, with constant number of operations per each recursive call. Nevertheless, I am getting timeout errors for something like n = 1000, which probably indicates this is not an \$O(n)\$ implementation after all.

Can I get some advice on what my misunderstanding is?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int pick(vector<int> stack, int idx, int end, vector<int> memo){
    // Check if memoized.
    if (memo[idx] != -1) return memo[idx];

    int last = end - 1;
    // Base Case
    // Nothing to Pick.
    if(idx > last) return 0;
    // Only one brick.
    else if(idx > last - 1) return stack[last];
    // Two bricks.
    else if(idx > last - 2) return stack[last] + stack[last - 1];
    // Three bricks.
    else if(idx > last - 3) return stack[last] + stack[last - 1] + stack[last - 2];

    int case1,case2,case3;
    int p2,p3,p4,p5,p6;

    p2 = pick(stack,idx+2,end,memo);
    p3 = pick(stack,idx+3,end,memo);
    p4 = pick(stack,idx+4,end,memo);
    p5 = pick(stack,idx+5,end,memo);
    p6 = pick(stack,idx+6,end,memo);

    case1 = stack[idx] +
            min({p2,p3,p4});

    case2 = stack[idx] +
            stack[idx+1] +
            min({p3,p4,p5});

    case3 = stack[idx] +
            stack[idx+1] +
            stack[idx+2] +
            min({p4,p5,p6});

    memo[idx] = max({case1,case2,case3});

    return memo[idx];
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int tests;
    int stackSize;
    vector<int> stack(100000,0),memo(100000,-1);
    cin >> tests;
    for(int test = 0 ;test < tests; test++){
        cin >> stackSize;
        for(int i=0;i<stackSize;i++) cin >> stack[i];
        cout << pick(stack,0,stackSize,memo) << endl;
        fill(memo.begin(),memo.begin() + stackSize ,-1);
    }
    return 0;
}


texts:
For a while now I've been playing around with various ways of passing a logical predicate E.G. >= someValue as an argument to a function. (see: If ComparisonIsTrue(thisPost, ComparisonOperator.NotEqualTo, goodCode) Then Me.Answer and a global enum for comparison operators)

In the end, I've decided to build a CLS_Comparison_Predicate class with Operator and RightValue properties, with a Compare() function that takes a LeftValue as an argument.

Thoughts?

Example Usage:

Dim predicate As CLS_Comparison_Predicate
Set predicate = New CLS_Comparison_Predicate

predicate.Operator = GreaterThan
predicate.RightValue = 9000

If predicate.Compare(inputValue) Then
    MsgBox "It's over 9,000!"
End If

Enum:

Public Enum ComparisonOperator
    NotEqualTo = 0
    LessThan = 1
    LessThanOrEqualTo = 2
    EqualTo = 3
    GreaterThanOrEqualTo = 4
    GreaterThan = 5
End Enum

Code:

Option Explicit

Private pOperator As ComparisonOperator
Private pRightValue As Variant

Private Const NULL_ERROR_TEXT As String = "Invalid Compare input. Cannot compare against Null"
Private Const OBJECT_ERROR_TEXT As String = "Invalid compare input. Input must be a value, not an object"

Public Property Let Operator(ByVal inputOperator As ComparisonOperator)
    pOperator = inputOperator
End Property

Public Property Let RightValue(ByVal inputValue As Variant)
    If IsNull(inputValue) Then
        PrintErrorMessage NULL_ERROR_TEXT
        Stop
    ElseIf IsObject(inputValue) Then
        PrintErrorMessage OBJECT_ERROR_TEXT
        Stop
    End If

    pRightValue = inputValue
End Property

Public Function Compare(ByVal leftValue As Variant) As Boolean

    If IsNull(leftValue) Then
        PrintErrorMessage NULL_ERROR_TEXT
        Stop
    ElseIf IsObject(leftValue) Then
        PrintErrorMessage OBJECT_ERROR_TEXT
        Stop
    End If

    Dim isTrue As Boolean
    Select Case pOperator
        Case NotEqualTo
            isTrue = (leftValue <> pRightValue)

        Case LessThan
            isTrue = (leftValue < pRightValue)

        Case LessThanOrEqualTo
            isTrue = (leftValue <= pRightValue)

        Case EqualTo
            isTrue = (leftValue = pRightValue)

        Case GreaterThanOrEqualTo
            isTrue = (leftValue >= pRightValue)

        Case GreaterThan
            isTrue = (leftValue > pRightValue)

        Case Else
            '/ TODO: Error Handling
            Stop
    End Select

    Compare = isTrue

End Function


texts: Loop Through bitarray to retrieve subsets of that bitarray

texts:
Objective:

I want to loop through a bitarray and store subsets of that bitarray in a table.

Context:

I have a bitarray with 48 elements where each element represent one hour. I want to look back 24 hours from the start of the second day and retrieve the intervals where the last bit is 1.

I was able to achieve this but want to know if someone can provide a better solution :)

I have a table called [Numbers] that has 5000 rows that was created in accordance to this link https://www.mssqltips.com/sqlservertip/4176/the-sql-server-numbers-table-explained--part-1/ .

SCRIPT:

DECLARE @Ba NVARCHAR(48) = '000011110000000001110000000011111111000011110000'
DECLARE @numberOfIntervals INT = 24;
DECLARE @intervals TABLE(
    SequenceId INT,
    [Periods] NVARCHAR(24)
)

INSERT INTO @intervals
SELECT number-1 AS [SequenceId], SUBSTRING(@Ba, number, @numberOfIntervals) AS [Values]
FROM [dbo].[Numbers]
WHERE  number > 1 AND number <= (LEN(@Ba)-(@numberOfIntervals-1)) AND RIGHT(SUBSTRING(@Ba, number, @numberOfIntervals), 1) = '1'

SELECT * FROM @intervals

RESULTS:

[SequenceId]    [Values]
_________________________
5               111000000000111000000001
6               110000000001110000000011
7               100000000011100000000111
8               000000000111000000001111
9               000000001110000000011111
10              000000011100000000111111
11              000000111000000001111111
12              000001110000000011111111
17              111000000001111111100001
18              110000000011111111000011
19              100000000111111110000111
20              000000001111111100001111


texts: Are nested fmap calls idiomatic Haskell?

texts:
Given:

*Main> :t text
text
  :: (Selectable s, StringLike str, Ord str) => s -> Scraper str str

I need to perform "second level" fmap operation:

*Main> let z = fmap (fmap (:[])) text
*Main> :t z
z :: (Selectable s, StringLike a, Ord a) => s -> Scraper a [a]

On one hand z follows API structure, but otherwise I find such code hard to read. It feels like programming against stack-based machine.


texts: Dijkstra's Algorithm modified to take negative edge weights

texts:
In the following Python implementation I have used color coded vertices to implement the Dijkstra's Algorithm in order to take negative edge weights.

G16 = {'a':[('b',3),('c',2)], 'b':[('c',-2)], 'c':[('d',1)], 'd':[]}
# the graph is a dictionary with they "key" as nodes and the "value" as a
# list of tuples
# each of those tuples represent an edge from the key vertex to the first
# element of the tuple
# the second element of the tuple is the weight of that edge.
# so, 'a':[('b',3),('c',2)] means an edge from a to b with weight 3
# and another edge from a to c with weight 2.

class minq:           #min_queue implementation to pop the vertex with the minimum distance
    def __init__(self,dist):
        self.elms = []

    def minq_len(self):
        return len(self.elms)

    def add(self,element):
        if element not in self.elms:
            self.elms.append(element)

    def min_pop(self,dist):
        min_cost = 99999999999
        for v in self.elms:
            min_cost = min(min_cost,dist[v])
        for key,cst in dist.items():
            if cst == min_cost:
                if key in self.elms:
                    v = key
        self.elms.remove(v)
        return v

def modified_dijkstras(graph,n):
    cost = {}
    color = {}            # color interpretation: w = white = unvisited, g = grey = to be processed, b = black = already processed
    for vertex in graph:
        cost[vertex] = 9999999     #setting cost of each vertex to a large number
        color[vertex] = 'w'        #setting color of each vertex as 'w'
    q = minq(cost)
    q.add(n)
    cost[n] = 0
    while q.minq_len() != 0:
        x=q.min_pop(cost)
        color[x] = 'g'
        for j,cost_j in graph[x]:
            temp = cost[j]
            cost[j] = min(cost[j],cost[x] + cost_j)
            if cost[j] < temp and color[j] == 'b':  #if the cost varries even when the vertex is marked 'b'
                color[j] = 'w'                      #color the node as 'w'
            if  color[j] != 'g':
                color[j] = 'g'
                q.add(j)                        #this can insert a vertex marked 'b' back into the queue.
        color[x] = 'b'
    return cost

The following is what is returned when you run the code on the Python interpreter with the graph defined on top:

>>>import dijkstra
>>>G16 = {'a':[('b',3),('c',2)], 'b':[('c',-2)], 'c':[('d',1)], 'd':[]}
>>>dijkstra.modified_dijkstras(G16,'a')
{'a': 0, 'b': 3, 'c': 1, 'd': 2}

Please let me know if this algorithm has a better runtime than Bellman Ford as I am not iterating through all the vertices repeatedly.

Please also report your analysis of the run time for this algorithm, if any.


texts:
I've this function to list products from database by category. I'm using prepared statements, but wouldn't this make it pretty pointless to use them?

function getProducts($category,$search_param,$pdo){
      $query = "SELECT * FROM renkaat
        INNER JOIN ajoneuvotyypit ON tyyppiID = ajoneuvotyyppiID
        INNER JOIN vuodenajat ON vuodenaikaID = renkaat.vuodenaika
        INNER JOIN valmistajat ON renkaat.valmistaja = valmistajat.valmistajaID
        WHERE renkaat.$category= ?
        ";
    $smt = $pdo->prepare($query);
    $smt->execute(array($search_param));

      //do stuff
  }

And the function is simply called like this, with no escaping done:

getProducts($_GET['category'],$_GET['search_param'],$pdo);

Should I escape the $category?


texts:
I am working on a Monte Carlo simulation using OpenMP multithreading. To avoid race conditions when multiple threads work on the same resolution element, I have implemented the following module to atomically (using OMP atomic, since AFAIK there's no easy way to do atomic operations directly in Fortran) acquire and release a lock:

module portability
  use, intrinsic :: iso_fortran_env
  implicit none
  integer, parameter :: al=ATOMIC_LOGICAL_KIND
end module portability

module atomic_lock
  use portability
  implicit none
contains

  subroutine acquire_atomic_lock(have_lck, lck, error, blocking)
    logical(al), intent(inout) :: have_lck
    logical(al), intent(inout) :: lck

    integer, intent(out), optional :: error

    logical(al), intent(in), optional :: blocking

    logical(al) :: lck_copy, blk
    integer :: err

    if(present(blocking)) then
       blk = blocking
    else
       blk = .true.
    endif

    lck_copy = .true.
    err = 0
    if(have_lck) then
       ! already have a lock, can not acquire new one
       err = 1
    else
       if(blk) then
          ! PROBLEM: busy waiting here
          do while(lck_copy)
             !$omp atomic capture
             lck_copy = lck
             lck = .true.
             !$omp end atomic
          end do
          have_lck = .true.
       else
          !$omp atomic capture
          lck_copy = lck
          lck = .true.
          !$omp end atomic
          have_lck = .not. lck_copy
       end if
    end if

    if(present(error)) then
       error = err
    end if
  end subroutine acquire_atomic_lock

  subroutine release_atomic_lock(have_lck, lck, error)
    logical(al), intent(inout) :: have_lck
    logical(al), intent(inout) :: lck

    integer, intent(out), optional :: error

    logical(al) :: lck_copy
    integer :: err

    err = 0
    if(.not. have_lck) then
       ! can not release a lock we do not have
       err = 1
    else
       !$omp atomic capture
       lck_copy = lck
       lck = .false.
       !$omp end atomic

       if(.not. lck_copy) then
          ! lock was released while we thought we had it
          err = 2
       end if
    end if

    if(present(error)) then
       error = err
    end if
  end subroutine release_atomic_lock
end module atomic_lock

Here's an MWE:

program main
  use portability
  use atomic_lock
  use omp_lib
  implicit none

  logical(al) :: lock_sum, have_lock
  integer :: sum
  integer :: nthreads=4

  call omp_set_num_threads(nthreads)

  lock_sum = .false.
  have_lock = .false.
  sum = 0

  !$omp parallel default(none) shared(lock_sum, sum) firstprivate(have_lock)
  call acquire_atomic_lock(have_lock, lock_sum)

  sum = sum + omp_get_thread_num()

  call release_atomic_lock(have_lock, lock_sum)
  !$omp end parallel

  write(*,*) sum == (nthreads*(nthreads-1))/2
end program main

It works well even with 20000 or so threads on my four core processor and is, unsurprisingly, much faster than using OMP critical instead of atomic.

However, I would still like to know what shortcomings you can identify in my implementation and how you would fix them. One problem I see and don't know how to fix is that acquire_atomic_lock does busy waiting if the lock isn't available. In my case this will not be a huge problem, I presume, since I have many more resolution elements than threads and consequently collisions will be unlikely but it would be nice to fix it anyway.


texts:
This is a fully functional code that i have just completed today. I just want to know how efficient is this. and how could i improve it or if theres any bugs that i have miss out.
import os
from AskUser import ask_user as As
from random import randint

#initialising the board
class Board():
    def __init__(self):
        self.boxs = [' '] * 10

    def display(self):
        print(f' {self.boxs[1]}  |  {self.boxs[2]}  |  {self.boxs[3]} \n---------------')
        print(f' {self.boxs[4]}  |  {self.boxs[5]}  |  {self.boxs[6]} \n---------------')
        print(f' {self.boxs[7]}  |  {self.boxs[8]}  |  {self.boxs[9]} ')

    def update_box(self, box_num, key):
        def valid_position(box_num, key):
            return 0 < box_num < 10 and self.boxs[box_num] == ' '
        while not valid_position(box_num, key):
            box_num = As("Please enter a valid position: ", int)
        self.boxs[box_num] = key

    def win_solution(self,key):
        if (self.boxs[1] == key and self.boxs[2] == key and self.boxs[3] == key) or\
            (self.boxs[4] == key and self.boxs[5] == key and self.boxs[6] == key) or\
            (self.boxs[7] == key and self.boxs[8] == key and self.boxs[9] == key) or\
            (self.boxs[1] == key and self.boxs[4] == key and self.boxs[7] == key) or\
            (self.boxs[2] == key and self.boxs[5] == key and self.boxs[8] == key) or\
            (self.boxs[3] == key and self.boxs[6] == key and self.boxs[9] == key) or\
            (self.boxs[1] == key and self.boxs[5] == key and self.boxs[9] == key) or\
            (self.boxs[3] == key and self.boxs[5] == key and self.boxs[7] == key):
            return True
        return False

    def tie_game(self):
        count = 0
        for i in self.boxs:
            if i != ' ':
                count += 1
        return count == 9

    def reset_board(self):
        self.boxs = [' '] * 10

board = Board()
Turn = randint(0,1)

#Introduction
def clear_screen():
    os.system('clear')
    print('Welcome to the TicTacToe simulator')
    #Displays the board
    board.display()

while True:
    if Turn == 1:
        #Updates the board after input
        clear_screen()

        #For X Player
        x_move = As('X, Choose a position between 1 - 9 : ',int)
        #Put x input into the board
        board.update_box(x_move, "X")
        Turn = 0
        #Updates the board after input
        clear_screen()
    #Check for win for X or tie
        if board.win_solution("X"):
            print('Congrats, X you have won')
            Turn = 3
        elif board.tie_game():
            print('This is a tie game')
            Turn = 3
        else:
            pass

    elif Turn == 0:
        clear_screen()
        #For O Player
        o_move = As('O, Choose a position between 1 - 9 : ',int)
        #Put o input into the board
        board.update_box(o_move, "O")
        Turn = 1
        #Updates the board after input
        clear_screen()

        #Check for win for O or tie
        if board.win_solution("O"):
            print('Congrats, O you have won')
            Turn = 3
        elif board.tie_game():
            print('This is a tie game')
            Turn = 3
        else:
            pass

    else:
        p_again = As('Do you want to play again? (Y/N) : ').upper()
        if p_again == "Y":
            board.reset_board()
            Turn = randint(0,1)
            continue
        else:
            exit('Game is over')

This is the AskUser function
Function to check for the user input
def ask_user(message, type_= str, valid=lambda x: True, invalid_message="Invalid"):
    while True:
        try:
            user_input = type_(input(message))
        except (ValueError, TypeError):
            print("Invalid input")
            continue
        if valid(user_input):
            return user_input
        else:
            print(invalid_message)


texts:
Here is my code:

triangle_numbers = []
number = 0
for i in range(0, 10000):
    number = number+i
    triangle_numbers.append(number)

for number in triangle_numbers:
    number_of_divisors = 1
    for i in range(1, int(number/2)+1):
        if number % i == 0:
            number_of_divisors = number_of_divisors + 1
            if number_of_divisors > 500:
                print("FOUND AT ", number)

It takes forever to return the answer. How do I make it faster? I'm a beginner, so if you could walk me through your answer that would be great!

The challenge that I am doing is Highly divisible triangular number -
Problem 12.


texts: Idiomatic way of handling optional values in Swift

texts:
I'm new to iOS development and also Swift. I'm working on a project consisting of a menu that leads to my various experimentations with the iOS SDK.

I've written the menu titles and segueIdentifiers in a plist and I'm populating an array of NavigationItem in viewDidLoad().

Is the following code idiomatic, particularly in the way it handles optional values? What might be better?

override func viewDidLoad() {
        super.viewDidLoad()

        let path = NSBundle.mainBundle().pathForResource("NavigationMenu", ofType: "plist")

        if path == nil{
            NSLog("Unable to locate file : NavigationMenu.plist")
            return
        }

        let items = NSArray(contentsOfFile: path!)

        if items == nil {
            NSLog("Navigation menu items could not be read from plist.")
            return
        }

        for var i = 0 ; i < items!.count ; i++ {

            let item : NSDictionary = items!.objectAtIndex(i) as! NSDictionary
            navigationItems.append(NavigationItem(
                name:(item.objectForKey("name") as! String),
                andSegueIdentifier: (item.objectForKey("segueIdentifier") as! String)
                ))

        }

    }


texts:
I'm solving this simple challenge:

Given a vector A with N unique elements greater than 0 and lower or equal than N+1, find the missing element. Example:

A = [1,3,2,5] -> missing number 4

A = [1,3,5,4] -> missing number 2

I've come to the following solution. I'm interested in thoughts and ideas on how to write it as expressive as possible:

Option 1, compact but not very expressive:

int solution_1(std::vector<int> &v) {
    sort(v.begin(), v.end());
    for (std::size_t i = 0; i < v.size(); ++i) {
        if (v[i] != i+1) return i+1;
    }
    return v.size()+1;
}

Option 2

int solution_2(std::vector<int> &v) {
    sort(v.begin(), v.end());
    auto missing_element = std::find_if(
        v.begin(), v.end(),
        [index=1](auto& element) mutable {
            if (element != index++) {
                return true;
            } else {
                return false;
            }
        });
    if (missing_element == v.end()) {
        return v.size() + 1;
    } else {
        return *missing_element - 1;
    }
}

Any ideas on how to improve this or how to make it more expressive?


texts: 'Countdown' Numbers round - combine numbers arithmetically to reach a target

texts:
Countdown is a British gameshow where contestants compete in word and number challenges. During the numbers round, six numbers are chosen semi-randomly and the task is to combine them using addition, subtraction, multiplication and division in order to reach a target number.

For example, the numbers might be [75; 25; 7; 2; 5; 8] and the target 491.

One winning solution is ((75 + 25) * 5) - 7 - 2 = 491

Below is some F# code that I wrote to try and improve my functional skills. The compute function accepts an int list and an int and returns an Expr which is the closest it could find to the target.

First, declaring the recursive type and functions to evaluate and print them

module Numbers

type Expr =
| Number of int
| Add of Expr * Expr
| Subtract of Expr * Expr
| Multiply of Expr * Expr
| Divide of Expr * Expr

let rec eval = function
| Number x        -> x
| Add (x, y)      -> eval x + eval y
| Subtract (x, y) -> eval x - eval y
| Multiply (x, y) -> eval x * eval y
| Divide (x, y)   -> eval x / eval y

// string representation of an expression, with evaluated result
let write n =
    let rec write' = function
    | Number x        -> x.ToString()
    | Add (x, y)      -> "(" + write' x + " + " + write' y + ")"
    | Subtract (x, y) -> "(" + write' x + " - " + write' y + ")"
    | Multiply (x, y) -> "(" + write' x + " * " + write' y + ")"
    | Divide (x, y)   -> "(" + write' x + " / " + write' y + ")"
    write' n + " = " + (eval n).ToString()

This function that takes an Expr list (in the first case, a list of Numbers) and produces a seq<Expr list> which is calculated by all the possible applications of a single arithmetic operator (+*/-) to any/all pairs of expressions.

let generate exprs =
    // a specialised choose2 function that returns the pair plus the remainders
    // uses indices for comparison in case of duplicate values
    let pairTwo exprs =
        let indexed = List.mapi (fun i x -> i,x) exprs
        [ for (i,x) in indexed do
          for (j,y) in indexed do
          if j > i then
            yield (x,y), [ for (k,z) in indexed do if k <> i && k <> j then yield z ] ]

    // for two given expressions, get possible combinations
    let getExpressions x y =
        let isDivisible x y =
            let denom = eval y
            denom <> 0 && eval x % denom = 0

        let a = max x y
        let b = min x y
        seq {
            yield Multiply (x, y)
            yield Add (x, y)
            yield Subtract(a, b) // don't bother with negatives
            if isDivisible a b
                then yield Divide(a, b)
            yield x // yielding each partial result prevents near-misses getting lost
            yield y // although expands the search tree
        }

    seq {
        for (x,y),zs in pairTwo exprs do
        for expr in getExpressions x y do
        yield expr :: zs }

Finally the compute function which drives the calculation, iterating over all candidate expressions until a match is found or there are no more possibilities

let compute numbers target =
    let distance = eval >> ((-) target) >> abs
    let fitness = Seq.map distance >> Seq.min

    let iterate =
        Seq.collect generate
        >> Seq.sortBy fitness

    let rec compute' candidates =
        let first = Seq.head candidates
        match first, fitness first with
        | x::[], _  -> x // no more iterations, this is the best one
        | exprs,  0 -> Seq.minBy distance exprs // woop, got it
        | _,     _  -> candidates |> iterate |> compute'
    seq { yield numbers |> List.map Number }
    |> compute'

I'd really like feedback on my use of closures, pattern matching, choices of list vs seq, and if anyone can think of a nicer way to implement the pairTwo function I would like to see it


texts:
Firstly, apologies if this is not the correct type of question for here, I had it on the stackoverflow but it was closed with a suggestion I post here.

I’m in the process of converting from Latin 15 to Unicode/UTF-8 and researched several tutorials, and am looking here for a critique of what I have implemented based on them (or, IOW, did I understand it!) :

I want to parse form data in PHP to ensure it is safe from SQL injection and email header attacks, and any other security holes I've not considered.

Although I’m using UTF-8, I just want to cater for English plus some of the extra acute, tilde etc. characters that would normally encounter, plus the Euro symbol. Everything else is disallowed and throws an error, as opposed to silently being replaced/removed.

This is my code so far:

// ensure it's valid unicode / get rid of invalid UTF8 chars
$text = iconv("UTF-8","UTF-8//IGNORE",$text);

// and just allow a basic english...ish.. chars through - no controls, chinese etc
$match_list = "\x{09}\x{0a}\x{0d}\x{20}-\x{7e}"; // basic ascii chars plus CR,LF and TAB
$match_list .= "\x{a1}-\x{ff}"; // extended latin 1 chars excluding control chars
$match_list .= "\x{20ac}"; // euro symbol

if (preg_match("/[^$match_list]/u", $text) )
    $error_text_array[] = "<b>INVALID UNICODE characters</b>";

This code should only allow the characters shown in yellow here http://solomon.ie/unicode/

My main question is does this do as I want (it seems to work) or have I missed anything? My understanding of this is that the iconv function will remove any invalid sequences (i.e. hack attempts at the bit level) and leave just valid UTF-8, then my regexp checks for the characters I want allowed.

Although it seems to work I’m still confused by the regexp and the hex notation. Am I matching the Unicode code points, or, the actual binary UTF-8 representation of those code points? * It appears to be the former.

*my understanding is that a codepoint is basically the virtual location of a specific character in the Unicode “world” or characters, i.e. Euro symbol is the 20ACth character from the start, but it’s actual binary code, and number of bytes, is depended on if you use UTF-8, or 16 or 2 etc. So the codepoint never changes but the bit sequence can.

And, I have seen both, say, \x{20}-\x{7e} and \x20-\x7e used – what is the difference with and without the braces?

I intend to use the above few lines on all form fields, then follow it by further checks depending on the nature of the input.

For example if expecting an integer of the 0-9 kind, can I just use preg_match("/[^0-9]/", $text) without the /u modifier and specify literal characters (from x00 to x7e)? And suppose I want to allow 0-9 and the Euro in, is this the correct way preg_match("/[^0-9\x{20ac}]/u", $text)? And if I’m expecting a hidden field with ”ADD” or “EDIT” is if (!preg_match("/^(ADD|EDIT)$/", $text)) is still valid to test that?


texts: Length of longest non-repeating substring challenge using sliding window

texts:
I am working on Leetcode challenge #3 (https://leetcode.com/problems/longest-substring-without-repeating-characters/)

Here is my solution using sliding window and a dictionary. I specifically added start = seen[s[i]]+1 to skip ahead. I am still told I am far slower than most people (for example, given abcdefgdabc, I am skipping abc when I see the second d. I thought this would save ton of time, but apparently this algorithm has a poor run time.

 class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        seen = {}
        start = 0
        max_size = 0

        # check whether left pointer has reached the end yet
        while start < len(s):
            size = 0
            for i in range(start, len(s)):
                if s[i] in seen:
                    start = seen[s[i]]+1
                    seen = {}
                    break
                else:
                    seen[s[i]] = i
                    size += 1
            max_size = max(size, max_size)
        return max_size

UPDATE

    i = 0
    j = 0
    seen = {}
    max_length = 0

    while j < len(s):
        if s[j] not in seen:
            seen[s[j]] = j
            j += 1
            max_length = max(max_length, j-i)
        else:
            i = j = seen[s[j]] + 1
            seen = {}
    return max_length


texts: Recursion function for prime number check

texts:
I have this code:

def has_divisors(n, i=2):
    """
    Check if a number is prime or not
    :param n: Number to check
    :param i: Increasing value that tries to divide
    :return: True if prime, False if not
    """
    if n <= 1:
        return False
    if i + 1 == n:
        return True
    if n <= 2 and n > 0:
        return True
    if n % i == 0:
        return False
    return has_divisors(n, i + 1)

Which tell if a number is prime or not, problem is that it can check if a number is prime up to +- 1500 after that it enters into maximum recursion depth error. Does anyone has any idea how to make this code more efficient and get to higher numbers (I don't want a completely different code if possible, yes I know recursion is not a good idea for this function but I have to use it) Thank you!