texts: A generic IEnumerator to enumerate COM collections

texts:
As I wrapped the VBIDE API, I encountered a number of "collection types" (Windows, CodePanes, VBComponents, VBProjects, References, etc.) - these types implement the non-generic IEnumerable interface, so if I wanted to be able to iterate my wrappers like this for example:

using (var projects = _vbe.VBProjects)
{
    foreach (var project in projects.Where(p => p.Protection == ProjectProtection.Unprotected))
    {
        yield return project.Name;
    }
}

...then I was going to be needing some custom IEnumerator implementation, because even if I could explicitly .Cast<Rubberduck.VBEditor.DisposableWrappers.Project>() every time, at runtime the cast would fail because the enumerator yields a COM object, not a wrapper type.

So I made a generic ComWrapperEnumerator<TComCollection, TWrapperItem>, where TComCollection is the collection type (must implement IEnumerable) and TWrapperItem is the type of the SafeComWrapper<T> to be created and returned - am I doing this right? I don't like the way I'm assuming the constructor only has a single T parameter (where T is the COM type being wrapped by TWrapperItem), is there a better way?

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

namespace Rubberduck.VBEditor.DisposableWrappers
{
    public class ComWrapperEnumerator<TComCollection, TWrapperItem> : IEnumerator<TWrapperItem>
        where TComCollection : IEnumerable
    {
        private readonly IEnumerator _internal;

        public ComWrapperEnumerator(TComCollection items)
        {
            _internal = items.GetEnumerator();
        }

        public void Dispose()
        {
            var disposable = _internal as IDisposable;
            if (disposable == null)
            {
                return;
            }
            disposable.Dispose();
        }

        public bool MoveNext()
        {
            return _internal.MoveNext();
        }

        public void Reset()
        {
            _internal.Reset();
        }

        public TWrapperItem Current
        {
            get { return (TWrapperItem)Activator.CreateInstance(typeof(TWrapperItem), _internal.Current); }
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }
    }
}

Anything else?

For context, here's the SafeComWrapper<T> abstract base class' constructor:

protected SafeComWrapper(T comObject)
{
    _comObject = comObject;
}

Here's how the enumerator is used, here in the CodePanes wrapper:

IEnumerator<CodePane> IEnumerable<CodePane>.GetEnumerator()
{
    return new ComWrapperEnumerator<Microsoft.Vbe.Interop.CodePanes, CodePane>(ComObject);
}

IEnumerator IEnumerable.GetEnumerator()
{
    return new ComWrapperEnumerator<Microsoft.Vbe.Interop.CodePanes, CodePane>(ComObject);
}

I can't think of a clean way to get generic type parameters inferred by the compiler, so every new ComWrapperEnumerator needs these ugly generic type parameters.


texts:
For a homework assignment I've been given the task of parsing out information from an 32-bit MIPS instruction. (For more information on the instruction formats, see here). The instructor has provided us with a header file enumerating all of the functions required, and it's my job to implement them.

Currently, this is what the implementation for one of my functions looks like:

void instruction_partition(unsigned instruction, unsigned *op, unsigned *r1, unsigned *r2, unsigned *r3, unsigned *funct, unsigned *offset, unsigned *jsec)
{
    assert(op && r1 && r2 && r3 && funct && offset && jsec);

    *op = (instruction >> 26) & 0x3F;
    *r1 = (instruction >> 21) & 0x1F;
    *r2 = (instruction >> 16) & 0x1F;
    *r3 = (instruction >> 11) & 0x1F;
    *offset = (instruction >> 6) & 0x1F;
    *funct = instruction & 0x3F;
    *jsec = instruction & 0x3FFFFFF;
}

In a scenario such as this, I'd almost be tempted to hard-code the shift values and bitmasks, despite it being ingrained within me to avoid doing so at all costs.

I tried a few other configurations, but neither resonated with me. Any thoughts?

void instruction_partition(unsigned instruction, unsigned *op, unsigned *r1, unsigned *r2, unsigned *r3, unsigned *funct, unsigned *offset, unsigned *jsec)
{
    assert(op && r1 && r2 && r3 && funct && offset && jsec);

    struct { unsigned offset; unsigned bitMask; }
        opMaskFormat = { 26, 0x3F },
        r1MaskFormat = { 21, 0x1F },
        r2MaskFormat = { 16, 0x1F },
        r3MaskFormat = { 11, 0x1F },
        functMaskFormat = { 6, 0x1F },
        offsetMaskFormat = { 0, 0x3F },
        jsecMaskFormat = { 0, 0x3FFFFFF };

    *op = (instruction >> opMaskFormat.offset) & opMaskFormat.bitMask;
    *r1 = (instruction >> r1MaskFormat.offset) & opMaskFormat.bitMask;
    *r2 = (instruction >> r2MaskFormat.offset) & r2MaskFormat.bitMask;
    *r3 = (instruction >> r3MaskFormat.offset) & r3MaskFormat.bitMask;
    *offset = (instruction >> offsetMaskFormat.offset) & offsetMaskFormat.bitMask;
    *funct = (instruction >> functMaskFormat.shift) & functMaskFormat.bitMask;
    *jsec = (instruction >> jsecMaskFormat.offset) & jsecMaskFormat.bitMask;
}

void instruction_partition(unsigned instruction, unsigned *op, unsigned *r1, unsigned *r2, unsigned *r3, unsigned *funct, unsigned *offset, unsigned *jsec)
{
    assert(op && r1 && r2 && r3 && funct && offset && jsec);

    unsigned SIX_BIT_MASK = 0x3F,
        FIVE_BIT_MASK = 0x1F,
        TWENTY_SIX_BIT_MASK = 0x3FFFFFF;

    *op = (instruction >> 26) & SIX_BIT_MASK;
    *r1 = (instruction >> 21) & FIVE_BIT_MASK;
    *r2 = (instruction >> 16) & FIVE_BIT_MASK;
    *r3 = (instruction >> 11) & FIVE_BIT_MASK;
    *offset = (instruction >> 6) & FIVE_BIT_MASK;
    *funct = instruction & SIX_BIT_MASK;
    *jsec = instruction & TWENTY_SIX_BIT_MASK;
}


texts:
I'm working through a scraping function where pages of results lead to product pages.  I've added a default maximum number of results pages, and pages per set of results, to prevent a simple mistake of crawling the whole site.

Here's what I have so far.  Does the way I'm implementing the maximums with the for loops make sense?  Is there a more "pythonic" way? I'm coming at this from a completely learning perspective.

def my_crawler(url, max_pages = 1, max_items = 1):

    for page_number in range(1, max_pages + 1):
        source_code = requests.get(url + str(page_number)).text

        products = SoupStrainer(class_ = 'productTags')
        soup = BeautifulSoup(source_code, 'html.parser', parse_only=products)

        for item_number, a in enumerate(soup.find_all('a')):
            print(str(item_number) + ': ' + a['href'])

            if item_number == max_items - 1: break

my_crawler('http://www.thesite.com/productResults.aspx?&No=')


texts: Find value from other dataset based on 6 variables that must be equal in both datasets

texts:
I have two datasets that are both within a worksheet, call them Data and IBES. The code checks whether the 6 variables are the same in each dataset and then writes the value from a specific column to the other dataset. To find this value the code runs through 288503 lines which is dramatically slow.

How can I speed up this code?

Public Function GetRightValue()

Dim i As Integer
Dim j As Long

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False

For i = 2 To 1511           'Loop over all values from total dataset
        For j = 2 To 288503      'Loop over all values from IBES file
            If Worksheets("Data").Cells(i, 3) = Worksheets("IBES").Cells(j, 1) Then
                If Worksheets("Data").Cells(i, 7) = Worksheets("IBES").Cells(j, 6) Then
                    If Worksheets("Data").Cells(i, 10) = Worksheets("IBES").Cells(j, 9) Then
                        If Worksheets("Data").Cells(i, 13) = Worksheets("IBES").Cells(j, 11) Then
                            If Worksheets("Data").Cells(i, 8) = Worksheets("IBES").Cells(j, 7) Then
                                If Worksheets("Data").Cells(i, 14).Text = Worksheets("IBES").Cells(j, 13).Text Then
                                    Worksheets("Data").Cells(i, 12) = Worksheets("IBES").Cells(j, 10).Text
                                    Worksheets("Data").Cells(i, 18) = Worksheets("IBES").Cells(j, 16).Text
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Next j
Next i

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True

End Function


texts: Efficiently index rows of numpy array by exclusion

texts:
I need a function that takes a numpy array and a row number as inputs and returns the array (or copy of the array) excluding the given row. I want to do this as efficiently as possible.

# Test array
x = np.repeat(range(10),2).reshape([10,2])

Indexing by slices is very fast in numpy, but as far as I can tell this can only be used to get a contiguous set of rows. For instance, I know I can use slicing to exclude the first row

def index_rows_by_exclusion_firstrow(arr):
    """
    Return slice of arr excluding first row using slice-based indexing
    """
    return arr[1:]

%timeit index_rows_by_exclusion_firstrow(x)

#The slowest run took 33.84 times longer than the fastest. This could mean that an intermediate result is being cached
#1000000 loops, best of 3: 204 ns per loop

There is a numpy function, numpy.delete, that does the operation that I'm looking for, but it creates a new array and is therefore very slow.

def index_rows_by_exclusion_npdel(arr, i):
    """
    Return copy of arr excluding single row of position i using
    numpy delete function
    """
    return np.delete(arr, i, 0)

%timeit index_rows_by_exclusion_npdel(x, 1)
#The slowest run took 5.51 times longer than the fastest. This could mean that an intermediate result is being cached
#100000 loops, best of 3: 9.65 µs per loop

The best I have come up with is indexing by a list, which is about twice as fast as the numpy.delete version of the function, but still ~30 times as slow as slicing

def index_rows_by_exclusion_list(arr, i):
    """
    Return slice of arr excluding single row of position i using
    list-based indexing
    """
    return arr[[ x for x in range(arr.shape[0]) if x != i]]

%timeit index_rows_by_exclusion_list(x,1)
#The slowest run took 12.54 times longer than the fastest. This could mean that an intermediate result is being cached
#100000 loops, best of 3: 5.82 µs per loop

My question is: is there any faster way to index a numpy array like this? Is there any way to use slicing to index all but one row in an array?

One additional note: the code I'm writing has to be compatible with Cython, which means I can't use boolean masking arrays because Numpy in Cython does not support boolean arrays (this is what I was doing before I realized that boolean arrays don't work in Cython).


texts: Core Data code for manually creating a lot of entries from old ones

texts:
Does this looks ok to everyone?

NSFetchRequest *oldFetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *oldEntryEntity = [NSEntityDescription entityForName:@"Entry"
                                                  inManagedObjectContext:oldContext];

[oldFetchRequest setEntity:oldEntryEntity];

int numberOfEntries = [oldContext countForFetchRequest:oldFetchRequest error:nil];

int batchSize = 10;
[oldFetchRequest setFetchBatchSize:10];
int offset = 0;

while (numberOfEntries - offset > 0) {

    [oldFetchRequest setFetchOffset:offset];
    NSError *error;
    NSArray *entries = [oldContext executeFetchRequest:oldFetchRequest error:&error];

    for (NSManagedObject *entry in entries) {
        Entry *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry"
                                                        inManagedObjectContext:newContext];

        [newEntry setupCreationDate:[entry valueForKey:@"creationDate"] withSave:NO];
        newEntry.entryID = [entry valueForKey:@"entryID"];

        NSMutableOrderedSet *newMediaSet = [[NSMutableOrderedSet alloc] init];

        NSOrderedSet *mediaSet = [entry valueForKey:@"media"];

        int i = 0;

        for (NSManagedObject *media in mediaSet) {

            Media *newMedia = [NSEntityDescription insertNewObjectForEntityForName:@"Media"
                                                            inManagedObjectContext:newContext];

            newMedia.positionInEntry = [NSNumber numberWithDouble:i + 1]; //Potentially needs changing
            newMedia.mediaID = [Entry generateString];

            MediaImageData *imageData = [NSEntityDescription insertNewObjectForEntityForName:@"MediaImageData"
                                                                      inManagedObjectContext:newContext];

            if ([newMedia.type isEqualToString:@"Image"]) {
                imageData.data = [media valueForKey:@"originalImage"];;
            }
            else if ([newMedia.type isEqualToString:@"Movie"]) {
                NSURL *movieURL = [NSURL URLWithString:newMedia.movie];
                MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
                [moviePlayer stop];
                UIImage *screenshot = [moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
                [moviePlayer stop];

                imageData.data = UIImageJPEGRepresentation(screenshot, 1.0);
            }

            newMedia.imageData = imageData;

            newMedia.entry = newEntry;
            [newMediaSet addObject:newMedia];

            i++;
        }

        newEntry.media = newMediaSet;

    }

    [newContext save:&error];

    offset = offset + batchSize;
}


texts:
I'm newish to obj-c and I have some code that works, but I'm thinking I may be leaking memory as I have two retain statements and no release statements.

In both cases if I remove the retain I get a bad access error on [btPairedDevices count]

Am I doing this right or is there a better way?

//===================================================================================================
- (id)init
{
    self = [super init];
    if (self) {
        indexDeviceSearch = 0;
        // Grab a list of paired devices
        btPairedDevices = [IOBluetoothDevice pairedDevices];
        [btPairedDevices retain];
    }

    return self;
}

//===================================================================================================
- (void) applicationDidFinishLaunching:(NSNotification *)notification
{
    if(IOBluetoothValidateHardwareWithDescription(nil, nil) != kIOReturnSuccess)
    {
        [NSApp terminate:self];
    }

    NSLog(@"Application up an running");

    // Start our timer looking for paired phones
    timerDeviceSearch = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                         target:self
                                                       selector:@selector(timerDeviceSearchFired)
                                                       userInfo:nil
                                                        repeats:YES];
}

//===================================================================================================
- (void) timerDeviceSearchFired
{
    // Check out the device
    if (indexDeviceSearch < [btPairedDevices count])
    {
        IOBluetoothDevice *device = [btPairedDevices objectAtIndex:indexDeviceSearch];
        if ([device deviceClassMajor] == kBluetoothDeviceClassMajorPhone)
        {
            // Found a phone
            [self addNewDeviceIfAcceptable:device];
        }
    }

    // Update the list of devices just in case the use
    // paired something while we are running
    btPairedDevices = [IOBluetoothDevice pairedDevices];
    [btPairedDevices retain];

    // Inc the index
    indexDeviceSearch++;
    if (indexDeviceSearch >= [btPairedDevices count])
        indexDeviceSearch = 0;
}

//===========================================================================================================================
-(BOOL)addNewDeviceIfAcceptable:(IOBluetoothDevice*)device
{
    NSEnumerator *enumerator;
    IOBluetoothDevice *tmpDevice;
    const BluetoothDeviceAddress *newDeviceAddress = [device getAddress];

    // Allocate our array of monitored devices
    if(!btMonitoredDevices)
    {
        btMonitoredDevices = [[NSMutableArray alloc] initWithCapacity:1];
        if(!btMonitoredDevices)
            return(FALSE);
        [btMonitoredDevices retain];
    }

    // Walk the devices in the array.
    enumerator = [btMonitoredDevices objectEnumerator];
    if(enumerator)
    {
        const BluetoothDeviceAddress* tempAddress = NULL;
        while((tmpDevice = [enumerator nextObject]))
        {
            tempAddress = [tmpDevice getAddress];
            if(memcmp(newDeviceAddress, tempAddress, sizeof(BluetoothDeviceAddress)) == 0 )
            {
                // Already have it.
                return(FALSE);
            }
        }
    }

    // Add new device to array
    NSLog(@"Monitoring new device: %@", [device nameOrAddress]);
    [btMonitoredDevices addObject:device];

    // Return that we haven't seen it.
    return(TRUE);
}


texts: Search iteratively in a ternary search tree

texts:
I was trying to write an iterative search function for my Ternary Search Tree class based on a pseudo-code, and now it seems to work, but I think it can definitely be improved.

def search(self, key: str):
    return TST._search(self.root, key)

@staticmethod
def _search(node: TSTNode, key: str):
    """Note that node.key is a character"""
    if node is None or not key:
        return None

    for i in range(len(key) - 1):

        while node is not None and key[i] != node.key:
            if key[i] < node.key:
                node = node.left
            else:
                node = node.right

        if node is None:  # Unsuccessful search
            return None
        else:
            node = node.mid

    # In case the length of the key is 1 (but NOT only, see edit below)
    return node.value if node.key == key else None

Is my algorithm correct? My algorithm does not allow keys or characters to be empty strings.

Edit 1

I think there's a small bug in the code above in the last statement, which should be:

if not node or node.key != key[-1]:
    return None
else:
    return node.value

This is because there's one more way to arrive at that return statement (apart from having initially the key of length 1, as I wrote in the comment), which is to exit from the while loop because the condition key[i] != node.key is false.

In that case, we would be comparing a character, i.e. node.key, with a string key (if the node is not None: see note below!). In Python this can be easily hidden leading to bugs like this one.

Note also that node could still be None (I think) after we do node = node.mid.

Edit 2

After testing this method, I noticed that the last correction of the previous edit didn't solve all problems with the function. The last problem is that we still may need to go left or right after we exit the for loop. Here you can find the correct version:

  https://github.com/nbro/ands/blob/master/ands/ds/TST.py


texts: SPOJ problem: Life, the Universe, and Everything

texts:
Your program is to use the brute-force approach in order to find the answer to Life, the Universe, and Everything. More precisely, rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

I was solving this problem and I submitted 3 solutions and I got "SEGMENTATION FAULT" for the first 2. The third one finally executed successfully, but I wanted to know where I made a mistake while solving.

1st I submitted:

#include <stdio.h>
  int main(void)
    {
      int i=0,j,a[9];

      while(a[i]!= 42)
       {
         ++i;
         scanf("%d",&a[i]);
       }
     for(j=0;j<i;j++)
     {
      printf("%d",a[j]);
       printf("\n");
      }
    return 0;
  }

2nd I submitted (after reading a comment that output has to be printed immediately after taking the input):

#include <stdio.h>
int main(void)
 {
  int i=0,j,a[9];

 scanf("%d",&a[i]);
 printf("%d\n",a[i]);

 while(a[i]!=42)
  {
   ++i;
   scanf("%d",&a[i]);
   if(a[i]!=42)
    printf("%d\n",a[i]);
  }
}

Third one (it was correct):

 #include <stdio.h>

  int main(void)
  {
   int i = 0;
   while (scanf("%d\n", &i) > 0 && i != 42)
   {
    printf("%d\n", i);
   }
    return 0;
   }

Can anyone point where my approach has gone wrong? When I executed the first 2 on www.ideone.com they both ran successfully over there but on SPOJ there was a runtime error (segmentation fault).


texts: Square root approximation with Newton's method

texts:
I designed a program that calculates the square root of a number using Newton's method of approximation that consists of taking a guess (g) and improving it (improved_guess = (x/g + g)/2) until you can't improve it anymore:

#include <iostream>
#include <iomanip>
using namespace std;

template <class Y>
Y sqrt (Y x)
{
    double g (1), ng;
    while (true) {
        ng = (x/g + g)/2;
        if (g != ng) g = ng;
        else if (g == ng) break;
    }
    return g;
}

void menu()
{
    double x, g;
    string a = "";
    do {
        cout << "Enter a number to get the sqrt of: ";
        cin >> x;
        g = sqrt(x);
        cout << "The result is: " << setprecision(100) << g << endl;
        cout << "Result^2 = " << setprecision(100) << g*g << endl;
        cout << "\nDo it again ? <y/n> ";
        cin >> a;
        cout << endl;
    } while (a == "y");
}

int main()
{
    menu();
    return 0;
}

Can you see any way to improve this ? Like in the "do it again" part, I just couldn't use y/n...


texts:
I have two implementations of a function that prints out a basic board for Tic-Tac-Toe.

Which of these should I include and why?

def display_board(board)
  for i in 0...9
    print " #{ board[i] }"
    if (i+1)%3 != 0
      print " |"
    elsif i != 9
       print " \n#{'-'*11}\n"
    end
  end
end

def display_board(board)
  puts " #{board[0]} | #{board[1]} | #{board[2]} "
  puts "-----------"
  puts " #{board[3]} | #{board[4]} | #{board[5]} "
  puts "-----------"
  puts " #{board[6]} | #{board[7]} | #{board[8]} "
end


texts: A simple Java game where the player guesses the word

texts:
It's a simple word guessing game. The game picks a random word - you guess a letter until it's correct, the game automatically starts a new one.

Is my code readable? Am I doing anything that could be simplified?
Am I doing the right thing by using only one class besides Main?

import java.util.Scanner;
import java.util.Random;

class Word {
  private String censoredWord = "";
  private String word = "";
  private String[] words = {"cow", "giraffe", "deer", "cat", "dog",   "cheese"}; ////words

  public String randomizeWord() { //randomizes word
      Random rand = new Random();
      int randNum = rand.nextInt(words.length);
      word = words[randNum];
      for (int i = 0; i < word.length(); i++) { //makes a word filled with blank spots the same length as the word chosen
        censoredWord = censoredWord + "_";
      }
      return word;
  }

  public String showProgress(char letter) { //uncensors letters
    char[] wordArray = word.toCharArray(); //sets the word to an array so it can loop though it
    char[] censoredWordArray = censoredWord.toCharArray();
    for (int i = 0; i < wordArray.length; i++) {
      char ichar = wordArray[i];
      if (letter == ichar) {
        censoredWordArray[i] = ichar; //fills in censored letter
      }
    }
    censoredWord = String.valueOf(censoredWordArray);
    System.out.println(censoredWord);
    return censoredWord;
  }
}

class Main {
  public static void main(String[] args) {
    Word word = new Word();
    String currentWord = word.randomizeWord();
    while (true) { //handles the game structure and guessing
      System.out.println("Guess!");
      Scanner guessLetter = new Scanner(System.in); //takes input
      char letterGuessed = guessLetter.nextLine().charAt(0); //puts input into variable
      //checks if user got the word
      guessLetter.close();
      if (word.showProgress(letterGuessed).equals(currentWord)) {
        System.out.println("Hooray! Resetting...");
        word = new Word();
        currentWord = word.randomizeWord();
      }
    }
  }
}
```


texts: Sorting seems to be slower with 2 threads instead of 1

texts:
I'm implementing a simple merge sort to practice with Python's Threads. I've tried to split the job into two threads, that sort normally, then I can join them and merge the result. However, it takes almost twice as long with two threads than it does with the "normal" algorithm. Did I do something wrong or is it normal ? How can I improve this code to make it run faster with two threads ? What advice would you give me ? Thanks a lot.

CODE

# -*- encoding: utf-8 -*-

from collections import deque
from random import randint
from time import clock
from itertools import islice
from threading import Thread

sort_dict = dict()

def merge(da, db):
    res = deque()
    a = da.popleft()
    b = db.popleft()
    while True:
        if a < b:
            res.append(a)
            try:
                a = da.popleft()
            except IndexError:
                res.append(b)
                res.extend(db)
                break
        else:
            res.append(b)
            try:
                b = db.popleft()
            except IndexError:
                res.append(a)
                res.extend(da)
                break
    return res

def sort(d, put_in_global = False, nb = 0):
    l = len(d)
    if l <= 1:
        return d
    else:
        da = deque(islice(d, 0, l/2))
        db = deque(islice(d, l/2, l))
        sda = sort(da)
        sdb = sort(db)
        if put_in_global:
            sort_dict[nb] = merge(sda, sdb)
        else:
            return merge(sda, sdb)

def multi_sort(d):
    l = len(d)
    if l <= 1:
        return d
    else:
        da = deque(islice(d, 0, l/2))
        db = deque(islice(d, l/2, l))
        sda = Thread(target=sort, args=(da, True, 1))
        sdb = Thread(target=sort, args=(db, True, 2))
        sda.start()
        sdb.start()
        sda.join()
        sdb.join()
        return merge(sort_dict[1], sort_dict[2])

def check_sorted(d):
    if d:
        s = d.popleft()
    while True:
        try:
            f = s
            s = d.popleft()
            if f > s:
                return False
        except IndexError:
            return True

if __name__=='__main__':
    with open('results.txt', 'wb') as f:
        lengths = [2*10**i for i in xrange(1, 7)]
        f.writelines(['Length  One_time  Multi_time  Ratio\r\n'])
        for length in lengths:
            print '----------------------------'
            print 'List length : ' + str(length)
            lst = [randint(0, 10**4) for i in xrange(length)]
            # print 'List : ' + str(lst)
            print 'ONE THREAD'
            start = clock()
            res = sort(lst)
            one_time = clock() - start
            print 'Sorting time (s) : ' + str(one_time)
            print 'Sort checking : ' + str(check_sorted(res))
            print 'MULTIPLE THREAD'
            start = clock()
            res = multi_sort(lst)
            multi_time = clock() - start
            print 'Sorting time (s) : ' + str(multi_time)
            print 'Sort checking : ' + str(check_sorted(res))
            print 'CONCLUSION'
            print 'Time ratio multi/one : ' + str(multi_time/one_time)
            f.writelines([str(length)+'  '+
                          str(one_time)+'  '+
                          str(multi_time)+'  '+
                          str(multi_time/one_time)+'\r\n'
                          ])

results.txt (changed the display a little bit because it was ugly)

Length  One_time          Multi_time        Ratio
20      0.00010350001112  0.00121833484164  11.7713498623
200     0.00101618192736  0.00266847549331  2.62598204265
2000    0.0117950095317   0.0210672419328   1.7861148714
20000   0.134505249988    0.2356253311      1.7517928194
200000  1.46486474003     2.59513874989     1.77158933448
2000000 16.4877353912     31.8037152227     1.92893168577


texts:
I am using this jQuery code to get two carousels working in bootstrap, and it's working for me.

$('#image-gallery-carousel').carousel({
  interval: 5000
});

$('#carousel-caption-text').html($('#slide-content-0').html());

// When the carousel slides, auto update the text
$('#image-gallery-carousel').on('slid.bs.carousel', function (e) {
  var id = $(this).find('.item.active').data('slide-number');
  //alert(id);
  $('#carousel-caption-text').html($('#slide-content-'+id).html());
});

$('#video-gallery-carousel').carousel({
  interval: 12000
});

$('#carousel-caption-video-text').html($('#slide-content-0').html());

// When the carousel slides, auto update the text
$('#video-gallery-carousel').on('slid.bs.carousel', function (e) {
  var id = $(this).find('.item.active').data('slide-number');
  //alert(id);
  $('#carousel-caption-video-text').html($('#slide-content-'+id).html());
});

If there is any better way to implement this, please point it out to me.


texts:
This method tests an array of integers satisfies to see if its a max binary heap. This means

each node is greater than or equal to it's children
each node has at most 2 children
the leaf nodes are filled from left to right

This is for heaps that do not use element 0. See here.

/*returns true if array satisfies heap property for heap from [START, END]*/
private boolean isHeap(final int[] heap, final int START, final int END) {
    for(int i = START; i <= Math.ceil(END / 2); i++) {
       if(2 * i + 1 <= END && heap[i] < heap[2 * i + 1])
               return false;
       else if(2 * i <= END && heap[i] < heap[2 * i])
               return false;
   }

   return true;

}


texts:
I recently learned that sometimes, when running code, the compiler(or whatever it is) ignores when there isn't enough memory for say, a string, and interacts with the string normally.

Yes, I know this is a "lucky" thing that shouldn't happen, but sometimes does.

I often find trouble when I'm trying to interact with the contents of file, as I often run out of allocated memory and I have trouble dynamically re-allocating.

To fix this, I created two functions:

fsizeof_full <- returns the full size of the file(as if it were a string)
fsizeof_buffer <- returns the size of the largest line in the file

So far, as I have been using these, I have not come across any problems involving segmentation faults, but I am not sure if I am just getting lucky.

Here is my code(these both have stdio.h included):

fsizeof_full

unsigned int fsizeof_full(FILE *fp) {
    unsigned int size;
    while(getc(fp) != EOF)
        ++size;
    return size;
}

fsizeof_buffer

int fsizeof_buffer(FILE *fp) {
    int buff = 0; // holds the largest size of a line
    int temp = 0; // holds the size of the current line

    int c;
    while((c = getc(fp)) != EOF) {
        ++temp;
        if(c == '\n') {
            buff = (temp > buff)?(temp):(buff);
            temp = 0;
        }
    }
    return buff;

Along with the above question("So far, as I have..."), could you possibly include more thoughts about the code regarding efficiency, necessity, etc.


texts: Error handling for an Erlang 2D point class

texts:
I am working on a math library for an online game. I want to prevent as many errors as possible and I want to catch all errors as early as possible to simplify debugging in the long run. However, I feel like I drown in details. This is quite different from "let it crash" motto.

point has {number(), number()} type or better say {0, 0} is a point. I started with Dialyzer specs and guard statements which work as a poor man's assertions.

Here is my point class.

-module(point).
-author("nt").

-export([is_point/1, distance/2, translate/2, pointToMap/1]).

-type point() :: {number(), number()}.
-export_type([point/0]).

is_point({X, Y}) when is_number(X), is_number(Y) -> true;
is_point(_) -> false.

distance({X1, Y1} = A, {X2, Y2} = B) ->
  case is_point(A) of false -> error(badarg); _ -> ok end,
  case is_point(B) of false -> error(badarg); _ -> ok end,
  math:sqrt(math:pow((X2 - X1), 2) + math:pow(Y2 - Y1, 2)).

translate({X1, Y1} = A, {X2, Y2} = B) ->
  case is_point(A) of false -> error(badarg); _ -> ok end,
  case is_point(B) of false -> error(badarg); _ -> ok end,
  {X1 + X2, Y1 + Y2}.

pointToMap({X, Y} = A) ->
  case is_point(A) of false -> error(badarg); _ -> ok end,
  #{
    x => X,
    y => Y
  }.

%% Spec
-spec is_point(P :: point()) -> boolean().
-spec distance(A :: point(), B :: point()) -> float().
-spec translate(A :: point(), B :: point()) -> point().
-spec pointToMap(A :: point()) -> #{x:= number(), y := number()}.

{{0, 0}, {0, 0}} is a rect.
rect "class" relies on point.

-module(rect).
-author("nt").

%% API
-export([is_rect/1, contains/2]).

-type rect() :: {point:point(), point:point()}.
-export_type([rect/0]).

is_rect({{OriginX, OriginY}, {W, H}}) when is_number(OriginX), is_number(OriginY), is_number(W), is_number(H) -> true;
is_rect(_) -> false.

-spec contains(Rect, Point) -> boolean() when Rect :: rect(), Point :: point:point().
contains({{OriginX, OriginY}, {W, H}} = R, {X, Y} = P) ->
  case is_rect(R) of false -> error(badarg); _ -> ok end,
  case point:is_point(P) of false -> error(badarg); _ -> ok end,
  ((OriginX < X) and (X < (OriginX + W))) and ((OriginY < Y) and (Y < (OriginY + H))).

Things are getting really massive and daunting. Given the fact there is almost no business logic I wonder how fast codebase will become a complete mess if I continue to check all the required preconditions in all functions.

Update:

I think about removing all the specs and "assertions" from the code. Functions like pointToMap will be also removed as I don't need to rely on concrete types anymore. Something like tupleToMap should be used instead.

point.erl:

-module(point).
-author("nt").

-export([distance/2, translate/2]).

distance({X1, Y1}, {X2, Y2}) ->
  math:sqrt(math:pow((X2 - X1), 2) + math:pow(Y2 - Y1, 2)).

translate({X1, Y1}, {X2, Y2}) ->
  {X1 + X2, Y1 + Y2}.

rect.erl

-module(rect).
-author("nt").

-export([contains/2]).

contains({{OriginX, OriginY}, {W, H}}, {X, Y}) ->
  ((OriginX < X) and (X < (OriginX + W))) and ((OriginY < Y) and (Y < (OriginY + H))).


texts: Automating the install of PostgreSQL from Shell

texts:
When my Debian server deploys it can run a shell script so I wanted to make one to install postgreSQL, create a role, create two databases and then import a schema into one.

Can anyone please look at this code and tell me if I have done an ok job?

 # POSTGRES
apt-get install -y postgresql
echo "CREATE ROLE deploy LOGIN ENCRYPTED PASSWORD '$APP_DB_PASS';" | sudo -u postgres psql
su postgres -c "createdb db1 --owner deploy"
su postgres -c "createdb db2 --owner deploy"
service postgresql reload

# IMPORT SQL
psql --username=postgres spider < /etc/schema.sql


texts:
I have a table with (CompanyNumber, File_Date, [various financial results])
I wanted to get only the most recent set of accounts for each company.

After various googling I eventually got a query that does what I want it to do.

Is this a good way of doing it?

N.B. the File_Date field is actually a text field, so needs converting to Date before comparisons. Specifically, text --> varchar --> date.

select * from uk_registered_companies.dbo.Filed_Accounts
JOIN
(
Select companyNumber, max(convert(date, CONVERT(varchar(20),file_date),103)) as MaxDate from uk_registered_companies.dbo.Filed_Accounts
group by CompanyNumber
) mostRecentAccounts
on
Filed_Accounts.CompanyNumber = mostRecentAccounts.CompanyNumber
and
(convert(date, CONVERT(varchar(20),Filed_Accounts.File_Date),103)) = mostRecentAccounts.MaxDate


texts: Custom data validation approach for store items and prices

texts:
I came up with a validation design for my project and wanted to hear if there's anything I could improve.

Here's how it works. I have the models (code first)

public class Item : IEntity<Item>
{
    public Item()
    {

    }

    public int ID { get; set; }
    public string StoreCode { get; set; }
    public string UPCCode { get; set; }
    public string Description { get; set; }
    public double ABV { get; set; }
    public string URL { get; set; }
    public string Producer { get; set; }

    //each model has its validation method...
    public bool IsValid(Repository<Item> repository)
    {
        if (repository.Single(x => x.StoreCode == this.StoreCode) != null)
            return false;
        else
            return true;
    }
}

public class Price : IEntity<Price>
{
    public Price()
    {

    }

    public int ID { get; set; }
    public double Value { get; set; }
    public DateTime FetchedDate { get; set; }

    public bool IsValid(Repository<Price> repository)
    {
        var price = repository.Find(x => x.ItemID == this.ItemID).OrderByDescending(x => x.FetchedDate).Take(1).SingleOrDefault();

        if (price != null && price.Value == this.Value)
            return false;
        else if (price == null)
            return true;
        else
        {
            price = repository.Find(x => x.ItemID == this.ItemID && x.FetchedDate.ToString("yyyyMMdd") == this.FetchedDate.ToString("yyyyMMdd")).SingleOrDefault();
            return (price != null) ? false : true;
        }

    }
}

The IEntity interface is as such:

public interface IEntity<TEntity> where TEntity: class, IEntity<TEntity>
{
    int ID { get; set; }
    bool IsValid(Repository<TEntity> repository);

}

And in my repository class, I have an IsValid method, among other read/write methods.

public class Repository<TEntity> where TEntity: class, IEntity<TEntity>
{
    private EntitiesContext = new EntitiesContext ();
    private DbSet<TEntity> AppDbSet;

    public Repository()
    {
        this.AppDbSet = Context.Set<TEntity>();
    }

    public bool IsValid(TEntity entity)
    {
        return entity.IsValid(this);
    }

    //other Get, Single, Update, Add, Save methods...
}

And here's how I use it:

Repository<Price> priceRepo = new Repository<Price>();

//...gather data...

foreach (Price price in prices)
{
    if (priceRepo.IsValid(price))
        priceRepo.Add(price);
    }
}

Is that a good way to implement such a feature? Any areas for improvement (not in the validation methods themselves, but the approach in general)? This will be mostly used for a Web API project.


texts:
Problem

A function is needed, that obfuscates text but preserves line breaks. Line breaks may be encoded by "\r\n" or "\r", even mixed. myObfuscator is an object that obfuscates text, ignoring line breaks (would be replaced by any other character).

Example:

  ABC\r\nDEF\rGHE

should be obfuscated to something like

  XXX\r\nXXX\rXXX

where XXX depends on myObfuscator (not important for the question).

Implementation

My approach works, but seems a little too complicated.

public string Obfuscate(string text)
{
    var stringBuilder = new StringBuilder();
    var lineCount = 0;
    var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.None);
    foreach (var line in lines)
    {
        var innerLineCount = 0;
        if (lineCount > 0) stringBuilder.Append("\r\n");
        foreach (var innerLine in line.Split(new[] { "\r" }, StringSplitOptions.None))
        {
            if (innerLineCount > 0) stringBuilder.Append("\r");
            var obfuscatedLine = string.IsNullOrEmpty(innerLine) ? string.Empty : myObfuscator.Obfuscate(innerLine);
            stringBuilder.Append(obfuscatedLine);
            innerLineCount++;
        }
        lineCount++;
    }
    return stringBuilder.ToString();
}

Is there a more elegant solution?


texts: Determining if an std::string contains a numerical type

texts:
I recently came across this SO question asking for methods to determine if a std::string represents an integer. There is also this SO question for floats. I decided to code up a few methods consolidating these questions.

#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>

namespace detail
{
    const auto is_digit = [] (const char c) { return std::isdigit(c); };
}

bool is_integral(const std::string& str)
{
    return !str.empty() && std::all_of(std::cbegin(str), std::cend(str), detail::is_digit);
}

bool is_floating_point(const std::string& str)
{
    using std::cbegin; using std::cend;

    auto it = std::find_if_not(cbegin(str), cend(str), detail::is_digit);

    return it != cend(str) && *it++ == '.' && std::all_of(it, cend(str), detail::is_digit);
}

bool is_arithmetic(const std::string& str)
{
    using std::cbegin; using std::cend;

    if (str.empty()) return false;

    auto it = std::find_if_not(cbegin(str), cend(str), detail::is_digit);

    return it == cend(str) || (*it++ == '.' && std::all_of(it, cend(str), detail::is_digit));
}

Here's an example/expected behaviour:

#include <iostream>

int main()
{
    std::string empty {};
    std::string integer {"123"};
    std::string floating1 {"123."};
    std::string floating2 {"123.4"};
    std::string neither1 {"123..4"};
    std::string neither2 {"1r23"};

    std::cout << std::boolalpha;

    std::cout << is_integral(empty) << std::endl; // false
    std::cout << is_floating_point(empty) << std::endl; // false
    std::cout << is_arithmetic(empty) << std::endl; // false
    std::cout << std::endl;

    std::cout << is_integral(integer) << std::endl; // true
    std::cout << is_floating_point(integer) << std::endl; // false
    std::cout << is_arithmetic(integer) << std::endl; // true
    std::cout << std::endl;

    std::cout << is_integral(floating1) << std::endl; // false
    std::cout << is_floating_point(floating1) << std::endl; // true
    std::cout << is_arithmetic(floating1) << std::endl; // true
    std::cout << std::endl;

    std::cout << is_integral(floating2) << std::endl; // false
    std::cout << is_floating_point(floating2) << std::endl; // true
    std::cout << is_arithmetic(floating2) << std::endl; // true
    std::cout << std::endl;

    std::cout << is_integral(neither1) << std::endl; // false
    std::cout << is_floating_point(neither1) << std::endl; // false
    std::cout << is_arithmetic(neither1) << std::endl; // false
    std::cout << std::endl;

    std::cout << is_integral(neither2) << std::endl; // false
    std::cout << is_floating_point(neither2) << std::endl; // false
    std::cout << is_arithmetic(neither2) << std::endl; // false
    std::cout << std::endl;

    std::cout << is_integral(neither2) << std::endl; // false
    std::cout << is_floating_point(neither2) << std::endl; // false
    std::cout << is_arithmetic(neither2) << std::endl; // false
    std::cout << std::endl;

    return 0;
}

I'm looking for any improvements.


texts: A PDO connection classto initiate multiple connection and easy access

texts:
I've been looking for a way to make the database connection easy available directry from any script, and from inside other classes. And since I tend to have different connections based on what action to execute, I had to find a way to easily scale the amount of connection needed.

Here's the solution I come up with.

I created this class:

class database{
    protected static $details = array();  //  holds all connection(s) details
    protected static $con = array();  //  holds the actual PDO connection(s)

/**
 *  addConnection()
 *  Adds a new connection
 *  @param string $alias a unique identifier for the connection
 *  @param string $db the database name
 *  @param string $un username
 *  @param string $pw password for the user
 *  @param string $desc a short description for this connection
 */
    public static function addConnection($alias,$db,$un,$pw,$desc){
        self::$details[$alias]=array('alias'=>$alias,'db'=>$db,'un'=>$un,'pw'=>$pw, 'desc'=>$desc);
    }

/**
 *  getConnection()
 *  @return array of a specific connection if a valid alias is provided. Othervise return a multidimensional array of all connections.
 */
    public static function getConnections($alias=''){
        if(!empty($alias)) return self::$details[$alias];
        else return self::$details;
    }

/**
 *  setConnection()
 *  This function moves the connection to $con[] for easy access both inside and outside of this class
 *  @param string $alias a unique identifier for the connection
 *  @param string $connection the string of a new pdo connection
 */
    public static function setConnection($alias,$connection){
        self::$con[$alias] = $connection;
    }

/**
 *  useConnection()
 *  @param string $alias a unique identifier for the connection
 *  @return a specific PDO connection based on the given alias
 */
    public static function useConnection($alias){
        return self::$con[$alias];
    }
}

And this script to set/initiate multiple connections:

if(database::getConnections()){
    try{
        $dbh_options = array(
            PDO::ATTR_EMULATE_PREPARES=>false,
            PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8',
            PDO::ATTR_ERRMODE=>PDO::ERRMODE_SILENT,
        );
        foreach(database::getConnections() as $dbh){
        #   initiate connection
            database::setConnection($dbh['alias'],new PDO('mysql:host=localhost;dbname='.$dbh['db'].';charset=utf8',$dbh['un'],$dbh['pw'],$dbh_options));
        //
        #   put the connection to a an array for easy access when coding
            $con[$dbh['alias']]=database::useConnection($dbh['alias']);
        //
        }
    } catch(PDOException $e) {
        file_put_contents('PDOException.txt',$e->getMessage(), FILE_APPEND);
        die('OBS! Something went wrong connecting to your database.<br>Please see PDOException.log for more details.');
    }
}

Here's how I add new connections:

database::addConnection('alias','database','username','password','a optional short description');
database::addConnection('alias2','database','username','password',null);

Amd this is how I can use the connection from whitin another class:

$select = $con['alias']->prepare('SELECT...');
$insert = $con['alias2']->prepare('INSERT INTO...');

And from other classes, I just extends the database class.

class sql extends database {
    public static function query($id){
        $query = self::$con['alias']->prepare('SELECT column FROM table WHERE id = ?');
        $query->execute(array($id));
        return $query->fetchColumn();
    }
}

But I would really like your oppinion on this. If there's any security issues with this setup?


texts: Performance of summing one value from join of three tables

texts:
I have a table I want to get a sum of information on, but the value I need to query on is in two different tables.

The one with values I need to sum is say, kudos, which has a value indicating +1 (1) or -1 (2) in the Action column, which is associated to the discussion it's on, or the comment it's on:

Kudos
+-----------+--------------+--------+
| CommentID | DiscussionID | Action |
+-----------+--------------+--------+
|        24 |         NULL |      1 |
|      NULL |            4 |      1 |
|        60 |         NULL |      2 |
+-----------+--------------+--------+

  The value I want to filter by is the author's ID, which is either in
  the Comment table or the Discussion table:

Comments
+-----------+--------+
| CommentID | Author |
+-----------+--------+
|        29 |      5 |
|        24 |      1 |
|        22 |      1 |
|        21 |      1 |
+-----------+--------+

Discussions
+--------------+--------+
| DiscussionID | Author |
+--------------+--------+
|            4 |      1 |
|            5 |      2 |
|            6 |      2 |
|            7 |      7 |
+--------------+--------+

In this example, Author 1 would have a score of 2, because row 1 in the Kudos table would count because it matches with row 1 in the comment table, and row 2 in the Kudos table matches the 1st row in the Discussions table.

Additionally, I need to use the query that does this as a subquery, because I'm getting all the users in a select statement, and then getting the sum of this subquery as a field associated with the userID, like:

SELECT tblUser.Name AS Name, (subquery) AS rep FROM User_Table AS tblUser;

What I've come up with is the following:

SELECT tblU.Name AS Name, tblU.UserID AS ID,
    (SELECT SUM(IF(Action=1, 1, -1)) FROM Kudos AS tblK
    LEFT JOIN Discussions AS tblD ON tblK.DiscussionID = tblD.DiscussionID
    LEFT JOIN Comments AS tblC ON tblC.CommentID = tblK.CommentID
    WHERE tblD.InsertUserID = id OR tblC.InsertUserID = id) AS rep
FROM Users AS tblU;

which gives me:

+--------------+----+------+
| Name         | id | rep  |
+--------------+----+------+
| Jack         |  1 |  357 |
| Joe          |  2 |  824 |
| Jim          | 12 |   48 |

But it takes 0.23 seconds to run for a small set (like 13 users). I've heard from co-workers that the OR condition is bad for performance, but I'm not sure how this can be optimized at all.


texts:
Consider the following code:

#include <iostream>
#include <vector>
using namespace std;

struct test {
    int j;
    test& operator>>(int & i) { i = ++j%26; return *this; }
    operator bool() { return j%26; }
};

int main () {
    test t;
    int i;
    while (t >> i) {
        cout << i << endl;
    }
}

I have implemented a simple class that can be used in a similar fashion as for example std::cin. I implemented it this way, because I wanted to have an object that hides some IO-operations from me and provide a nice interface to yield the data items each one-at-a-time.

Although it does want I want, I know there is at least one issue with the implementation:

ignorance w.r.t. the safe bool idiom

Are there probably any more?


texts:
I have written a windows service for one of our local servers. This service works like a gem on my local machine, does what it's supposed to (ACCP to exchange db data), but I'm not overly familiar with dependencies. Is this an appropriate way to receive/send a message?

string DBP3_US = DBP3_US;
string PING_DEPENDENCY = "SELECT [SomeColumn] FROM [SomeTable];";
protected override void OnStart(string[] args)
{
    SqlDependency.Start(DBP3_US);
    Thread Ping_US = new Thread(PingThread);
    Ping_US.Name = "ping_US";
    Ping_US.Start();
}

private void PingThread()
{
    CreateCommandWithDependency(PING_DEPENDENCY, Ping_OnChange);
}

private void CreateCommandWithDependency(string queryText, OnChangeEventHandler e, string db = DBP3_US)
{
    using (SqlConnection con = new SqlConnection(db))
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = queryText;
        cmd.CommandType = CommandType.Text;
        cmd.Notification = null;
        SqlDependency sqlDep = new SqlDependency(cmd);
        sqlDep.OnChange += new OnChangeEventHandler(e);
        con.Open();
        cmd.ExecuteNonQuery();
    }
}

private void Ping_OnChange(object sender, SqlNotificationEventArgs e)
{
    PingDependency();
    Thread Ping_US = new Thread(PingThread);
    Ping_US.Start();
}

private void PingDependency(string db = DBP3_US)
{
    // Do whatever operations are required.
}


texts:
I built a Simon Says game using an Arduino UNO board. This was my first "real" arduino project. I would like to know how to make it better, game mechanics and code efficiency.

#define RedTone 165
#define GreenTone 330
#define YelloTone 659
#define BlueTone 1319
#define FailTone 100

#define BuzzerPin 8

/* The led and button pins are set this way because I use their position as a hexadecimal.
 *  LED PINS:
      red:0
      green:1
      yello:2
      blue:3
    Button Pins:
      red:4
      green:5
      yello:6
      blue:7
*/

byte mem[20];
int sound[16] = {0, RedTone, GreenTone, 0, YelloTone, 0, 0, 0, BlueTone, 0, 0, 0, 0, 0, 0, FailTone};  //the tones are placed in the arrey in the hex spot for turning on the leds.

void setup() {
  DDRD = 0x0F;
  randomSeed(analogRead(0));
  pinMode(BuzzerPin, 1);
}

void blink(int i) { //Blinking and making sound
  PORTD = i;
  tone(BuzzerPin, sound[i]);
  delay(500);
  PORTD = 0x00;
  noTone(BuzzerPin);
  delay(500);
}

void NT(int i) { //Just blinking
  PORTD = i;
  delay(500);
  PORTD = 0x00;
  delay(500);
}

void set_mem() {  //sets the random order of the leds and transforms into the led's pin in hexadecimal
  int b;
  for (int i = 0; i < 20; i++) {
    b = random(4);
    if (b == 3)
      mem[i] = 0x08;
    else if (b == 2)
      mem[i] = 0x04;
    else if (b == 1)
      mem[i] = 0x02;
    else
      mem[i] = 0x01;
  }
}

bool check(int i) { //checks if the pressed button is correct
  byte look;
  for (int x = 0; x <= i; x++) {
    look = 0;
    do
    {
      look = PIND >> 4;  //makes the button press pin to the pin of led with the same color
    }
    while (look == 0);  //waits until a button is pressed
    blink(look); //lights up the button's led
    if (look != mem[x])
      return 0;
  }
  return 1;
}

void loop() {
  set_mem();
  for (int i = 0; i < 20; i++) {
    for (int x = 0; x <= i; x++)
      blink(mem[x]);
    NT(0x09); //signals when it finnished showing the order
    if (check(i) == 0) {
      blink(0x0F); //shows if the player failed
      break; //couses a restart
    }
    NT(0x06); //signals when the player finished pressing the leds
  }
}

How it looks and works:

(I'm having problems making the snippet work, so here is the link to the site itself and here is a video of it working (sorry for the low quality).)

<iframe frameborder='0' height='448' marginheight='0' marginwidth='0' scrolling='no' src='https://circuits.io/circuits/4145099-simon-says-leds-and-buttons/embed#breadboard' width='650'></iframe>


texts:
How can I simplify this code?

<?php
class smth {
    protected static $MARK_UNDEFINED = 'Undefined';
    protected static $MARK_F  = 'ECTS-F';
    protected static $MARK_FX = 'ECTS-FX';
    protected static $MARK_E  = 'ECTS-E';
    protected static $MARK_D  = 'ECTS-D';
    protected static $MARK_C  = 'ECTS-C';
    protected static $MARK_B  = 'ECTS-B';
    protected static $MARK_A  = 'ECTS-A';

    protected function getECTSMark($rate, $current, $examRate)
    {
        $color = self::$MARK_UNDEFINED;
        if ($current > 0) {
            $percent = $rate / $current;
            if ($examRate !== NULL AND $examRate < 22)
                $color = self::$MARK_FX;
            elseif ($percent < 0.31)
                $color = self::$MARK_F;
            elseif ($percent < 0.60)
                $color = self::$MARK_FX;
            elseif ($percent < 0.65)
                $color = self::$MARK_E;
            elseif ($percent < 0.71)
                $color = self::$MARK_D;
            elseif ($percent < 0.85)
                $color = self::$MARK_C;
            elseif ($percent < 0.95)
                $color = self::$MARK_B;
            else
                $color = self::$MARK_A;
        }
        return $color;
    }
}


texts:
What the advantages & disadvantages to each of these approaches pertaining to creating file that takes care of the view configuration to reduce a controller's file size.

Main Purposes Are:

Memory
Performance
Testing
Usability

This is the simplest, capable of working, example to demonstrate the question, but when many views are present using many methods do any of the above concerns alter when comparing the Extension & ViewModel Class?

Reminder: The ViewModel Class or Extension would be placed in a separate file.

ViewModel Approach:

    class VC: UIViewController {
        lazy var viewModel: ViewModel {
            return (main: self)
        }()

        override viewDidLoad() {
            super.viewDidLoad()

            initializeUI()
        }

        func initializeUI() {
            viewModel.configureView()
        }
    }

    class ViewModel {
        private let main: UIViewController

        init(main: UIViewController) {
            self.main = main
        }

        func configureView() {
            main.view.backgroundColor = UIColor.blue
        }
    }

Extension Approach:

    class VC: UIViewController {
        lazy var viewModel: ViewModel(main: self)

        override viewDidLoad() {
            super.viewDidLoad()

            initializeUI()
        }

        func initializeUI() {
            configureView()
        }
    }

    extension VC {
        func configureView() {
            main.view.backgroundColor = UIColor.blue
        }
    }


texts:
I am trying to learn some Common Lisp, except basically all of my computing background is the C family of languages. So, I'm starting small. I have made a Tic-Tac-Toe game, and I am looking for some constructive criticism.

In particular, is this idiomatic Lisp? Is it styled normally? What would an experienced lisper improve about this?

Some concerns I have about this code are:

The win checking seems repetitive.
Can it be simplified?
The get-player-move is very long. Should it be broken up?

;;;; A simple tic-tac-toe game

(defvar p1 88) ; char code for 'X'
(defvar p2 79) ; char code for 'O'
(defvar tie 49) ; arbitrary constant to represent ties

(defun is-move-free (move board)
  (let ((player (elt board move)))
    (not (or (= player p1) (= player p2)))))

(defun is-same (a b c)
  (and (= a b) (= b c)))

(defun win-on-rows (board)
  (defun check-a-row (offset)
    (or (is-same (elt board offset) (elt board (+ offset 1)) (elt board (+ offset 2)))))
  (or (check-a-row 0) (check-a-row 3) (check-a-row 6)))

(defun win-on-columns (board)
  (defun check-a-column (offset)
    (or (is-same (elt board offset) (elt board (+ offset 3)) (elt board (+ offset 6)))))
  (or (check-a-column 0) (check-a-column 1) (check-a-column 2)))

(defun win-on-diagonals (board)
  (or (is-same (elt board 0) (elt board 4) (elt board 8)) (is-same (elt board 2) (elt board 4) (elt board 6))))

;;; This function gets the players move, plays it if possible
;;; then gets the next move. The game will play out in it's
;;; entirety through recursively calling this function.
(defun get-player-move (player board move-num)
  (apply #'format t " ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C~%" (map 'list #'code-char board)) ; Print the board
  (if (>= move-num 9) ; if all the moves have been played, and there is no winner
    tie               ; return the tie constant
    (let ((move (- (parse-integer (read-line)) 1))) ; get the move from input, and convert it to list location
      (if (is-move-free move board)
        (let ((board (substitute player (elt board move) board))) ; apply the move, and get the new board
          (if (or (win-on-columns board) (win-on-rows board) (win-on-diagonals board)) ; check if this was the winning move
            (elt board move) ; return the winner
            (get-player-move (if (= player p1) p2 p1) board (+ move-num 1)))) ; continue the game
        (get-player-move player board move-num))))) ; move again, if the move was taken

(let ((result (get-player-move p1 '(49 50 51 52 53 54 55 56 57) 0)))
  (if (= result tie)
    (format t "It's a tie!")
    (format t "The winner is ~C" (code-char result))))


texts: Removing and counting words that appear more than once

texts:
The assignment is to remove the repeating string from a given string and get the count of repeated string.

The code I have tried is below :

public static void main(String[] args) {

        String longString = "Energy in the form of seismic waves is released " +
                            "after an earthquake and seismometers measure its amplitude to calculate the " +
                            "quake's intensity. For a long time, earthquakes were measured on the Richter scale." +
                            " Since the scale was based on conditions in California and was not reliable in measuring large earthquakes," +
                            " it was replaced by a 'moment magnitude' scale in the 1970s";

        // replace the special characters
        String freeString = longString.replaceAll("[^\\w\\s-]", "");
        //the new string is
        System.out.println("freeString ::  " + freeString);
        //Calculate the length of the string
        String[] countOfString = freeString.split(" ");

        System.out.println("countOfString  ::  " + countOfString.length);

        Set<String> uniqueString = new HashSet<String>();
        Map<String, Integer> countMap = new HashMap<String, Integer>();
        for (int i = 0; i < countOfString.length; i++) {
            String tempString = countOfString[i];
            if(!uniqueString.contains(tempString)){
                uniqueString.add(tempString);
            }else{
                if(!countMap.containsKey(tempString)){
                    countMap.put(tempString, 1);
                }else{
                    Integer count = countMap.get(tempString);
                    count++;
                    countMap.put(tempString, count);
                }

                System.out.println("found the repeating string " + tempString);
            }
        }

        //remove the repeating string set from the uniqueString set
        uniqueString.removeAll(countMap.keySet());
        System.out.println("the repeating string " + countMap);
        System.out.println("the set has the uniuqe strings " + uniqueString);
        System.out.println("the set has the uniuqe strings of length " + uniqueString.size());

    }

Is there any best way/approach other than this?
Will this code work for very large string (e.g. parsing the text of a book)
Will it have any performance issue?


texts: java code design puzzle for common function result module

texts:
I am trying to solve a puzzle. I came up with a few classes to represent results. They looked similar, so I defined a common Result class. But what if I need to define different results according to different functions?

In other words, do I need TypeOneResult and TypeTwoResult or only CommonResult?

If I get rid of the different result classes and rely on CommonResult, how can I store some specific information about the result?

public class Result {
    private String id;
    private String data;

    public Result(String id, String data) {
        super();
        this.id = id;
        this.data = data;
    }
}

class CommonResult extends Result{
    private String type;

    public CommonResult(String id, String data, String type) {
        super(id, data);
        this.type = type;
    }
}

class TypeOneResult extends CommonResult{

    public TypeOneResult(String id, String data, String type) {
        super(id, data, type);
    }
}

class TypeTwoResult extends CommonResult{

    public TypeTwoResult(String id, String data, String type) {
        super(id, data, type);
    }
}


texts: Output the most used non-trivial words from a file

texts:
For fun I'm solving some university homework assignments, and here is one that I was lucky enough to stumble upon. Basically, here are all the requirements (modified a bit from the original because some points are nonsensical):

Write a program that reads a text file and an amount of words from the command line, and outputs the most used words with more than 4 characters in the text file along with their frequency.
You should convert every word to lowercase. Every word is a sequence of letters, and every other character is a separator.

I wanted to use the (hopefully) upcoming ranges from C++20, but because there is no implementation of them in a Standard Library yet, I used C++17 and the range-v3 library.
I couldn't get the official test file, and so I had to make my own. I'm not sure if I'm allowed to upload it though.
Every suggestion from naming to performance to code quality is welcome.
#include <fstream>
#include <iterator>
#include <iostream>
#include <range/v3/all.hpp>
#include <vector>
#include <algorithm>
#include <string>

auto group() noexcept {
    return ranges::view::group_by([](auto&& lhs, auto&& rhs) {
            return std::isalpha(lhs) == std::isalpha(rhs);
        })
        | ranges::view::transform([](auto&& list) {
            return ranges::accumulate(list, std::string{});
        });
}

auto remove_separators() noexcept {
    return ranges::view::filter([](auto&& str) {
        return std::all_of(str.begin(), str.end(), [](auto&& c) {
            return std::isalpha(c);
        });
    });
}

auto restrict() noexcept {
    return ranges::view::filter([](auto&& str) {
        return str.length() >= 5 && std::all_of(str.begin(), str.end(), [](auto&& c) {
            return std::isalpha(c);
        });
    });
}

auto lowercase() noexcept {
    return ranges::view::transform([](auto str) {
        std::transform(str.begin(), str.end(), str.begin(), [](auto&& c) {
            return std::tolower(c);
        });
        return str;
    });
}

auto map() noexcept {
    return ranges::view::group_by([](auto&& lhs, auto&& rhs) {
            return lhs == rhs;
        })
        | ranges::view::transform([](auto&& list) {
            return std::pair(list | ranges::view::take(1), ranges::distance(list));
        });
}

int main(int argc, char* argv[]) noexcept {
    if (argc != 3) {
        std::cout << "Usage: ./" << argv[0] << " [file] [word-amount]\n";
        return -1;
    }

    std::ifstream file{argv[1]};
    if (!file.is_open()) {
        std::cout << "Couldn't open file " << argv[1] << "!\n";
        return -1;
    }

    auto amount = 0u;
    try {
        amount = std::stoi(argv[2]);
    }
    catch (const std::exception&) {
        std::cout << "Invalid number " << argv[2] << "!\n";
    }

    std::vector<char> character_list;
    char character = '\0';
    while (file.read(&character, 1))
        character_list.push_back(character);

    auto words = character_list | group() | remove_separators()
        | restrict() | lowercase() | ranges::to_<std::vector>() | ranges::action::sort;

    auto highlights = words | map() | ranges::to_<std::vector>()
        | ranges::action::sort([](auto&& lhs, auto&& rhs) {
            return lhs.second > rhs.second;
        });

    for (auto&& word : highlights | ranges::view::take(amount))
        std::cout << word.first << ": " << word.second << '\n';
    return 0;
}


texts:
I am calculating parameters for a time series and the data size is very big. How can I make my function faster? The following function, param, calculates parameters for a time series model.

Input:

import pandas as pd
import statsmodels.api as sm

  data = [['01-01-2018', 150,661,396,286,786],['01-02-2018',231,341,57,768,941], ['01-03-2018',486,526,442,628,621],
    ['01-04-2018',279,336,140,705,184],['01-05-2018',304,137,800,94,369],['01-06-2018',919,340,372,494,117],
    ['01-07-2018',947,920,848,716,719],['01-08-2018',423,20,313,368,909],['01-09-2018',422,678,656,604,674],
    ['01-10-2018',422,678,656,604,674],['01-11-2018',337,501,743,606,991],['01-12-2018',408,536,669,903,463]]
df = pd.DataFrame(data, columns = ['date', 'A','B','C','D','E'])
df.index = df.date

def param(data_param):
    w = []
    x = []
    y = []
    z = []
    p = d = q = range(0, 2) # Define the p, d and q parameters to take any value between 0 and 2
    pdq = list(itertools.product(p, d, q)) # Generate all different combinations of p, q and q triplets
    seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))] # Generate all different combinations of seasonal p, q and q triplets

    for i in data_param:
        for param in pdq:
            for param_seasonal in seasonal_pdq:
                try:
                    results = sm.tsa.statespace.SARIMAX(data_param[i],
                                                        order=param,
                                                        seasonal_order=param_seasonal,
                                                        enforce_stationarity=False,
                                                        enforce_invertibility=False).fit()
                    #print(i,param, param_seasonal,results.aic)
                    w.append(i)
                    x.append(param)
                    y.append(param_seasonal)
                    z.append(results.aic)
                    mod_score_param = pd.DataFrame({
                        'id': w,
                        'param': x,
                        'param_seasonal': y,
                        'results_aic': z,
                        })
                except:
                    continue
    mod_score_param = mod_score_param.sort_values(by='results_aic')
    mod_score_param = mod_score_param.dropna()
    mod_score_param = mod_score_param[mod_score_param['results_aic']>3.0]
    mod_score_param = mod_score_param.sort_values(['id','results_aic'])
    mod_score_param = mod_score_param.drop_duplicates(['id'],keep='first')
    return(mod_score_param)

Output= param(df)

Output:

+-----+----+-----------+----------------+-------------+
|     | id |   param   | param_seasonal | results_aic |
+-----+----+-----------+----------------+-------------+
| 199 | A  | (1, 0, 1) | (1, 0, 0, 12)  |       4.565 |
| 197 | B  | (1, 0, 0) | (1, 0, 0, 12)  |      21.752 |
|  30 | C  | (0, 1, 1) | (1, 0, 0, 12)  |      87.847 |
|  22 | D  | (1, 1, 1) | (0, 1, 0, 12)  |      91.183 |
|  50 | E  | (0, 1, 1) | (0, 1, 0, 12)  |       92.87 |
+-----+----+-----------+----------------+-------------+


texts: Usertool For Website Admins -- Follow up

texts:
A while ago, I posted about creating a user tool for forum admins that allows them to add, edit, and delete users from their desktops. This still is not complete, posting for review on tool so far

I've finished with the delete_user method and also added a couple new features to it, what this code does, is take your input, and save it to a YAML file ( will be converting YAML to JSON ). It's advantages are that you don't have to go directly to your database until you actually need to uplaod the file, so you can create an entire list of users from your desktop without sending one validation e-mail, or having to validate one user.

#!/usr/bin/env ruby

require 'yaml'

def menu
  print "Welcome to User Menu. Would you like to [A]dd users, [D]elete users, [E]dit users, [V]iew all users, or [Q]uit the system?\n"
  input = gets.chomp!
  case input
  when /a/i
    add_user
  when /d/i
    delete_user
  when /e/i
    edit_user
  when /v/i
    view_all
  else
    puts "Exiting system.."
    exit
  end
end

def load_hash
  File.exist?('users.yml') ? YAML.load_file('users.yml') : {users: {}}
end

def save_hash(hash)
  File.open('users.yml', 'w') { |s| s.write(hash.to_yaml) }
end

def add_user
    hash = load_hash
    hash[:users][:"#{prompt('Enter username:')}"] =
      {email_address: prompt("Enter email:"),
       member_status: prompt("Enter member status:")}
    save_hash(hash)
    add_user if restart
end

def delete_user
    hash = load_hash
    to_delete = prompt("Enter username:").to_sym
    if hash[:users].has_key?(to_delete)
        hash[:users].delete(to_delete)
    else
        puts 'User not found'
    end
    save_hash(hash)
    delete_user if restart
end

def edit_user
  edit_user if restart
end

def view_all
  puts load_hash
end

def restart
  puts "Would you like to edit another user?"
  input = gets.chomp
  if input =~ /yes/i
    return true
  else
    puts "Exiting program.."
    exit
  end
end

def prompt ( message )
  puts message
  gets.chomp
end
menu

Overview of the YAML file:

---
:username: TEST
:email_address: TEST
:member_status: TEST

Is there anything here that I can do better? Better syntax, combine methods, edit something? I'm looking for every possible example.


texts:
Ada the Ladybug has several coins in her wallet. She is wondering, how many different values [sum of some subset of coins] is she able to make (in given range).

Input

The first line contains two integer numbers \$1 ≤ N ≤ 10^4, 1 ≤ Q ≤ 5*10^5\$, the number of coins and number of queries.

The next line contains \$N\$ integer numbers , the values of coins in Ada's wallet.

Afterward, Q lines follow, each containing two integers \$1 ≤ B ≤ E ≤ 10^5\$, beginning and end of range, for which ada wants to know the answer

Output

For each query, output the number of distinct values Ada can generate in given range.

This is the link to the problem.

  I am getting TLE and i have optimized it to the best of my abilities. I am already using memoization. What else i can improve?

CODE

import java.io.*;

public class Main
{
    public static int maxSize = (int)Math.pow(10,5) + 1;
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //int[][] mat = new int[maxSize][maxSize];
        String[] strArr = null;
        strArr = br.readLine().split(" ");
        int n = Integer.parseInt(strArr[0]);
        int q = Integer.parseInt(strArr[1]);
        int[] arr = new int[n];
        int[][] mat = new int[n + 1][maxSize];
        strArr = br.readLine().split(" ");
        for(int i = 0 ; i < n ; i++)
        {
            arr[i] = Integer.parseInt(strArr[i]);
        }
        int[] rangeSum = new int[maxSize];
        preprocess(arr,mat,n,rangeSum);
        for(int i = 0 ; i < q ; i++)
        {
            strArr = br.readLine().split(" ");
            int start = Integer.parseInt(strArr[0]);
            int end = Integer.parseInt(strArr[1]);
            //System.out.println(rangeSum[end] - rangeSum[start] + 1);
            if(mat[n][start] == 1)
            {
                System.out.println(rangeSum[end] - rangeSum[start] + 1);
            }
            else
            {
                System.out.println(rangeSum[end] - rangeSum[start]);
            }
        }

    }

    public static void preprocess(int[] arr,int[][] mat,int n,int[] rangeSum)
    {
        for(int i = 1 ; i < n + 1 ; i++)
        {
            for(int j = 1 ; j < maxSize ; j++)
            {
                if(j < arr[i - 1])
                {
                    mat[i][j] = mat[i - 1][j];
                }
                else if(j == arr[i - 1])
                {
                    //System.out.println("changed from second");
                    mat[i][j] = 1;
                }
                else
                {
                    if(mat[i - 1][j] == 1)
                    {
                        //System.out.println("changed from third");
                        mat[i][j] = 1;
                    }
                    else
                    {
                        mat[i][j] = (mat[i - 1][j - arr[i - 1]] == 1) ? 1 : 0;
                    }
                }
                //System.out.println("mat[i][j]")
            }
        }
        for(int i = 1 ; i < maxSize ; i++)
        {
            if(mat[n][i] == 1)
            {
                //System.out.println("increasing");
                //mat[n][i] = mat[n][i - 1] + 1;
                rangeSum[i] = rangeSum[i - 1] + 1;
            }
            else
            {
                //mat[n][i] = mat[n][i - 1];
                rangeSum[i] = rangeSum[i - 1];
            }
        }
    }
}


texts: Get the Key of the highest Value in JavaScript object

texts:
Given a hashmap (or a "Dictionary") as a JavaScript object, I'd like to get the Key who has the maximum Value - assuming all Values are integers.

In case there's more than one, I don't care which one of them.

Considering

var b = { '1': 9, '2': 7, '3': 7, '4': 9, '5': 3 };

I can extract the desired Key by:

parseInt(_(b).chain().pairs().max(function(p){return p[1];}).value()[0])

which returns 1.

How can this be achieved more elegantly?

I tried with _.invert as well but couldn't make it look better.


texts: Working with Mobile Device Orientation Detection

texts:
One hassle with working with mobile websites is inconsistency between how the device reports the screen's width and height.  James Pearce wrote a fantastic article about the headaches that come with detecting screen width and height from JavaScript.  Furthermore, not all mobile devices support window.onOrientationChange and window.orientation members (and those that do don't necessarily do so consistently either).

Because of this, I'm working on a snippet to detect orientation and polyfill if it's not supported.  The issue that I have, though, is dealing with identifying when the orientation changes on multiple devices.

The below snippet works on small screens (e.g. Android and iPhones):

var newOrientation
, currentWidth = document.getElementsByTagName("body")[0].clientWidth;
// since there's bugs around devices supporting and reporting screen.width, using body instead

// set orientation
// TODO: Correct hard coded breakpoint.
if (window.hasOwnProperty("orientation")) { newOrientation = window.orientation; }
if (typeof newOrientation === "undefined") { newOrientation = (currentWidth > 400) ? 1 : 0; }

The code declares the newOrientation to test for the change against the currentOrientation variable (not shown).
Because of issue with screen.width, I'm grabbing the body tag's clientWidth property as a benchmark (CSS has body.width set to 100%)
Next, I set newOrientation to window.orientation if the browser supports such.
Finally, I check if newOrientation has been defined yet and if not, change it if the width is over a certain breakpoint (in this case, 400 which covers most phones).

I'm trying to find a better way to do point 4 since it doesn't scale well if I apply it to a Kindle Fire (600x1024) or an iPad2 (768x1024).  One thing preventing me from comparing height to width is how long pages would skew this logic.

Does anyone have any suggestions how I might be able to modify this to compensate for larger screen widths?

Update
After reviewing the linked article more and also taking into consideration GGG's suggestions, the code was refactored to the following:

var newWidth = window.outerWidth
  , newOrientation = window.orientation || (newWidth !== currentWidth) ? 1 : 0;

if (newOrientation !== currentOrientation) {
    currentOrientation = newOrientation;
    currentWidth = newWidth;
}


texts: Deleting/sending to trash files with Python

texts:
I made this program to automate/simplify the erasing of a lot of files, I have some ideas to improve it but that's not why I'm putting it here, it's because it's a very dangerous program(it deletes stuff permanently) and since I'm a beginner(ish) I want some advice from better programmers to improve it.

import os
import send2trash
import shutil
file = input("Type the file path")
while os.path.exists(file) is False:  # validation
    file = input("Path not found, try again:")
for i, j, k in os.walk(file):  # files check
    print("The folder is in this path:", i)
    print("The subfolders are named:", j)
    print("The files are named:", k)
while True:
    try:
        command = int(input("1 - Delete permanently the file\n2 - Send the file to the bin"))
    except ValueError:
        print("Just the numbers 1 or 2 are accepted, follow the instructions")
        continue
    if command not in range(1, 3):
        print("Just the numbers 1 or 2 are accepted, follow the instructions")
        continue
    else:
        break
if command == 1:
    try:
        os.rmdir(file)  # deletes if there is no inside folder
    except OSError:
        shutil.rmtree(file)  # deletes if there is inside folders
else:
    send2trash.send2trash(file)  # send to the bin


texts:
As plain r5rs is lacking in useful string processing utilities, such as string-split and string-join (I'm using MIT/GNU Scheme), I decided to implement my own.  My procedure, string-join, works just fine, but I would like my code to be critiqued by seasoned Schemers, and also find out if there are other, more efficient ways to implement the same thing.

(define string-join
  (lambda (ls delim)
  (define out (open-output-string))
    "Join list of strings together by delim into one string."
    (let loop ((ls ls))
      (if (null? (cdr ls))
          (begin
            (display (car ls) out)
            (get-output-string out))
          (begin
            (display (car ls) out)
            (display delim out)
            (loop (cdr ls)))))))


texts:
I solved bubble sort in an exam, but the examiner wasn't satisfied with the solution. Please tell me why my solution is unsatisfactory.

function bubbleSort(myArray){
  var temp = undefined,isSwap = false;

  for(var x = 0; x < myArray.length; x++){
   if(((x+1) <= (myArray.length - 1)) && myArray[x] > myArray[x+1]){
     temp = myArray[x];
     myArray[x] = myArray[x+1];
     myArray[x+1] = temp;
     isSwap = true;
   }else if(isSwap === true && x === (myArray.length - 1)){
     x = -1;
     isSwap = false;
   }else{
     continue;
   }
 }
 return myArray;
}

Just to see the performance I added a print statement i.e. console.log
in the start of the loop like below

for(var x = 0; x < myArray.length; x++){
    console.log(myArray);

This is what I am able to see for the specific input:

console.log(bubbleSort([5,1,6,2,0]));

Output:

rahul@rahul:~/myPractise/Algo$ node sorting.js
[ 5, 1, 6, 2, 0 ]
[ 1, 5, 6, 2, 0 ]
[ 1, 5, 6, 2, 0 ]
[ 1, 5, 2, 6, 0 ]
[ 1, 5, 2, 0, 6 ]
[ 1, 5, 2, 0, 6 ]
[ 1, 5, 2, 0, 6 ]
[ 1, 2, 5, 0, 6 ]
[ 1, 2, 0, 5, 6 ]
[ 1, 2, 0, 5, 6 ]
[ 1, 2, 0, 5, 6 ]
[ 1, 2, 0, 5, 6 ]
[ 1, 0, 2, 5, 6 ]
[ 1, 0, 2, 5, 6 ]
[ 1, 0, 2, 5, 6 ]
[ 1, 0, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]
[ 0, 1, 2, 5, 6 ]


texts: Script to download Annual Reports (~70,000 in total) from a Website

texts:
It's only 38 lines of code and I haven't worked with web scraping that much before.

  How heavy would my code be on their server?
  It's for Deep Learning purposes and I haven't ran it yet but would it result in my IP getting banned a quarter way through once I start
  downloading the 70k pdfs?

Also, I'm not sure how efficient this is (right now I don't think I'm even checking if a file exists and I'm overwriting it each time I run my program, so if my code is interrupted halfway through, I'll have to run it again and it'll start downloading everything again from scratch. I'll have to fix that).

But anyways, here is the code:

# Scrapes all pdfs off from www.annualreports.com
# Haven't tested yet but should be somewhere around 70,963 pdfs since my empty search returned 5,479/5,674 stated companies

import requests
from urllib.parse import urljoin
import pandas as pd
from bs4 import BeautifulSoup as bs
import os, re
import pickle

def extract_table():
    r = requests.get('http://www.annualreports.com/Companies?search=')
    soup = bs(r.content, 'lxml')
    df = pd.DataFrame([(i.text, 'http://www.annualreports.com' + i['href']) for i in soup.select('tbody td:nth-of-type(1) a')], columns = ['Company','Link'])
    df.to_pickle('links.pkl') # saves into a dataframe the name of the company plus the href link it points to

def scrap_pdfs():
    df = pd.read_pickle('links.pkl')
    a = 0 # for naming the filenames numerically

    for x in range(df.Link.count()):

        url = df['Link'][x] # reads the "Link" column from the dataframe

        folder_location = r'/home/duke/Annual_Reports/Data' # SPECIFY FULL DIRECTORY

        response = requests.get(url)
        soup= bs(response.text, "html.parser")

        for link in soup.select("a[href$='.pdf']"): #goes through all the .pdfs in all of the href links

            #filename = os.path.join(folder_location, ['href'].split('/')[-1]) # Names the pdf files using the last portion of each link

            filename = os.path.join(folder_location, str(a))
            a+=1

            with open(filename, 'wb') as f:
                f.write(requests.get(urljoin(url,link['href'])).content)


texts:
I wrote a python function that writes a integer to a file in binary form. But are there any ways that I can reduce the number of steps, is there a more efficient way to write a integer to a file?

def IntWrite(FileName, Integer):
    #convert to hexadecimal
    data = str('{0:0x}'.format(Integer))
    #pad number if odd length
    if(len(data) % 2 != 0):
        data="0"+data
    #split into chucks of two
    info = [data[i:i+2] for i in range(0, len(data), 2)]
    #convert each chuck to a byte
    data2 = "".join([chr(int(a, 16)) for a in info])
    #write to file
    file(FileName, "wb").write(data2)

#convert back to integer
def IntRead(FileName):
    RawData = file(FileName, "rb").read()
    HexData = "".join(['{0:0x}'.format(ord(b)) for b in RawData])
    return int(HexData, 16)

IntWrite("int_data.txt", 100000)
print IntRead("int_data.txt")


texts: Grouping work hours for consecutive days

texts:
Problem Description
The problem was initially posted here: Parse and clean up text block of store hours in Python.
Given the following multi-line string:
"""Hours
Monday 9:30 AM - 9:00 PM
Tuesday 9:30 AM - 9:00 PM
Wednesday 9:30 AM - 9:00 PM
Thursday 9:30 AM - 9:00 PM
Friday 9:30 AM - 11:00 PM
Saturday 9:30 AM - 11:00 PM
Sunday 11:00 AM - 6:00 PM
Holiday Hours
Thanksgiving Day 11:00 AM - 6:00 PM"""

Group the consecutive weekdays by the work hours, producing the following output:
"""Mon-Thu 9:30AM-9:00PM
Fri-Sat 9:30AM-11:00PM
Sun & Hol 11:00AM-6:00PM"""

Solution
My approach is based on parsing the weekday lines, splitting by the first space and then using itertools.groupby() to sort by the second item of every row, using the groupby's implementation detail - it would only group the consecutive matches together:
from itertools import groupby
from operator import itemgetter

data = """Hours
Monday 9:30 AM - 9:00 PM
Tuesday 9:30 AM - 9:00 PM
Wednesday 9:30 AM - 9:00 PM
Thursday 9:30 AM - 9:00 PM
Friday 9:30 AM - 11:00 PM
Saturday 9:30 AM - 11:00 PM
Sunday 11:00 AM - 6:00 PM
Holiday Hours
Thanksgiving Day 11:00 AM - 6:00 PM"""

# filter relevant rows with weekdays only
rows = [row.split(" ", 1) for row in data.splitlines()[1:-2]]

# group consecutive days by a time range
result = []
for time_range, group in groupby(rows, key=itemgetter(1)):
    days_in_group = [item[0] for item in group]

    first_day, last_day = days_in_group[0][:3], days_in_group[-1][:3]
    range_end = "-" + str(last_day) if first_day != last_day else ""

    result.append("{begin}{end} {time_range}".format(begin=first_day,
                                                     end=range_end,
                                                     time_range=time_range))

print("\n".join(result))

Is this the most optimal solution to the problem? Is it Pythonic? What would you improve code quality-wise?


texts: Clipboard support in jQuery using revealing module pattern

texts:
I have recently been getting into the habit of leveraging the revealing module pattern for all my code. I used this guide for inspiration, but my code doesn't feel as elegant.

var styleGuide = (function styleGuideHandler() {
        'use strict';

        var publicAPI,
            intervalId = null,
            clipboard = new Clipboard('.copyButton'),
            btns = document.querySelectorAll('.style-guide');

        function setTooltip(btn, message) {
            $(btn).attr('data-original-title', message);
            setTimeout(function() {
                $(btn).tooltip('show');
            }, 150);
        }

        function hideTooltip(btn) {
            if (intervalId !== null) {
                clearTimeout(intervalId);
            }
            intervalId = setTimeout(function() {
                $(btn).tooltip('hide');
                intervalId = null;
            }, 500);
        }

        publicAPI = {
            init: function() {
                clipboard.on('success', function(e) {
                    setTooltip(e.trigger, 'Copied!');
                    hideTooltip(e.trigger);
                    e.clearSelection();
                    console.log(e);
                });

                clipboard.on('error', function(e) {
                    setTooltip(e.trigger, 'Failed!');
                    hideTooltip(e.trigger);
                    console.log(e);
                });

                $('.copyButton').tooltip({
                    trigger: 'click',
                    placement: 'bottom'
                });

                $('pre code').each(function(i, block) {
                    hljs.highlightBlock(block);
                });

                /* preventDefault on buttons */
                for (var i = 0, l = btns.length; i < l; i++) {
                    btns[i].addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                    });
                }
            }

        };

        return publicAPI;
    })();

    $(document).ready(styleGuide.init);

Also, would executing the ready function like this $(document).ready(function(){styleGuide.init}); encapsulate the module further? Meaning, there would be no chance the styleGuide module could overwritten?


texts: Prime generator program SPOJ time limit exceed

texts:
Problem Statement

Input
The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5

Output:
2
3
5
7

3
5

My Problem
I have tried very hard to optimize the code to my best, but still the online judge shows that I am exceeding the time limit. Is it possible to optimize the following code further or I should look for an alternative approach?
import sys
final=[]

for i in xrange(int(sys.stdin.readline())):
    start,end=[int(x) for x in sys.stdin.readline().split()]
    if start==1:
        start=2
    # sieve of eras** algorithm
    final.append(list(sorted(set(xrange(start,end+1)).difference(set((p * f) for p in xrange(2, int(end ** 0.5) + 2) for f in xrange(2, int(end/p) + 1))))))

# print final list items
for item1 in final:
    print("\n".join([str(x) for x in item1]))
    print('\n')


texts:
This is my first C++ program. It would be nice if you can tell me anything I could add or do differently.
I am new to C++ programming and I hope to learn more.
#include <iostream>
using namespace std;

int main()
{
    float a, b, result;
    char op;

    cout << "Enter an operator." << endl;

    cin >> op;

    cout << "Enter first value." << endl;

    cin >> a;

    cout << "Enter second value." << endl;

    cin >> b;

    cout << "----------------------" << endl;

    switch (op)
    {
    case '+':
        result = a + b;
        cout << result;
        break;

    case '-':
        result = a - b;
        cout << result;
        break;

    case '*':
        result = a * b;
        cout << result;
        break;

    case '/':
        result = a / b;
        cout << result;
        break;

    default:
        cout << "Invalid operation. Program terminated." << endl;
        return -1;
    }
}


texts:
I'm trying to teach myself Clojure by reading the Brave Clojure book online, and at the end of Chapter 7 there is an exercise to parse a mathematical expression written as a list in infix notation to s-expressions, following operator precedence rules.

To do this I implemented the shunting-yard algorithm in Clojure. However I am not sure if I am doing this in a functional way, as I am used to programming in languages like C++ and Python. In particular, I am uncertain whether the use of the loop operator is valid, as I'm coding this in basically the same way I would as in C++, just using recur on every loop iteration instead of mutating variables. This makes it seem a little repetitive.

Below is the code. It would be greatly appreciated someone takes a look and offers advice about how to do this in a more idiomatic functional way, or about anything else.

(def operator-precedence {'= 1, '+ 5, '- 5, '* 6, '/ 6})

(defn infix-parse
  "Converts an infix expression to s-expressions in linear time with the
  shunting-yard algorithm."
  [expr]
  (if (list? expr)
    (loop [val-stack ()
           op-stack ()
           remaining expr
           next-op false]
      (if next-op
        (let [prec (if (empty? remaining)
                     ##-Inf
                     (operator-precedence (first remaining)))
              popped (take-while #(>= (operator-precedence %) prec) op-stack)
              result (reduce
                       (fn [[a b & vals] op]
                         (cons (list op b a) vals))
                       val-stack
                       popped)]
          (if (empty? remaining)
            (first result)
            (recur result
                   (cons (first remaining)
                         (drop (count popped) op-stack))
                   (rest remaining)
                   false)))
        (recur (cons (infix-parse (first remaining)) val-stack)
               op-stack
               (rest remaining)
               true)))
    expr))

(defmacro infix
  [form]
  (infix-parse form))

(infix (1 + 3 * (4 - 5) * 10 / 2))
=> -14
(infix-parse '(1 + 3 * (4 - 5) * 10 / 2))
=> (+ 1 (/ (* (* 3 (- 4 5)) 10) 2))


texts: Sending file[type="file"] multiple content as list of base64's

texts:
There is a code that takes all files from input of multiple files, gets base64 for each of them, packs to array and jsonifies it. How to simplify and improve quality of code?

text = $('#input-' + id).val();
var files = document.querySelector('#files' + id + ' > input[type=file]').files;
if (text != '' || files.length > 0) {
    var files_obj = [];
    var reader = new FileReader();
    reader.onload = function(readerEvt) {
        var binaryString = readerEvt.target.result;
        files_obj.push(btoa(binaryString));
    };
    for (var i = 0; i < files.length; i++) {
        reader.readAsBinaryString(files[i]);
    }
    while (files_obj.length < files.length) {}
    $('input[type="file"]').val("");
    files_json = JSON.stringify(files_obj);
    json = '{"action": "message", "from": ' + userId + ', "text": "' + text + '", "room": ' + id + ', "files": ' + files_json + '}';
    socket.send(json);
    $('#input-' + id).val("");
}


texts: Function that provides callback for promise or non-promise

texts:
Below I created a use function that wraps a promise or non-promise, providing the a value callback all-while preserving the original function type.

type ThenArg<T> = T extends Promise<infer U> ? U : T
type Func = (...args: any[]) => any

type RelatedThen<PP, V> = PP extends Promise<infer U> ? Promise<V> : V

function isPromise(obj: any) {
    return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}

function use<A extends Func, G>(fn: A, callback: (e: Error | null, a: ThenArg<ReturnType<A>>) => G) {
    return (...args: Parameters<A>): RelatedThen<ReturnType<A>, G> => {
        try {
            const v = fn(...args as any[])
            if (isPromise(v)) {
                return v.then((r: any) => callback(null, r)).catch((e: Error) => callback(e, undefined as ThenArg<ReturnType<A>>))
            }
            return callback(null, v) as RelatedThen<ReturnType<A>, G>
        } catch (e) {
            return callback(e, undefined as ThenArg<ReturnType<A>>) as unknown as RelatedThen<ReturnType<A>, G>
        }
    }
}

const p = async () => 'hi'
const n = () => 'hi'

const a = use(p, (value) => {
    return value + ' mom'
})

const b = use(n, (value) => {
    return value + ' dad'
})

a().then(console.log)
console.log(b())

Playground


texts: Positioning text and images on a site grid

texts:
I've just started learning HTML and CSS. Currently I'm creating a test site to practice with.

I'm just after an early idea if the principles I'm using are correct. The below is an snippet from the main body of my HTML code. It's just about positioning text and images on a grid at the moment. I seem to be using a lot of divs with IDs in the CSS for styling etc.

Some of the alt text is work in progress and repeated currently hence why it repeats.

Can someone tell me if the structure is ok, or not and what I'd need to do to change this?

    About Us &nbsp &nbspOur Cheeses &nbsp &nbspContact Us

"QUOTE 1 - We really love the taste of your cheese, we will be back for more"

"QUOTE 2 - We really love the taste of your cheese, we will be back for more"


texts: Using dependency injection for Node payment system

texts:
I would like some feedback on my code. I am currently building a payments solution in a serverless lambda project. This what I came up with (very basic code at the moment):

// "interface implementation"
export default class Stripe {
  constructor() {
    this.stripe = new Stripe()
  }

  async charge(data) {
    try {
      const result = await this.stripe.chargeCustomerByToken(data);
      return result;
    } catch (error) {
      throw error;
    }
  }
}

export default class PaymentRepository {
  constructor(PaymentInterface) {
    this.ipayment = PaymentInterface;
  }

  async charge(data) {
    try {
      const result = await this.ipayment.charge(data);
      return result;
    } catch (error) {
      throw error;
    }
  }
}

export const charge = async (repository, data) => {
  if (!repository || !data) {
    throw new InvalidParameterError('Missing dependencies');
  }

  try {
    const result = await repository.charge(data);
    return result;
  } catch (error) {
    throw error;
  }
};

I would then use it like this in my main handler: charge(new PaymentRepository(new Stripe())).

This is my current structure. It feels super repetitive but still flexible and is easy to test, and also easy to change payment API (maybe to PayPal or something). But I'm not really sure if I'm just over-complexing the whole project, or maybe this isn't even the Node/JS way to code.


texts: Hackerrank: "Cut the sticks" Javascript solution

texts:
I took a stab at solving this problem from Hackerrank in Javascript, and would like your valuable feedback as to time/space complexity and just about any additional improvements.

Problem URL: https://www.hackerrank.com/challenges/cut-the-sticks

My JS implementation:

function main() {
    var n = parseInt(readLine());
    arr = readLine().split(' ');
    arr = arr.map(Number);

    arr = arr.sort(function(a,b){ return a-b; });

    function cut(barr){
        if(barr.length>0){//checks array length
            var min = barr[0]; //save min value in current array
            process.stdout.write(barr.length+'\n'); //write initial array length
            var b = [];
            for(var i=0; i<barr.length; i++){ //iterate over array
                var result = barr[i]-min; //math ops
                if(result>0){
                    b.push(result); //build new array if value is greater than 0
                }
            }

            cut(b); // call cut operation again with new array
        }else{
            return; //halt operation if no values left to check for
        }
    }

    cut(arr);

}