texts: Template function specialization with code duplication

texts:
I'm working on a libcurl binding for NodeJS, and to get info from a curl handler, using curl_easy_getinfo, I've created a template function, the issue, is that the result of the call can be a null pointer.

To make sure this was correctly addressed, I've created a template specialization that handle the edge case:

template<typename ResultType, typename v8MappingType>
v8::Handle<v8::Value> Curl::GetInfoTmpl( const Curl &obj, int infoId )
{
    v8::HandleScope scope;

    ResultType result;

    CURLINFO info = (CURLINFO) infoId;
    CURLcode code = curl_easy_getinfo( obj.curl, info, &result );

    if ( code != CURLE_OK )
        return Curl::Raise( "curl_easy_getinfo failed!", curl_easy_strerror( code ) );

    return scope.Close( v8MappingType::New( result ) );
}

//The null pointer is only possible when the value returned is a c string
template<> //workaround for null pointer, aka, hack.
v8::Handle<v8::Value> Curl::GetInfoTmpl<char*,v8::String>( const Curl &obj, int infoId )
{
    //duplicated code
    v8::HandleScope scope;

    char *result;

    CURLINFO info = (CURLINFO) infoId;
    CURLcode code = curl_easy_getinfo( obj.curl, info, &result );

    if ( !result ) { //null pointer
        return v8::String::New( "" );
    }

    if ( code != CURLE_OK )
        return Curl::Raise( "curl_easy_getinfo failed!", curl_easy_strerror( code ) );

    return scope.Close( v8::String::New( result ) );
}

Is this the correct way to handle that, or are there better ways to do so?

The full code is on GitHub.


texts:
I am writing a function to calculate the total size of a "player appearance".

There are various "item slots" the player has, and if they are empty then 1 byte will be sent, otherwise there will be 2.

const getAppearanceBlockSize = (appearance: PlayerAppearance) => {
    const headObscured = isCoveringHead(appearance.outfit.head);

    return (
        40
        + (appearance.outfit.head ? 2 : 1)
        + (appearance.outfit.cape ? 2 : 1)
        + (appearance.outfit.amulet ? 2 : 1)
        + (appearance.outfit.weapon ? 2 : 1)
        + (appearance.outfit.shield ? 2 : 1)
        + (appearance.outfit.head ? 2 : 1)
        + (headObscured ? 2 : 4)
    );
};

The code seems fairly clear to me, but Code Climate has given it a high "cognitive complexity" score - indicating that the code is complex and should be broken up.

I can't think of any ways to break the code up, however, that wouldn't result in it being more complex than it currently is.


texts:
Problem statement is as follows

  Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.

  For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.

This is supposed to be an easy challenge but it was not the case for me.

Here is my solution in JavaScript

// Given an array of time intervals (start, end) for classroom lectures (possibly overlapping),
// find the minimum number of rooms required.
// For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
exports.roomsRequired = function roomsRequired(lectureIntervals) {
    function Room() {return {busy: []};}

    let rooms = [];
    lectureIntervals.forEach(lectureInterval => {
        let roomFound = false;
        rooms.forEach(room => {
            let roomBusyInLectureHours = false;
            room.busy.forEach(reserved => {
                if (lectureInterval[0] > reserved[0] && lectureInterval[0] < reserved[1]) roomBusyInLectureHours = true;
                if (lectureInterval[1] > reserved[0] && lectureInterval[1] < reserved[1]) roomBusyInLectureHours = true;
                if (reserved[0] > lectureInterval[0] && reserved[0] < lectureInterval[1]) roomBusyInLectureHours = true;
                if (reserved[1] > lectureInterval[0] && reserved[1] < lectureInterval[1]) roomBusyInLectureHours = true;
            });
            if (!roomBusyInLectureHours) {
                room.busy.push(lectureInterval);
                roomFound = true;
            }
        });
        if (!roomFound) {
            let room = new Room();
            room.busy.push(lectureInterval);
            rooms.push(room);
        }
    });
    return rooms;
};

The only test case I have so far

let rooms = exports.roomsRequired([[30, 75], [0, 50], [60, 150]]);
for (let i = 0; i < rooms.length; i++) {
    console.log(rooms[i].busy)
}

Which prints

[ [ 30, 75 ] ]
[ [ 0, 50 ], [ 60, 150 ] ]

I am aware that I am not returning the number of rooms, but that is essentially the number of rows seen, so for example in the case above it is 2 as expected.

My question is, can this code be much shorter? I suspect I am missing something obvious being this challenge easy.

Pseudo code of my implementation would be something like this

For Each Interval:
    For Each Room in Rooms:
        For Each IntervalWithinThatRoom:
            Check If IntervalWithinThatRoom overlaps with Interval
        If No Overlaps Found
            Push Interval to Room
    If Interval Not pushed to any Room
        Create new Room
        Push Interval to Room
        Push new Room to Rooms

Edit - Unit Tests I have

expect(roomsRequired.roomsRequired([[30, 75], [0, 50], [60, 150]]).length).eq(2);
expect(roomsRequired.roomsRequired([[5, 7], [0, 9], [5, 9]]).length).eq(3);


texts:
I'm brand new at Python, but I've been working in general at granulating my functions and being as self-readable as possible without suffering readability. This CodingBat question is a little interesting because it demands a function with a lot of repetitive case checks. I decided, rather than having a bunch of nested ifs, it might be better to break them out into separate functions, but I'm not sure if this actually goes -against- my goal of better readability. However, I decided to break out is_weekday because the number encoding wasn't immediately clear. I also wasn't sure if it'd be better to have alarm_time(is_weekday(day), '10:00', 'off') or do alarm_time(day, '10:00', 'off') and have alarm_time handle the is_weekday(day) check. I decided the first way because it seemed there was a separation of concern issue otherwise, but I'm not sure.

I was at first hesitant to ask because this might be gray-space into asking a general opinion, but I'm specifically asking in terms of this exercise to use in similar situations.

  Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".

def is_weekday(day):
    return 1 <= day <= 5

def alarm_time(is_weekday, weekday_time, weekend_time):
  if is_weekday:
    return weekday_time
  return weekend_time

def alarm_clock(day, vacation):
  if vacation:
    return alarm_time(is_weekday(day), '10:00', 'off')
  return alarm_time(is_weekday(day), '7:00', '10:00')

def test_fun(fun):
    cases = [[1, False, '7:00'], [5, False, '7:00'], [0, False, '10:00'], [6, False, '10:00'], [0, True, 'off'], [6, True, 'off'], [1, True, '10:00'], [3, True, '10:00'], [5, True, '10:00']]

    print('{:^30}     {:^11}'.format('Expected', 'Run'))
    for case in cases:
        funstr   = '{}({}, {})'.format(fun.__name__, case[0], case[1])
        result   = fun(case[0], case[1])
        expected = case[-1]
        success  = result == expected

        print('{:21} -> {:5} ==> {:5}  {}'.format(funstr, expected, result, success))

The test cases were positive:

>>> test_fun(alarm_clock)
           Expected                    Run
alarm_clock(1, False) -> 7:00  ==> 7:00   True
alarm_clock(5, False) -> 7:00  ==> 7:00   True
alarm_clock(0, False) -> 10:00 ==> 10:00  True
alarm_clock(6, False) -> 10:00 ==> 10:00  True
alarm_clock(0, True)  -> off   ==> off    True
alarm_clock(6, True)  -> off   ==> off    True
alarm_clock(1, True)  -> 10:00 ==> 10:00  True
alarm_clock(3, True)  -> 10:00 ==> 10:00  True
alarm_clock(5, True)  -> 10:00 ==> 10:00  True


texts:
My code is a module to simplify accessing a weather API. I'm quite certain it could be simplified, just not sure how yet. Some advice would very much be appreciated. Possibly use individual classes for day, astro, condition etc? I am not quite sure, some advice would be nice.

import requests

class Day:
    """Used for finding information on a weekday."""
    def __init__(self, data):
        self.data = data
        self.date = data['date']
        day = data['day']
        astro = data['astro']
        condition = day['condition']
        self.maxtemp_c = day['maxtemp_c']
        self.maxtemp_f = day['maxtemp_f']
        self.mintemp_c = day['mintemp_c']
        self.mintemp_f = day['mintemp_f']
        self.avgtemp_c = day['avgtemp_c']
        self.avgtemp_f = day['avgtemp_f']
        self.maxwind_mph = day['maxwind_kph']
        self.totalprecip_mm = day['totalprecip_mm']
        self.totalprecip_in = day['totalprecip_in']
        self.avgvis_km = day['avgvis_km']
        self.avgvis_miles = day['avgvis_miles']
        self.avghumidity = day['avghumidity']
        self.condition_text = condition['text']
        self.condition_icon = condition['icon']
        self.sunrise = astro['sunrise']
        self.sunset = astro['sunset']
        self.moonrise = astro['moonrise']
        self.moonset = astro['moonset']

class CurrentDay:
    """Used for finding information on a current day."""
    def __init__(self, day):
        location = day['location']
        current = day['current']
        condition = current['condition']
        self.location_name = location['name']
        self.location_region = location['region']
        self.location_country = location['country']
        self.location_coords = (location['lat'], location['lon'])
        self.tz_id = location['tz_id']
        self.localtime_epoch = location['localtime_epoch']
        self.localtime = location['localtime']
        self.last_updated_epoch = current['last_updated_epoch']
        self.last_updated = current['last_updated']
        self.temp_c = current['temp_c']
        self.temp_f = current['temp_f']
        self.is_day = current['is_day']
        self.wind_mph = current['wind_mph']
        self.wind_kph = current['wind_kph']
        self.wind_degree = current['wind_degree']
        self.wind_dir = current['wind_dir']
        self.pressure_mb = current['pressure_mb']
        self.pressure_in = current['pressure_in']
        self.precip_mm = current['precip_mm']
        self.precip_in = current['precip_in']
        self.humidity = current['humidity']
        self.cloud = current['cloud']
        self.feelslike_c = current['feelslike_c']
        self.feelslike_f = current['feelslike_f']
        self.vis_km = current['vis_km']
        self.vis_miles = current['vis_miles']
        self.condition_text = condition['text']
        self.condition_icon = condition['icon']

class Weather:
    """Handler"""
    def __init__(self, location, key):
        self.location = location
        self.key = key
        status = requests.get("http://api.apixu.com/v1/current.json?key={0}&q={1}".format(key, location)).status_code
        if status != 200:
            raise ConnectionError("There was an issue connecting to the weather API!")

    def getForcecast(self, days):
        data = {}
        forecast = requests.get("http://api.apixu.com/v1/forecast.json?key={2}&q={0}&days={1}".format(self.location, days, self.key)).json()

        week = forecast['forecast']['forecastday']
        for day in week:
            date = day['date']
            data[date] = Day(day)
        return data
    def getCurrent(self):
        day = requests.get("http://api.apixu.com/v1/current.json?key={1}&q={0}".format(self.location, self.key)).json()
        return CurrentDay(day)


texts: Extend OnClickListener and animate view in android

texts:
I'm working on animation and I want to organize my code in best way I'm new in android and not know too much about this. Here is my code that I'm using to animate views

TestClick

   public class TestClick implements OnClickListener {

Context context;
ImageView iv1,iv2,iv3;
public static boolean bActive = false;

public TestClick(Context ctx, ImageView imageView1, ImageView imageView2, ImageView imageView3){
    context = ctx;
    iv1 = imageView1;
    iv2 = imageView2;
    iv3 = imageView3;
}

@Override
public void onClick(View v) {
    if(bActive) {
        active();
    }else{
        Animation animPictureDeactiveLeft = AnimationUtils.loadAnimation(context, R.anim.deactivate_picturebtn_onleft);
        Animation animVideoMiniLeft = AnimationUtils.loadAnimation(context, R.anim.activate_videobtn_onleft);
        Animation animGifMiniLeft = AnimationUtils.loadAnimation(context, R.anim.move_gifbtn_onleft);

        iv1.startAnimation(animPictureDeactiveLeft);
        iv2.startAnimation(animVideoMiniLeft);
        iv3.startAnimation(animGifMiniLeft);
        bActive = true;
    }
}

public void active(){

}

 }

MainActivity

  button1.setOnClickListener(new TestClick(MainActivity.this, view1, view2, view3){
        public void active(){
            // do some work
        }
    });
   button2.setOnClickListener(new TestClick(MainActivity.this, view1, view2, view3){
        public void active(){
            // do some work
        }
    });

This code is working fine there is no problem in this.
What I need Actually I need to manage my all animation in separate file. I don't want to write whole code in MainActivity it's not look good.

As you can see in my code I'm passing views in constructor is it a good way passing two many views in constructor ?
Animations load in onClick override method everytime when onClick called animation load again Right ?
As you can see button2 also need same animation I want when button1 is clicked it load animations but when button2 click don't load again animation just use the previous loaded animation is it possible if yes how ?
Is there any heap memory problem by passing views in such manner.

I'm asking these questions because I'm new to Android. If there is another method to achieve this please let me know.
I want efficient code.


texts:
I'm learning C with K&R 2nd Ed. I've just completed the exercise 1-20 and I would know if my code is correct (i.e. answering the question) and if my style is not too bad. Or just some feebacks to improve myself!

  K&R Exercise 1-20 p.34

  Write a program detab that replaces tabs in the input with the proper number  * of blanks to space to the next tab stop.  Assume a fixed set of tab stops, say every n
  columns.  Should n be a variable or a symbolic parameter?

More info here

I put '-' because it's more readable than ' '. But you can totally change it.

#include <stdio.h>
#define COLUMN 8

int main()
{
    int c, i, nc;
    nc = 0;

    while ((c = getchar()) != EOF)
    {
        if (c != '\t' && c != '\n')
            nc = (nc + 1) % COLUMN;

        if (c == '\n')
            nc = 0;

        if (c == '\t') {
            for (i=1; i<=(COLUMN - nc); ++i) {
                putchar('-');
            }
            nc = 0;
        }
        else
            putchar(c);
    }

return(0);
}


texts: Find minimal modulo-sum of pairs from two lists

texts:
Recently I appeared for an job challenge organised on HackerEarth.
Question:
There are two teams T1 and T2. Power of each player is represented in array. The rules of game are as follow.
There are only N fights.

No player from any team can fight twice.
At any instance, only one fight can occur.
For each fight score is calculated as (P1+P2)%N where P1, P2 is the power of player from T1 and T2 respectively and % is modulo operator.

Task in Hand is to arrange T2 players in such a way so that score is minimum. We have to print the score of the match after every fight. T2 is aware of the sequence of T1 players.
Input format is first line contains T denoting the number of test cases. It also denotes the number of times we have to run our function.
Second line contains N i.e. the number of fights
Third line contains the power of players from Team T1. The sequence in which T1 player power is shown is the sequence in which T1 players would fight.
Fourth line contains the power of players from Team T2.
Constraints:

1<=T<=10^5
1<=N<=10^5
0<=T1[i],T2[i]<= N for all i's.

I wrote the following code:
def solve (N, T1, T2):
    # Write your code here
    final_list=''
    for each in T1:
        temp_list=[]
        flag=True
        for i in range(0,len(T2)):
            if (each + T2[i])%N==0:
                T2.pop(i)
                final_list+='0'
                flag=False
                break
            else:
                temp_list.append((each + T2[i])%N)
        if flag:
            j=temp_list.index(min(temp_list))
            final_list+=str(min(temp_list))
            T2.pop(j)

    return final_list

T = int(input())
for _ in range(T):
    N = int(input())
    T1 = list(map(int, input().split()))
    T2 = list(map(int, input().split()))

    out_ = solve(N, T1, T2)
    print (' '.join(map(str, out_)))

It took 0.1 seconds for few test cases and more than 10.2 seconds for few test cases(so basically the test case failed for taking too much time).
Looking for optimal code


texts: Crawling through a YouTube channel via the YouTube API

texts:
This code uses the YouTube API for crawling through a YouTube channel, parsing responses and syncing the channel videos with a local directory.

Can this be optimised or improved?

import subprocess
import os
import urllib.request as urlreq
import urllib.parse as urlparse
import simplejson as json

playlistIds = []
titles = []

def getPlaylistId():
    data = {}
    data['maxResults'] = '50'
    data['channelId'] = 'UCtESv1e7ntJaLJYKIO1FoYw' # Put the channelId of channel you want to Sync to.
    data['part'] = 'snippet'
    data['key'] =   'AIzaSyAngcF6oKnyEbhk3KyL9Wz1OhSi28JjbzE'
    requestValues = urlparse.urlencode(data)
    request = "https://www.googleapis.com/youtube/v3/playlists?" + requestValues
    string = urlreq.urlopen(request).read().decode('utf-8')
    items = json.loads(string)['items']

    for item in items:
        playlistIds.append(item['id'])
        titles.append(item['snippet']['title'])

def download():
    for ids,title in zip(playlistIds,titles):
            url = "https://www.youtube.com/playlist?list=" + ids
            if not os.path.exists(title):
                os.makedirs(title)
            os.chdir("./" + title)
            url_down = "youtube-dl -o '%(title)s' " + url
            subprocess.call(url_down, shell=True)
            os.chdir("..")

getPlaylistId()
download()


texts: Finding line numbers of duplicate lines in a log file

texts:
I have a log file with a million lines, and my task is to code something that outputs the lines that have duplicates, and the line numbers.

I've thought of two ways to approach this :

1) Use python's inner tools :

load my file's lines in a list,
load them in a dict in which the keys are the lines, and the values are the number of times they appear
for each element of my dict where value >= 2, output the element and the indexes of this element in my list

Here's my code :

def find_dupl(log):
    # put in list
    with open(log) as l:
        liste = l.readlines()

    # put in dict
    dico = dict()
    for i in liste:
        dico[i] = dico.get(i, 0) + 1

    output_dict = {}
    for i in dico:
        if dico[i] > 1: # for dico's element where value >= 2
#            print(i,        # print the element
#                dico[i],    # how many times it appears
#                [a+1 for a, b in enumerate(liste) if b == i] # the lines where it appears
#                )
            output_dict[i] = [a+1 for a, b in enumerate(liste) if b == i]
    return(output_dict)

2) Go bruteforce, which is something like this :

load my file's lines in a list
for each element i of the list
check all the elements j after i
if i == j, output i, i's index and j's index

Option 1's code works fine and is fast (like 1 second on my (pretty average) computer), so my job is done and I haven't written the code for option 2. But I'm being curious on which one would be faster : I can see that option 2 is something like O(n^2) (or am I mistaken ?), but as I don't know the inner workings of lists and dicts (I didn't major in CS), I'm not really able to tell the O() of option 1.

I'm also curious about if there would be an even faster way (without modules) ?


texts: Telling me what lesson I have tomorrow and emailing me the results

texts:
This program tells me what lessons I have tomorrow then emails them to me.

This program works fine, but I was wondering whether there is a way to simplify the script or make it more efficient. I have removed my email and password and who it is to for privacy, but it does work.

import smtplib
import time
import datetime
from datetime import date

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
English = ["MondayA", "WednesdayA", "ThursdayA", "FridayA", "TuesdayB", "WednesdayB", "ThursdayB"]
Maths = ["MondayA", "TuesdayA", "WednesdayA", "ThursdayA", "FridayA", "TuesdayA", "FridayB"]
Bioligy = []    #I will fill the following three
Physics = []
Chemistry = []
Computing = ["TuesdayA", "WednesdayA", "ThursdayA", "WednesdayB", "ThursdayB"]
History = ["MondayA", "TuesdayA", "MondayB", "TuesdayB", "WednesdayB"]
PE = ["ThursdayA", "WednesdayB", "FridayB"]
BaV = ["TuesdayA", "FridayB"]
French = ["MondayA", "FridayA", "MondayB", "TuesdayB", "FridayB"]
Course42 = ["MondayB"]
lesson = []
Comma = (", ")

day1 = (datetime.datetime.today().weekday())
day = (days[day1 + 1])

def WeekA(a):
    Oday = (a + "A")

    if Oday in English:
        lesson.append("English")

    if Oday in Maths:
        lesson.append("Maths")

    if Oday in Bioligy:
        lesson.append("Bioligy")

    if Oday in Physics:
        lesson.append("Physics")

    if Oday in Chemistry:
        lesson.append("Chemistry")

    if Oday in Computing:
        lesson.append("Computing")

    if Oday in History:
        lesson.append("History")

    if Oday in PE:
        lesson.append("PE")

    if Oday in BaV:
        lesson.append("B&V")

    if Oday in French:
        lesson.append("French")

    if Oday in Course42:
        lesson.append("Course42")

def WeekB(b):
    Oday = (b + "B")

    if Oday in English:
        lesson.append("English")

    if Oday in Maths:
        lesson.append("Maths")

    if Oday in Bioligy:
        lesson.append("Bioligy")

    if Oday in Physics:
        lesson.append("Physics")

    if Oday in Chemistry:
        lesson.append("Chemistry")

    if Oday in Computing:
        lesson.append("Computing")

    if Oday in History:
        lesson.append("History")

    if Oday in PE:
        lesson.append("PE")

    if Oday in BaV:
        lesson.append("B&V")

    if Oday in French:
        lesson.append("French")

    if Oday in Course42:
        lesson.append("Course42")

WeekA(day)

content = ("You have " + Comma.join(lesson) + ".")

mail = smtplib.SMTP('smtp.gmail.com',587)

mail.ehlo()

mail.starttls()

mail.login('*email*','*password*')

mail.sendmail('*email*','*email*', content)

mail.close()


texts:
I created this method that adds a new situation to the situation list. The situation has a many-to-one relation with project.task. This method seems a little longer than it should be and I don't know how to optimize it:

@api.multi
def create_situation(self):
    active_id = self.env.context.get('active_ids', []) or []
    proj_obj = self.env['project.task'].browse(active_id)
    situation_orders = self.env['project.task.situation'].browse([])
    task_lines = self.env['task.situation.line'].browse([])
    situation_ids = self.env['project.task.situation'].search([('task_id', '=', proj_obj.id)], order='id desc', limit=1)
    size_list_situation_ids = len(situation_ids)
    last_id = situation_ids and max(situation_ids)
    s_sequence = "Situation N° " + str(proj_obj.sequence)

    for record in proj_obj:
        task_lines = [(0, 0, {'ref': line.ref,
                                      'product_id': line.product_id.id,
                                      'quantity': line.quantity,
                                      'um_id': line.um_id,
                                      'price_unit': line.price_unit,
                                      'price_subtotal': line.price_subtotal,
                                      'progress': line.progress,
                                      'cumulative_amount_ht': line.cumulative_amount_ht,
                                      'previous_amount_ht':line1.cumulative_amount_ht if size_list_situation_ids != 0 else 0,
                                      'amount_net_ht': line.cumulative_amount_ht if size_list_situation_ids == 0 else (line.cumulative_amount_ht - line1.cumulative_amount_ht)}) for line, line1 in izip_longest(record.task_line_ids, last_id.task_line)]
    situation_order = {'partner_id': proj_obj.project_id.partner_id.id,
                        'task_id':proj_obj.id,
                        'task_line':task_lines,
                        'user_id': proj_obj.user_id.id,
                        'name':s_sequence,
                        'tyoe': 'situation' if self._context.get('type', 'situation') else 'final_count',
                        'project_id':proj_obj.project_id.id,
                        'due_date': self.date_id.id}
    situation_orders+=situation_orders.with_context(self._context).create(situation_order)
    proj_obj.write({'sequence':proj_obj.sequence+1})


texts: Is this good practice with unit-testing?

texts:
I've created unit test for the "student" CRUD operations that looks like this:

[Test]
    public void Can_Exec_CrudOps()
    {
        #region Prepare

        var account = Processor.Execute(new CreateAccount
        {
            Email = "email@example.com",
            Username = "username",
            Password = "password",
        }).Result;

        #endregion

        var student = Processor.Execute(new CreateStudent
        {
            AccountId = account.EntityID
        }).Result;

        Assert.NotNull(student);
        student.AreEqual(Processor.Execute(new GetStudent
        {
            EntityId = student.EntityID
        }).Result);
        student.AreEqual(Processor.Execute(new GetStudentByAccount
        {
            AccountId = account.EntityID
        }).Result);

        var upd_student = Processor.Execute(new UpdateStudent
        {
            EntityId = student.EntityID,
            Flags = StudentFlags.Active
        }).Result;

        Assert.NotNull(upd_student);
        upd_student.AreEqual(student);
        upd_student.Flags.AreEqual(StudentFlags.Active);

        Processor.Execute(new DeleteStudent
        {
            EntityId = student.EntityID
        });
    }

As you can see, the region #prepare contains code that will insert required data to the database for the current test to be possible.

Is it good practice to create a single test for each CRUD operation and then call that test inside the tests that require them?

What I'm thinking about would look like this:

 [TestFixture]
public class StudentTest : OperationTest
{
    protected override IEnumerable<Type> ModelMappings
    {
        get
        {
            return NHMappings.EDUCATION;
        }
    }

    [Test]
    public void Can_Exec_CrudOps()
    {
        #region Prepare
        // here is what changed //
        var acc = new AccountTests();
        var acc_id=    acc.create_account();

        #endregion

        var student = Processor.Execute(new CreateStudent
        {
                        //here too//
            AccountId = acc_id
        }).Result;

        Assert.NotNull(student);
        student.AreEqual(Processor.Execute(new GetStudent
        {
            EntityId = student.EntityID
        }).Result);
        student.AreEqual(Processor.Execute(new GetStudentByAccount
        {
                        // and here//
            AccountId = acc_id
        }).Result);

        var upd_student = Processor.Execute(new UpdateStudent
        {
            EntityId = student.EntityID,
            Flags = StudentFlags.Active
        }).Result;

        Assert.NotNull(upd_student);
        upd_student.AreEqual(student);
        upd_student.Flags.AreEqual(StudentFlags.Active);

        Processor.Execute(new DeleteStudent
        {
            EntityId = student.EntityID
        });
        // and here //
        acc.deleteaccount(acc_id);
    }
}

So the point is not to write the same code over and over again.


texts: Python - use a list of names to find exact match in pandas column containing emails

texts:
I have an Excel file containing a free-form text column (that sometimes is structured like an email), where I need to find all first and last names and add an extra columns saying TRUE/FALSE to these fields. I do not need to extract matched data (i.e. note it down in an adjacent column), although that could be an advantage.
NB: I do not know the names that I need to find, so it is pure guesswork. I have a list of registered first names with 40k+ entries, as well as a list of most common last names with another 16k+ entries.
So far, I managed to filter out roughly 10000 rows out out ~20000 row file, although my solution contains a lot of false positives. e.g. some rows marked TRUE for first names, contain text like "Det er OK.", where Python (I assume) merges the entire text together and extracts any matching substing to a name from a list, in this case I guess that could be "t er O" or "r OK", since my list has names "Tero" and "Rok" (although the case does not match and it combines letters from 2/3 separate words, which is not what I want)... Weirdly enough, this is NOT TRUE for the same text written in lowercase and without "." at the end, i.e. "det er ok", which is marked as FALSE! P.S. there are unfortunatelly few names in the emails that are written in lowercase letters and not sentence case as it should be...
Sample email (with names Thomas, Lars, Ole, Per):

Hej Thomas,
De 24 timer var en af mange sager som vi havde med til møde med Lars og Ole. De har godkendt den under dette møde.
Mvh. Per

My code:
# Import datasets and create lists/variables
import pandas as pd
from pandas import ExcelWriter

namesdf = pd.read_excel('names.xlsx', sheet_name='Alle Navne')
names = list(namesdf['Names'])

lastnamesdf = pd.read_excel('names.xlsx', sheet_name='Frie Efternavne')
lastnames = list(lastnamesdf['Frie Efternavne'])

# Import dataset and drop NULLS
df = pd.read_excel(r'Entreprise Beskeder.xlsx', sheet_name='dataark')
df["Besked"].dropna(inplace = True)

# Compare dataset to the created lists to match first and last names
df["Navner"] = df["Besked"].str.contains("|".join(names)) # Creates new column and adds TRUE/FALSE for first names
df["Efternavner"] = df["Besked"].str.contains("|".join(lastnames)) # Creates new column and adds TRUE/FALSE for last names

# Save the result
writer = ExcelWriter('PythonExport.xlsx')
df.to_excel(writer)
writer.save()

I would appreciate any suggestions that could potentially improve my code and reduce manual work that it will take to filter out all of these false positive cells that I found! I think the best case scenario would be a case sensitive piece of code that finds only the specific name without merging the text together. Also, it would be great if I could extract a specific string that Python finds a match in, as that would reduce manual work when trying to figure out why exactly a specific block of text was marked as TRUE. All in all, every suggestion is welcome! Thanks :)


texts:
The problem is stated in Encrypt this!:

Your message is a string containing space separated words. You need to
encrypt each word in the message using the following rules:

The first letter needs to be converted to its ASCII code.

The second letter needs to be switched with the last letter

Keepin' it simple: There are no special characters in input.

Kata.encryptThis("Hello") => "72olle"
Kata.encryptThis("good")` => "103doo"
Kata.encryptThis("hello world") => "104olle 119drlo"

class NewEnpc{
    public static String encryptThis(String text) {
        StringBuilder sb=new StringBuilder();
        String[] arry=text.split(" ");
        if(text!=""){
            for(int j=0;j<arry.length;j++){
                char[] sd=arry[j].toCharArray();
                int number=(int)sd[0];
                if(sd.length>1){
                    for(int k=0;k<sd.length;k++){
                        if(k==0){
                            sb.append(number);
                        }
                        else if(k==1){
                            int len=sd.length-1;
                            char c=sd[len];
                            sb.append(c);
                        }
                        else if(k==sd.length-1){
                            char c=sd[1];
                            sb.append(c);
                        }
                        else{
                            char c=sd[k];
                            sb.append(c);
                        }
                    }
                }
                else{
                    sb.append(number);
                }
                sb.append(" ");
            }
        }
        return sb.toString().trim();
    }
}

public class EncryPt {
    public static void main(String[]args){
        System.out.println("Hello");

      System.out.println(NewEnpc.encryptThis("A
        wise old owl lived in an oak"));
    }
}

Can someone help me improve my coding standards. I have solved the problem.


texts:
Yesterday I saw a CodeTrain video in where Daniel Shiffman tried to approximate Pi using the Leibniz series. It was interesting so I decided to try it too.

I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cycle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.

It starts by first running two background threads which execute two functions that do all the job: piLoop(), for calculating the series; and displayLoop(), for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCycles reaches the maximum value a long long int can get OR the End key is pressed.

The final program runs, by glancing at it (that means a very unreliable measurement), at an approximated rate of 30 million cycles per second in my computer. That means it can calculate the 10th digit of PI (around 87 billion cycles) in about an hour.

I want to know if there are some optimizations that can be made so the program can run at all his power.

main.cpp

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <windows.h>
#include <limits>

void piLoop();
void displayLoop();
void getShouldStop();

namespace {
    typedef std::numeric_limits<long double> ldbl;
    typedef std::numeric_limits<long long int> ullint;

    const char displayDigits = ldbl::max_digits10;
    const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing.
    const long long int maxCicles = ullint::max();

    bool shouldStop = false;
    long double PI = 0;
    unsigned long long int piCicles = 0;
    std::mutex piLock;
}

int main()
{
    std::thread piCalculatorThread( piLoop );
    std::thread displayUpdaterThread( displayLoop );
    piCalculatorThread.join();
    displayUpdaterThread.join();

    std::cin.get();

    return 0;
}

void getShouldStop() {
    shouldStop = GetAsyncKeyState( VK_END ) || shouldStop;
}

// If PI mutex is not locked, proceed to calculate the next PI, else wait
void piLoop() {
    while ( true ) {
        piLock.lock();

        if ( shouldStop ) {
            piLock.unlock();
            return;
        }

        // Here the series is calculated
        PI += ((long double)((piCicles&1)>0 ? -1 : 1)) / (piCicles*2 + 1);

        if ( piCicles == maxCicles ) {
            shouldStop = true;
            piLock.unlock();
            return;
        }

        piCicles++;

        piLock.unlock();
    }
}

// Wait until PI mutex is unlocked, then refresh the screen.
void displayLoop() {
    std::cout.precision( displayDigits );
    while ( true ) {
        piLock.lock();

        system("cls");
        std::cout << "\n\n  ----- PI Calculator ----- \n\n  - \"Seeing how PI is calculated is more enjoyable while eating some snacks.\"";
        std::cout << "\n\n\n    PI:      " << PI * 4;
        std::cout << "\n    Cicles:  " << piCicles << std::endl;
        if ( maxCicles == piCicles ) //  Just in case someone has the time to run this program for long enough
            std::cout << "\n    Max precise 64-bit computable value reached!" << std::endl;

        if ( !shouldStop ) getShouldStop();

        piLock.unlock();

        if ( shouldStop ) return;

        std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) );
    }
}

I think this code can also be run on other operating systems by removing the windows.h header and the getShouldStop() function as well, so Linux users may also give it a try.

Here is a link to download the Windows executable if you want to test it.


texts: Hackerrank Insertion Sort Algorithm 1 (creating duplicates to show shifting)

texts:
During an interview, I was given this Hackerrank question to solve within 15 minutes but at that time I was interested in solving this without performance in my mind. I know a similar question has been asked Hackerrank Insertion Sort - Java and probably a lot in CR.
Problem Statement

Given a sorted list with an unsorted number e  in the rightmost cell, can you write some simple code to insert  into the array so that it remains sorted?
Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.
Guideline: You can copy the value of  to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until  can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with .

Input Format
There will be two lines of input:

Size - the size of the array
Arr -  the unsorted array of integers

Output Format
On each line, output the entire array every time an item is shifted in it.
Constraints

1 ≤ Size ≤ 1000
-10000 ≤ e ≤ 1000, e E Arr

Sample Input
5
2 4 6 8 3

Sample Output
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
    public static void printArray(int[] array)
    {
        var b = array.Select((x) => Convert.ToString(x) + " ").Cast<string>();
        Console.WriteLine(String.Concat(b));
    }

    public static void insertionSort(int[] unsortedArray)
    {
        int unsortedElement = unsortedArray.ElementAt(unsortedArray.Count() - 1);
        int i = unsortedArray.Length - 1;
        while (i != -1)
        {
            if (i - 1 != -1)
            {
                if (unsortedArray[i - 1] > unsortedElement)
                {
                    unsortedArray[i] = unsortedArray[i - 1];
                    printArray(unsortedArray);
                }
                else
                {
                    unsortedArray[i] = unsortedElement;
                    printArray(unsortedArray);
                    break;
                }
            }
            else
            {
                unsortedArray[i] = unsortedElement;
                printArray(unsortedArray);
                break;
            }
            i--;
        }
    }
}

Any thoughts on performance, style or shortened code length?


texts: Looking for a better way to handle this growing array used for preg_replace

texts:
first time visiting Code Review.  I figured this was a more appropriate spot than SO for this question.   Here goes...

Currently, I have a php function that converts bbcode format text in to HTML (among other things).   A code snippet is as follows...

function bbcode_format ($str) {

 $simple_search = array(
    '/\[b\](.*?)\[\/b\]/is',  // bold
    '/\[i\](.*?)\[\/i\]/is',  // italics
    '/\[u\](.*?)\[\/u\]/is',  // underline
)

  $simple_replace = array(
    '$1',
    '$1',
    '$1'
)

    $str = preg_replace ($simple_search, $simple_replace, $str);
    return $str;
}

The code itself works fine.   However, in my actual code, there are currently around 60 items in each array I'm checking for, as I also used it to convert smileys, for example.

My concern is that this approach doesn't seem to be scalable, at least in the sense that the array just keeps growing and growing.

I'm wondering if anyone has another approach as to how this might be done, or any suggestions to improve my current method.   Thanks!

Additional Info

Thanks for the suggestions so far...   I may not have used the best examples above, as b / i / u are only a small set of what I'm replacing.    I probably have more "smiley" replacements, than anything, so those generally look like this...

'/:\)/is',          // smiley :)
'/:d/is',           // laugh smiley :D
'/\:gift1\:/is',    // Holiday Gift 1 :gift1:
'/\:gift2\:/is',    // Holiday Gift 2 :gift2:

Each of those is then replaced with an  tag.


texts:
I have been asked to refactor the below code using SOLID principles and I was just wondering how you would go about it. I am not really sure if I am winning or not.

Could you have a stab at it and let me see what you come up with?

public class Box
    {
        private BoxType _boxType;

        public double Width { get; set; }
        public double Height { get; set; }
        public double Radius { get; set; }

        public BoxType BoxType
        {
            get { return _boxType; }
            set { _boxType = value; }
        }

        public void Add()
        {
            using (var con = new SqlConnection())
            {
                SqlCommand cmd;

                if (_boxType == BoxType.Circle)
                {
                    cmd = new SqlCommand(string.Format("insert into [Table] values({0}, {1})", _boxType, Radius), con);
                }
                else
                {
                    cmd = new SqlCommand(string.Format("insert into [Table] values({0}, {1}, {2})", _boxType, Width, Height), con);
                }

                cmd.ExecuteNonQuery();
            }
        }

        public double CalculateArea()
        {
            if (_boxType == BoxType.Rectangle)
            {
                return Width * Height;
            }
            else if (_boxType == BoxType.Square)
            {
                return Width * Height;
            }
            else if (_boxType == BoxType.Circle)
            {
                return Radius * Math.PI;
            }
            else
            {
                return 0;
            }
        }
    }

    public enum BoxType
    {
        Unknown,
        Square,
        Rectangle,
        Circle
    }


texts: Find the number closest to 0, breaking ties in favor of positive numbers

texts:
I'm a Perl beginner and I really love this language, and I was wondering if it was possible to reduce the size of this code, just for fun and so as to learn Perl specificities:

chomp($n=<STDIN>);
if (!$n) {
   print 0;
} else {
   @t=split/ /,<STDIN>;
   foreach $i(0..$n-1) {
      $m=$t[$i]if(!$m)||(abs($t[$i])<abs($m))||(($t[$i]==-$m)&&($t[$i]>0));
   }
}print $m;

The goal of this code is to give the closest number to 0 of a list , and if there are -4 and 4 for exemple, it will always return the positive number.

$n is the number of numbers in the list
@t is the list as an array
$m is the min

This is "Temperatures" game on the website Codingame.com.

This code is working pretty well, and I'm trying to reduce its size so as to discover some Perl secrets.

I have some precise questions:

Is it possible to use a the ternary operator with several instructions in Perl?
Is is possible to write the foreach loop on one line in this case, or even replace the foreach loop with something else?

I don't really want perfect code as an answer, but some indications, and then I can search details and learn by myself.


texts: Loading configuration properties from XML

texts:
I would like a review of the transformation of the first method to the updated one below:

 private static ArrayList<String> getValuesfromXML(String key1, String key2) {
    ArrayList<String> valueArray = new ArrayList<String>();
    try {

        String scriptPath = getScriptPath("prop.xml");
        File file = new File(scriptPath);
        FileInputStream fileInput = new FileInputStream(file);
        Properties properties = new Properties();
        properties.loadFromXML(fileInput);
        fileInput.close();
        valueArray.add(properties.getProperty(key1));
        valueArray.add(properties.getProperty(key2));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valueArray;
}

It looks as if it's GC'd so there's no memory leaks. And is not using a finally on the filehandle really an issue?

    /**
     * read property values from the configuration file. Using standard Java Properties class.
     *
     * @param key1
     *            - Property key
     * @param key2
     *            - Property Key
     * @return - ArrayList values of properties based on keys
     */

    private static ArrayList<String> getPropertyValue (String key1, String key2){

        final ArrayList<String> valueArray = new ArrayList<>();
        String scriptPath = getScriptPath(propertiesFileName);

        try (FileInputStream fileInput = new FileInputStream(scriptPath)) {
            Properties properties = new Properties();
            properties.loadFromXML(fileInput);
            valueArray.add(properties.getProperty(key1));
            valueArray.add(properties.getProperty(key2));

        } catch (Exception  ex) {
            ex.printStackTrace();
        }

        return valueList;
    }


texts: How could I remove repetition from this linq-to-entities query?

texts:
This linq query works, and it does what I want it to do, but is there any other way I could improve the query so I'm not repeating a.AnswerRevisions.OrderByDescending(r => r.DateCreated).FirstOrDefault()?

IQueryable<Article> query = from a in _db.Articles
                            orderby a.DateCreated descending
                            where a.AnswerRevisions.Count > 0 &&
                            (a.AnswerRevisions.OrderByDescending(r => r.DateCreated).FirstOrDefault().UpVotes -
                             a.AnswerRevisions.OrderByDescending(r => r.DateCreated).FirstOrDefault().DownVotes < 0)
                            select a;


texts: Finding the number of times the code will generate an alert depending upon whether the transaction is fraudulent

texts:
Please refer to this problem from Hackerrank

  HackerLand National Bank has a simple policy for warning clients about
  possible fraudulent account activity. If the amount spent by a client
  on a particular day is greater than or equal to the client's median
  spending for a trailing number of days, they send the client a
  notification about potential fraud. The bank doesn't send the client
  any notifications until they have at least that trailing number of
  prior days' transaction data.

I have written the following code. However, the code is working for some of the test cases and is getting 'terminated due to timeout' for some. Can anyone please tell how can I improve the code?

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the activityNotifications function below.
    static int activityNotifications(int[] expenditure, int d)     {
        //Delaring Variables

        int iterations,itr,length,median,midDummy,midL,midR,               midDummy2,i,i1,temp,count;
        float mid,p,q;
        length = expenditure.length;
        iterations = length-d;
        i=0;
        i1=0;
        itr=0;
        count = 0;

        int[] exSub = new int[d];

        while(iterations>0)
        {

            // Enter the elements in the subarray
            while(i1<d)
            {
                exSub[i1]=expenditure[i+i1];
                //System.out.println(exSub[i1]);
                i1++;
            }

            //Sort the exSub array
            for(int k=0; k<(d-1); k++)
            {
                for(int j=k+1; j<d; j++)
                {
                    if(exSub[j]<exSub[k])
                    {
                        temp = exSub[j];
                        exSub[j] = exSub[k];
                        exSub[k] = temp;
                    }
                }
            }

            //Printing the exSub array in each iteration

            for(int l = 0 ; l<d ; l++)
            {
                System.out.println(exSub[l]);
            }

            i1=0;

            //For each iteration claculate the median

            if(d%2 == 0) // even
            {
                midDummy = d/2;
                p= (float)exSub[midDummy];
                q= (float)exSub[midDummy-1];
                mid = (p+q)/2;
                //mid = (exSub[midDummy]+exSub                                   [midDummy-1])/2;
                //System.out.println(midDummy);
            }
            else // odd
            {

                midDummy2 =d/2;
                mid=exSub[midDummy2];
                //System.out.println(midDummy2);
            }

            if(expenditure[itr+d]>=2*mid)
            {
                count++;
            }
            itr++;
            i++;
            iterations--;

            System.out.println("Mid:"+mid);
            System.out.println("---------");

        }

        System.out.println("Count:"+count);
        return count;

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);

        int d = Integer.parseInt(nd[1]);

        int[] expenditure = new int[n];

        String[] expenditureItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int expenditureItem = Integer.parseInt(expenditureItems[i]);
            expenditure[i] = expenditureItem;
        }

        int result = activityNotifications(expenditure, d);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}


texts: Reusing objects using a generic object pool

texts:
After reading a lot of documents, I wrote this object pooling code. Can anyone help me to improve this code? I am lagging in validating the object, confirming whether I can reuse it or not.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iaccount.ui;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 *
 * @author system016
 */
public class ObjectPool<T> {

    private long expirationTime;
    private Hashtable locked, unlocked;

    ObjectPool() {
        expirationTime = 30000; // 30 seconds
        locked = new Hashtable();
        unlocked = new Hashtable();
    }
//   abstract

    public Object create(Class<T> clazz) throws InstantiationException, IllegalAccessException {
        Object obj = clazz.newInstance();
        unlocked.put(clazz.newInstance(), expirationTime);

        return obj;

    }

    ;
//   abstract boolean validate( Object o );
//   abstract void expire( Object o );
    synchronized Object checkOut(Class<T> clazz) {
        long now = System.currentTimeMillis();
        Object o = null;

        if (unlocked.size() > 0) {
            Enumeration e = unlocked.keys();
            while (e.hasMoreElements()) {
                o = e.nextElement();
                if ((clazz.isAssignableFrom(o.getClass()))) {

//                }
                    if ((now - ((Long) unlocked.get(o)).longValue())
                            > expirationTime) {
                        // object has expired
                        unlocked.remove(o);
//                        expire(o);
                        o = null;

                    } else {
//                        if (validate(o)) {
                            unlocked.remove(o);
                            locked.put(o, new Long(now));
                            return (o);
//                        } else {
//                            // object failed validation
//                            unlocked.remove(o);
////                            expire(o);
//                            o = null;
//                        }
                    }
                }
            }
        }
        return o;
    }
//    public boolean validate(Object o){return true;};
}
//   synchronized void checkIn( Object o ){...}


texts: Custom view for data input (in-app (non-system) keyboard)

texts:
I have made a custom keyboard that gets loaded from an .xib file.

I decided to go with an in-app only keyboard rather than a system-wide keyboard because the documentation states:

  Make sure a custom, systemwide keyboard is indeed what you want to
  develop. To provide a fully custom keyboard for just your app or to
  supplement the system keyboard with custom keys in just your app, the
  iOS SDK provides other, better options. Read about custom input views
  and input accessory views in Custom Views for Data Input in Text
  Programming Guide for iOS.

Implementation highlights

Keyboard layout comes from Keyboard.xib, whose file owner is Keyboard.swift.
Keyboard.xib uses auto layout to resize all individual keys (UIButtons) when the keyboard view size changes.
Use of a delegate to communicate between the keyboard view and the view controller.
Use of the inputView method of UITextField to replace the system keyboard with my custom keyboard.

ViewController.swift

import UIKit

class ViewController: UIViewController, KeyboardDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // initialize custom keyboard
        let keyboardView = Keyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300))
        keyboardView.delegate = self

        // replace system keyboard with custom keyboard
        textField.inputView = keyboardView
    }

    // required method for keyboard delegate protocol
    func keyWasTapped(character: String) {
        textField.insertText(character)
    }
}

Keyboard.swift

import UIKit

protocol KeyboardDelegate {
    func keyWasTapped(character: String)
}

class Keyboard: UIView {

    var delegate: KeyboardDelegate?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeSubviews()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeSubviews()
    }

    func initializeSubviews() {
        let view = NSBundle.mainBundle().loadNibNamed("Keyboard", owner: self, options: nil)[0] as! UIView
        self.addSubview(view)
        view.frame = self.bounds
    }

    @IBAction func keyTapped(sender: UIButton) {
        self.delegate?.keyWasTapped(sender.titleLabel!.text!)
    }

}

Concerns

I never could find a single tutorial or full example of implementing an in-app only custom keyboard that makes use of the inputView method. This seems to work, but since I don't have anything else to compare it to, I wanted to run it by other programmers first.
I've gotten the impression from various reading that using .xib files to build a view is an outdated practice.


texts: A program that accepts numbers and computes their sum, and displays smallest and largest number

texts:
I am self learning programming by reading "Programming: Principles, and Practice" by Bjarne Stroustrup. I have solved a drill. Please review my code and give suggestions.

Drill

  Write a program that:

  Accepts numbers with units m, cm, ft, and in and rejects other units.
  Keeps a record of all the numbers in a single unit and computes the      sum of the numbers.
  Prints the smallest and the largest numbers.

My solution:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    double temp{0};
    string temp_unit;
    vector<double> numbers;
    double sum{0};

    constexpr double cm_to_m = 0.01;
    constexpr double ft_to_m = 0.3048;
    constexpr double in_to_m = 0.0254;

    cout<<"Enter an integer with its unit. E.g 2m or 2 m \n";
    while(cin>>temp>>temp_unit){
        if(temp_unit=="m"){
            numbers.push_back(temp);
        }
        else if(temp_unit=="cm"){
            numbers.push_back(temp*cm_to_m);
        }
        else if(temp_unit=="ft"){
            numbers.push_back(temp*ft_to_m);
        }
        else if(temp_unit=="in"){
            numbers.push_back(temp*in_to_m);
        }
        else{
            cout<<"Incorrect Unit\n";
        }
    }
    sort(numbers.begin(),numbers.end());
    for(auto& i:numbers){
        cout<<i<<" ";
        sum+=i;
    }
    cout<<"\nNumber of elements "<<numbers.size()<<endl;
    cout<<"Sum of numbers: "<<sum<<endl;
    cout<<"Smallest number: "<<numbers[0]<<endl;
    cout<<"Largest number: "<<numbers[numbers.size()-1]<<endl;
    return 0;
}


texts: Boolean class using shared referenced memory

texts:
To improve my knowledge I am trying to make a bool class from scratch, or derivative of. I am using MinGW g++11 compiler on a Windows 7 laptop.

#include <iostream>
#include <bitset>

class Zeroth{

    uint8_t* MEM = nullptr;

    public:
        const static uint8_t NullSet; // if data is declared sttic it is shared acros all instances, const means it can not be changed
        const static uint8_t UnitSet;

        /*
            the idea is that instead copying integers i can define a constant shared memories [ generated on a fly or in a header ]
            and then just store memory of the value that is pointed to
            so if object is present: point to memory of UnitSet
            if object isn't present: point to memory of NullSet

            therefore i have 1 8 bit space instanced and deleted with every value, but all those spaces point to the same constant memories
        */

        Zeroth():MEM(new uint8_t){ this->MEM = (uint8_t*)&Zeroth::NullSet; }
        Zeroth(int VAL):MEM(new uint8_t) {
            this->MEM = (uint8_t*)( VAL&0x1 ? &Zeroth::UnitSet : &Zeroth::NullSet );
        }
        ~Zeroth(){ delete MEM; }

        const bool isPresent() const {
            return (int)&Zeroth::UnitSet == (int)&(*this->MEM);
        }
        const bool isNotPresent() const {
            return (int)&Zeroth::NullSet == (int)&(*this->MEM);
        }

        friend std::ostream& operator<<( std::ostream& os, const Zeroth& data );
};
std::ostream& operator<<( std::ostream& os, const Zeroth &data ){
    return os << ( data.isPresent() ? 'T' : 'F');
}

const uint8_t Zeroth::NullSet = 0;
const uint8_t Zeroth::UnitSet = 1;

int main(){

    Zeroth Az(3);
    std::cout << Az << std::endl;
    std::cout << Az.isPresent() << std::endl;
    std::cout << Az.isNotPresent() << std::endl;

    Zeroth Bz;
    std::cout << Bz << std::endl;
    std::cout << Bz.isPresent() << std::endl;
    std::cout << Bz.isNotPresent() << std::endl;

    return 0;
}

And result is :

CD: F:\cppDMmods
Current directory: F:\cppDMmods
g++  -Wno-unused-variable -O2 F:\cppDMmods\test.cpp -o F:\cppDMmods\test.exe
Process started (PID=4296) >>>
<<< Process finished (PID=4296). (Exit code 0)

IF: "Exists" != "Exists" goto NOEXE
test.exe
Process started (PID=5516) >>>

T // Az printout
1 // Az "presence" :> aka true
0 // Az "negated presence" :> aka !true
F // Bz printout
0 // Bz "presence"
1 // Bz "negated presence"

<<< Process finished (PID=5516). (Exit code 0)
cmd /c del test.exe
Process started (PID=6124) >>>
<<< Process finished (PID=6124). (Exit code 0)
NO EXE FILE TO DELETE
================ READY ================

I am worried that due to my presumed lack of knowledge there might be some memory leaks, massive future bugs and etc.
Any suggestions, recommendations and pointed out issues are welcomed.


texts: Maximal pythagorean triplet that sums to n

texts:
Write a function maxPythagTriple that accepts an integer n and returns the maximum product of three numbers that are both a Pythagorean triplet and sum to the integer n. If no such pythagorean triplet exists, return -1.

i.e. maxPythagTriple(4) == -1
i.e. maxPythagTriple(12) == 60
{3,4,5} --> 3+4+5 = 12 --> 3^2+4^2= 5^2 --> 3*4*5 = 60

Below is my solution the preceeding challenge. I have been told there is a better solution. Any help would be much appreciated!

package challenges;

public class MathChallenges {

    private static boolean isValidTriple(int i, int j, int k) {
        return k > 0 && i != j && j != k && i > j && j > k;
    }

    private static boolean isPythagTriple(int i, int j, int k) {
        return (i*i + j*j) == k*k;
    }

    public static int maxPythagTriple(int n) {
        for (int i = n-1; i >= 1; i--) {
            for (int j = i-1; j >= 1; j--) {
                int k = n - (i + j);
                if (isValidTriple(i, j, k) && isPythagTriple(k, j, i)) {
                    return i * j * k;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println("maxPythagTriple(4) = " + maxPythagTriple(4));
        System.out.println("maxPythagTriple(12) = " + maxPythagTriple(12));
    }

}


texts: Get collection in blade and check if empty

texts:
If I want to display the addresses of a user in a blade file I do it like this:

@if(!$user->addresses->isEmpty())

  @foreach ($user->addresses as $address)

      {!! displayText($address->toString()) !!}

  @endforeach

@endif

If addresses would be an array instead of an collection I could shorten the code to:

@if(!empty($addresses = $user->addresses))

  @foreach ($addresses as $address)

      {!! displayText($address->toString()) !!}

  @endforeach

@endif

I wonder if there is a better way to check if a collection is empty in a blade file.


texts:
I'm diving into "modern CPP", with wide usage of templates and containers,
So I started with FIR filter.

In signal processing, a finite impulse response (FIR) filter is a filter whose impulse response (or response to any finite length input) is of finite duration, because it settles to zero in finite time. This is in contrast to infinite impulse response (IIR) filters, which may have internal feedback and may continue to respond indefinitely (usually decaying).

So I define FIR filter as a class and apply it to single scalar value or to the vector itself
Could you please review my code in terms of C++ coding?
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <complex>
#include <cmath>
#include <iomanip>
#include <sstream>

// - Class method : operator(), constructor, various methods
// - Templates class and function
// - List and vector containers
// - Functors

template <typename T> std::string to_str(T & arr){
  std::ostringstream os;
  os << "[";  for (auto x: arr){    os<<" "<< x <<" ";  }  os << "]\n";
  return os.str();
}

template <class T> class FIR {
public:
    std::vector< T > coeff;  // Array of coefficents is static all the time
    std::list< T > taps;  // Array of is are shifting each tick
    int order;

    FIR(std::vector< T > v)
    {
       coeff = v;
       order = coeff.size();
       taps = std::list< T > (coeff.size(), 0);
    }
    void reset(){
       taps = std::list< T > (coeff.size(), 0);
    }
    void append( T  x){
      taps.push_front( x);
      taps.pop_back();
    }

    auto sum_product(){
      T  psum = 0;
      typename   std::list< T >::iterator t;
      typename std::vector< T >::iterator c;
      // Can we do better here?
      for (   c =coeff.begin(),     t  =taps.begin();
              c!=coeff.end(),       t !=taps.end();
            ++c             ,     ++t             ){
        psum += (*c) * (*t);
      }
      return psum;
    }

    auto operator() ( T  x){
      append(x);
       T  psum = sum_product();
      return psum;
    }

     auto operator() (std::vector< T > x){
     std::vector< T > y( x.size(), 0);
     for (int i = 0; i<x.size(); ++i){
        y[i] =  operator()(x[i]);
     }
     return y;
     }
};

int main()
{
    std::vector<double> coeff = {0.0,1.0,5.0, 1.0, 0.0};

    FIR<double> fir(coeff);
    std::cout <<"Coeff: " << to_str(fir.coeff);
    std::cout <<"Taps : "  << to_str(fir.taps);

    std::cout<<"\nTRANSFORM IN THE LOOP \n";
    std::vector<double> x_array = {0,1,2,3,4,5,6,0,0,0,0,0,0,13};
    for (auto x:x_array){
      auto p = fir(x);
      std::cout<<p<<"  ";
    }
    std::cout<<"\n";
    fir.reset();

    std::cout<<"\nTRANSFORM WITH FUNCTOR FOR SCALAR\n";
    std::vector<double> y_array( x_array.size(), 0);
    std::transform(x_array.begin(), x_array.end(), y_array.begin(), fir);
    std::cout << to_str(y_array);
    fir.reset();

    std::cout<<"\nAPPLY FUNCTOR FOR CONTTAINER \n";
    auto y_2 = fir(x_array);
    std::cout << to_str(y_2);
    fir.reset();

    return 0;
}


texts: Parsing strings with escaped characters using Parsec

texts:
I have been working through the exercises in a Write Yourself a Scheme in 48 Hours/Parsing and hacked together something to get parseString to comprehend escaped characters. Also had some inspiration from Real World Haskell chapter 16 minus the applicative parts.

parseString :: Parser LispVal
parseString = do char '"'
                 x <- many $ chars
                 char '"'
                 return $ String x
    where chars = escaped <|> noneOf "\""
          escaped = choice $ map tryEscaped escapedChars
          tryEscaped c = try $ char '\\' >> char (fst c) >> return (snd c)
          escapedChars = zip "bnfrt\\\"/" "\b\n\f\r\t\\\"/"

This works but I am not fond of my 'tryEscaped' definition. What are the alternatives?


texts: Rock Paper Scissors in Java (I just want to know whatever feedback you have :) Thank you!)

texts:
Any feedback on this code would be greatly appreciated! I am just trying to improve so I can move on to bigger projects. Thank you so much!

    import java.util.*;
   import java.util.Random;

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

    Random rd = new Random();
    Scanner kb = new Scanner(System.in);
    System.out.println("Welcome to Rock Paper Scisscors!");

    while(true)
    {
    int rock = 1;
    int paper = 2;
    int scissors = 3;

    int conditions [] = {rock, paper, scissors};
    int random = (conditions[new Random().nextInt(conditions.length)]);

    System.out.print("Please Enter: \n1 for Rock, \n2 for Paper, \n3 for Scissors: ");
    int player1 = kb.nextInt();

    if(player1 == rock && random == rock)
    {
        System.out.print("You have tied, computer rock, please try again\n");
    }
    else if(player1 == paper && random == paper)
    {
        System.out.print("You have tied, computer chose paper, please try again");
    }
    else if(player1 == scissors && random == scissors)
    {
        System.out.print("You have tied, computer chose scissors, please try again");
    }

    if(player1 == rock && random == paper)
    {
        System.out.print("Computer chose paper, computer has won");
        break;
    }
    else if(player1 == paper && random == rock)
    {
        System.out.print("You win!, computer chose rock");
        break;
    }
    else if(player1 == paper && random == scissors)
    {
        System.out.print("Computer chose scissors, computer has won");
        break;
    }
    else if(player1 == scissors && random == paper)
    {
        System.out.print("You win, computer chose paper");
        break;
    }
    else if(player1 == rock && random == scissors)
    {
        System.out.print("You win!, computer chose scissors");
        break;
    }
    else if(player1 == scissors && random == rock)
    {
        System.out.print("Computer chose rock, computer has won");
        break;
    }

    if(player1 != rock && player1 != paper && player1 != scissors )
    {
        System.out.print("Invalid response");
        break;
    }
    }

     }

   }


texts: Procedural style Rock Paper Scissors game using Python 3

texts:
I am a newbie to Python and am trying to do the Rock, Paper and Scissors game to revise my knowledge that I have earned so far.

Overview of the program:

This is a two-player game
Ask for player plays (including name, their choice: rock or paper or scissors using input)
Print out a message of winner
Ask if the user want to start a new game

This code is written in procedural style.

Can anyone show me some weaknesses in my code and how I can improve on them?

def beats(a, b):
    tup = ('rock', 'paper', 'scissors')
    if (a == tup[1] and b == tup[2]) or (a == tup[2] and b == tup[1]):
        return tup[2]
    elif (a == tup[1] and b == tup[0]) or (a == tup[0] and b == tup[1]):
        return tup[1]
    elif (a == tup[0] and b == tup[2]) or (a == tup[2] and b == tup[0]):
        return tup[0]

def players_input():
    name = input('What is your name?: ')
    while True:
        decision = input('Paper, Rock, or Scissors?: ')
        if decision == 'rock' or decision == 'paper' or decision == 'scissors':
            break
        else:
            print("Invalid choice! Try again!")
            continue
    return '{} chooses {}'.format(name, decision)

def play():
    player1 = players_input()
    player2 = players_input()
    print('{}\n{}'.format(player1, player2))
    name1, verb, decision1 = player1.split(" ")
    name2, verb, decision2 = player2.split(" ")
    returnvalue = beats(decision1.lower(), decision2.lower())
    if decision1.lower() == returnvalue and decision2.lower() != returnvalue:
        print('{} wins'.format(name1))
    elif decision2.lower() == returnvalue and decision1.lower() != returnvalue:
        print('{} wins'.format(name2))
    else:
        print('It\'s a tie')

def play_again():
    while True:
        choice = input('Do you want to continue?(Y/N): ')
        if choice.upper() == "Y":
            play()
        elif choice.upper() == "N":
            print("Game over")
            break
        else:
            print("Invalid Input! Try again!")

play()
play_again()


texts: Retrieving all directorie names (relative path)

texts:
Just a small code review.
Is there a better way to get all folder names?

<?php
$folders = glob(dirname(__FILE__) . '/myFolder', GLOB_ONLYDIR);
foreach ( $folders as $f ) {
    $lastDsPos = strrpos($v, DIRECTORY_SEPARATOR);
    $myFolders[] = substr($v, $lastDsPos+1);
}


texts:
Since I use C++ mainly to do physical calculations, I often come across the problem that I forget which units a certain variable is in, e.g. radian or degree, or meter vs. millimeter.

For this reason, I started using a custom header file defining my units, which is posted below. The basic idea is that I never create something like:

double myAngle = 10;

Instead of using:

radian_t myAngle = 10;

Later, when passing it somewhere else, nobody will know whether it is in radian or degree. The upsides are listed below.

Are there any downsides to this?

Example implementation:

units.h:

#ifndef INCLUDE_UNITS_H_
#define INCLUDE_UNITS_H_

namespace units {
  using meter_t  = double;
  using newton_t = double;
  using radian_t = double;
  using joule_t  = double;

} // units

#endif /* INCLUDE_UNITS_H_ */

sample.h:

using namespace units;

joule_t myEnergy (newton_t force, meter_t length)
{ joule_t myEnergy = force * length; }

The upsides are:

Fast unit lookup: In Eclipse, I only need to hover over a variable and instantly know the unit it is in, simple by seeing its type (meter_t myLength vs double myLength).
Easy debugging: The following code is obviously wrong, since Joule is Newton * meter:

joule_t myEnergy (newton_t force, millimeter_t length)
{ joule_t myEnergy = force * length; }

Is this function correct? Who knows!

double myEnergy (double force, double length)
{ double myEnergy = force * length; }

Overloading? In theory, I could even implement classes instead of using "using" declarations. Is that correct? This would let me overload the operators, making sure that sin.operator*(radian_t rad) is different from sin.operator*(degree_t deg)?


texts: Cut and paste rows to new sheet based on different criteria in Column A

texts:
I have a "working sheet" that contains 15000+ rows. In column A is an identifier for that row. There are over 20 different identifiers i.e 9W, AM, AV, BG, CY, HJ etc. etc.

My current code looks for each row on "Working Sheet" that has 9W in column A, cuts and pastes that row into a sheet called 9W. Once finished it moves to AM, finds am in Column A, cuts and pastes each row into a sheet called AM. Process repeats until all Identifiers have been done.

Here is a sample of the current code that I have created with my limited knowledge:

Sub Test()

'Do 9W

    Dim sht1 As Worksheet, sht2 As Worksheet
    Dim i As Long

    Set sht1 = ThisWorkbook.Worksheets("Working Sheet")
    Set sht2 = ThisWorkbook.Worksheets("9W")

    For i = 2 To sht1.Cells(sht1.Rows.Count, "A").End(xlUp).Row
        If sht1.Range("A" & i).Value = "9W" Then
            sht1.Range("A" & i).EntireRow.Cut sht2.Range("A" &
 sht2.Cells(sht2.Rows.Count, "A").End(xlUp).Row + 1)
        End If
    Next i

'Do AM

Dim sht3 As Worksheet, sht4 As Worksheet
Dim i1 As Long

Set sht3 = ThisWorkbook.Worksheets("Working Sheet")
Set sht4 = ThisWorkbook.Worksheets("AM")

For i1 = 2 To sht3.Cells(sht3.Rows.Count, "A").End(xlUp).Row
    If sht3.Range("A" & i1).Value = "AM" Then
        sht3.Range("A" & i1).EntireRow.Cut sht4.Range("A" &
sht4.Cells(sht4.Rows.Count, "A").End(xlUp).Row + 1)
    End If
Next i1

'DO AV

Dim sht5 As Worksheet, sht6 As Worksheet
Dim i2 As Long

Set sht5 = ThisWorkbook.Worksheets("Working Sheet")
Set sht6 = ThisWorkbook.Worksheets("AV")

For i2 = 2 To sht5.Cells(sht5.Rows.Count, "A").End(xlUp).Row
    If sht5.Range("A" & i2).Value = "AV" Then
        sht5.Range("A" & i2).EntireRow.Cut sht6.Range("A" &
sht6.Cells(sht6.Rows.Count, "A").End(xlUp).Row + 1)
    End If
Next i2

'DO BG

Dim sht7 As Worksheet, sht8 As Worksheet
Dim i3 As Long

Set sht7 = ThisWorkbook.Worksheets("Working Sheet")
Set sht8 = ThisWorkbook.Worksheets("BG")

For i3 = 2 To sht7.Cells(sht7.Rows.Count, "A").End(xlUp).Row
    If sht7.Range("A" & i3).Value = "BG" Then
        sht7.Range("A" & i3).EntireRow.Cut sht8.Range("A" &
    sht8.Cells(sht8.Rows.Count, "A").End(xlUp).Row + 1)
    End If
Next i3

End Sub


texts: 3Sum 2 Different implementations complexity

texts:
These are 2 implementations for the http://en.wikipedia.org/wiki/3SUM problem,
The first one is mine.
and in the second one I implemented Wiki's pseudo code.

Can someone please tell me if there is a difference between the two in complexity of runtime and memory space?

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

namespace ConsoleApplication2
{

    //the 3SUM problem asks if a given set of n integers,
    //each with absolute value bounded by some polynomial in n, contains three elements that sum to zero
    public class ThreeSum
    {
        public ThreeSum()
        {
            List<int> array = new List<int> { 25, -10, -7, -3, 2, 4, 8, 10 };
            List<int> res = SolveThreeSum(array);
            res = SolveThreeSumWiki(array);
        }

        public List<int> SolveThreeSum(List<int> array)
        {
            for (int i = 0; i < array.Count - 2; i++ )
            {
                for (int j = i + 1; j < array.Count -1; j++)
                {
                    for (int k = i + 2; k < array.Count ; k++)
                    {
                        if ((array[i] + array[j] + array[k]) == 0)
                        {
                            return new List<int> { array[i], array[j], array[k] };
                        }
                    }
                }
            }
            return null;
        }

        public List<int> SolveThreeSumWiki(List<int> array)
        {
            array.Sort();
            for (int i = 0; i < array.Count - 3; i++)
            {
                int a = array[0];
                int start = i + 1;
                int end = array.Count - 1;
                while (start < end)
                {
                    int b = array[start];
                    int c = array[end];
                    if ((a + b + c) == 0)
                    {
                        return new List<int> { a, b, c };
                    }
                    else if (a+b+c > 0)
                    {
                        end = end - 1;
                    }
                    else
                    {
                         start = start + 1;
                    }
                }
            }
            return null;
        }
    }
}


texts: Simple, flexible, and thread-safe key/value memory cache

texts:
MemoryCache.cs

public class MemoryCache<TKey, TValue>
{
    private static readonly object Lock = new object();
    private static readonly IDictionary<TKey, TValue> Cache = new ConcurrentDictionary<TKey, TValue>();

    /// <summary>
    /// Function for setting the cache's value when the key isn't found.
    /// </summary>
    public Func<TKey, TValue> Set { get; set; }

    /// <summary>
    /// Retrieves the value marked by the indicated key in a thread-safe way.
    /// If the item is not found, uses Set to retrieve it and store it in the cache before returning the value.
    /// </summary>
    public TValue Get(TKey key)
    {
        lock (Lock)
        {
            if (Cache.TryGetValue(key, out var value) == false)
            {
                value = Set(key);
                Cache.Add(key, value);
            }

            return value;
        }
    }

    /// <summary>
    /// Clears all values in the cache.
    /// </summary>
    public void Clear()
    {
        lock (Lock)
        {
            Cache.Clear();
        }
    }

}

Usage

Set is being used to retrieve the customer information from the database via stored procedure. GetBasicCustomer is a service/repository function for retrieving a customer by customerId or sapCustomerId.

public class CustomerService : ICustomerService
{
    private static readonly MemoryCache<Tuple<int?, string>, Customer> CustomerCache = new MemoryCache<Tuple<int?, string>, Customer>()
    {
        Set = (Tuple<int?, string> key) =>
        {
            var ds = Database.ExecuteStoredProcedure("EXEC usp_Experiment_BasicCustomerInformation @CustomerID, @SAPCustomerID", key.Item1, key.Item2);
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            {
                return null;
            }

            var dr = ds.Tables[0].Rows[0];
            return new Customer(
                 id: dr.Field<int>("CustomerID"),
                 sapCustomerId: dr.Field<string>("SAPCustomerID"),
                 companyName: dr.Field<string>("CompanyName"),
                 isSbtCustomer: dr.Field<bool>("IsSBTCustomer")
             );
        }
    };

    /// <summary>
    /// Retrieves the customer's basic information given CustomerID or SAPCustomerID (only one is required, make the other null).
    /// </summary>
    public Customer GetBasicCustomer(int? customerId, string sapCustomerId)
    {
        var key = new Tuple<int?, string>(customerId, sapCustomerId);
        return CustomerCache.Get(key);
    }
}

public CustomerController()
{
    public ActionResult Index(int? customerId, string sapCustomerId)
    {
        var customerInfo = CustomerService.GetBasicCustomer(customerId, sapCustomerId);
        return View(customerInfo);
    }
}

Concerns

I was thinking Set should maybe be named FindAndSet or something like that, but not really sure. I like the aesthetic of Get/Set.
Is ConcurrentDictionary necessary to be thread-safe since I'm using a lock? Is it doing anything for me?


texts: Idea of 'parser' to make the writing of asynchronous functions chains easier

texts:
Why this thing :

I work on a project where I need to call many asynchronous functions to get data, chain them, execute them if conditions are met,.. and I ended up having unreadable code.
At some point, I looked at promises library like Q.js but even with such tools my code was complicated, so I decided to write something which would make my cases of use simple to read.

 Code + what it does :

The whole concept is to help someone generate the code for the asynchronous calls as a string and then call eval() to run it (the latter probably being a major case of evil programming).  At the moment, it has only two functions because I am not sure how good this idea is.

First function : chain
This functions chains two asynchronous calls, optionally with a condition on the result of the first asynchronous call.

pp_chain_function = function (fname,condition_string) {
var queue=this;
var prec_result = 'result_'+queue.queue_length;
queue.queue_string += !condition_string ? '.then(function(){return '+fname+'();})'
        :'.then(function('+prec_result+'){if('+prec_result+condition_string+'){return '+fname+'();}return $.when();})';
queue.length++;

return queue;
};

Second function : fail  Adds fail handler for the whole queue.

pp_fail_function = function(fname) {
    var queue = this;
    queue.queue_string += '.fail(function(error){return '+fname+'(error);})';
    return queue;
};

Global queue prototype :

queue_object = {
        pp_chain : pp_chain_function,
        pp_fail : pp_fail_function
        };

Initializing the queue :

pp_begin = function(){
    var pp_queue = Object.create(queue_object);
    pp_queue.queue_string='$.when()';
    pp_queue.queue_length=0;
    console.warn(pp_queue);
    return pp_queue;
};

 Usage case :

var chain = pp_begin(); //init the chain
    chain.pp_chain('async_0').pp_chain('async_1');  //add two standard async functions
    if(condition two){chain.pp_chain('async_2','.length>0');} //if external conditions and async_1 gave a result with length>0, execute async_2
    chain.pp_fail('fail_handler');  //add fail handler
    console.warn(chain);  //replace with eval if you want to actually run it

I would love some feedback on that idea mainly, and on the code if applicable (even if there is very few).

EDIT : jsfiddle for up-to-date version

 Concrete example :

Before :

 if (online_mode && i_s_r) { //if sync clear collections and reload them
            access.findAll()
                .then(function (result) {
                    if (result.length > 0) {
                        access.remove(result, {
                                push: false
                            })
                            .then(function () {
                                access.load()
                                    .then(function () {
                                        callback_function(i, true);
                                    });
                            });
                    } else {
                        access.load()
                            .then(function () {
                                callback_function(i, true);
                            });
                    };
                })
                .fail(function (errorObject) {
                    alert(errorObject);
                });
        } else {
            callback_function(i, true);

After :

var q0 = begin();
        if(online_mode && i_s_r){q0.chain('access.findAll()').chain('access.remove(result_1,{push: false})','.length>0').chain('access.load()').failure('alert');}
        q0.chain_sync('callback_function(i,true)');
        eval(q0.queue_string);


texts:
I'm basically trying to write a helper function that reads a whole file and returns the data and the number of bytes read.

Can you tell me if is correctly written and used?

#include <iostream>

static char * ReadAllBytes(const char * filename, int * read)
{
    ifstream ifs(filename, ios::binary|ios::ate);
    ifstream::pos_type pos = ifs.tellg();
    int length = pos;
    char *pChars = new char[length];
    ifs.seekg(0, ios::beg);
    ifs.read(pChars, length);
    ifs.close();
    *read = length;
    return pChars;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const char * filename = "polar00.map";
    int read ;
    char * pChars = ReadAllBytes(filename, &read);
    delete[] pChars;
    return 0;
}


texts:
Some fellow code reviewers (hi @Janos!) have been inquiring about a SEDE query to allow to check progress of the Red Shirt "hat" progression.

Try it here!

Background

  Red Shirt

  cast 5 downvotes on posts that are later deleted or closed

Limitations

There are certain Stack Exchange limitations which make querying this information a bit tricky. Namely:

The data is only refreshed once a week, on Sundays. This makes it impossible to have "real time" results.
User voting activity is anonymous, in that a user can only see their own voting activity in their own profile. This disallows joining voting and user data on SEDE.

Assumptions

I have made certain assumptions, based on the trends I generally see on closed questions. They are:

A user who votes to close/delete a bad question will usually also downvote the question.
A user who downvotes a question will usually do so before voting to close/delete.

Usage

To get usefulness out of this (and as indicated in the SQL comments at the top of the query):

  The way that this report can be used is by comparing the results set
  side-by-side with your "votes" under your activity reports.
  Filter by down-votes and look to see if questions you down-voted are
  in the result set below.

For example:

Query

/*
Winter Bash 2014
"Red Shirt" hat estimation
"Cast 5 downvotes on posts that are later deleted or closed"

The way that this report can be used is by comparing the results set
side-by-side with your "votes" under your activity reports.
Filter by down-votes and look to see if questions you down-voted are
in the result set below.
*/

-- NumberWeeks: Number of weeks to go back

-- DATETIME VARIABLES

DECLARE @today DATETIME;
SET @today = CURRENT_TIMESTAMP;

DECLARE @weeks_ago INT;
SET @weeks_ago = ##NumberWeeks:int?4##;
-- Number of weeks must not go into the future, hence the following:
SET @weeks_ago = (CASE WHEN @weeks_ago >0 THEN -@weeks_ago ELSE @weeks_ago END);

DECLARE @target_week DATETIME;
SET @target_week = DATEADD(WEEK, @weeks_ago, CURRENT_TIMESTAMP);

-- POST-RELATED VARIABLES

DECLARE @downvote TINYINT;
SET @downvote = (SELECT Id FROM VoteTypes WHERE Name LIKE 'Down%'); --3

DECLARE @question_post TINYINT;
SET @question_post = (SELECT Id FROM PostTypes WHERE Name = 'Question'); --1

DECLARE @closed_post TINYINT;
SET @closed_post = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Post Closed'); --10

DECLARE @deleted_post TINYINT;
SET @closed_post = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Post Deleted'); --12

-- QUERY BEGINS

WITH cte_downvoted_posts AS
(
  SELECT Votes.PostId AS dvote
  FROM Votes
  INNER JOIN Posts ON Votes.PostId = Posts.Id
  WHERE VoteTypeId = @downvote
)

SELECT
    Posts.Id AS [Post Link]               -- magic column
  , Posts.OwnerUserId AS [User Link]      -- magic column
  , Posts.CreationDate AS [Creation Date]
  , Posts.ClosedDate AS [Closed Date]

FROM Posts
INNER JOIN cte_downvoted_posts
    ON Posts.Id = cte_downvoted_posts.dvote
INNER JOIN PostHistory
    ON Posts.Id = PostHistory.PostId

WHERE Posts.CreationDate <= @today
  AND Posts.CreationDate > @target_week
  AND Posts.PostTypeId = @question_post
  AND Posts.ClosedDate IS NOT NULL

GROUP BY
    Posts.Id
  , Posts.OwnerUserId
  , Posts.CreationDate
  , Posts.ClosedDate

ORDER BY
    Posts.CreationDate DESC

Concerns

Nitpicks are fine! Anything from naming to indentation to inconsistencies, please don't be shy to point out anything at all!
I noticed a lot of nested loops in the execution plan, when it's doing joins. Is there a better way to do this to avoid them?
Is there a way to make this query result set more useful, or user-friendly?
Are my comments appropriate/useful? Should I have fewer, or more of them?


texts:
I would like to hear your suggestions about my shuffling function in C++. I've decided to take advantage of using rand() to build a shuffling function.

#include <iostream>
#include <vector>
#include <ctime>

bool find(const std::vector<int>& vec, int index)
{
    for (int i = 0; i < vec.size(); ++i){
        if ( index == vec[i] )
            return true;
    }

    return false;
}

void shuffle(int array[], const int size)
{
    int temp[size];
    std::vector<int> indices;

    for ( int i(0); i < size; ++i)
        temp[i] = array[i];

    int index = rand() % size;
    indices.push_back(index);

    for ( int i = 0; i < size; ++i){
        if ( i == 0 )
            array[i] = temp[index];
        else{
              while( find(indices, index) )
                index = rand()%size;

            indices.push_back(index);
            array[i] = temp[index];
        }
    }

}

int main(void)
{
    srand((unsigned int)time(NULL));

    int a[7] = {1,2,3,4,5,6,7};

    for ( int i = 0; i < 7; ++i)
        std::cout << a[i] << " ";
    std::cout << std::endl;

    shuffle(a, 7);

    for ( int i = 0; i < 7; ++i)
        std::cout << a[i] << " ";
    std::cout << std::endl;

    return 0;
}

The result:

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


texts: Is this the wrong way to handle AggregateException with Tasks

texts:
I'm seeing a lot of code like this at my new site

        try
        {
            Task.Factory.StartNew(() =>
            {
            ...
            });
        }
        catch (AggregateException ex)
        {
            ex.Handle((x) =>
            {
                Log.Write(x);
                return true;
            });
        }

From what I've read, as Wait(), Result or Exception are not called the AggregateException will not have been marshalled. Also the Task may not even of started yet.
I'm thinking of using Joe Albahari's extension method that uses a continuation as these are mainly fire and forget Tasks

public static void PrintExceptions (this Task task)
{
       task.ContinueWith (t => { var ignore = t.Exception; },
       TaskContinuationOptions.OnlyOnFaulted);
}

Am I on the right track?


texts: Multi-dimensional view of a one-dimensional object

texts:
Sometimes, we create a one-dimensional object, but want to access it in a multi-dimensional way. For example, you can access an int[8] array object in a 2x2x2 way. So, I made a multi_view class template to make this easy. Any comments are welcome~ Original code can be found here and documentation here.

template <typename Iterator>
class multi_view {
public:
  static constexpr std::size_t max_dim = 10;

dimensions.
  template <typename... Ts>
  multi_view(Iterator base, Ts... extents)
      : base_(base) {
    constexpr auto n = sizeof...(extents);
    static_assert(0 < n && n <= max_dim, "");
    auto init_list = { extents... };
    std::copy(init_list.begin(), init_list.end(), steps_);
    auto i = n - 1;
    std::size_t acc = 1;
    do {
      acc *= std::exchange(steps_[i], acc);
    }
    while (i-- > 0);
    assert(acc);
    num_elements_ = acc;
  }

  template <typename... Ts>
  auto begin() const {
    return base_;
  }

  template <typename... Ts>
  auto begin(Ts... indices) const {
    auto idxes = std::begin({ indices... });
    std::size_t offset = 0;
    for (std::size_t i = 0; i < sizeof...(indices) && steps_[i]; ++i) {
      assert(idxes[i] >= 0);
      offset += idxes[i] * steps_[i];
    }
    return (base_ + offset);
  }

  template <typename... Ts>
  auto end() const {
    return base_ + num_elements_;
  }

  template <typename... Ts>
  auto end(Ts... indices) const {
    return end_impl(std::make_index_sequence<sizeof...(Ts) - 1>{}, indices...);
  }

  template <typename... Ts>
  auto operator ()(Ts... indices) const {
    return *begin(indices...);
  }

private:
  template <std::size_t... seq, typename... Ts>
  auto end_impl(std::index_sequence<seq...>, Ts... indices) const {
    auto tup = std::tie(indices...);
    return begin(std::get<seq>(tup)..., std::get<sizeof...(Ts) - 1>(tup) + 1);
  }

  Iterator base_;
  std::size_t steps_[max_dim + 1]{};
  std::size_t num_elements_ = 0;
};

template <typename Iterator, typename... Ts>
auto make_multi_view(Iterator base, Ts... extents) {
  return multi_view<Iterator>(base, extents...);
}

A usage example:

std::vector<int> vec{ 1, 2, 3, 4 };
auto view2x2 = make_multi_view(vec.begin(), 2, 2);
assert(view2x2(0, 0), 1);
assert(view2x2(0, 1), 2);
assert(view2x2(1, 0), 3);
assert(view2x2(1, 1), 4);
assert(view2x2(), 1);
assert(view2x2(1), 3);
assert(std::distance(view2x2.begin(), view2x2.end()), 4);
assert(std::distance(view2x2.begin(1), view2x2.end(1), 2);
assert(std::distance(view2x2.begin(1, 1), view2x2.end(1, 1), 1);


texts:
Problem

  For the given binary tree return the list which has sum of every paths in a tree. i.e Every path from root to leaf.

I've written following solution.

void check()
    {
        List<Integer> out = new ArrayList<>();
        leafsum(root, 0, out);
        System.out.println(out);
    }

    void leafsum(TreeNode root, int curr , List<Integer> sum)
    {

        if(root != null)
        {
            leafsum(root.left, curr+root.data, sum);
            if(root.left == null && root.right == null ) sum.add(curr+root.data);
            leafsum(root.right, curr+root.data, sum);
        }

    }

  Inorder traversal of Tree

2 4 3 5 1 9 2 5 15

root = new TreeNode(5);
root.left = new TreeNode(4);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(3);
root.right = new TreeNode(9);
root.right.right = new TreeNode(5);
root.right.left = new TreeNode(1);
root.right.right.left = new TreeNode(2);
root.right.right.right = new TreeNode(15);

  Output

[11, 12, 15, 21, 34]

I would like review about improvements and suggestions.


texts: ES6 class that generates an area where you can draw on a page

texts:
I have the following javascript es6 class (along with some functions) that generates an area where you can draw in a page.

class Painter {
    constructor(selector, cols, rows, style) {
        this.looper = null;
        if (!selector)
            throw new TypeError("Provide a valid table selector");
        this.cols = cols || 20;
        this.rows = rows || 20;
        this.selector = selector;
        this.style = style;
        let markup = "";
        for (let height = 0; height < this.rows; height++) {
            markup += "
";
            for (let width = 0; width < this.cols; width++)
                markup += "	";
            markup += "
";
        }
        $(function() {
            $(selector).html(markup);
            $(selector).on("click", "td", function() {
                $(this).toggleClass("tile-active");
            });
        });
    }
    setStyleSheet(stylesheet) {
        this.style = stylesheet;
    }
    changeTileColor(stylesheet, newColor) {
        if (!newColor)
            return;
        var css = ".tile-active{\n\tbackground:" + newColor + ";\n}";
        try {
            changeCss((stylesheet || this.style), css);
        } catch (e) {
            console.log("Suppressed error");
        }
    }

    createChessBoard() {
        var id = this.selector;
        $(function() {
            $(id + " tr:nth-child(even) td:nth-child(even)").addClass("black-tile");
            $(id + " tr:nth-child(odd) td:nth-child(odd)").addClass("grey-tile");
        });
    }
    toggleBorder() {
        var bname = $(this.selector).css("border");
        $(this.selector).css("border", bname.indexOf("none") != -1 ? "2px solid" : "none");
    }
    clearBoard() {
        $(this.selector + " .tile-active").removeClass("tile-active");
    }
    createRandowDraw() {
        this.clearBoard();
        let mat = $(this.selector + " td");
        let max = mat.length;
        for (let i = 0; i < max; i++) {
            let num = Math.floor(Math.random(2) * 2);
            if (num && num <= 1)
                $(mat[i]).addClass("tile-active");
        }
    }
}

As I am new to classes in ECMAScript 6 I was wondering if there is anything I can do to improve the performance/readability of this code.

Here is a link to the following code:
Painter


texts: Efficiently concatenate substrings of long list of strings

texts:
I am having performance problems with the following python function:

def remove_comments(buffer):
    new_buffer = ''
    lines = buffer.split('\n')
    for line in lines:
        line_wo_comments = line.split('--')[0] + '\n'
        new_buffer = new_buffer + line_wo_comments
    return new_buffer

When buffer is very large (thousands+ lines), the function gets slower and slower as it processes the buffer.

What techniques could I use to speed this function call up?

Assume that the input is a source code file. Lines of length 1 - ~120 characters. Lines may or may not have comments. The files could be many lines long. The especially problematic ones are machine generated (1-10k+ lines long).

Update: The intention is to use this as a "pre-processing" step for the buffer contents (a file). I guess I am not too interested in possibly ways to completely refactor this (i.e. methods to avoid needing to iterate through all the lines multiple times), but rather make the essence of buffer in / buffer out as fast as possible.