texts: Solving Project Euler Problem 1 using extension methods

texts:
As a self taught developer I never did any of the Project Euler problems, so I decided to just start with Problem 1 which states

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

The first step had been to create an extension method which takes a lowerLimit and an upperLimit returning an IEnumerable<int>
public static IEnumerable<int> GetSequence(this int lowerLimit, int upperLimit)
{
    if (upperLimit < lowerLimit) { throw new ArgumentOutOfRangeException("lowerLimit needs to be less or equal to upperLimit"); }

    for (int i = lowerLimit; i < upperLimit; i++)
    {
        yield return i;
    }
}

which can be called for instance like so
int lowerLimit = 1;
var sequence = lowerLimit.GetSequence(1000);

I am not 100% sure about the name of that method but couldn't come up with an alternative name so for sure I would like to hear suggestions for that.
The meat about solving the problem
public static class SolverOfProblemOne
{
    public static int Solve(this int lowerLimit, int upperLimit, params int[] multiples)
    {
        if (upperLimit < 0 || lowerLimit < 0) { throw new ArgumentOutOfRangeException("lowerLimit and upperLimit needs to be greater than or equal to 0"); }
        if (multiples == null || multiples.Length == 0) { return 0; }

        return lowerLimit.GetSequence(upperLimit)
            .Where(i => i.IsMultipleOf(multiples))
            .Sum();
    }

    private static bool IsMultipleOf(this int value, IEnumerable<int> multiples)
    {
        foreach (int multiple in multiples)
        {
            if (value % multiple == 0) { return true; }
        }
        return false;
    }

}

To solve the actual problem one would call it like
int lowerLimit = 1;
int upperLimit = 1000;
int res = lowerLimit.Solve(upperLimit, 3, 5);

Any suggestions about the shown code are welcome.
Because math has closed its doors for me after finishing school, I don't know if there is any math trick to do this any faster or easier.


texts:
I'm completely new to C and my first project is to create a simple cURL-like HTTP request client... but first, I need to create a function that can parse a URL. I've created this function, and it seems to work quite well, but since I'm so new to the complexities of C, can someone check for any errors or to see if I can improve clock efficiency?

Example usage can be found here.

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

void filterURLstring(char *weburl, char **protocol, char **username, char **password, char **host, char **port, char **path);

int main() {
    char *text = "http://mhdfffffjddj:abc123@192.168.0.2:8888/servlet/rece/";
    char *protocol, *username, *password, *host, *port, *path;
    filterURLstring(text, &protocol, &username, &password, &host, &port, &path);
    printf("Protocol:\"%s\"\n", protocol);
    printf("Username:\"%s\"\n", username);
    printf("Password:\"%s\"\n", password);
    printf("Host:\"%s\"\n", host);
    printf("Port:\"%s\"\n", port);
    printf("Path:\"%s\"\n", path);
    free(protocol);
    free(username);
    free(password);
    free(host);
    free(port);
    free(path);
    return 0;
}

void filterURLstring(char *weburl, char **protocol, char **username, char **password, char **host, char **port, char **path) {
    char *postprotocol, *postuserinfo, *postusername, *login, *posthost, *posthostname, *hostloc, *postport;
    int isPath;
    if ((postprotocol = strstr(weburl, "://")) == NULL) {
        printf("Input URL is invalid. Exiting...\n");
        exit(1);
    }
    *protocol = malloc(sizeof(char) * (postprotocol - weburl + 1));
    strncpy(*protocol, weburl, postprotocol - weburl);
    postprotocol = (postprotocol + (*(postprotocol+3)=='/'?4:3));
    if ((postuserinfo = strstr(postprotocol, "@")) != NULL) {
        if ((postusername = strchr(postprotocol, ':')) != NULL) {
            *password = malloc(sizeof(char) * (postuserinfo - postusername + 1));
            strncpy(*password, postusername + 1, (postuserinfo - postusername - 1));
        } else {
            *password = NULL;
        }
        int userlen = (postusername?postusername:postuserinfo) - postprotocol;
        *username = malloc(sizeof(char) *  userlen + 1);
        strncpy(*username, postprotocol, userlen);
    }
    hostloc = (postuserinfo?postuserinfo + 1:postprotocol);
    if ((posthost = strchr(hostloc, '/')) == NULL) {
        posthost = hostloc + strlen(hostloc);
        isPath = 1;
    }
    if ((posthostname = strchr(hostloc, ':')) == NULL) {
        posthostname = posthost;
    }
    *host = malloc(sizeof(char) * (posthostname - hostloc + 1));
    strncpy(*host, hostloc, (posthostname - hostloc));
    if (posthostname != posthost) {
        posthostname++;
        *port = malloc(sizeof(char) * (posthost - posthostname + 1));
        strncpy(*port, posthostname, (posthost - posthostname));
    } else {
        *port = malloc(sizeof(char) * 2 + 1);
        strncpy(*port, "80", 2);
    }
    if (isPath) {
        *path = malloc(sizeof(char) * strlen(posthost));
        strncpy(*path, posthost, strlen(posthost));
    } else {
        *path = calloc(1, 1);
    }
}

I changed my code according to the answer. It can be seen here.


texts: Split string into parts of varying lengths

texts:
I need to split a string into parts of varying predefined lengths, given as a sequence of integers. After a first imperative attempt using a sequence expression and a reference cell, I have now come up with this implementation that uses Seq.scan and doesn't need mutability:

let segmentString lengths (input : string) =
    let folder (start, parts) lengthHere =
        let partHere = input.Substring(start, lengthHere)
        start + lengthHere, partHere :: parts

    let results = lengths |> Seq.scan folder (0, [])

    let _, resultParts = Seq.last results
    List.rev resultParts

This works and is probably "good enough", but I wonder whether there are things that could be improved or more idiomatic (other than error handling and allowing more generic inputs than strings; I left those out because they are not a concern right now). What especially bugs me is the need to reverse the results list at the end, but obviously, I could only add the new part as the head of the aggregate list in the folder function.


texts:
This is my first deep dive into C, and I want to make sure that I'm not doing anything stupid. The code below creates an "Array List" of sorts, which automatically resizes itself.

This code is meant to run on a PIC24, where memory is at a premium.

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

#ifndef CHAR_QUEUE_H
#define CHAR_QUEUE_H
#define QUEUE_INIT_SIZE 128

typedef struct CharQueue_t{
    uint16_t size;
    uint16_t capacity;
    unsigned char *data;
    void (*append) (struct CharQueue_t *, unsigned char);
    void (*destroy) (struct CharQueue_t *);
    unsigned char (*get) (struct CharQueue_t *, uint16_t);
    unsigned char (*next) (struct CharQueue_t *);
} CharQueue_t;

CharQueue_t *CharQueueInit();

void CharQueueAppend(struct CharQueue_t *queue, unsigned char value);

void CharQueueDestroy(struct CharQueue_t *queue);

unsigned char CharQueueGet(struct CharQueue_t *queue, uint16_t idx);

unsigned char CharQueueNext(struct CharQueue_t *queue);

#endif  /* CHAR_QUEUE_H */

CharQueue_t *CharQueueInit() {
    CharQueue_t *queue = malloc(sizeof(CharQueue_t));
    // Initialize size and capacity
    queue->size = 0;
    queue->capacity = QUEUE_INIT_SIZE;
    queue->data = malloc(sizeof(unsigned char) * queue->capacity);
    queue->append = CharQueueAppend;
    queue->destroy = CharQueueDestroy;
    queue->get = CharQueueGet;
    queue->next = CharQueueNext;
    return queue;
}

void CharQueueAppend(struct CharQueue_t *queue, unsigned char value) {
    // Resize the queue if it's at capacity
    if (queue->size >= queue->capacity) {
        queue->capacity *= 2;
        queue->data = realloc(queue->data, sizeof(unsigned char) * queue->capacity);
    }
    queue->data[queue->size] = value;
    queue->size++;
}

void CharQueueDestroy(struct CharQueue_t *queue) {
    free(queue->data);
    free(queue);
}

unsigned char CharQueueGet(struct CharQueue_t *queue, uint16_t idx) {
    if (idx >= queue->size || idx < 0) {
        return 0;
    }
    return queue->data[idx];
}

unsigned char CharQueueNext(struct CharQueue_t *queue) {
    char data = queue->data[0];
    queue->size = queue->size - 1;
    // Move the pointer up the stack -- Does this leak memory?
    *queue->data++;
    return data;
}

int main(void) {
    CharQueue_t *queue = CharQueueInit();
    int i;
    for (i = 0; i < 256; i++) {
        queue->append(queue, i);
    }
    printf("Queue Size is %d\r\n", queue->size);
    for (i = 0; i < 256; i++) {
        printf("#%d in queue: 0x%d\r\n", i, queue->next(queue));
    }
    return 0;
}


texts: Python. Refactoring a function to increase its capabilities

texts:
I'm writing a bot, it turns out pretty big (1000 lines).
In code, I often use the "show profile" function. I noticed that I greatly complicate it by adding functionality with kwargs.
I am a newbie, I don’t know if I should create a class instead of a function, break it into different functions or continue in the same manner.

Now I need to add 2 features:

"show profile when creating for confirmation"
"Keyboard selection", if you want to show a group of profiles (the most important)

Basically, these problems arise because I make a bot using a module and in the conditions of a strict API.
If you have some remarks related to security, performance, etc - please, tell me them.

Sum up: I have three functions:

get_keyboard
show_profile
show_group_of_profiles

show_group_of_profiles must call show_profile, and show_profile must call get_keyboard. But show_group_of_profiles must call get_keyboard (via show_profile) with a specific argument, that in reality hardcoded in show_profile. I can pass this argument via kwargs, but it is a bad approach I think

def show_profile(user_id, profile_data=None, photo=None):

""" Profile it is just a message object with photo, text (caption) and (inline) keyboard (markup).
    Photo=None because While a recreating a new profile, old photos will be taken from DB,
    but you can't remove them until a user will approve a new profile (first missing feature).
    db_execute - manually created function, the short version of cursor.execute (pymysql)"""

    if not profile_data:
        profile_data = db_execute('SELECT goal, age, gender, country, city, comment FROM users WHERE user_id = %s',
                                  user_id, fetchone=True, get_tuple=True)
    else:
        profile_data = list(profile_data.values())

    if not photo:
        photo = db_execute('SELECT photo FROM photos WHERE user_id = %s and id = (SELECT MIN(id) FROM photos)',
                           user_id, fetchone=True)
        if not photo:
            photo = DEFAULT_PHOTO[0]

    username = bot.get_chat(user_id).username  # Get first and last name of user
    caption = f'Имя - {username}.\n'  # add link to user inside a message
    profile_data = {'Goal': profile_data[0], 'Agr': profile_data[1], 'Gender': profile_data[2],
                    'Country': profile_data[3], 'City': profile_data[4], 'Comment': profile_data[5]}

    # Remove None data from profile
    for key, value in dict(profile_data).items():  # Dict() to avoid 'dictionary changed size during iteration' error
        if value is None:
            del profile_data[key]
        else:
            caption += f'{key} - {value}\n'

    message = bot.send_photo(user_id, photo, caption=caption, parse_mode=ParseMode.HTML,
                             reply_markup=get_scrolling_profile_keyboard(user_id))
    return message  # To allow edits

def get_scrolling_photos_keyboard(shower_id):
    return InlineKeyboardMarkup([[
        InlineKeyboardButton('<', callback_data=f'back_photo {shower_id}'),
        InlineKeyboardButton('>', callback_data=f'next_photo {shower_id}')]])

def get_scrolling_profiles_keyboard(shower_id):

""" Add more buttons for scrolling, group of photos and group of profiles
(the profile is still just a message object with photo, text, and buttons)
(The second missing feature)"""

    keyboard_obj = get_scrolling_photos_keyboard(shower_id)
    buttons = keyboard_obj.inline_keyboard  # Get list from object
    buttons.append(InlineKeyboardButton('Back', callback_data=f'back_profile'))
    buttons.append(InlineKeyboardButton('Next', callback_data=f'next_profile'))
    return InlineKeyboardMarkup(buttons)


texts: Cross-cutting delete flag in a repository

texts:
I want to have a cross-cutting delete flag in my repository. I have the following repository pattern at the moment:

public interface IRepo<TModel> where TModel : EntityBase<int>
    {
        TModel Add(TModel item);
        void Add(IEnumerable<TModel> entities);
        TModel Remove(TModel item);
        TModel Find(int itemId);
        TModel Get(int itemId);
        IQueryable<TModel> Query { get; }
    }

I am exposing IQueryable which makes it hard to control whether deleted entities are retrieved or not in my service layer. Would adding a method to my repository which replaces Query and exposes a pre-filtered IEnumerable be bad form?

public IEnumerable<TEntity> GetAll
{
    get { return this.dbset.AsEnumerable().Where(x => x.IsDeleted == false); }
}

I am assuming since IQueryable is lazily loaded I won't pulling more entities into memory than required? Is this naive?


texts: Table component for scrolling through lines of data

texts:
I'm working on a table component that is able to scroll through millions of lines of data. Not bad for the front end. The way I'm doing this is to only render a small table with 10 rows and then, when the user scrolls, I change the data in that table.

The table itself is not in a scrollable div because the entire html element fits on the page. This is working OK, but it means that the scroll on the page is not disabled the way it would be if the table were in a scrollable div.

I really don't like how I have to hide the overflow on the body when the mouse enters the component to stop the scroll event from moving the whole page instead of just the data in the component.

import Ember from 'ember';
import layout from '../templates/components/table';

let TableComponent = Ember.Component.extend(
  {
    tagName: 'table',
    layout: layout,
    firstRow: 0,
    lastRow: 10,
    isScrollEnabled: false,

    maxRow: Ember.computed('content',
      function () {
        return Ember.get(this, 'content.length');
      }
    ),

    setup: function () {
      this.$().on('mousewheel', Ember.run.bind(this, this._didScroll));
      this.$(window).on('focus', Ember.run.bind(this, this._focus));
      this.$(window).on('blur', Ember.run.bind(this, this._blur));
    }.on('didInsertElement'),

    tearDown: function () {
      this.$().off('mousewheel', Ember.run.bind(this, this._didScroll));
      this.$(window).off('focus', Ember.run.bind(this, this._focus));
      this.$(window).off('blur', Ember.run.bind(this, this._blur));
    }.on('willDestroyElement'),

    visibleContent: Ember.computed('content', 'firstRow', 'lastRow',
      function () {
        let content = Ember.get(this, 'content');
        let firstRow = Ember.get(this, 'firstRow');
        let lastRow = Ember.get(this, 'lastRow');

        return content.slice(firstRow, lastRow);
      }
    ),

    _didScroll(event) {
      if (!Ember.get(this, 'isScrollEnabled')) {
        return;
      }
      if (event.originalEvent.wheelDelta >= 0) {
        // scroll up but not past first row
        if (Ember.get(this, 'firstRow') > 0) {
          this.decrementProperty('firstRow');
          this.decrementProperty('lastRow');
        }
      } else {
        // scroll down but not past last row
        if (Ember.get(this, 'lastRow') < Ember.get(this, 'maxRow')) {
          this.incrementProperty('firstRow');
          this.incrementProperty('lastRow');
        }
      }
    },

    _focus() {
      Ember.set(this, 'isScrollEnabled', true);
    },

    _blur() {
      Ember.set(this, 'isScrollEnabled', false);
    },

    mouseEnter() {
      Ember.$('body').css('overflow', 'hidden');
    },

    mouseLeave() {
      Ember.$('body').css('overflow', 'auto');
    }
  }
);

export default TableComponent;

The mouseEnter and mouseLeave functions are my big concerns.


texts:
At now I have such code, creating or updating some entity by dto items.

public void Upsert(List<Object> items)
{
    var existings = _db.Get().Where().ToList();
    foreach (var item in items)
    {
        var existing = existings.FirstOrDefault(x => x.Id == item.SomeId);
        if (existing == null)
        {
            if (item.Property != 645)
            {
                throw new EntityNotFoundException();
            }

            // create new
        }
        else
        {
            // update existing
        }
    }
    _db.Save();
}

I want to move if (item.Property logic out of this layer. I cannot add some method to Object, it is simply dto. I also cannot subclass UpsertService.

What I can do is to pass Action<Object> checkWhenNotFound to Upsert method. Disadvantage - I need to write all those mocking It.IsAny<Action<Object, NotOnlyObjectInReal, AndMaybeMore>> in tests.

Other way is to inject checker inside Upsert caller ctor:

interface IUpsertService {
    void Upsert(List<Object> items);
    void SetChecker(Action<Object>);
}
public Owner(IUpsertService service)
{
    _service = service;
    service.SetChecker(CheckWhenNotFound)
}
private CheckWhenNotFound(Object item)
{
    if (item.Property != 645)
    {
        throw new EntityNotFoundException();
    }
}

Is there commmon solution for such problem?


texts:
Given a strings like 'param1.param2.param3' and a value that should be set on the last parameter, is there a better way than the following to dynamically create an Object and reuse the function to create more parameters on the Object, some which may share a parent parameter? This function also assumes every parameter on the parent Object is an Object with parameters. The purpose is to construct a JSON Object dynamically for a PUT/PATCH request.

function(o,prop,val) {
            prop = prop.split('.');
            prop.forEach(function(property,i){
                if(i===0 && typeof(o[property]) === 'undefined'){
                    o[property] = {};
                    if(prop.length === 2){
                        o[prop[0]][prop[1]] = val;
                    }
                }
                else if(i===1 && typeof(o[prop[0]][property]) === 'undefined'){
                    o[prop[0]][property] = {};
                    if(prop.length === 3){
                        o[prop[0]][prop[1]][prop[2]] = val;
                    }
                } else if(i===1 && typeof(o[prop[0]][property]) === 'object'){
                    if(prop.length === 3){
                        o[prop[0]][prop[1]][prop[2]] = val;
                    }
                }
                else if(i===2 && typeof(o[prop[0]][prop[1]][property]) === 'undefined'){
                    o[prop[0]][prop[1]][property] = {};
                    if(prop.length === 4){
                        o[prop[0]][prop[1]][prop[2]][prop[3]] = val;
                    }
                } else if(i===2 && typeof(o[prop[0]][prop[1]][property]) === 'object'){
                    if(prop.length === 4){
                        o[prop[0]][prop[1]][prop[2]][prop[3]] = val;
                    }
                }
            });
            return o;
        };

Here is a Fiddle https://jsfiddle.net/cn25o1vf/


texts: Game of Life Neighbour count optimization

texts:
This is a working Neighbours method. Is there any way to make this simpler and concise?

public int Neighbours(int xCoordinate, int yCoordinate)
        {
            xCoordinate = xCoordinate -1;
            yCoordinate = yCoordinate -1;
            int NeighbourCounter =0;
            int incrementer = 0;
            int i1 =-1;
            int j1 =-1;
            int i2 =1;
            int j2 =1;

            if(yCoordinate==0)
            {
                j1=1;
            }

            if(xCoordinate==0)
            {
                i1=1;
            }

            if(yCoordinate+1==xLen)
            {
                j2=0;
            }

            if(xCoordinate+1==yLen)
            {
                i2=0;
            }

            for(int j=j1; j<=j2; j++)
            {
                if(j==0)
                {
                    incrementer = 2;
                }
                else
                {
                    incrementer = 1;
                }

                for(int i=i1; i<=i2; i+=incrementer)
                {
                    if(CG[yCoordinate + j][xCoordinate + i] == 1)
                    {
                        NeighbourCounter++;
                    }
                }
            }
                return NeighbourCounter;
        }


texts: Counting multiples of 3 or 5 using threads

texts:
I have a modified version of the first Project Euler problem — where I find the sum of all the numbers below the value 2100000000 that are multiples of 3 or 5 using a multi-threaded program.

The concept of the partially-multi-threaded version: we have a value sum, where we add together all the multiples of 3 (that are not multiples of 3 and 5). Then, we add all the multiples of 5 (that were multiples of 3 and 5) to sum.

On my computer, this code executes at (an average)  4050 milliseconds.  How can the execution time be reduced?

MultipleOf3.java

//Calculates the sum of multiples of 3 from 3 to 2100000000.
public class MultipleOf3  implements Runnable {
    private volatile int sum = 0;

    public void run() {
        int counter = 1;
        for(int i = 3; i < 2100000000; i += 3) {

          //If the multiple of 3 ends with a 5 or 0, then skip it because
           // it is a multiple of 5.
          if(counter == 5) {
                counter = 1;
                continue;
           }

           sum += i;
           counter++;
        }
    }

   public int getSum() {
       return sum;
   }
}

MultipleOf5.java

// Calculates the sum of multiples of 5 from 5 to 2100000000.

    public class MultipleOf5  implements Runnable {
         private volatile int sum = 0;

         public void run() {
              //This time we added all multiples of 5 - including the
             //values that were skipped that were multiples of 3 and 5
             for(int i = 5; i < 2100000000; i += 5) {
                sum += i;
             }
         }

         public int getSum() {
             return sum;
         }

    }

Main.java

public class Main {

    private static int parallelSolution() throws InterruptedException{
        int totalSum = 0;

        MultipleOf3 multipleOf3 = new MultipleOf3();
        Thread newThread = new Thread(multipleOf3);

        MultipleOf5 multipleOf5 = new MultipleOf5();
        Thread secondThread = new Thread(multipleOf5);

        newThread.start();
        secondThread.start();

        newThread.join();
        secondThread.join();

        totalSum += multipleOf3.getSum();
        totalSum += multipleOf5.getSum();

         return totalSum;
   }

    public static void main(String[] args) throws InterruptedException  {
        long startTime = System.currentTimeMillis();
        int sum = parallelSolution();
        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;

        System.out.println("The total sum = " + sum);
        System.out.println("Elapsed time is " + elapsedTime);
    }

}


texts: Make a Deal program - using sets in Python

texts:
Mostly because I didn't believe the outcome of the classic game play Make-a-Deal (see https://math.stackexchange.com/questions/608957/monty-hall-problem-extended) I made this little program... and indeed if there are 3 doors and the quiz-master opens a door and you then switch from your initial choice of door your chances go up from 33% to 67%! This program is the generalized version whereby you can choose the number of doors and how many doors the quiz-master will open, it calculates the chance for a price for the initial choice (basically 1 over the number of doors) and the chance if you change your selected door after the doors have been opened.

I was pleasantly taken by the elegant solution using Python sets, but I wonder if this is the most efficient way. Comparing with other methods it looks like it becomes relatively more efficient with more doors and doors to open.

Thank you for your input...

#!/usr/bin/env python
'''  application of Make a deal statistics
     application is using sets {}
     for reference:
 https://math.stackexchange.com/questions/608957/monty-hall-problem-extended
'''
import random

def Make_a_Deal(doors, doors_to_open):
    '''  Generalised function of Make_a_Deal. Logic should be self explanatory
         Returns win_1 for the option when no change is made in the choice of
         door and win_2 when the option to change is taken.'''

    win_1, win_2 = False, False

    doors_set = set(range(1, doors+1))
    price_set = set(random.sample(doors_set, 1))
    choice1_set = set(random.sample(doors_set, 1))
    open_set = set(random.sample(doors_set.difference(price_set).
                   difference(choice1_set), doors_to_open))
    choice2_set = set(random.sample(doors_set.difference(open_set).
                      difference(choice1_set), 1))
    win_1 = choice1_set.issubset(price_set)
    win_2 = choice2_set.issubset(price_set)

    return win_1, win_2

def main():
    '''  input:
         - throws: number of times to Make_a_Deal (must be > 0)
         - doors: number of doors to choose from (must be > 2)
         - doors_to_open: number of doors to be opened before giving the option
           to change the initial choice (must be > 0 and <= doors-2)'''

    try:
        throws = int(input('how many throws: '))
        doors = int(input('how many doors: '))
        doors_to_open = int(input('how many doors to open: '))
        if (throws < 1) or (doors < 3) or \
                (doors_to_open > doors-2) or (doors_to_open < 1):
            print('invalid input')
            return

    except Exception as e:
        print('invalid input: ', e)
        return

    number_of_wins_1, number_of_wins_2, counter = 0, 0, 0

    while counter < throws:
        win_1, win_2 = Make_a_Deal(doors, doors_to_open)

        if win_1:
            number_of_wins_1 += 1
        if win_2:
            number_of_wins_2 += 1

        counter += 1
        print('completion is {:.2f}%'.
              format(100*counter/throws), end='\r')

    print('number of wins option 1 is {:.2f}%: '.
          format(100*number_of_wins_1/counter))
    print('number of wins option 2 is {:.2f}%: '.
          format(100*number_of_wins_2/counter))

if __name__ == '__main__':
    main()


texts:
I am learning programming with Guice and I am trying to write my own program for each of the concepts in the Guice official wiki.

Here is my example program for the Injector builtin binding. Please review this and suggest any corrections/improvements.

package guicePractice.guiceOfficial.BindingsExamples;

import com.google.inject.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by uday on 8/23/16.
 */
public class BuiltInBindingInjector {
    private static final Logger logger = LoggerFactory.getLogger
            (BuiltInBindingInjector.class);

    @ImplementedBy(Bb.class)
    interface B {
        String getMessage();
    }
    static class Bb implements B {
        private String message = "Hi!";
        public String getMessage(){
            return message;
        }
    }

    interface A {
        String getMessage();
    }

    static class Aa implements A {
        private B b;

        @Inject
        public Aa(Injector injector){
            b = injector.getInstance(B.class);
        }

        public String getMessage(){
            return b.getMessage();
        }
    }

    static class BuiltInBindingInjectorModule extends AbstractModule {
        @Override
        public void configure(){
            bind(B.class).to(Bb.class);
            bind(A.class).to(Aa.class);
        }
    }

    public static void main(String args[]){
        Injector injector = Guice.createInjector(new
                BuiltInBindingInjectorModule());
        A a  = injector.getInstance(A.class);
        logger.info("Message from injected Injector {}", a.getMessage());
    }
}


texts:
The task

  You are given a list of data entries that represent entries and exits
  of groups of people into a building. An entry looks like this:

  {"timestamp": 1526579928, count: 3, "type": "enter"}

  This means 3 people entered the building. An exit looks like this:

  {"timestamp": 1526580382, count: 2, "type": "exit"}

  This means that 2 people exited the building. timestamp is in Unix
  time.

  Find the busiest period in the building, that is, the time with the
  most people in the building. Return it as a pair of (start, end)
  timestamps. You can assume the building always starts off and ends up
  empty, i.e. with 0 people inside.

const stamp = [
  {"timestamp": 1526579928, count: 3, "type": "enter"},
  {"timestamp": 1526580382, count: 2, "type": "exit"},
  {"timestamp": 1526579938, count: 6, "type": "enter"},
  {"timestamp": 1526579943, count: 1, "type": "enter"},
  {"timestamp": 1526579944, count: 0, "type": "enter"},
  {"timestamp": 1526580345, count: 5, "type": "exit"},
  {"timestamp": 1526580351, count: 3, "type": "exit"},
];

My imperative solution:

const findBusiestPeriod = lst => {
  let visitors = 0;
  const busiestPeriod = {
    start: null,
    end: null,
    maxVisitors: null,
  };

  lst.forEach((v, i) => {
    visitors = v.type === "enter" ?
      visitors + v.count :
      visitors - v.count;

    if (visitors > busiestPeriod.maxVisitors) {
      busiestPeriod.maxVisitors = visitors;
      busiestPeriod.start = v.timestamp;
      busiestPeriod.end = lst[i + 1].timestamp;
    } else if (visitors === busiestPeriod.maxVisitors){
      busiestPeriod.end = lst[i + 1].timestamp;
    }
  });
  return [busiestPeriod.start, busiestPeriod.end];
};

console.log(findBusiestPeriod(stamp));

My functional solution

const findBusiestPeriod2 = lst => {
  const {start, end} = lst.reduce((busiestPeriod, v, i) => {
    busiestPeriod.visitors = v.type === "enter" ?
      busiestPeriod.visitors + v.count :
      busiestPeriod.visitors - v.count;
    const visitors = busiestPeriod.visitors;
    if (!busiestPeriod.maxVisitors || visitors > busiestPeriod.maxVisitors) {
      busiestPeriod.maxVisitors = visitors;
      busiestPeriod.start = v.timestamp;
      busiestPeriod.end = lst[i + 1].timestamp;
    } else if (visitors === busiestPeriod.maxVisitors){
      busiestPeriod.end = lst[i + 1].timestamp;
    }
    return busiestPeriod;
  }, {visitors: 0, maxVisitor: null,});
  return [start, end];
};

console.log(findBusiestPeriod2(stamp));


texts: Set of matrix operations for summing around a matrix element

texts:
I have a results of simulations, which are discrete complex numbers representing wave function on a NxN grid. I calculate phase of the wavefunction. For every point on that grid I have to perform this set of operations. Example:

|a b c|
|d e f|
|g h i|

Sum of difference between neighbours around element e:

 (a-b)+(b-c)+(c-f)+(f-i)+(i-h)+(h-g)+(g-d)+(d-a)

But every substraction δ have is subjected to this conditions

if δ > π than δ = δ - 2π
if δ < -π than δ = δ + 2π

I wrote a code in Octave, which is extremaly inefficient and slow, but I was hoping there is a way to move from buteforce calculations to faster calculations using some of the functions in image package. I know I can perfom sumation using convolution but I still have problem with other operations.

Code in Octave:

function deltaPhi = phaseDifference(phi1, phi2)
 deltaPhi = phi1 - phi2;
  if(deltaPhi > pi)
    deltaPhi = deltaPhi - 2*pi;
  endif

  if(deltaPhi < -pi)
    deltaPhi = deltaPhi + 2*pi;
  endif;
end

function [phase] = checkPhase(M)

phase = zeros(size(M)-2);

  for i = 2:size(M,1)-1
    for j = 2:size(M,2)-1
      phase(i-1,j-1) = phaseDifference(M(i-1,j-1),M(i,j-1)) + phaseDifference(M(i,j-1),M(i+1,j-1)) + phaseDifference(M(i+1,j-1),M(i+1,j)) + phaseDifference(M(i+1,j),M(i+1,j+1)) + phaseDifference(M(i+1,j+1),M(i,j+1)) + phaseDifference(M(i,j+1), M(i-1,j+1)) + phaseDifference(M(i-1,j+1), M(i-1,j)) + phaseDifference(M(i-1,j), M(i-1,j-1));
    endfor
  endfor

end

The idea is to rewrite this code in OpenCV and use some of that librarys methods.


texts: Insert an interval into a list of sorted disjoint intervals

texts:
The code works on my one test case. What do you think about it? Can it be simplified?

/*
if the interval list is [[1,5], [10,15], [20,25]]
and you need to insert the interval [12,27],
then your program should return the new list: [[1,5], [10,27]].
 */

var insertInterval = function(insert, intervals) {
    var result = [];
    for (var i = 0; i < intervals.length; i++) {
        var curr_interval = intervals[i];
        if (insert[1] < curr_interval[0]) {
            result.push(insert);
        }

        var prev_interval = i > 0 ? result[result.length - 1] : null;
        if (prev_interval && prev_interval[1] > curr_interval[0]) {
            if (prev_interval[1] < curr_interval[1]) prev_interval[1] = curr_interval[1];
        } else {
            if (insert[0] < curr_interval[0] && insert[1] >= curr_interval[0]) {
                curr_interval[0] = insert[0];
                if (insert[1] > curr_interval[1]) {
                    curr_interval[1] = insert[1];
                }
            } else if (insert[1] > curr_interval[1] && insert[0] >= curr_interval[0] && insert[0] < curr_interval[1]) {
                curr_interval[1] = insert[1];
            }
            result.push(curr_interval);
        }
    }

    return result;
};

var intervals = [
    [1, 5],
    [10, 15],
    [20, 25]
];
console.log(insertInterval([12, 27], intervals));


texts: Given suffix array and a pattern, search if given pattern exists

texts:
Given a suffix array for a word, check if a pattern (consecutive chars) exists.

  Example:

  A suffix array constructed for "ameya" should return true for "ame" but false for "foo" or false for "ameyp".

  This algoritm is case sensitive.

I'm looking for code-review, best practices and optimizations.

public final class SuffixArrayPatternMatch {

    private final String[] suffixArray;

    public SuffixArrayPatternMatch(String[] suffixArray) {
        this.suffixArray = suffixArray;
    }

    /**
     * Returns  0, if the string starts with the pattern.
     * Returns  1, if the string is greater than 1.
     * Returns -1, if the string is smaller than pattern.
     *
     *
     * @param str           the string to be matched with the pattern.
     * @param pattern       the pattern to be searched in the string
     * @return              -1, 0, or 1.
     */
    private int compare(String str, String pattern) {
        int length = str.length() < pattern.length() ? str.length() : pattern.length();

        for (int i = 0; i < length; i++) {
            if (str.charAt(i) < pattern.charAt(i)) return -1;
            if (str.charAt(i) > pattern.charAt(i)) return  1;
        }

        // string was greater than myself. thus return 0.
        return str.length() < pattern.length() ? -1 : 0;
    }

    private boolean binarySearch(int lb, int hb, String pattern) {
        if (lb > hb) {
            return false;
        }
        int mid = (lb + hb) / 2;

        int match = compare(suffixArray[mid], pattern);

        if (match == 0) return true;

        if (match > 0) {
            return binarySearch(lb, mid -1, pattern);
        } else {
            return binarySearch(mid + 1, hb, pattern);
        }
    }

    /**
     * Checks the pattern if present in the string
     *
     * @param pattern   the pattern to be searched in the string
     * @return          true if pattern is found else false.
     */
    public boolean search (String pattern) {
        return binarySearch(0, suffixArray.length - 1, pattern);
    }
}

public class SuffixArrayPatternArrayTest {

    @Test
    public void testTrue() {
        String[] suffix = {"a", "ameya", "eya", "meya", "ya"};
        SuffixArrayPatternMatch sapm = new SuffixArrayPatternMatch(suffix);

        for (int i = 0; i < suffix.length; i++) {
            assertTrue(sapm.search(suffix[i]));
        }

        assertTrue(sapm.search("mey"));
        assertTrue(sapm.search("ame"));
    }

    @Test
    public void testFalse() {
        String[] suffix = {"a", "ameya", "eya", "meya", "ya"};
        SuffixArrayPatternMatch sapm = new SuffixArrayPatternMatch(suffix);

        assertFalse(sapm.search("foo"));
        assertFalse(sapm.search("yap"));
        assertFalse(sapm.search("ameyap"));
    }
}


texts:
I'm learning Python 3 at the moment, so to test the skills I've learned, I am trying the puzzles at Python Challenge.

I've created some code to solve the 2nd puzzle here. it works, but I think that the way I've done it is very convoluted.  Any suggestions on how to solve the puzzle in a simpler way?

(The code basically needs to substitute each letter in a message to the letter 2 spaces to the right of it, such as E->G.)

import string
alphabet = string.ascii_lowercase
letter=0
replaceLetter = 2
times=1
message = input()
newMessage=''
while times < 26:
    newMessage = message.replace(alphabet[letter], str(replaceLetter)+',')
    message = newMessage
    letter = letter + 1
    replaceLetter = replaceLetter + 1
    time = times + 1
    if letter == 26:
        times = 0
        break
newMessage = message.replace('26'+',', 'a')
message = newMessage
newMessage = message.replace('27'+',', 'b')
message = newMessage
number = 25
message = newMessage
while times < 26:
    newMessage = message.replace(str(number)+',', str(alphabet[number]))
    message = newMessage
    letter = letter + 1
    number = number - 1
    time = times + 1
    if number == -1:
        times = 0
        break
print(newMessage)


texts: Java splitting too large text file enhance performance

texts:
I have a too large data.txt file containing data as follows:

a = line0
line1
line2
€
b = line0
line1
line2
€
...
z = line0
line1

I am still beginner with java, I wrote this code to split the data.txt into multiple .txt files named a.txt , b.txt etc... it splits the data.txt at each €\n character.

It works perfectly, but it is so slow, I noticed, as if it reads everything at once and makes its mission, then at once the result .txt files are created and showed  at once in the destination folder.

How could I make my code faster, for example when it is finished with the first part then it should create the result a.txt file immediatly then the second, third and so on...
Thank in advance

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

public class Main
{
    public static void main(String[] args)
    {
        File file = new File("/path/path2/file.txt");

        try{
            Scanner scanner = new Scanner(file);
            String str = "";

            while(scanner.hasNext()){

                str+=scanner.nextLine()+"\n";

            }

            String charac = "€";
            String end = "end of file";

            for(int i = 0; i < (str.split(charac).length)-1; i++){

                String name = str.split(charac)[i].split(" = ")[0];

                String out= "/path/path2/path3/Folder/"+name+".txt";
                FileWriter fw = new FileWriter(out);
                BufferedWriter bw = new BufferedWriter(fw);

                bw.write(str.split(charac)[i]+"\n"+end);
                bw.close();
            }

            System.out.println("Splitting is finished");

        }
        catch(Exception e){}
    }
}


texts:
For part of a project, I was given this directive:

  The find command will use the directory (dirent) function calls, but
  will require you to start at a directory and then determine if a file
  is a directory or a file and if it is a directory you will need to
  walk down that directory as well. You will need a method/algorithm to
  note the new directories and build a logical graph or thread out every
  directory to find if the filename is in that directory and display the
  "absolute" path to that file.

I thought the nftw() function would be optimal for this, and I believe it makes my application pretty robust and fast.  On my Mac (ommiting 196 lines of filename output each):

$ time find ../../ -name "CMakeLists.txt"
real    0m0.337s
user    0m0.025s
sys 0m0.292s

$ time ./my_find ../../ -name "CMakeLists.txt"
real    0m0.326s
user    0m0.022s
sys 0m0.278s

find.c:

#define _XOPEN_SOURCE 1
#define _XOPEN_SOURCE_EXTENDED 1

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <ftw.h>
#include <unistd.h>

#ifndef streq
#define streq(x, y) (strcmp((x), (y)) == 0)
#endif

typedef enum {SUCCESS, INVALD_DIR, OPENDIR_ERR, NFTW_ERR} Return;

const char* str = NULL;

int check_path(const char* path)
{
    DIR* dir = opendir(path);
    if (dir)  // directory exists
    {
        closedir(dir);
        return 0;
    }
    else if (ENOENT == errno) // directory doesn't exist
        return INVALD_DIR;
    else // opendir failed for some other reason
        return OPENDIR_ERR;
}

int callback(const char *file, const struct stat *sb, int flag, struct FTW *s)
{
    int err = 0;
    const char *name = file + s->base;

    switch (flag)
    {
        case FTW_F:
            if (streq(name, str))
                puts(file);
            break;
        case FTW_D:
        case FTW_DNR:
        case FTW_SL:
        case FTW_NS:
            break; // continue as normal
        case FTW_DP:
        case FTW_SLN:
        default:
            err = NFTW_ERR; // error occured
            break;
    }

    return err;
}

int process(const char* path)
{
    int err = nftw(path, callback, getdtablesize(), 0);
    return err;
}

void usage(const char* prog_name)
{
    fprintf(stdout, "usage: %s [path] -name <name>\n", prog_name);
    exit(EXIT_SUCCESS);
}

int main(int argc, char **argv)
{
    if(argc < 4)
        usage(argv[0]);

    const char* path = argv[1];
    str = argv[3];

    int err = check_path(path);
    if (err)
    {
        fprintf(stderr, "%s: %s: %s\n", argv[0], path, strerror(errno));
        return err;
    }
    else
        process(path);

    return err;
}

Any suggestions?


texts: Rock, Paper, Scissors game in JavaScript

texts:
I built this as part of completing the Codecademy JavaScript lesson. I wanted to perfect it, make it readable and functional, and as efficient as possible. As far as I can tell it can't be any more efficient than this. But maybe I can't tell. What do you think? I know there are little things, maybe the victory variable should have a console.log in it. Probably one or two more. But hopefully this is a good example for people who need help with writing their Rock, Paper, Scissors challenge.

//Loop ensures only valid user input is rock, paper, scissors
var i, infiniteloop;
for (i=0; i<1; infiniteloop++) //infiniteloop allows loop to continue if user is infinitely retarded
{
    var userChoice = prompt("You're playing rock, paper, scissors against the computer. Type your choice in lower case letters.")
    if (userChoice === "rock") {i=1;} //escapes loop
        else if (userChoice === "paper") {i=1;} //escapes loop
        else if (userChoice === "scissors") {i=1;} //escapes loop
        else {alert("Try again, stupid.");} //alerts, loops back to start
}

console.log("You chose " + userChoice + "!"); //announces userChoice

//generate a random computer choice, assign a string to replace it
var computerChoice = Math.random(); //random function. generates a number between 0 and 1
if (computerChoice <= .33) { computerChoice = "rock"; }
    else if (computerChoice <= .66) { computerChoice = "paper"; }
    else { computerChoice = "scissors"; }

console.log("Computer chose " + computerChoice + "!"); //announces computerChoice

var victory = "You win! A master strategist is you." //preset victory announcement
if (userChoice === computerChoice) { console.log("Tie game!"); }
    else if (userChoice === "rock" && computerChoice === "scissors") { victory }
    else if (userChoice === "paper" && computerChoice === "rock") { victory }
    else if (userChoice === "scissors" && computerChoice === "paper") { victory }
    else {console.log("You have suffered a devastating loss.");}


texts:
I had a code for a layout library which looked like :

$this->layout->setLayout($layout)->setTitle($title)->render()
etc.

Today I started writing a new code, simpler and smaller :

$this->layout->data(array(
    'view_name'     => 'layout_admin',
    'title'         => 'Administration',
    'js'            => 'admin/matrix.chat'
))->view('admin/index');

The previous setters/add methods were like :

public function setDoctype($doctype) {
    $this->doctype = $doctype;
    return $this;
}

public function addJs($name) {
    if(!in_array($name, $this->js)) {
        $this->js[] = $name;
    }
    return $this;
}

The new data method :

public function data($data = array()) {
    if(isset($data['view_name'])) $this->ci->config->load($data['view_name']);
    else $this->ci->config->load($this->data['view_name']);

    // Mark as forbid because are stored in arrays and
    // I can add values to those
    $forbid = array('css', 'js', 'rss');

    foreach($this->ci->config->config['layout'] as $key => $value) {
        if(isset($data[$key]) && !in_array($key, $forbid))
            $this->data[$key] = $data[$key];
        else
            $this->data[$key] = $value;

        if(isset($data[$key]) && in_array($key, $forbid)) {
            if(is_array($data[$key])) {
                if(count($array) != count($array, COUNT_RECURSIVE))
                    foreach($data[$key] as $key2 => $value2)
                        $this->data[$key][$key2] = $value2;
                else
                    foreach($data[$key] as $value2)
                        $this->data[$key][] = $value2;
            } else
                $this->data[$key][] = $data[$key];
        }
    }

    return $this;
}

I changed to this because of the many things that I can update for every page. And use ->setThing would be annoying. But I don't find that my code is so OOP.

Note that I'm using CodeIgniter.

What's the best oop code ? If you want more indications, please tell me I'm new and don't know how to  say more ;) .


texts:
I am new to Python. I have built a model with randomforest in python. But I think my code is not optimized. Please look into my code and suggest if I have deviated from best practices.

Overview about the data I have:

The data has response columns and predictor columns. Also there is a column 'TestOrTrainingDataRandom' which specifies the test and training data.(There are also columns like index, Timestamp,etc which have to be removed) The predictor columns start with '3000' and ends at '3680' with a step increase of 5 (i.e in total there are 137 predictor columns) But there are some predictor columns missing. So the missing predictor columns has been interpolated.

Here is my code. Please give the feedback.

from sklearn.ensemble import RandomForestClassifier   #Package for random forest classification
import pandas as pd
from sklearn.metrics import classification_report,confusion_matrix

data = pd.read_csv("combined_spectra_and_gas_params_3.csv") #Reading the file

#creating response column

data["response"] = None
s = pd.Series(["verylow","low","medium","high","veryhigh"], dtype="category")
n=0

for row in data["H2S"]:
    if row < 120:
        data['response'].iloc[n] = s[0] #Assign 'verylow' if H2S concentration is less than 120 and do indexing
        n=n+1
    elif row >=120 and row <500:
        data['response'].iloc[n] = s[1] #Assign 'low' if H2S concentration is between 120 and 500 and also do indexing
        n=n+1
    elif row >=500 and row <1000:
        data['response'].iloc[n] = s[2] #Assign 'medium' if H2S concentration is between 500 and 1000 and also do indexing
        n=n+1
    elif row >=1000 and row <1300:
        data['response'].iloc[n] = s[3] #Assign 'high' if H2S concentration is between 1000 and 1300 and also do indexing
        n=n+1
    else:
        data['response'].iloc[n] = s[4] #Assign 'veryhigh' if H2S concentration is greater than 1300 and do indexing
        n=n+1

#create the training & test sets
b=len(data)
a=data.TestOrTrainingDataRandom [data.TestOrTrainingDataRandom == 1].count() #Count the number of training data

new_data=data.drop(data.columns[[0,1,2,3,4,5,6,7,8,121,120,119,118]], axis=1)

colnames=list(new_data)
len_column = len(new_data.columns)
len_iteration=len_column-1
j=3000;i=0;k=0

new_col=pd.DataFrame(index=range(0,b),columns=['temp'])

# To insert missing columns
while i < len_iteration:
    if int(colnames[i])== j:
        i=i+1
        j=j+5;

    else:
        for k in range(0,b):
            new_col.iloc[k]=(new_data.iloc[k,i-1]+new_data.iloc[k,i+1])/2
        new_data.insert(i,str(j),new_col)
        colnames=list(new_data)
        j=j+5
        i=i+1
        len_iteration=len_iteration+1;

new_data.insert(1,"dataselection_col",data['TestOrTrainingDataRandom'])
new_data.insert(1,'response',data['response'])

train = pd.DataFrame(index=range(0,a),columns=list(new_data))   #Creating dataframe for training data
test = pd.DataFrame(index=range(0,abs(a-b)),columns=list(new_data)) #Creating dataframe for test data

m=0;n=0;p=0;
for value in new_data['dataselection_col']:
    if value == 1 :

        train.iloc[m]=new_data.irow(n)  #If 'TestOrTrainingDataRandom' column has 1, then append that row data to train and also do indexing
        n=n+1
        m=m+1
    else:
        test.iloc[p]=new_data.irow(n)   #If 'TestOrTrainingDataRandom' column has other than 0, then append that row data to test and also do indexing
        p=p+1
        n=n+1

trainRes = train['response']    #Response column
Actuals=test['response']         #Actuals
new_train=train.drop(train.columns[[1,2]],axis=1)
colnames=list(new_train)
trainArr = train.as_matrix(colnames) #Convert dataframe into array matrix representation

#For random forest
rf = RandomForestClassifier(n_estimators=100) #Random forest generation for Classification
rf.fit(trainArr, trainRes) #Fit the random forest model

testArr = test.as_matrix(colnames)

results = rf.predict(testArr)
print 'confusion matrix\n', confusion_matrix(Actuals, results)


texts: Bash script that creates a local environment for CHICKEN scheme (like virtualenv for Python)

texts:
Usage

To create a localenv called sicp, do $ localenv sicp
Activate the localenv: $ . sicp/bin/activate
Check installed eggs in the local repository: $ chicken-status
Install a new egg called 'sicp' in the local repository: $ chicken-install sicp
Deactivate the localenv: $ deactivate

This is the first time I have used bash for any purpose at all. Is there any other way to get the grandparent directory of the current directory?

#!/bin/bash

if [ -z "${1}" ]; then
    echo 'Usage: localenv DIR'
    echo
    echo 'localenv: You must provide the name of the directory to install the chicken environment.'
    exit 1
elif [ -e "$(pwd)/${1}" ]; then
    echo 'localenv: file or directory already exists.'
    exit 1
fi

# check if chicken is installed and save the location of csi and chicken-install.
CSI=$(command -v csi)

if [ -z "${CSI}" ]; then
    echo 'CHICKEN is not installed!'
    exit 1
else
    echo "CHICKEN interpreter is at ${CSI}"
fi

CHICKEN_INSTALL=$(command -v chicken-install)

# obtain global CHICKEN_HOME, CHICKEN_PREFIX, CHICKEN_REPOSITORY paths
CHICKEN_HOME=$(${CSI} -p "(chicken-home)")
CHICKEN_PREFIX="$(dirname $(dirname ${CHICKEN_HOME}))"
CHICKEN_REPOSITORY=$(${CSI} -p "(repository-path)")
# chicken binary version
BINARY_VERSION=$(basename "${CHICKEN_REPOSITORY}")

# local copy of chicken files are kept here
LOCAL_CHICKEN_PREFIX=$(realpath "${1}")

# remember where we were before jumping directories
OLDPWD=$(pwd)

# create all the necessary directories
mkdir -p "${LOCAL_CHICKEN_PREFIX}" && cd "$_" || exit 1
mkdir -p bin lib/chicken share/chicken include/chicken

# populate ./bin
for file in ${CHICKEN_PREFIX}/bin/{chicken,chicken-bug,chicken-install,chicken-profile,chicken-status,chicken-uninstall,csi,csc,feathers}; do
    [ -f "${file}" ] && cp "${file}" ./bin
done

# initialize empty alternative repository
${CHICKEN_INSTALL} -init "./lib/chicken/${BINARY_VERSION}"

# include files are essential
cp -R "${CHICKEN_PREFIX}"/include/chicken/{chicken.h,chicken-config.h} ./include/chicken

# populate ./share
cp -R "${CHICKEN_HOME}/setup.defaults" ./share/chicken

# create init file for the localenv
# init file acts like .csirc for the localenv
touch "${LOCAL_CHICKEN_PREFIX}/.init"

# write activate file
# Backslash escapes '$' and prevents expansion of the shell variables
cat << EOF > "${LOCAL_CHICKEN_PREFIX}/bin/activate"
export OLDPATH="\${PATH}"
export PATH="${LOCAL_CHICKEN_PREFIX}/bin:\${PATH}"

export OLDPS1="\${PS1}"
export PS1="($1)\${PS1}"

export CHICKEN_PREFIX="${LOCAL_CHICKEN_PREFIX}"
export CHICKEN_HOME="${LOCAL_CHICKEN_PREFIX}/share/chicken"
export CHICKEN_REPOSITORY="${LOCAL_CHICKEN_PREFIX}/lib/chicken/${BINARY_VERSION}"
export LOCAL_CSIRC="${LOCAL_CHICKEN_PREFIX}/.init"

# register a feature identifier 'localenv'
# this is required to override commands in the .csirc file
alias csi="csi -D localenv"

# deactivation function
deactivate()
{
    export PATH="\${OLDPATH}"
    export PS1="\${OLDPS1}"
    unset OLDPATH
    unset OLDPS1
    unset CHICKEN_PREFIX
    unset CHICKEN_HOME
    unset CHICKEN_REPOSITORY
    unset LOCAL_CSIRC
    unalias csi
    unset -f deactivate
}

EOF

cd "${OLDPWD}"


texts:
I've wrote a function where the doubles from a string are removed:

def removeDoubles(string):
    output = ' '
    for char in string:
        if output[-1].lower() != char.lower():
            output += char
    return output[1:]

For example:

removeDoubles('bookkeeper') = 'bokeper'
removeDoubles('Aardvark') = 'Ardvark'
removeDoubles('eELGRASS') = 'eLGRAS'
removeDoubles('eeEEEeeel') = 'el'

As you see, it will remove every double letter from a string no matter if it's uppercase or lowercase.

I was wondering if this could be more pythonic. As I have to start with a string containing a space, output[-1] does exist. I was also wondering if it's possible to use list comprehensions for this.


texts:
I wanted to implement the Sieve of Erathosthenes up to int.MaxValue in C#. No object is allowed to exceed 2Gb so you can't allocate a bool[int.MaxValue] array. In order to solve the problem, I created a class that packs the bits into an array of bytes instead.

I know that it's possible to use a segmented sieve: this was just for 'fun'.

public class SieveOfEratosthenes
{
    private readonly int highestNumber;

    // Flags for each number are stored packed in a byte array.
    // Least significant bit is flag for 1 - by starting at 1 and not 0 we can seive to int.MaxValue
    //                             8 7 6 5 4 3 2 1
    // e.g. for highestNumber = 8: 1 0 1 0 1 0 0 1 => 1, 4, 6 and 8 have been marked non-prime.
    private readonly byte[] data;

    private SieveOfEratosthenes(int highestNumber)
    {
        if (highestNumber < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(highestNumber));
        }
        this.highestNumber = highestNumber;
        var sizeRequired = (int)Math.Ceiling(highestNumber/8.0);
        data = new byte[sizeRequired];
    }

    public static SieveOfEratosthenes CreateSeive(int highestNumber)
    {
        var result = new SieveOfEratosthenes(highestNumber);
        result.Populate();
        return result;
    }

    public bool IsPrime(int number)
    {
        if (number < 0 || number > highestNumber)
        {
            throw new ArgumentOutOfRangeException(nameof(number));
        }
        // 0 not stored in byte array so we have to test separately.
        if (number == 0)
        {
            return false;
        }
        return ((data[(number-1)/8] >> (number-1)%8) & 1) == 0;
    }

    private void Populate()
    {
        for (var i = 2; i < Math.Sqrt(highestNumber); i++)
        {
            if (!IsPrime(i))
            {
                continue;
            }
            // j += i can overflow so need to guard against that in for loop.
            for (var j = i * i; j <= highestNumber && j > 0; j += i)
            {
                data[(j-1) / 8] = (byte)(data[(j-1) / 8] | (1 << ((j-1) % 8)));
            }
        }
        data[0] = (byte)(data[0] | 1); // Mark 1 as not prime.
    }
}

The algorithm for the Populate method is just from the wikipedia article with true and false the other way around, see: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode

The reason I'm using a static factory method is that I don't like constructors that do non-trivial work.

Here's a simple test harness that prints the primes under 100:

class Program
{
    static void Main(string[] args)
    {
        var sw = Stopwatch.StartNew();
        var sieve = SieveOfEratosthenes.CreateSeive(100);
        sw.Stop();
        Console.WriteLine(string.Join(", ", Enumerable.Range(0, 100).Where(sieve.IsPrime)));
        Console.WriteLine("Took {0}ms", sw.ElapsedMilliseconds);
        Console.ReadKey();
    }
}

On my machine it takes about 20 seconds to seive to int.MaxValue which takes just over 250mb of memory (roughly int.MaxValue/8 bytes).

Any room for improvement, bugs or style issues?


texts: Find string in sorted array with interspersed empty strings

texts:
(from McDowell) Given a sorted array of strings which is interspersed with empty strings, find the location of a given string.
eg. "ball" in

{"at", "", "", "", "ball", "", "", "car",
            "", "", "dad", "",""}

would output 4

Any comments on the code below?

Also, correct me if I am wrong please:
- space complexity: in place
- time complexity: worst case O(n), average case O(log(n))

  public static int findString(String[] array, String target, int low, int high){
    if (high < low) return -1;

    int middle = (low+high)/2;

    if (array[middle].equals(target)) return middle;

    if (array[middle].equals("")){
      int left = middle;
      int right = middle;

      while (array[left].equals("") && left >= low) left--;
      while (array[right].equals("") && right <= high)  right++;

      if (array[left].compareTo(target) >= 0) return findString(array, target, low, left);
      else if (array[right].compareTo(target) <= 0) return findString(array, target, right, high);
      else  return -1;
    }
    else{
      if (array[middle].compareTo(target) >= 0) return findString(array, target, low, middle);
      else if (array[middle].compareTo(target) <= 0) return findString(array, target, middle, high);
      else  return -1;
    }
  }


texts: List 130. Surrounded Regions leetcode solution using bfs

texts:
Given a 2D board containing 'X' and 'O' (the letter O), capture all
  regions surrounded by 'X'.

  A region is captured by flipping all 'O's into 'X's in that surrounded
  region.

Input:

X X X X
X O O X
X X O X
X O X X

Output:

X X X X
X X X X
X X X X
X O X X

All I am doing is to traverse all the edges and set all of them to x_not_possible and also there connected neighbors. Connected neighbors are found by doing bfs.

Traverse once more and set x_not_possible back to O and all the nodes not set to x_not_possible to X.

Code:

class Solution(object):
    def solve(self, board):
        if not board:
            return

        row_len, col_len = (len(board), len(board[0]))
        if row_len == 1 and col_len == 1:
            return

        def get_neighbours((i, j)):
            directions = []
            map_direction = {"left":(0, -1), "right":(0, 1), "up":(-1, 0), "down":(1, 0)}
            for _i, _j in map_direction.values():
                __i, __j = _i + i, _j + j
                if __i < row_len and __i >= 0 and __j < col_len and __j >= 0:
                    yield __i, __j

        increment_col, decrement_row, decrement_col, increment_row = (False, False, False, True)
        queue = []
        stop = [0, 0]
        while True:
            row, col = 0, 1
            if increment_row:
                if stop[row] + 1 >= row_len:
                    increment_col, increment_row = True, False
                    continue
                else:
                    stop[row] += 1
            elif increment_col:
                if stop[col] + 1 >= col_len:
                    decrement_row, increment_col = True, False
                    continue
                else:
                    stop[col] += 1
            elif decrement_row:
                if stop[row] - 1 < 0:
                    decrement_col, decrement_row = True, False
                    continue
                else:
                    stop[row] -= 1
            elif decrement_col:
                if stop[col] - 1 < 0:
                    break
                else:
                    stop[col] -= 1
            i, j = stop
            if board[i][j] == "O":
                queue.append((i, j))

        while len(queue):
            i, j = queue.pop()
            board[i][j] = "x_not_possible"
            for k, l in get_neighbours((i, j)):
                if board[k][l] == "O":
                    board[k][l] = "x_not_possible"
                    queue.append((k, l))

        for i in range(row_len):
            for j in range(col_len):
                if board[i][j] == "O":
                    board[i][j] = 'X'
                elif board[i][j] == "x_not_possible":
                    board[i][j] = 'O'


texts: Imperative code in R keeping track of state

texts:
A friend of mine has a spreadsheet where she coded a classroom video for various teaching events, which I needed to help her plot. For each recording, she used several video cassettes, and her time codes were relative to each video cassette (ie. they always start on 0). To be able to plot these on a timeline, I needed to convert the times into a relative (continuous) time. The code below works perfectly (and I've solved the problem), however it doesn't look good to me. It looks like the code I used to write in Ruby, before I began playing with R, Haskell etc.

This is not the first time I've come across this kind of a problem - iterating through rows, or lines of text, needing to keep track of several different kinds of "state", etc. I would be curious if this code could be rewritten to look cleaner, more idiomatic.

Example dataset

structure(list(code = structure(c(4L, 3L, 1L, 1L, 5L, 4L, 3L,
1L, 5L, 2L), .Label = c("CC-NoZZ", "CC-ZZ", "FBP", "KK-NoZZ",
"KK-ZZ"), class = "factor"), src = structure(c(1L, 1L, 1L, 2L,
2L, 3L, 3L, 4L, 4L, 4L), .Label = c("alfred1.mov", "alfred2.mov",
"claire1.mov", "claire2.mov"), class = "factor"), class = structure(c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("alfred's class",
"claire's class"), class = "factor"), start = c(0L, 2L, 6L, 0L,
10L, 1L, 5L, 0L, 6L, 14L), end = c(2L, 4L, 8L, 4L, 12L, 3L, 9L,
4L, 10L, 20L)), .Names = c("code", "src", "class", "start", "end"
), class = "data.frame", row.names = c(NA, -10L))

Example code

src = ""
class = ""
delta = 0
db$corr.start = NA
db$corr.end = NA
db$delta = NA

for(i in 1:nrow(db)) {
    row <- db[i,]
    if(row$src != src) {
      delta = db[i-1,]$end + delta
      src = row$src
    }

    if(row$class != class) {
      delta = 0
      class = row$class
    }

    db[i,]$corr.start = db[i,]$start + delta
    db[i,]$corr.end = db[i,]$end + delta

    db[i,]$delta = delta
}

Example output

      code         src          class start end corr.start corr.end delta
1  KK-NoZZ alfred1.mov alfred's class     0   2          0        2     0
2      FBP alfred1.mov alfred's class     2   4          2        4     0
3  CC-NoZZ alfred1.mov alfred's class     6   8          6        8     0
4  CC-NoZZ alfred2.mov alfred's class     0   4          8       12     8
5    KK-ZZ alfred2.mov alfred's class    10  12         18       20     8
6  KK-NoZZ claire1.mov claire's class     1   3          1        3     0
7      FBP claire1.mov claire's class     5   9          5        9     0
8  CC-NoZZ claire2.mov claire's class     0   4          9       13     9
9    KK-ZZ claire2.mov claire's class     6  10         15       19     9
10   CC-ZZ claire2.mov claire's class    14  20         23       29     9


texts: Easier way to find matching array from a lot of arrays

texts:
I have the following arrays which save the MAC-adresses of a lot of bluetooth beacons and their positions in a building:

private static final String[][] MAC_ADDRESSES_A_BLUETOOTH = {{"B09122F5D126", "210.105"}, {"B09122F5F26B", "136.121"}, {"B09122F5F619", "181.172"}};
...
private static final String[][] MAC_ADDRESSES_Q_BLUETOOTH = {{"B09122F5D124", "210.105"}, {"B09122F5F26Z", "136.121"}, {"B09122F5F61Q", "181.172"}};

Then I'm looking for the matching triple based on a current triple:

private String[][] compareArrays(String[] beacon) {
        if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_A_BLUETOOTH))) {
            return MAC_ADDRESSES_A_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_B_BLUETOOTH))) {
            return MAC_ADDRESSES_B_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_C_BLUETOOTH))) {
            return MAC_ADDRESSES_C_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_D_BLUETOOTH))) {
            return MAC_ADDRESSES_D_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_F_BLUETOOTH))) {
            return MAC_ADDRESSES_F_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_G_BLUETOOTH))) {
            return MAC_ADDRESSES_G_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_H_BLUETOOTH))) {
            return MAC_ADDRESSES_H_BLUETOOTH;
        } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_I_BLUETOOTH))) {
            return MAC_ADDRESSES_I_BLUETOOTH;
        } ...
        } else {
            return null;
        }
}

This code looks horrible and it bugs me. Is there an easier way to do this without having to write 16 if statements? getFirstArray returns all first values from a two-dimensional array.


texts:
I devised a new primality test isPrimeNumber() below which determines if 1000000007 is prime.
It works fine but the code looks unprofessional in my opinion. Is there any way to refactor it to make it more readable? Maybe inline the recursive gcd() function so everything is self-contained in the isPrimeNumber() function etc.,...? Any tips? Thanks!
// Primality Test
// Every n is prime if all lattice points on x+y=n are visible from the origin.

#include <stdio.h>
#include <stdint.h>
#include <math.h>

#define NOT_PRIME_NUMBER 0
#define PRIME_NUMBER 1

uint64_t gcd(uint64_t a, uint64_t b)
{
    return (b != 0) ? gcd(b, a % b) : a;
}

int isPrimeNumber(uint64_t n)
{
    if (n == 2 || n == 3 || n == 5)
    {
        return PRIME_NUMBER;
    }

    uint64_t m = n % 10;

    if (m == 1 || m == 3 || m == 7 || m == 9)
    {
        uint64_t x, y;
        uint64_t step = 0, maxStep = sqrt(n) / 2;

        // Start near line x=y.
        x = (n / 2) + 2;
        y = n - x;

        do {

            // Check lattice point visibility...
            if (gcd(x, y) != 1)
            {
                return NOT_PRIME_NUMBER;
            }

            x++; y--; step++;

        } while (step < maxStep);
    }
    else
    {
        return NOT_PRIME_NUMBER;
    }

    return PRIME_NUMBER;
}

int main(int argc, char* argv)
{
    uint64_t n = 1000000007;

    if (isPrimeNumber(n) == PRIME_NUMBER)
    {
        printf("%llu prime.", n);
    }
    else
    {
        printf("%llu not prime.", n);
    }

    return 0;
}


texts: Fetching a weather report on an Arduino from a web service

texts:
I'm writing some code which is basically supposed to http get some information from my own website and parse it, which (finally) works. However, when I compile the code, it shows this:

  Sketch uses 14,466 bytes (44%) of program storage space. Maximum is
  32,256 bytes. Global variables use 1,281 bytes (62%) of dynamic
  memory, leaving 767 bytes for local variables. Maximum is 2,048 bytes.

Considering I'm going to add additional functionality which I'm afraid will use a ton of memory, is there any way that I can get the memory footprint of this code down?

#include <SoftwareSerial.h> // Include software serial library, ESP8266 library dependency
#include <SparkFunESP8266WiFi.h> // Include the ESP8266 AT library
#include <WString.h>

const char WIFI_NAME[] = "********";
const char WIFI_PASS[] = "********";

const String FORECAST_API_KEY = "********";
const String DOMAIN_NAME = "********";

const String LATITUDE = "********";
const String LONGITUDE = "********";

const String httpRequest = "GET /weather.php?apiKey=" + FORECAST_API_KEY + "&lat=" + LATITUDE + "&lon=" + LONGITUDE + "&units=us HTTP/1.1\n"
                           "Host: " + DOMAIN_NAME + "\n"
                           "Connection: close\n\n";

String weather; // CLEAR_DAY, CLEAR_NIGHT, RAIN, SNOW, SLEET, WIND, FOG, CLOUDY, PARTLY_CLOUDY_DAY, PARTLY_CLOUDY_NIGHT
int temp;

void setup() {
  Serial.begin(9600);
  Serial.print(F("Initializing esp8266: "));
  if (esp8266.begin()) // Initialize the ESP8266 and check it's return status
    Serial.println(F("Success")); // Communication and setup successful
  else
    Serial.println(F("Failure"));

  Serial.print(F("Connecting to network: "));
  int retVal = esp8266.connect(WIFI_NAME, WIFI_PASS);
  if (retVal >= 0){
    Serial.println(F("Success"));
  } else {
    Serial.print(F("Failure("));
    Serial.print(retVal);
    Serial.println(')');
  }
  updateWeather();
  Serial.print(F("Temperature: "));
  Serial.println(temp);
  Serial.print(F("Weather: "));
  Serial.println(weather);
}

void loop() {
  // put your main code here, to run repeatedly:

}

void updateWeather(){
  Serial.print("Attempting to connect to weather service: ");
  ESP8266Client client;
  if (client.connect(DOMAIN_NAME, 80) <= 0)
  {
    Serial.println(F("Failure"));
    return;
  }else {
    Serial.println(F("Success"));
  }
  // print and write can be used to send data to a connected
  // client connection.
  client.print(httpRequest);

  // wait for response from server
  while(!client.available()) {
    delay(100);
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\n');
    //Serial.println(line);
    String key = getKey(line);
    if (key.length() > 0) {
      String value = getValue(line);
        if (key=="CURRENT_TEMP") {
         temp = value.toInt();
        } else if (key =="CURRENT_ICON") {
          weather = value;
        }
     }
  }

  // connected() is a boolean return value - 1 if the
  // connection is active, 0 if it's closed.
  if (client.connected())
    client.stop(); // stop() closes a TCP connection.
}
String getKey(String line) {
  int separatorPosition = line.indexOf("=");
  if (separatorPosition == -1) {
    return "";
  }
  return line.substring(0, separatorPosition);
}
String getValue(String line) {
  int separatorPosition = line.indexOf("=");
  if (separatorPosition == -1) {
    return "";
  }
  return line.substring(separatorPosition + 1);
}

I've heard strings are a big memory hog in Arduino code — is this true and is there a way I can mitigate this?


texts:
I created a small program that hides arbitrary files in png images using steganography - it encodes the files in the two least significant bits of every channel, so using a 4-channel png we can encode one byte per pixel.

I also wanted to hide the presence of secret data by encrypting it, and, in effect, making it indistinguishable from random noise to make it impossible to prove there is any data at all hidden in the image without a valid key.

I would like to know if the method I'm using is safe and robust, and if there is anything I should have done better. I'm using a python library called cryptography to do the encryption. It would be also nice to know what attacks (if any) my code could be vulnerable to.

The whole code of my program can be found here.

Here are the functions that do the encryption and decryption. The idea is that the password string you pass to the program is turned into a large key using a key derivation function.

def encrypt(data, password, padding=0):
    """Encrypts data using the password.
    Encrypts the data using the provided password using the cryptography module.
    The password is converted into a base64-encoded key which is then used in a
    symmetric encryption algorithm.
    """

    if padding < 0:
        print "Image too small to encode the file. \
You can store 1 byte per pixel."
        exit()

    password = bytes(password)

    #Use key stretching to generate a secure key
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=bytes(password),
        iterations=100000,
        backend=default_backend())

    key = kdf.derive(bytes(password))

    nonce = os.urandom(16)

    cipher = Cipher(algorithms.AES(key),\
                    modes.CTR(nonce), backend=default_backend())
    enc = cipher.encryptor()
    ct = enc.update(data) + enc.finalize()

    #Add padding if needed
    ct += os.urandom(padding-16)

    #add nonce to data to allow decryption later (nonce does not need to be kept
    #secret and is indistinguishable from random noise)
return bytes(nonce) + ct

def decrypt(data, password):
    """Decrypts data using the password.
    Decrypts the data using the provided password using the cryptography module.
    If the pasword or data is incorrect this will return None.
    """

    password = bytes(password)

    #Salt is equal to password as we want the encryption to be reversible only
    #using the password itself
    kdf = PBKDF2HMAC(algorithm=hashes.AES(),
                     length=32,
                     salt=bytes(password),
                     iterations=100000,
                     backend=default_backend())

    key = base64.urlsafe_b64encode(kdf.derive(password))
    f = Fernet(key)
    token = f.decrypt(data)
return token

I expect that those two functions are where vulnerabilities and/or otherwise faulty code could be. If anyone feels like this is not enough to determine the quality of the code, feel free to read the rest of the program (at the link at the top) and review it as well.

Cheers


texts:
Merge function:

void merge(int outputArray[], int firstArray[], int sizeFirst, int secondArray[], int sizeSecond){
    int p = 0;
    int p1 = 0;
    int p2 = 0;
    while(p1 < sizeFirst && p2 < sizeSecond){
        if(first[p1] < second[p2])
            outputArray[p++] = firstArray[p1++];
        else
            outputArray[p++] = secondArray[p2++];
    }

    while(p1 < sizeFirst) outputArray[p++] = firstArray[p1++];
    while(p2 < sizeSecond) outputArray[p++] = secondArray[p2++];
}

Sort function:

void sort(int numbers[], int size){
    if(size == 1) return;
    int mid = size/2;
    int firstPartSize = mid;
    int secondPartSize = size - mid;

    int firstArray[firstPartSize];
    int secondArray[secondPartSize];

    for(int i = 0 ; i < size ;i++){
        if(i < mid)
            firstArray[i] = numbers[i];
        else
            secondArray[i - mid] = numbers[i];
    }

    sort(firstArray, firstPartSize);
    sort(secondArray, secondPartSize);
    merge(numbers, first, firstPartSize, second, secondPartSize);
}

Personally I think the number of arguments in the merge function are bit too many. I considered making a different function that calculates size of the array but that didn't seem to work with my current knowledge of the language.

Should I care about readability in standard algorithms?
What other names would you suggest instead of p, p1, p2 so that readability is not hampered?
Are there any other bugs or problems with the code?


texts:
I started learning kotlin recently,with some background in java.

So I wrote a merge sort algorithm in kotlin.
I am looking for best practices in kotlin and looking for this code review.

I also wanted to know about its efficiency and ways to increase it.

Thanks

fun merge(list: List<Int>,lo: Int,hi: Int): List<Int>{
    val mid=(lo+hi)/2
    var i=lo
    var j=mid+1
    var new_list=mutableListOf<Int>()
    for(k in 0..(lo-1)) new_list.add(list[k])
    while(!(i==mid+1 && j==hi+1)){
        if(i==mid+1){
            new_list.add(list[j])
            j++
        }
        else if(j==hi+1){
            new_list.add(list[i])
            i++
        }
        else if(list[i]>list[j]){
            new_list.add(list[j])
            j++
        }
        else{
            new_list.add(list[i])
            i++
        }
    }
    for(k in (hi+1)..(list.size-1)) new_list.add(list[k])
    return new_list.toList()
}

fun mergeSort(list: List<Int>,lo: Int,hi: Int): List<Int>{
    if(lo<hi){
        val mid=(lo+hi)/2
        val list1=mergeSort(list,lo,mid)
        val list2=mergeSort(list1,mid+1,hi)
        val list3=merge(list2,lo,hi)
        return list3
    }
    return list
}


texts: Excessive use of lambda with variant of Sieve of Eratosthenes?

texts:
This is a function which produces the sum of primes beneath (not including) a certain number (using a variant on the sieve of Eratosthenes).

erastosum = lambda x: sum([i for i in xrange(2, x) if i == 2 or i == 3 or reduce(lambda y,z: y*z, [i%j for j in xrange(2,int(i ** 0.5) + 1)])])

Excessive use of lambda? Perhaps. Beautification would be nice, but I'm looking for performance optimizations. Sadly, I'm not sure if there is any further way to optimize the setup I've got right now, so any suggestions (on how to, or what else to do) would be nice.


texts: Convert uppercase characters to lowercase and insert a space where each uppercase character used to be

texts:
Prompt:

  You have been given a string s, which is supposed to be a sentence.
  However, someone forgot to put spaces between the different words, and
  for some reason, they capitalized the first letter of every word.
  Return the sentence after making the following amendments:

  Put a single space between the words. Convert the uppercase letters to
  lowercase.

Any suggestions on my code?

String amendTheSentence(String s) {
    StringBuilder modifiedString = new StringBuilder();
    char[] sToArray = s.toCharArray();
    if (Character.isUpperCase(sToArray[0])) {
        modifiedString.append(Character.toLowerCase(sToArray[0]));
    } else {
        modifiedString.append(sToArray[0]);
    }

    for (int i = 1; i < sToArray.length; i++) {
        char currentChar = sToArray[i];

        if (Character.isUpperCase(sToArray[i])) {
           currentChar = Character.toLowerCase(currentChar);
            modifiedString.append(" ");
        }
        modifiedString.append(currentChar);
    }
    return modifiedString.toString();
}


texts: Computed properties vs methods with shape classes

texts:
I'd be interested in hearing what folk think are the pros and cons of the following two ways of writing classes like the following Circle, Square and Rectangle classes in Swift.

The first way has them extending a superclass (ShapeSC) with methods. The second has them implementing a protocol (ShapeP) with computed properties.
Both are tested with identical code, and give identical results.

Note: I've copied the code directly from a playground where it was working, so hopefully you'll find it error-free.

First way: subclasses extend a superclass and override "abstract" methods:

import UIKit
import Darwin

class ShapeSC {
   let π = M_PI
   var area: Double
   var perimeter: Double

   init() {
      area = 0
      perimeter = 0
   }

   func calcArea() -> Double {
      return 0
   }

   func calcPerimeter() -> Double {
      return 0
   }

class Circle: ShapeSC {
   var radius: Double

   init(radius: Double) {
      self.radius = radius
   }

   override func calcArea() -> Double {
      return π * radius * radius
   }

   override func calcPerimeter() -> Double {
      return π * 2 * radius
   }
}

class Square: ShapeSC {
   var side: Double

   init(side: Double) {
      self.side = side
   }

   override func calcArea() -> Double {
      return side * side
   }

   override func calcPerimeter() -> Double {
      return 4 * side
   }
}

class Rectangle: ShapeSC {
   var width: Double
   var height: Double

   init(width: Double, height: Double) {
      self.width = width
      self.height = height
   }

   override func calcArea() -> Double {
      return width * height
   }

   override func calcPerimeter() -> Double {
      return 2 * width + 2 * height
   }

}

let c1 = Circle(radius: 10)
c1.calcArea()
c1.calcPerimeter()

let s1 = Square(side: 10)
s1.calcArea()
s1.calcPerimeter()

let r1 = Rectangle(width: 5, height: 5)
r1.calcArea()
r1.calcPerimeter()

Second way: classes conform to a protocol and use computed properties:

import UIKit
import Darwin

protocol ShapeP {
   var area: Double { get }
   var perimeter: Double { get }
}

class Circle: ShapeP {
   let π = M_PI
   var radius: Double

   init(radius: Double) {
      self.radius = radius
   }

   var area: Double {
      return π * radius * radius
   }

   var perimeter: Double {
      return π * 2 * radius
   }
}

class Square: ShapeP {
   var side: Double

   init(side: Double) {
       self.side = side
   }

   var area: Double {
      return side * side
   }

   var perimeter: Double {
      return 4 * side
   }
}

class Rectangle: ShapeP {
   var height: Double
   var width: Double

   init(height: Double, width: Double) {
      self.height = height
      self.width = width
   }

   var area: Double {
      return width * height
   }

   var perimeter: Double {
      return 2 * width + 2 * height
   }
}

let c1 = Circle(radius: 10)
c1.area
c1.perimeter

let s1 = Square(side: 10)
s1.area
s1.perimeter

let r1 = Rectangle(height: 5, width: 5)
r1.area
r1.perimeter


texts:
This is my first take on fork, exec and waitpid. I didn't quite understand why I had to use a while loop with waitpid. I discovered that waitpid sets errno to EINTR which is translated to this:

#define EINTR        4  /* Interrupted system call */

And I saw a suggestion in comp.unix.programmer archives to use a while loop for waitpid.

My implementation works on OSX 10.10.3 but it doesn't quite satisfy me. Can you provide suggestions?

main.c

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include "common.h"

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

    int exit_status_raw;

    pid_t pid = fork();

    if (pid < 0) {
        printerr("Forking failed");
        return -1;
    }

    if (pid == 0) {
        printf("CHILD says Hello\n");

        execlp("./child", "./child", NULL);

        printerr("exec failed");
        return -1;
    }

    if (pid > 0) {
        printf("PARENT says Hello\n");

        while ((pid = waitpid(pid, &exit_status_raw, 0)) == -1) {
            switch (errno) {
                case EINTR:
                    printerr("waitpid failed with EINTR. Retrying...");
                    continue;
                default:
                    printerr("waitpid failed");
                    break;
            }
        }

        printf("Child exited with %d\n", WEXITSTATUS(exit_status_raw));
    }

    return 0;
}

child.c

#include <stdio.h>
#include "common.h"

int main(int argc, const char * argv[]) {
    printf("This is a time consuming computation\n");
    // ...
    printerr("Sorry. I failed to compute");
    return 127;
}

common.h

#ifndef my_common_h
#define my_common_h

void printerr(const char *message) {
    fprintf(stderr, "%s\n", message);
}

#endif


texts:
I am trying to make an universal implementation of IDisposable (as a base class):

public abstract class DisposableObject : IDisposable
{
    private bool hasUnmanagedResources;
    private bool baseDisposeManagedResourcesCalled;
    private bool baseDisposeUnmanagedResourcesCalled;

    protected bool IsDisposed { get; private set; }
    protected bool IsDisposing { get; private set; }

    public DisposableObject()
        : this(false)
    {
    }

    public DisposableObject(bool hasUnmanagedResources)
    {
        this.hasUnmanagedResources = hasUnmanagedResources;

        if (!hasUnmanagedResources)
        {
            GC.SuppressFinalize(this);
        }
    }

    ~DisposableObject()
    {
        Dispose(false);
    }

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

    protected virtual void DisposeManagedResources()
    {
        if (!IsDisposing)
        {
            throw new InvalidOperationException(
                "In order to dispose an object call the Dispose method. Do not call DisposeManagedResources method directly." +
                    GetTypeString());
        }

        baseDisposeManagedResourcesCalled = true;
    }

    protected virtual void DisposeUnmanagedResources()
    {
        if (!IsDisposing)
        {
            throw new InvalidOperationException(
                "In order to dispose an object call the Dispose method. Do not call DisposeUnmanagedResources method directly." +
                    GetTypeString());
        }

        baseDisposeUnmanagedResourcesCalled = true;
    }

    protected void HasUnmanagedResources()
    {
        if (!hasUnmanagedResources)
        {
            hasUnmanagedResources = true;
            GC.ReRegisterForFinalize(this);
        }
    }

    protected void ThrowIfDisposed()
    {
        if (IsDisposed)
        {
            throw new ObjectDisposedException("Object is already disposed." + GetTypeString());
        }

        if (IsDisposing)
        {
            throw new ObjectDisposedException("Object is being disposed." + GetTypeString());
        }
    }

    private void Dispose(bool disposeManagedResources)
    {
        if (IsDisposed)
        {
            throw new InvalidOperationException("Dispose called on an object that is already disposed." + GetTypeString());
        }

        if (IsDisposing)
        {
            throw new InvalidOperationException("Dispose called on an object that is currently disposing." + GetTypeString());
        }

        IsDisposing = true;

        if (disposeManagedResources)
        {
            DisposeManagedResources();
            VerifyBaseDisposeManagedResourcesCalled();
        }

        if (hasUnmanagedResources)
        {
            DisposeUnmanagedResources();
            VerifyBaseDisposeUnmanagedResourcesCalled();
        }

        IsDisposed = true;
        IsDisposing = false;
    }

    private void VerifyBaseDisposeManagedResourcesCalled()
    {
        if (!baseDisposeManagedResourcesCalled)
        {
            throw new InvalidOperationException("DisposeManagedResources of the base class was not called." + GetTypeString());
        }
    }

    private void VerifyBaseDisposeUnmanagedResourcesCalled()
    {
        if (!baseDisposeUnmanagedResourcesCalled)
        {
            throw new InvalidOperationException("DisposeUnmanagedResources of the base class was not called." + GetTypeString());
        }
    }

    private string GetTypeString()
    {
        string typeName = GetType().FullName;
        return " Type: " + typeName;
    }
}

By default, the object is removed from the finalization queue (in the DisposableObject constructor). If some inheriting class has an unmanaged resource then it should invoke HasUnmanagedResources method to add the object back to the finalization queue.

The most important question is: can I invoke GC.SuppressFinalize(this) in the constructor?.

How do you find this implementation?


texts:
I want to filter the options of a large select group based on text input in a textbox. I am currently using this code to filter from a SELECT group based on the text of a input box.

Can you please tell me whether there is a more efficient way of doing this? My SELECT group is very large with around 7000 entries, which is why I am looking for the most optimized way.

<script>
var fullcelllist = $();
var lastVal ="";

$(window).load(function(){
    $("#celllist option").each(function(){
        fullcelllist.push($(this).val());
    });
});

$("#filtercell").keyup(function() {
    if(lastVal.length < $(this).val().length){
        $("#celllist option:not([value*='"+$(this).val().toUpperCase()+"'])").each(function() {
            $(this).remove();
        });
    }else{
        stregexp = new RegExp($(this).val(),"i");
        temparr = $.grep(fullcelllist, function (value) {
        if(value.match(stregexp)) return value;
            return null;
        });
        newopt = "";
        temparr.sort();
        $.each(temparr,function(i){
            newopt += "<option value='"+temparr[i]+"'>"+temparr[i]+"</option>";
        });
        $("#celllist").html("");
        $("#celllist").append(newopt);
    }
    lastVal = $(this).val();
});
</script>

<input type="text" id="filtercell">
<select id ="celllist" multiple="multiple">
// HERE all OPTIONS using PHP
<select>


texts: Basic functions (sum, len, etc.) with recursively-flattened arguments

texts:
Based on the excellent answers provided for my previous question, I've thoroughly revised my attempt at "deep" versions of all, any, etc. It uses the recommended encapsulated flattening function, and streamlines some unnecessary stuff.

def flatten(*sequence, preserve=False):
    for item in sequence:
        try:
            assert hasattr(item, '__iter__') and not isinstance(item, str)
            if preserve:
                next(iter(item))
        except (AssertionError, StopIteration):
            yield item
        else:
            for i in item:
                yield from flatten(i, preserve=preserve)

def dsum(*args, preserve=False, s=''):
    if any(isinstance(item, str) for item in flatten(args)):
        return s.join(map(str, flatten(args, preserve=preserve)))
    iter_ = flatten(args, preserve=preserve)
    first = next(iter_)
    return sum(iter_, first)

def dlen(*args, preserve=False, s=False):
    return sum(len(arg) if s and isinstance(arg, str) else 1 for arg in flatten(args, preserve=preserve))

The flatten() function is "public" and intended to be accessed from outside the module. It handles an arbitrary number of arguments and generates each non-iterable element (strings are treated as non-iterable). If the keyword argument preserve is set to True, empty iterables are preserved.

I am not aware of any way to use if to test whether a generator/iterable has any items to yield - is there such a way? If not, is my use of assert an acceptable way of turning the if statements into exceptions, or is it better to use if... raise, or something else entirely?

The dsum() function adds together all the items yielded by flatten(). If preserve is True, empty iterables are preserved. If at least one item is a string, everything is converted into a string and joined, connected by the optional s argument. If there are no strings, all items after the first are added onto the first item. If there aren't any strings and there are items that can't be added, the function fails, which I find acceptable.

The dlen() function finds the total length of all the items yielded by flatten(). If preserve is True, empty iterables are preserved and counted as a length of 1. Strings are counted as objects of length 1 unless the optional keyword argument s is True, in which case their actual lengths (number of characters) are counted.

I have removed dany(), dall(), etc. because they were just wrappers around flatten() with zero additional logic.

Test suite (passes):

from deep import *
import datetime as dt

assert dsum([1,2], 3, '1','2','3','456', []) == '123123456'
assert dsum([1,2], 3, '1','2','3','456', [], preserve=True) == '123123456[]'
assert dsum('a', 'b') == 'ab'
assert dsum(1, [2,[3,[4,[5],[]]]]) == 15
# dsum(1, [2,[3,[4,[5],[]]]], preserve=True) # can't sum int with preserved list
assert all(flatten(1, 1, [1, []]))
assert not all(flatten(1, 1, [1, []], preserve=True))
assert all(flatten(1, 1, set()))
assert not all(flatten(1, 1, set(), preserve=True))
assert list(flatten((1, 1, []))) == [1,1]
assert list(flatten((1, 1, []), preserve=True)) == [1,1,[]]
assert dsum(dt.timedelta(3), dt.timedelta(4), s=dt.timedelta()) == dt.timedelta(7)


texts: How should I refactor my image uploader script?

texts:
I come from a C background and need help refactoring the following imgur image uploader script I wrote.

It checks if a token_file with access_token and refresh_token exists. If not, it instructs the user to go to a webpage, allow access to my app and enter the PIN generated from the site back to my program so that I can exchange it with access and refresh tokens.

I upload the picture taken with the 'scrot' utility to the users album, put the direct link on clipboard, and show a system notification. I'm not using the libnotify gem because it segfaults.

If the upload failed because the access_token is expired, which lasts only 60 minutes, I use the refresh token I got from the first authorization step, get a new one and update the token_file as well.

I know I should be using a class to keep things more organized.

I just don't know what's the best way to deal with info like client_id and token_file. Should they be instance or class methods? Also what should I put in the initialize method, the reading of tokens from the file or launch scrot?

I know I don't error check for everything yet.

#!/usr/bin/env ruby

require 'httparty'
require 'json'
require 'clipboard'

$client_id     = 'xxxxxxxxxxx'
$client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$token_file    = '.imgur_token'

def auth_app

  puts 'Follow the link to allow the application access to your account and enter the pin',
  "https://api.imgur.com/oauth2/authorize?client_id=#{$client_id}&response_type=pin"

  print 'Pin: '
  pin = STDIN.gets.chomp

  response = HTTParty.post 'https://api.imgur.com/oauth2/token',
    :body => { 'client_id'     => $client_id,
               'client_secret' => $client_secret,
               'grant_type'    => 'pin',
               'pin'           => pin }

  if response['access_token'] == nil
    puts 'Authorization failed'
  else
    tokens = { 'access_token'  => response['access_token'],
               'refresh_token' => response['refresh_token'] }
    File.write($token_file, tokens.to_json)
  end
  tokens
end

def refresh_token(refresh_token)

  response = HTTParty.post 'https://api.imgur.com/oauth2/token',
    :body => { 'refresh_token' => refresh_token,
               'client_id'     => $client_id,
               'client_secret' => $client_secret,
               'grant_type'    => 'refresh_token' }

  response['access_token']
end

def upload_image(access_token)

  response = HTTParty.post 'https://api.imgur.com/3/upload.json',
    :headers => { 'Authorization' => "Bearer #{access_token}" },
    :body    => { 'image' => Base64.encode64(File.read('imgur.png')) }

  response['data']['link']
end

abort('scrot not found') unless system('scrot -s imgur.png')
tokens = File.exists?($token_file) ? JSON.parse(File.read($token_file)) : auth_app

if (link = upload_image(tokens['access_token'])) == nil
  tokens['access_token'] = refresh_token(tokens['refresh_token'])
  link = upload_image(tokens['access_token'])
  File.write($token_file, tokens.to_json)
end

if link != nil
  Clipboard.copy link
  system('notify-send Upload complete')
else
  system('notify-send Upload error')
end

File.delete('imgur.png')


texts: Cartesian product in racket (Is append-map okay?)

texts:
I've read several places that say it's really bad to use append, and I understand why. I read somewhere that it was never even correct to use append. However, I was working on a textbook exercise in Essentials of Programming Languages (Ex 1.21 pg27) that asked me to write a Cartesian product function. I couldn't think of any other easy way than using append-map. Below is my working solution to the exercise. Is there a better more idiomatic way of writing this? Thanks!

; product : Listof(SchemeVal) -> Listof(SchemeVal) -> Listof(List(SchemeVal))
; usage: (product '(a b c) '(x y)) -> '((a x) (a y) (b x) (b y) (c x) (c y))
(define (product lox loy)
  (append-map (lambda (x) (scalar x loy)) lox))
(define (scalar x loy)
  (map (lambda (y) (list x y)) loy))