texts:
The actions I'm wondering about are members, add_student, and remove_student.  They work just fine, but they aren't RESTful and it feels like they should be handled (perhaps) by the StudentsController.

Note that members and show are the same. The only difference is that the members.html.erb view iterates over and displays @classroom.students while show.html.erb displays info about the classroom itself.

class ClassroomsController < ApplicationController

  # GET /classrooms
  def index
    @classrooms = Classroom.all.order('name ASC')
  end

  # GET /classrooms/1
  def show
    @classroom = Classroom.find(params[:id])

    authorize @classroom
  end

  # GET /classrooms/1/members
  def members
    @classroom = Classroom.find(params[:id])

    authorize @classroom
  end

  # GET /classrooms/new
  def new
    @classroom = Classroom.new
    @classroom.build_avatar

    authorize @classroom
  end

  # GET /classrooms/1/edit
  def edit
    @classroom = Classroom.find(params[:id])
    @classroom.build_avatar unless @classroom.avatar

    authorize @classroom
  end

  # POST /classrooms
  def create
    @classroom = Classroom.new(classroom_params)

    authorize @classroom

    if @classroom.save
      redirect_to classrooms_path, notice: 'Classroom was successfully created.'
    else
      render action: "new"
    end
  end

  # PUT /classrooms/1
  def update
    @classroom = Classroom.find(params[:id])

    authorize @classroom

    if @classroom.update(classroom_params)
      redirect_to edit_classroom_path(@classroom), notice: 'Classroom was successfully updated.'
    else
      render action: "edit"
    end
  end

  def add_student
    @classroom = Classroom.find(params[:id])
    @student = Student.find(params[:classroom][:student_ids][0])

    authorize @classroom

    @classroom.students << @student

    respond_to do |format|
      @count = @classroom.students.count
      format.js
    end
  end

  def remove_student
    @classroom = Classroom.find(params[:id])
    @student = Student.find(params[:classroom][:student_ids][0])

    authorize @classroom

    @classroom.students.delete(@student)

    respond_to do |format|
      @count = @classroom.students.count
      format.js
    end
  end

  # DELETE /classrooms/1
  def destroy
    @classroom = Classroom.find(params[:id])

    authorize @classroom

    @classroom.destroy

    redirect_to classrooms_path
  end

  private

  def classroom_params
    params.require(:classroom).permit(:name, :description, avatar_attributes: [:id, :avatar, :_destroy],
      :student_ids => [])
  end

end

Here are the models:

# student.rb
class Student < ActiveRecord::Base
  has_many :classroom_memberships, :dependent => :destroy, :inverse_of => :student
  has_many :classrooms, :through => :classroom_memberships
end

# classroom.rb
class Classroom < ActiveRecord::Base
  has_many :classroom_memberships, :inverse_of => :classroom, :dependent => :destroy
  has_many :munchkins, :through => :classroom_memberships
end


texts: Getting an array from one property of an associative array best practice

texts:
I have an array of objects eg.

[
   array(
    'id' => 1,
   'name' => "simon"
),
...
]

and I need to get an array of IDs eg.
[1,2,3,4,5];

Currently I'm doing this:

    $entities = $this->works_order_model->get_assigned_entities($id);

    $employee_ids = array();

    foreach ($entities as $entity) {
        array_push($employee_ids, $entity->id);
    }

Is there a best practice way of doing this?


texts:
Hi i needed to find the max int of a list using recursion, I have done it this way I'd like to know if you think is a good way, and I have a couple of questions:

int trovaMassimo(node_t *head){

    int e;
    if(head == NULL){//this can happen just the first time right?
        printf("Lista vuota\n");
        exit(1);
    }

    if(head->next == NULL)
        return head->val;

    e = trovaMassimo(head->next); //what will be assigned to e? doing this way doesn't e get modified all times till the last value? if yes isn't useless that if right under?

    if ( e < head->val )
        return head->val;
    else
        return e;
}

```


texts: An iterator which behaves like an array with uniform values

texts:
I'm implementing an iterator which takes a single value and which you can advance for n times with a dereferencing yielding the single value - but before or after that range of n 'positions' you can't dereference. So it's as though you filled a length-n std::vector with a single value and were taking a const iterator over it.

Imlementation is intentionally not thread-safe.

#include <stdexcept>
#include <iterator>
#include <cstddef>

template <typename E>
struct iterate_n_wrapper : public std::iterator<std::input_iterator_tag, E, size_t> {
    iterate_n_wrapper() = delete; // ... so it doesn't meet the forward iterator requirements
    iterate_n_wrapper(const iterate_n_wrapper<E>& other) = default;
    iterate_n_wrapper(const E& datum_, size_t times_)
        : datum(datum_), times(times_), pos(0) { };

    const E & operator[](off_t offset) const {
        auto offset_pos = pos + offset;
        if (offset_pos >= 0 && offset_pos < times) { return datum; }
        throw std::out_of_range("iteration range exceeded");
    }

    const E & operator *() const { return operator[](0); }
    const E * operator ->() const { return &(operator *()); }

    iterate_n_wrapper& operator ++() { pos++; return *this; }
    iterate_n_wrapper& operator --() { pos--; return *this; }

    iterate_n_wrapper operator ++(int) { auto ret = *this; operator++(); return ret; }
    iterate_n_wrapper operator --(int) { auto ret = *this; operator--(); return ret; }

    bool operator ==(const iterate_n_wrapper &other) const {
        return
            datum == other.datum &&
            times == other.times &&
            pos   == other.pos;
    }
    bool operator !=(const iterate_n_wrapper &other) const { return !operator==(other); }

protected:
    const E   datum;
    size_t    times;
    ptrdiff_t pos;
};

A simple example of use:

int main() {
    int a = 123;
    iterate_n_wrapper<int> iwa(a, 6);
    for(int i = 0; i < 4; i++) {
         std::cout << "iwa[" << i << "] = " << iwa[i] << "\n";
    }
    for(int i = 0; i < 100; i++) {
        std::cout << "i = " << i << ", got " << *(iwa++) << "\n";
    }
    return 0;
}

produces:

iwa[0] = 123
iwa[1] = 123
iwa[2] = 123
iwa[3] = 123
i = 0, got 123
i = 1, got 123
i = 2, got 123
i = 3, got 123
i = 4, got 123
i = 5, got 123
terminate called after throwing an instance of 'std::out_of_range'
  what():  iteration range exceeded
Aborted (core dumped)

so, the motivation is that this is a stand-in for an array/vector iterator when you can get the length from someplace else. Although I guess the lack of some kind of corresponding end() is a shortcoming.


texts:
I built an easy inheritance implementation for JavScript that works similar to other OO languages and wanted some feedback on it. This works perfectly how I'd like it to, but I've read a lot of varying opinions about using __proto__ and was wondering if there's a better way to do this.

jsFiddle

/**
 *
 * Extensible Prototype
 *
 */
Object.prototype.extends = function(obj){
        this.__proto__ = new obj;

        return this;
};

/**
 *
 * Parent Object
 *
 */
var Person = function(name){

        this.name = name;

        this.sayName = function(){
                alert(this.name);
        };

        return this;
};

/**
 *
 * Child Object
 *
 */
var Programmer = function(name){
        this.extends(Person);

        this.name = name;
        this.title = "Software Engineer";

        this.sayTitle = function(){
                alert(this.title);
        };
};

var eric = new Programmer('eric');
eric.sayName();
eric.sayTitle();


texts: PreserveIds using inheritance id db auto incrementing

texts:
I am working on this project where I like to PreserveIds once inserted into the database. The id are auto incrementing and I return them once the data in inserted. I like to know if there is a better way using inheritance vs using a for each loop and checking if the value is 0?

 class Program
    {
        static void Main(string[] args)
        {
            var States = new List<StatesModel>();
            var CaliforniaCity = new List<CityModel>();
            CaliforniaCity.Add(new CityModel() { Id = 2, Name = "Los Angeles" });
            CaliforniaCity.Add(new CityModel() { Id = 3, Name = "Sacramento" });
            CaliforniaCity.Add(new CityModel() { Id = 4, Name = "San Francisco" });
            States.Add(new StatesModel() { Id = 1, Name = "California", CityModels = CaliforniaCity });

            var PhiladelphiaCity = new List<CityModel>();
            PhiladelphiaCity.Add(new CityModel() { Id = 5, Name = "Philadelphia" });
            PhiladelphiaCity.Add(new CityModel() { Id = 6, Name = "Pittsburgh" });
            PhiladelphiaCity.Add(new CityModel() { Id = 7, Name = "Harrisburg" });
            States.Add(new StatesModel() { Id = 8, Name = "Pennsylvania", CityModels = PhiladelphiaCity });

            var MichiganCity = new List<CityModel>();
            MichiganCity.Add(new CityModel() { Id = 9, Name = "Detroit" });
            MichiganCity.Add(new CityModel() { Id = 10, Name = "Lansing" });
            MichiganCity.Add(new CityModel() { Id = 11, Name = "Grand Rapids" });
            States.Add(new StatesModel() { Id = 12, Name = "Michigan", CityModels = MichiganCity });

///Insert Data in database

            PreserveIds(States)

///Update data in database

            foreach (var State in States)
            {
                Console.WriteLine(string.Format("{0}", State.Name));
                Console.WriteLine(string.Format("{0} = {1}", State.Id ,State.OriginaId));
                foreach (var city in State.CityModels)
                {
                    Console.WriteLine(string.Format("{0}", city.Name));
                    Console.WriteLine(string.Format("{0} = {1}", city.Id, city.OriginaId));
                }
            }

        }

        public static void PreserveIds(IEnumerable<StatesModel> States)
        {
            if (States != null)
            {
                foreach (var State in States)
                {
                    if (State.OriginaId == 0)
                    {
                        State.OriginaId = State.Id;
                    }

                    foreach (var city in State.CityModels)
                    {
                        if (city.OriginaId == 0)
                        {
                            city.OriginaId = city.Id;
                        }
                    }
                }
            }
        }
    }

Model

    public class StatesModel
    {
        public int Id { get; set; }
        public int OriginaId { get; set; }
        public string Name { get; set; }
        public List<CityModel> CityModels { get; set; }
        public StatesModel()
        {
            CityModels = new List<CityModel>();
        }
    }

    public class CityModel
    {
        public int Id { get; set; }
        public int OriginaId { get; set; }
        public string Name { get; set; }
    }


texts: Identifying surface events happening at specific time intervals

texts:
Here is some code I wrote to surface Mint.com transactions that occur at monthly intervals, in order to identify subscriptions I may be paying for without realizing it.

I'd like to have some friends try this out as well, but Pandas is not a very common package for non-Python users, and it's requirement is keeping a lot of people from trying this out.

I'm looking for any advice to improve the code, or better recognize the 'monthly interval' piece (without Pandas would be even better).

import sys
from datetime import datetime

import pandas as pd

MINT_DATE_FORMAT = "%m/%d/%Y"
MINT_MERCH_COLUMN = "Description"
MINT_DATE_COLUMN = "Date"
MINT_AMT_COLUMN = "Amount"

def parse_date(datestring, format):
  return datetime.strptime(datestring,  format)

def calculate_date_diff(list):
  diffs = []
  for i in range(0,len(list)-1):
    diffs.append(diff_month(parse_date(list[i], MINT_DATE_FORMAT),
    parse_date(list[i+1], MINT_DATE_FORMAT)))
  return diffs

def diff_month(d1, d2):
  return(d1.year - d2.year)*12 + d1.month - d2.month

def unique_merchants(df, merch_column = MINT_MERCH_COLUMN):
  return df[merch_column].unique().tolist()

def merchant_price_txn_list(df, merchant_name,  txn_amount,
                      merch_column = MINT_MERCH_COLUMN, date_column = MINT_DATE_COLUMN,
                      amt_column = MINT_AMT_COLUMN):
  return df[(df[merch_column] == merchant_name) & (df[amt_column] == txn_amount)][date_column].tolist()

def unique_pricepoints(df, merchant_name,
                      merch_column = MINT_MERCH_COLUMN, amt_column = MINT_AMT_COLUMN):
    return df[(df[merch_column] == merchant_name)][amt_column].unique().tolist()

def main(csv):
  foo = pd.read_csv(csv)
  print("reading csv")
  print("Read rows:", len(foo.index))
  for merch in unique_merchants(foo):
    for pricepoint in unique_pricepoints(foo, merch):
      unique_mo_diffs = set(calculate_date_diff(
                         merchant_price_txn_list(foo, merch, pricepoint)))
      if len(merchant_price_txn_list(foo, merch, pricepoint)) < 3:
        pass
      elif unique_mo_diffs != {1}:
        pass
      else:
        date_list = merchant_price_txn_list(foo, merch, pricepoint)
        print merch, "\n", "$", pricepoint, "\n", date_list, "\n"

if __name__ == '__main__':
  txn_csv = sys.argv[1]
  main(txn_csv)


texts:
I have an array which handles all the games being hosting on the server. Users can host games and cancel the host as they please. What I have below seems to work, but I'm not sure if it adds the object to the lowest free index, but it adds them and removes just fine. The code is a bit of a mess so I've commented a lot to help you understand.

var hostingGames = [];

server.em.addListener('hostGame', function(settings)
{
    if (hostingGames.length != 0) //If the array that contains all the games being hosted, contains at least 1 game
        {
            for (i in hostingGames)//Scroll through every game being hosted
            {
                if(hostingGames[i] != null)//If the current index in the array does contain a game being hosted
                {
                    if(hostingGames[i].userId === settings.userId)//If the user thats trying to host a game, is already hosting a game
                    {
                        break; //Then break
                    }
                    else if (i == (hostingGames.length - 1))//If hes not hosting a game and all the games have finished being scrolled through
                    {
                        hostGame(settings, i + 1); //Then host one in the next avaliable space
                    }
                }
                else //If the game is null
                {
                    for(var i = 0; i < hostingGames.length; i++) //Scroll through the list of the games being hosted again
                    {
                        if(hostingGames[i] === null) //If theres a free slot
                        {
                            hostGame(settings, i); //Host a game
                        }
                    }
                }
            }
        }
        else
        {
            hostGame(settings, 0); //If there is no games currently being hosted, host one
        }

    function hostGame (settings, index)
    {
        var hostGame = new HostGame();

        hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote);
        hostingGames.splice(index, 0, hostGame);
        server.updateGamesList(hostingGames);

        server.consoleLog('APP', settings.userName + ' is hosting a game. ID: ' + settings.userId);
    }
});

server.em.addListener('cancelHostGame', function(userId, userName)
{
    for (i in hostingGames)//For every game
    {
        if (hostingGames[i] != null) //If its not null
        {
            if (hostingGames[i].userId === userId) //If that user is hosting a game
            {
                hostingGames.splice(i, 1); //Remove their game
                server.updateGamesList(hostingGames);

                server.consoleLog('APP', userName + ' has stopped hosting a game. ID: ' + userId);
            }
        }
    }
});


texts:
I have a repository method which retrieve a list of items, for example:

StaffID: 250026965
Name: Abbasov Islam
FreeTextName: NULL

StaffID: NULL
Name: NULL
FreeTextName: Antonio Puccio

StaffID: 358
Name: Prosinecki Robert
FreeTextName: NULL

I have to sort this list in this manner:

First the items with StaffID > 0 by Name, then the items with StaffID == NULL by FreeTextName.

In the example case:

StaffID: 250026965
Name: Abbasov Islam
FreeTextName: NULL

StaffID: 358
Name: Prosinecki Robert
FreeTextName: NULL

StaffID: NULL
Name: NULL
FreeTextName: Antonio Puccio

At the moment I am doing:

var resList = conn.Query<TeamSheetStaffPoco>("[dbo].[TList]", p, commandType: CommandType.StoredProcedure).AsList();
var result = resList.Where(x => x.StaffID> 0).OrderBy(y => y.Name).ToList();
result.AddRange(resList.Where(x => x.StaffID== null).OrderBy(y => y.FreeTextName).ToList());

It works, but I am not sure if exist a more concise and elegant mode to to do the same thing.


texts:
I am trying to generate a simple map like this. Everything works as I want, but I am new to programing. Is it a good way to do something like this? And if not, could someone explain to me where and why it is bad to do something like this? And how bad is it on performance?

public GameObject cube;
public GameObject cube1;
public GameObject cube2;
Vector3 here;

void Start () {
    for (int y = 0; y < 50; y++) {
        for (int x = 0; x < 10; x++) {
            here = new Vector3(x,y,0);
            int change = (int)Random.Range(0,19);
            switch (change){
            case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10:
                Instantiate(cube,here,Quaternion.identity);
                break;
            case 11: case 12: case 13: case 14: case 15: case 16:
                Instantiate(cube1,here,Quaternion.identity);
                break;
            case 17: case 18:
                Instantiate(cube2,here,Quaternion.identity);
                break;
            }
        }
    }

Running this code generates something random like this:

Instantiate takes 3 things (GameObject you want to make, coordinates where to make it, and rotation), and it makes a copy of GameObject - prefab in those coordinates.

Cube - Red
Cube1 - Green
Cube2 - Blue

The reason for all of this is that I want to learn to make something random likea  map area of the game.


texts:
I wanted to create a function describing a sport game called "Leader". The idea is that you make as many push-ups as you can, increasing each repetition by 1 and as you reach your maximum, each next repetition is decreased by 1 until you reach 0 push-ups eventually.

I managed to do this using dictionaries, but I think this could be done in much easier way.

from typing import List, Tuple

def leader_step(max_pushups, step): # maximum pushups a person can do and a step of increment
    i = 0  # count of the repetitions
    pushups: List[Tuple[int, int]] = [(0, 0)]  # number of pushups at the beginning (at each repetition, it total)
    while pushups[i][0] <= max_pushups + abs(step): # +abs(step) in case step > 1
        if pushups[i][0] >= max_pushups:  # decrease push-ups as they reach max
            step = -step
        i += 1
        now = step + pushups[i - 1][0]
        sum = now + pushups[i - 1][1]  # counting the sum of all push-ups by adding previous sum and current pushups
        pushups.insert(i, (now, sum))
        if pushups[i][0] < 1:  # game stops when you reach 0 push-up
            break
    return pushups[1:-1]

Function should return 2 sequences:

showing the number of push-ups at each repetition
showing total sum of push-ups made at each repetition


texts:
Is there anything wrong with doing this:

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        For value As Integer = 0 To 1000000
            Dim p As New Person
            p.ID = value
            p.DoSomething()
            p = Nothing
        Next
    End Sub
    Public Class Person
        Dim _ID As Integer
        Public WriteOnly Property ID() As Integer
            Set(ByVal value As Integer)
                _ID = value
            End Set
        End Property

        Public Sub DoSomething()
            _ID = _ID + 1
            'Do more with ID
        End Sub
    End Class
End Class

As appose to this:

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        For value As Integer = 0 To 1000000
            Person.DoSomething(value)
        Next
    End Sub
    Public Class Person
        Public Shared Sub DoSomething(ByVal id As Integer)
            id = id + 1
            'Do more with ID
        End Sub
    End Class

End Class

I have written some code similar to that in sample 1. I have read online that code 1 can cause problems when threading is involved, but I do not understand why? Are there any other problems with sample 1? Sample 1 meets my requirements better.


texts: Insert an array[4] to an array[8] (C++, SSE)

texts:
I have this code to get audio output levels in dB to an array (peak_dB[8]) to be used in real time peakmeter:
#include <emmintrin.h>

float channelsPeak[8] = { 0 };
float peak_dB[8] = { 0 };

__m128 log2_sse(__m128 x) {
  // https://www.kvraudio.com/forum/viewtopic.php?p=7524831#p7524831
  // 12-13ulp
  const __m128 c0 = _mm_set1_ps(1.011593342e+01f);
  const __m128 c1 = _mm_set1_ps(1.929443550e+01f);
  const __m128 d0 = _mm_set1_ps(2.095932245e+00f);
  const __m128 d1 = _mm_set1_ps(1.266638851e+01f);
  const __m128 d2 = _mm_set1_ps(6.316540241e+00f);
  const __m128 one = _mm_set1_ps(1.0f);
  const __m128 multi = _mm_set1_ps(1.41421356237f);
  const __m128i mantissa_mask = _mm_set1_epi32((1 << 23) - 1);
  __m128i x_i = _mm_castps_si128(x);
  __m128i spl_exp = _mm_castps_si128(_mm_mul_ps(x, multi));
  spl_exp = _mm_sub_epi32(spl_exp, _mm_castps_si128(one));
  spl_exp = _mm_andnot_si128(mantissa_mask, spl_exp);
  __m128 spl_mantissa = _mm_castsi128_ps(_mm_sub_epi32(x_i, spl_exp));
  spl_exp = _mm_srai_epi32(spl_exp, 23);
  __m128 log2_exponent = _mm_cvtepi32_ps(spl_exp);
  __m128 num = spl_mantissa;
  num = _mm_add_ps(num, c1);
  num = _mm_mul_ps(num, spl_mantissa);
  num = _mm_add_ps(num, c0);
  num = _mm_mul_ps(num, _mm_sub_ps(spl_mantissa, one));
  __m128 denom = d2;
  denom = _mm_mul_ps(denom, spl_mantissa);
  denom = _mm_add_ps(denom, d1);
  denom = _mm_mul_ps(denom, spl_mantissa);
  denom = _mm_add_ps(denom, d0);
  __m128 res = _mm_div_ps(num, denom);
  res = _mm_add_ps(log2_exponent, res);
  return res;
}
__m128 lin2db(__m128 x) {
  const __m128 convert_10 = _mm_set1_ps(6.02059991328f);
  return _mm_mul_ps(log2_sse(x), convert_10);
}

float getPeaks_dB(int cCount) { // cCount = enabled channels (1...8)
    __m128 s1 = _mm_setzero_ps();

    s1 = _mm_set_ps(channelsPeak[3], channelsPeak[2], channelsPeak[1], channelsPeak[0]); //channels 1-4
    s1 = lin2db(s1);
    _mm_store_ps(peak_dB, s1);

    if(cCount > 4){
        float t2[4] = { 0 };
        __m128 s2 = _mm_setzero_ps();
        s2 = _mm_set_ps(channelsPeak[7], channelsPeak[6], channelsPeak[5], channelsPeak[4]); // channels 5-8
        s2 = lin2db(s2);

        _mm_store_ps(t2, s2);
        for (int i = 4; i < 8; i++){peak_dB[i] = t2[i-4];}
    }
    return 0;
}

where float channelsPeak[0..7] array is storage for linear levels (0.0f..1.0f) of  eight channels read from audio rendering device (one GetChannelsPeakValues() call), peak_dB is array of eight elements to hold this value in dB format (to be used in some later calculations and textual representation) and lin2db is 20log10(x) approximation (faster (because of lower accuracy) than std::log10) implemented using SSE intrinsics.
Q: Are there other (better) ways to insert data from s2 into last four elements of peak_dB (AVX excluded)?
I'm using VS2013 and, by Compiler Explorer, compiler seem to improve for-loop as used in code now but, as the 1st part in peak_dB stored with _mm_store_ps(peak_dB, s1) looks there much simpler, just wondering if there's a way doing it without for-loop.


texts: Function to convert a decimal number as a string to hexadecimal

texts:
I am designing a cipher and need to convert between bases repeatedly in a loop.  I have optimized everything else, but I'm not too familiar with C++ code, and and am trying to figure out how to make the conversion faster.

string digits = "0123456789abcdef";
string tohex(string number) {                        // Decimal to Hexadecimal function
    long length = number.length();
    string result = "";
    vector<long> nibbles;
    for ( long i = 0; i < length; i++ ) {
        nibbles.push_back(digits.find(number[i]));
    }
    long newlen = 0;
    do {
        long value = 0;
        newlen = 0;
        for ( long i = 0; i < length; i++ ) {
            value = (value * 10) + nibbles[i];
            if (value >= 16) {
                nibbles[newlen++] = value / 16;
                value %= 16;
            } else if (newlen > 0) {
                nibbles[newlen++] = 0;
            };
        };
        length = newlen;
        result = digits[value] + result;
    } while (newlen != 0);
    return result;
}


texts:
I've been implementing a custom internal server error page in ASP.Net MVC which will check if the current user is either an administrator or accessing the page from localhost, and if so, show them a whole bunch of details about the error to debug it with, otherwise just send them to a basic HTML error page.

So far, it works great, but one problem I had was that if there is an error in a partial view on the page, the system gets stuck in a loop trying to report the error.

To avoid this, I'm storing a temporary counter of how many times the current action has requested the error page in TempData, but I find the amount of lines and style of the code to get, set and check this variable a bit verbose:

using System.Web.Mvc;

namespace Test
{
    public class ErrorController : Controller
    {
        [ActionName("500")]
        public ActionResult InternalServerError(string aspxerrorpath = null)
        {
            int detectRedirectLoop = (TempData.Peek("redirectLoop") as int?) ?? 0;
            TempData["redirectLoop"] = detectRedirectLoop + 1;
            if((int) TempData.Peek("redirectLoop") <= 1)
            {
                // Check if user is admin or running locally and display error if so
            }
            return Redirect("/GeneralError.htm");
        }
    }
}

Is there a better/prettier/shorter way of doing this?


texts: Assigning an array of different (but convertible) type to concurrency::array in C++AMP

texts:
I am creating a vector class which can be manipulated on the GPU and I am using C++AMP for the GPU accelerated code.

I am wondering the most efficient way of assigning elements of a different type to a concurrency::array in C++AMP. There are two ways that I can think of (but there may be more):

Firstly, one could use a simple sequential for loop and use the concurrency::array_view object to assign the data members and then call concurrency::array_view::synchronize at the end to ensure the data is stored on the accelerator for subsequent operations, this would look like following:

template <typename T>
CVector& operator=( T tArray[Size] )
{
    static_assert( std::is_convertible<T, NumType>::value, "Cannot assign a vector from an array of non-convertible type" );

    concurrency::array_view<NumType, 1> avThis( m_numArray.view_as( m_numArray.extent ) );

    for( std::size_t s = 0; s < Size; ++s )
    {
         avThis(s) = static_cast<NumType>(tArray[s]);
    }

    avThis.synchronize();
    return *this;
}

Alternatively, one could construct a concurrency::array_view from the array and then use a concurrency::parallel_for_each to assign the data members as follows:

template <typename T>
CVector& operator=( T tArray[Size] )
{
    static_assert( std::is_convertible<T, NumType>::value, "Cannot assign a vector from an array of non-convertible type" );

    concurrency::array_view<const T, 1> avArray( Size, tArray );

    concurrency::parallel_for_each( m_numArray.extent, [=, &m_numArray]( concurrency::index<1> index ) restrict(amp) {
         m_numArray[index] = static_cast<NumType>(avArray[index]);
    } );

    return *this;
}

Which of these methods results in better performance or are they equal?

I profiled the code, and using the Microsoft Concurrency Visualizer, produced the following graph:


texts: Convenience function wrapping C++17's std::sample for distance=1 case

texts:
C++ has the function std::sample which randomly samples from a range and places the results via an output iterator. My goal is to create a utility that directly returns a single value in the event that we only want to sample a single random element from the container.
#include <iostream>
#include <random>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <array>

template<class InputIt, class URBG>
auto singleRandomSample(InputIt t_begin, InputIt t_end, URBG&& rng)
{
    using value_type = typename std::iterator_traits<InputIt>::value_type;
    std::array<value_type, 1> out;
    std::sample(t_begin, t_end, out.begin(), 1, rng);
    return out.at(0);
}

int main()
{
    std::default_random_engine rng{ std::random_device{}() };
    std::unordered_set<char> vowels{ 'a', 'e', 'i', 'o', 'u', 'y' };
    for (std::size_t i = 0; i < 10; ++i)
    {
        auto randomVowel = singleRandomSample(vowels.begin(), vowels.end(), rng);
        std::cout << "Random vowel: " << randomVowel << '\n';
    }
}

This function creates a temporary container out to which a single element is added, then returns that element by value. It uses an std::array because I know I only need room for a single element, although if I decided it was important to be able to use this with non-default-constructible types I could switch to a std::vector and a std::back_inserter.
Is it correct to call std::sample using rng as an argument directly, or should I be using std::forward(rng)?
It feels slightly clunky to have an entire temporary container just to store a single value that's immediately returned. Is there another way this functionality could be implemented?


texts:
There have been a number of questions asking for comments on code for the Project Euler problem to compute the largest prime factor of a number. A primary intent of this task is to find the factor as quickly as possible.

I decided to implement the code in C++ using at least some approximation of the best techniques/algorithms of which I was aware1.

#include <iostream>
#include <vector>
#include <time.h>

typedef unsigned long long integer;

const integer input = 60085147514377;

class prime_table {
    std::vector<integer> primes;
public:
    prime_table(integer num) {
        integer max = ceil(sqrt(num));
        std::vector<bool> table;
        table.resize(max, false);

        for (int i = 2; i < max; i++) {
            if (!table[i]) {
                primes.push_back(i);
                for (integer temp = 2 * i; temp < max; temp += i)
                    table[temp] = true;
            }
        }
    }

    unsigned size() {   return primes.size();   }

    integer back() { return primes.back(); }

    integer operator[](unsigned index) {    return primes[index];   }

    integer prime_factor(integer input) {
        for (int i = 0; primes[i] * primes[i] <= input; i++)
            if (input % primes[i] == 0)
                return prime_factor(input / primes[i]);
        return input;
    }
};

int main() {
    prime_table s(input);

    integer current = 1;

    clock_t start = clock();
    for (int i = 0; i < s.size(); i++) {
        if ((input % s[i]) == 0) {
            if (s[i]>current)
                current = s[i];
            integer candidate = input / s[i];
            candidate = s.prime_factor(candidate);
            if (candidate > current) {
                current = candidate;
                if (current > s.back())
                    break;
            }
        }
    }
    clock_t stop = clock();
    std::cout << "\n" << current << "\n";
    std::cout << "Time: " << double(stop - start) / CLOCKS_PER_SEC << " seconds\n";
}

Unfortunately, this has the exact opposite problem most attempts do: rather than taking far too long to run, it runs so fast that much of the time it simply shows the minimum interval (1 millisecond) the clock implementation I'm using can measure. Worse, a substantial part of the time, it shows up as running in 0 milliseconds.

To try to get a better idea of the speed, I chose a somewhat larger number to factor -- specifically I tacked 77 on the end to get of the input suggested by Project Euler to get 60085147514377. The code above gives the largest prime factor as 345937 (which Wolfram Alpha agrees is the largest prime factor of this number) in about 9 or 10 milliseconds.

Specific question: implicit in almost any question like this is one of whether further improvements in speed can be achieved easily. I'm reasonably certain there is room for improvement in the sieving part.

I'm also somewhat uncertain about the number theory part--I think this is correct, and it produces correct results for every test I've tried, but I feel slightly less than 100% certain that there couldn't be some input for which it could produce an incorrect result.

1. I'm aware, for example, that the sieve of Atkins is at least theoretically faster than the sieve of Eratosthenes, but it apparently requires fairly non-trivial code to actually achieve that theoretical speedup so I haven't attempted to implement it here.


texts: Retrieving Primary Key from Entity Framework entity

texts:
Entity Framework (version 6) generates classes based on your tables that look like this (where each property represents a field in the table):

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("dbo.MyTable")]
public partial class MyTable {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int MyTableID { get; set; }

    [Required]
    [StringLength(128)]
    public string SomeColumn { get; set; }

    public DateTime CreatedDate { get; set; }
}

I decided to provide a little more functionality, specifically a way to return an array containing the primary key of any given table. A primary key can be made up of multiple fields, and each field can be a different type. I came up with the following, using reflection and LINQ:

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

public abstract class Entity
{
    public object[] PrimaryKey
    {
        get
        {
            return (from property in this.GetType().GetProperties()
                    where Attribute.IsDefined(property, typeof(KeyAttribute))
                    orderby ((ColumnAttribute)property.GetCustomAttributes(false).Single(
                        attr => attr is ColumnAttribute)).Order ascending
                    select property.GetValue(this)).ToArray();
        }
    }
}

I then modify each of my Entity Framework table classes to inherit Entity (ie public partial class MyTable : Entity { ... }), so they get the PrimaryKey functionality.

A return type of object[] made the most sense - EntityFramework's DbSet has functions such as Find(params object[] args), where the return value of my PrimaryKey property slots neatly in.

First time using LINQ, and I'm not hugely experienced with reflection, attributes or the Entity Framework. Are there any problems/gotchas with this, or any improvements?


texts: Relying on short-circuit evaluation instead of using the IF control structure

texts:
Examples of where I've started migrating to short-circuit evaluation:

PHP

$id=0;//initialized in case of no result
$r=mysql_query(SQL);
if($r && mysql_num_rows($r)>0){
  list($id)=mysql_fetch_row($r);
}

becomes

$id=0;
$r=mysql_query(SQL);
$r && mysql_num_rows($r)>0 && list($id)=mysql_fetch_row($r);

JavaScript

var Req=jQuery.ajax(OBJECT);
//Something has happened and now i want to abort if possible
if(Req && Req.abort){
  Req.abort();
}

becomes

var Req=jQuery.ajax(OBJECT);
//Something has happened and now i want to abort if possible
Req && Req.abort && Req.abort();

I'm familiar with the short if style of

if(Req && Req.abort) Req.abort();

but it feels clunkier than short-circuit evaluation.


texts:
This was written for a coding challenge for a company I recently starting working for. I'm looking for any suggestions on how to clean up the code, as well as any issues anyone thinks may occur as it is written now. Fairly new to React.js, always looking to improve.

Currently the data is passed through the app component where I render the Nav Container (functional stateless component). The Nav container creates the classNames and passes data + classNames to the NestedNav that I've put below.

It started to feel a little sloppy while mapping twice below the render, not sure if that's a problem?

The data object example shows how I modeled my data. This example has a parent with children that also have children.

The parentClass is for the outer parent.
The nestedParentClass is for the children of the outer parent.
The childClass is reserved for any children of the nestedParent.

export const data = [
{
    id: 1,
    icon: <FontAwesomeIcon className='i' icon={faHeartbeat} />,
    title: 'SAFETY',
    children: [
      {title: 'Reporting', children: [
        {id: 11, title: 'I-21 Injury Reporting', url: '/safety/report'},
        {id: 12, title: 'ASAP Reporting', url: '/safety/asap-report'},
        {id: 13, title: 'General ASAP Information', url: '/safety/general'},
        {id: 14, title: 'Flight Attendant Incident Report', url: '/safety/flight-attendant-incident'},
      ]},
      {title: 'Agriculture and Customs', children: [
        {id: 15, title: 'Product Safety Data Search', url: '/safety/data-search'}]},
      {id: 16, title: 'Known Crewmember', url: '/safety/known-cremember'},
      {id: 17, title: 'Product Safety Data Search', url: '/safety/data-search'},
    ],
  },
 ]

class NestedNav extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selected: '',
      nestSelect: '',
      children: [],
      active: '',
    }
  }

 handleClick = (title) => {
   this.setState({
     selected: '',
     nestSelect: '',
     children: [],
     active: '',
   })
 }

 render() {

   const {data, parentClass, nestedParentClass} = this.props
   const renderedChildElements = this.state.children
   const active = this.state.active === 'true' ? 'true' : ''

   const mappedChildren = (child, title) => {
     let childElement
     if(child) {
       childElement = child.map((child, i) =>
<Link to={'/'}>{child.title}</Link>
         {child.children ?
           <FontAwesomeIcon
             onClick={() => mappedChildren(child.children, this.state.select)}
             className='i button'
             icon={faArrowCircleDown} /> : null}

)
       this.setState({
         selected: title,
         children: childElement,
         active: 'true',
       })
     }
     return ''
   }

   const navListItems = data.map((collection, i) =>
{collection.icon}<Link to={'/'}>{collection.title}</Link>
     {collection.children ?
       <FontAwesomeIcon
         onClick={() => mappedChildren(collection.children, collection.title)}
         className='i button'
         icon={faArrowCircleRight} /> : null}

)

   return (

{this.state.selected}

         {this.state.children}

{navListItems}

   )
 }
}
export default NestedNav


texts: C# asynchronous tasks training (turn-based simulation)

texts:
I know embarassingly little about asynchronous programming in C#, so decided to start catching up. It would help me a lot if anyone checked this basic example I've created.
Assumption: we're creating a simulation where the time passes turn by turn with predefined minimal interval, e.g. 1 second. However, if any important calculations during the turn would take longer than this interval, next turn should not begin until they're done.
I would be grateful if you could tell me if there any visible issues, code smells, or if it can be optimized. I've read bad things about using Task.Run, but I don't really know how to tackle it better.
public static class Program
{
    static void Main()
    {
        var gameTurnsController = new GameTurnsController();
        var cts = new CancellationTokenSource();

        try
        {
            // Asynchronously wait for input to send cancellation token
            Task.Run(() =>
            {
                Console.ReadKey(true);
                cts.Cancel();
            });

            gameTurnsController.PassTurns(TimeSpan.FromSeconds(1), cts.Token).Wait(cts.Token);
        }
        // It smells of controlling the execution flow through exception. Isn't there a better way to handle cancellation?
        catch (OperationCanceledException)
        {
            Console.WriteLine(Environment.NewLine + "Cancelled.");
            Environment.ExitCode = 0;
        }

        Console.WriteLine("Execution finished.");
    }
}

public class GameTurnsController
{
    public async Task PassTurns(TimeSpan interval, CancellationToken cancellationToken)
    {
        while (true)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            // Wait until both delay and calculation is finished
            await Task.WhenAll(Task.Delay(interval, cancellationToken), LongRunningOperation(cancellationToken));
        }
    }

    // expensive method example
    private async Task<long> LongRunningOperation(CancellationToken cancellationToken)
    {
        return await Task.Run(() =>
        {
            long result;
            // ...
            // expensive math operation that returns long value
            // ...
            return result;
        }, cancellationToken);
    }
}

In the above code I've removed most of the logs and stopwatches for clarity.


texts:
I have a server that uses Java NIO in non-blocking mode. Right now I'm using a single thread for the selector, and four worker threads to process the bytes after the selector reads them in. I'm going to switch to a thread pool soon enough. Anyway, that's not why I'm here.

Take a look at the code below. I have a state object of type CommunicationStatus called commsState which maintains various parameters relating to the SocketChannel, the number of bytes read, the current working state, whether the message is complete or not, the ByteBuffer for that particular SocketChannel, etc. This works well. The CommunicationStatus object is attached to the SelectionKey when the SocketChannel is registered with the Selector.

When I'm checking key.readyOps() to check what state the channel is in, I have an additional check within the OP_READ and OP_WRITE checks to make sure that the worker threads have finished processing the work before additional bytes are read from or written to the SocketChannel.
So for example, if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) returns true but if (commsState.getCurrentState() == CommunicationStatus.STATE_READ) returns false then no bytes will be read at this time.
I find this works really well, but is it the correct way to do things?
Is there a better way I could handle this?
Any other comments or thoughts are appreciated too.

private boolean running;
private ServerSocketChannel serverSocketChannel;

@Override
public void run() {

    try {

        Selector selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.bind(new InetSocketAddress(serverPort));

        log.info("Selector Thread: FirmwareServer " + FirmwareServer.SERVER_VERSION
                + " Runnable- Listening for connections on port: " + serverSocket.getLocalPort());

        running = true;

        @SuppressWarnings("unused")
        SelectionKey serverAcceptKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (running) {

            try {

                selector.select();
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

                while (keyIterator.hasNext()) {

                    SelectionKey key = (SelectionKey) keyIterator.next();
                    keyIterator.remove();

                    if (!key.isValid()) {
                        continue;
                    }
                    CommunicationStatus commsState = (CommunicationStatus) key.attachment();

                    if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                        acceptConnection(selector, key);

                    } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        if (commsState.getCurrentState() == CommunicationStatus.STATE_READ) {

                            commsState.setSelectionKey(key);
                            readFromSocketChannel(key);

                        }
                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        if (commsState.getCurrentState() == CommunicationStatus.STATE_WRITE) {

                            commsState.setSelectionKey(key);
                            writeToSocketChannel(key);

                        }
                    }
                }

            } catch (IOException e) {
                log.error("Selector IOException Occurred", e);
            }
        }

    } catch (IOException e) {

        log.error("Firmware Selector Thread: An IOException occurred", e);
        System.exit(-1);

    }

}


texts: C++ templates for sin, cos, tan taylor series

texts:
I used C++ metaprogramming to build taylor series for sin, cos, and tan (not really for tan). The whole thing is on my github. Please give any feedback related (but not limited) to style, functionality, etc.

Overall I think the biggest flaw is that the client needs to make their own struct with a static const long double member called value, and pass that struct to the "functions." I would have just passed the double, but C++ doesn't let you use floating-point numbers as template arguments. Using a struct was the only way I could think of to get around that.

Thanks!

#ifndef TRIG_HPP
#define TRIG_HPP

namespace mt
{
    const long double PI = 3.14159265358979323f;

    // FACTORIAL

    template <int N> struct fact
    {
        static const long long value = N * fact<N-1>::value;
    };

    template <> struct fact<1>
    {
        static const long long value = 1L;
    };

    // EXPONENTS

    template <class X, int N> struct power
    {
        static const long double value;
    };

    template <class X, int N> const long double power<X, N>::value = X::value * power<X, N-1>::value;

    template <class X> struct power<X, 0>
    {
        static const long double value;
    };

    template <class X> const long double power<X, 0>::value = 1.0f;

    // SIMPLIFY RADIAN TO INTERVAL [-2π, 2π]

    template <class X> struct SimplifyRad
    {
        static const long double value;
    };

    template <class X> const long double SimplifyRad<X>::value =

        X::value - (2 * PI * (double) (int) (X::value/(2*PI))); // float modulo?

    // COSINE

    template <class X, int N> struct cos
    {
        static const long double value;
    };

    template <class X, int N> const long double cos<X, N>::value =

        (((N % 2 == 0 ? 1 : -1) * power<SimplifyRad<X>, 2*N>::value) / ((long double) fact<2*N>::value)) + cos<X, N-1>::value;

    template <class X> struct cos<X, 0>
    {
        static const long double value;
    };

    template <class X> const long double cos<X, 0>::value = 1.0f;

    // SINE

    template <class X, int N> struct sin
    {
        static const long double value;
    };

    template <class X, int N> const long double sin<X, N>::value =

        (((N % 2 == 0 ? -1 : 1) * power<SimplifyRad<X>, 2*N-1>::value) / ((long double) fact<2*N-1>::value)) + sin<X, N-1>::value;

    template <class X> struct sin<X, 0>
    {
        static const long double value;
    };

    template <class X> const long double sin<X, 0>::value = 0.0f;

    // TANGENT

    template <class X, int N> struct tan
    {
        static const long double value;
    };

    template <class X, int N> const long double tan<X, N>::value = sin<X, N>::value / cos<X, N>::value;
}

#endif

Example usage:

#include <cstdio>
#include "../include/trig.hpp"

#define DEPTH 8

struct var
{
    static const long double value;
};

const long double var::value = mt::PI / 4;

int main(int argc, char *argv[])
{
    printf("%Lf\n", var::value);
    printf("sin(%Lf) = %Lf\ncos(%Lf) = %Lf\ntan(%Lf) = %Lf\n",
            var::value, mt::sin<var, DEPTH>::value,
            var::value, mt::cos<var, DEPTH>::value,
            var::value, mt::tan<var, DEPTH>::value);
}

Output:

$ g++ main.cpp
$ ./a.exe
0.785398
sin(0.785398) = 0.707107
cos(0.785398) = 0.707107
tan(0.785398) = 1.000000


texts: Writing/reading data structure to a file using C++

texts:
I wrote some piece of code which reads and write multiple data structures on a file
using C++. I would be grateful to get your feedback on what you think about the code (it works at least when I tested). Thanks.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

// data structure to be written to a file
struct WebSites
{
    char SiteName[100];
    int Rank;
}s1,s2,s3,s4;

int _tmain(int argc, _TCHAR* argv[])
{
    strcpy(s1.SiteName, "www.ppp.com");
    s1.Rank = 0;

    strcpy(s2.SiteName, "www.rrr.com");
    s2.Rank = 111;

    strcpy(s3.SiteName, "www.code.com");
    s3.Rank = 123;

    strcpy(s4.SiteName, "www.yahoo.com");
    s4.Rank = 14;

    // write
    fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
    binary_file.write(reinterpret_cast<char *>(&s1),sizeof(WebSites));
    binary_file.write(reinterpret_cast<char *>(&s2),sizeof(WebSites));
    binary_file.write(reinterpret_cast<char *>(&s3),sizeof(WebSites));
    binary_file.write(reinterpret_cast<char *>(&s4),sizeof(WebSites));
    binary_file.close();

    // Read data
    fstream binary_file2("c:\\test.dat",ios::binary|ios::in| ios::ate );
    int size = binary_file2.tellg();
    for(int i = 0; i<size/sizeof(WebSites); i++)
    {
        WebSites p_Data;
        binary_file2.seekg(i*sizeof(WebSites));
        binary_file2.read(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));

        cout<<p_Data.SiteName<<endl;
        cout<<"Rank: "<< p_Data.Rank<<endl;
    }
    binary_file2.close();

    return 0;
}


texts:
This is a function that converts an integer value to a null-terminated string using the specified base and stores the result in a char array that I must allocate (with malloc). I have decided not to use malloc. Allowed functions: malloc. Loops: while Please review my code.

char *itoa_base(int value, int base)
{
    static  char rep[] = "0123456789abcdef";
    static  char buf[50];
    char    *ptr;
    int     num;

    ptr = &buf[49];
    *ptr = '\0';
    num = value;
    if (value < 0 && base == 10)
        value *= -1;
    if (value == 0)
        *--ptr = rep[value % base];
    while (value != 0)
    {
        *--ptr = rep[value % base];
        value /= base;
    }
    if (num < 0 && base == 10)
        *--ptr = '-';
    return (ptr);


texts:
This is based off the popular Pokemon Turn Based project (here).

  GOAL

  Write a simple game that allows the user and the computer to take
  turns selecting moves to use against each other. Both the computer and
  the player should start out at the same amount of health (such as
  100), and should be able to choose between the three moves:

  The first move should do moderate damage and has a small range (such as 18-25).
  The second move should have a large range of damage and can deal high or low damage (such as 10-35).
  The third move should heal whoever casts it a moderate amount, similar to the first move.

  After each move, a message should be printed out that tells the user
  what just happened, and how much health the user and computer have.
  Once the user or the computer's health reaches 0, the game should end.

  SUBGOALS

  When someone is defeated, make sure the game prints out that their health has reached 0, and not a negative number.
  When the computer's health reaches a set amount (such as 35%), increase it's chance to cast heal.
  Give each move a name.

I am new to Python and I am trying to use OOP. Did I use my classes properly and is there a way to reduce the number of if statements in my code? Since this is my first code review, how is the formatting, number of comments, etc?

import random

class Pokemon:

    """Blueprint for turn based Pokemon battle"""

    def __init__(self, attack_choice):

        self.__attack_choice = attack_choice

    def attack(self):

        if self.__attack_choice == 1:
            attack_points = random.randint(18,25)
            return attack_points

        elif self.__attack_choice == 2:
            attack_points = random.randint(10,35)
            return attack_points

        else:
            print("That is not a selection. You lost your turn!")

    def heal(self):

        heal_points = random.randint(18,25)
        return heal_points

###########################################################################

user_health = 100
mew_health = 100
battle_continue = True

while battle_continue == True:
    print("\nATTACK CHOICES\n1. Close range attack\n2. Far range attack\n3. Heal")
    attack_choice = eval(input("\nSelect an attack: "))

    # Mew selects an attack, but focuses on attacking if health is full.
    if mew_health == 100:
        mew_choice = random.randint(1,2)

    else:
        mew_choice = random.randint(1,3)

    mew = Pokemon(mew_choice)
    user_pokemon = Pokemon(attack_choice)

    # Attacks by user and Mew are done simultaneously.
    if attack_choice == 1 or attack_choice == 2:
        damage_to_mew = user_pokemon.attack()
        heal_self = 0
        print("You dealt",damage_to_mew,"damage.")

    if mew_choice == 1 or mew_choice ==2:
        damage_to_user = mew.attack()
        heal_mew = 0
        print("Mew dealt", damage_to_user, "damage.")

    if attack_choice == 3:
        heal_self = user_pokemon.heal()
        damage_to_mew = 0
        print("You healed",heal_self,"health points.")

    if mew_choice == 3:
        heal_mew = mew.heal()
        damage_to_user = 0
        print("Mew healed", heal_mew, "health points.")

    user_health = user_health - damage_to_user + heal_self
    mew_health = mew_health - damage_to_mew + heal_mew

    # Pokemon health points are limited by a min of 0 and a max of 100.
    if user_health > 100:
        user_health = 100

    elif user_health <= 0:
        user_health = 0
        battle_continue = False

    if mew_health > 100:
        mew_health = 100

    elif mew_health <= 0:
        mew_health = 0
        battle_continue = False

    print("Your current health is", user_health)
    print("Mew's current health is", mew_health)

print("Your final health is", user_health)
print("Mew's final health is", mew_health)

if user_health < mew_health:

    print("\nYou lost! Better luck next time!")

else:

    print("\nYou won against Mew!")


texts: MVC Controller Error & Exception Handling .NET Core

texts:
I'm putting together a basic web app in .NET core 2.1 MVC to try and better understand how it works. Currently I'm working on returning validation to the UI. Once I have this working I then want to use the same service class for a Web API front end too.

Currently the Create Action in the Controller calls the service layer, which returns my ValidationResultModel. This is then checked and errors are displayed or redirected to the index if all was ok.

[HttpPost]
[ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateSupplierViewModel createSupplierViewModel)
    {
        if (ModelState.IsValid)
        {
            Suppliers suppliers = _mapper.Map<Suppliers>(createSupplierViewModel);
            SuppliersService suppliersService = new SuppliersService(_context);
            ValidationResultModel returnData = suppliersService.Add(suppliers);
            if(returnData.Message== "Success")
            {
                return RedirectToAction(nameof(Index));
            }

            foreach (ValidationError ve in returnData.Errors)
            {
                ModelState.AddModelError(ve.Field, ve.Message);
            }
        }
        return View(createSupplierViewModel);
    }

In the supplierService Add Method I check if the accounts ID has been used, and run some other fluentvalidaion in the SupplierValidator class

public ValidationResultModel Add(Suppliers newSupplier)
    {
        ValidationResultModel vrm = new ValidationResultModel();

        var suppliers = _stockContext.Suppliers.Where(supplier => supplier.AccountsId == newSupplier.AccountsId).FirstOrDefault();
        if (suppliers != null)
        {
            vrm.Message = "Failure";
            ValidationError re = new ValidationError("AccountsId", "This Accounts ID already exists");
            vrm.Errors.Add(re);
        }

        SupplierValidator supplierValidator = new SupplierValidator();
        var results = supplierValidator.Validate(newSupplier);
        if (!results.IsValid)
        {
            foreach (var validationError in results.Errors)
            {
                vrm.Message = "Failure";
                vrm.Errors.Add(new ValidationError(validationError.PropertyName, validationError.ErrorMessage));
            }
        }

        if (vrm.Message != "Failure")
        {
        _stockContext.Add(newSupplier);
        _stockContext.SaveChanges();
    }

        return vrm;
    }

Validation Classes:

public class ValidationError
{

    public string Field { get; }

    public string Message { get; }

    public ValidationError(string field, string message)
    {
        Field = field != string.Empty ? field : null;
        Message = message;
    }
}

public class ValidationResultModel
{
    public string Message { get; set; }

    public List<ValidationError> Errors { get; set; }

    public ValidationResultModel()
    {
        Message = "Success";
        Errors = new List<ValidationError>();
    }
}

Everything is functioning, but it feels very clunky. One of my main worries is what happens when I want to send back something in addition to the ValidationResultModel.
Is there a better way of doing this. Or indeed a set of Core classes that do exactly this, that I need to read up on?


texts:
I have the following diagram (did this only to ask here, it's obviously missing details):

From the diagram you can see I have to check if all sensors in an environment are respecting the established conditions, but I'm not comfortable with the way I'm implementing this...

class Environ:

    def __init__(self):
        self.load_conditions()
        self.load_modules()

    def load_modules(self):
        self.modules = []
        # Don't like this!
        m = Module(self.conditions)
        self.modules.append(m)

    def run_modules(self):
        for m in self.modules:
             m.process_sensors()

class Module:

    def __init__(self, conditions):
        self.conditions = conditions
        self.load_all_sensors()

    def load_all_sensors(self):
        self.sensors = []
        # Don't like this!
        s = Sensor(self.conditions)
        self.modules.append(m)

      def process_sensors(self):
         for s in sensors:
             if not s.is_sensor_respecting_conditions():
                 raise ...

e = Environ()
e.run_modules()

My question is: do I really have to replicate all these conditions? What can I do to make this code more clean?


texts:
I am new to Haskell, and wrote a script to verify credit number.
I did some tests, the script worked, but can it be improved further?

isCreditCardNumber :: String -> Bool
isCreditCardNumber number =
    0 == creditCardReminder ( creditCardDouble ( blowupCreditCardNumber ( reverse number)))

blowupCreditCardNumber :: String -> [(Int,Char)]
blowupCreditCardNumber creditCardNumber = zip [1..] creditCardNumber

creditCardDouble :: [(Int,Char)] -> [Int]
creditCardDouble [] = []
creditCardDouble ((index,digit):rest)
    | even index = (numberDoubleToList ((*2) $ digitToInt digit)) ++ creditCardDouble rest
    | otherwise = digitToInt digit : creditCardDouble rest

numberDoubleToList:: Int -> [Int]
numberDoubleToList number
    | number > 9 = map digitToInt (show number)
    | otherwise  = [number]

creditCardReminder :: [Int] -> Int
creditCardReminder xs = sum xs `mod` 10


texts: Swap images on click with specified image

texts:
I am new to jQuery and needed a solution for the following problem:

There are 3 images in a row and when the user clicks on one of them all three pictures are hiding and instead another image shows up (depending on the click). So while the markup and CSS is quite simple and only a quick draft the jQuery was the main issue. I came up with the following solution and would love to hear some advice, reviews, critiques or similar.

I also made a JSFiddle. for better understanding.

Here is my jQuery Code with similar click-functions (this bothers me a little):

var $button = '<button id="closebtn">Close</button>';

$($button).appendTo('#panzer');

// Pic1 hide and replace
$( "#pic1" ).click(function() {
    $('#featured li img').hide( "slow");
  $( ".undercon1" ).show( "fast", function() {
            $('#closebtn').show();
  });
});
// Pic2 hide and replace
$( "#pic2" ).click(function() {
    $('#featured li img').hide( "slow");
  $( ".undercon2" ).show( "fast", function() {
        $('#closebtn').show();
  });
});
// Pic3 hide and replace
$( "#pic3" ).click(function() {
    $('#featured li img').hide( "slow");
  $( ".undercon3" ).show( "fast", function() {
        $('#closebtn').show();
  });
});

// Button shows only with Replacement Images

$('button#closebtn').click(
     function ()
     {
         $(this).hide();

         $(".undercon1").hide( "slow");
         $(".undercon2").hide( "slow");
         $(".undercon3").hide( "slow");
         $('#featured li img').show( "slow");
     }
);


texts:
Here you go:

#define abort(msg) (fprintf(stderr, msg) && *((char*)0))


texts:
I have this code, which goes through a string and split it using a char delimiter.

I am concerned where it can be improved.

Main concerns are speed and memory usage with speed as the priority.
Any other improvements are welcome too.
Is there a better way (Without regex based split and without 3rd party libraries).

What it does:

  Iterate through string and extract all portions of strings delimited by given char
  return all portions, including empty ones.
  StringUtility class name is used because in future I can add other utility methods when necessory

Code:

public class StringUtility {

    /**
     * Split a string using a single char delimiter
     * @param strToSplit string to use
     * @param delimiter delimiter
     * @return String[] of portions
     */
    public static String[] split(String strToSplit, char delimiter) {
        ArrayList<String> arr = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strToSplit.length(); i++) {
            char at = strToSplit.charAt(i);
            if (at == delimiter) {
                arr.add(sb.toString());
                sb = new StringBuilder();
            } else {
                sb.append(at);
            }
        }
        arr.add(sb.toString());
        return arr.toArray(new String[0]);
    }
}

Unit Test:

This code currently passes following jUnit Test Cases

public class StringUtilityTest {

    @Test
    public void test1() {
        final String str1 = "Because";
        final String str2 = "I'm";
        final String str3 = "Batman";
        final char delim = ' ';
        String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3,
                delim);
        Assert.assertTrue(parts.length == 3);
        Assert.assertTrue(parts[0].equals(str1));
        Assert.assertTrue(parts[1].equals(str2));
        Assert.assertTrue(parts[2].equals(str3));
    }

    @Test
    public void test2() {
        final String str1 = "";
        final String str2 = "I'm";
        final String str3 = "Batman";
        final char delim = ' ';
        String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3,
                delim);
        Assert.assertTrue(parts.length == 3);
        Assert.assertTrue(parts[0].equals(str1));
        Assert.assertTrue(parts[1].equals(str2));
        Assert.assertTrue(parts[2].equals(str3));
    }

    @Test
    public void test3() {
        final String str1 = "";
        final char delim = ' ';
        String[] parts = StringUtility.split(str1,
                delim);
        Assert.assertTrue(parts.length == 1);
        Assert.assertTrue(parts[0].equals(str1));
    }
}

Speed Test:

From fastest to slowest

janos/Heslacher : split using index of and subString
Emanuele Paolini : split using subString
janos : split by setting string builder to zero length
me : original


texts:
I wrote a simple JSON schema validator.
The full code is over here on gist.github.com
However, the code without comment is...
validate = function(schema, instance) {
    var i;
    var errors = 0;

    var getType = function(attr) {
        return Object.prototype.toString.call(attr);
    }

    var addError = function(msg, attrs) {
        console.error(msg, attrs);
        errors += 1;
    }

    if(getType(schema) !== getType(instance)) {
        addError("Type Mismatch", [schema, instance]);
        return errors;
    }

    for(i in schema) {
        if(schema.hasOwnProperty(i)) {

            if(instance[i] == undefined) {
                addError("Property Not found", i);

            }
            //Special Handling for arrays
            else if( getType(schema[i]) === getType([]) ) {
                var zeroSchema = schema[i][0];
                var zeroInstance = instance[i][0];
                if(zeroInstance === undefined) {
                    continue;
                }
                for(var j=0;j<instance[i].length;j++) {
                    errors += validate(zeroSchema, instance[i][j]);
                }

            }
            //Special Handling for nested objects
            else if( getType(schema[i]) === getType({}) ) {
                errors += validate(schema[i], instance[i]);
            }

        }
    }
    return errors;

}

The code doesn't need the schema object to explicitly specify the type of object properties
unlike the official one
I'm fairly new to javascript. How do I improve the code?


texts: Functions for outputting the rows and columns of a matrix

texts:
I often want to iterate either row-wise or column-wise though a matrix in Julia, so I've created a pair of functions to help:

function cols(x::Matrix)
    function _it()
        for ii in 1:size(x,2)
            produce(x[:,ii])
        end
    end
    Task(_it)
end

function rows(x::Matrix)
    function _it()
        for ii in 1:size(x,1)
            produce(x[ii,:])
        end
    end
    Task(_it)
end

Example of use:

AA = [1 2 3; 1 2 3]

println("Columns are:")
for ii in cols(AA)
    println(ii)
end
println("\nRows are:")
for ii in rows(AA)
    println(ii)
end

Outputs:

Columns are:
[1,1]
[2,2]
[3,3]

Rows are:
[1 2 3]
[1 2 3]

Possible issues:

It seems like this could be one function, that just takes the dimension as a parameter.
This might confound the JIT, which would mean losing out out a bunch of speed. (The Julia JIT can normally vectorize for loops).
I feel like there should be a inbuild function for this, but the closest I know of is mapslice.


texts: ASP.NET REST controller with try-catch error handling

texts:
Yesterday someone guided me through this article and I'm wondering whether I should use try-catch implementation or not? I have the following code below which is actually a RESTful service and I have implemented the try-catch pattern. I'm throwing errors only in debug mode just for testing purpose and during the release mode, I'm catching errors and returning the meaningful error messages such as Http Status Codes.

After reading this article, I'm confused whether I'm on the right track and if not, do I need to remove try-catch and throw errors instead of such meaningful messages to the end user?

Any code review/feedback is appreciated.

namespace NewEmployeeBuddy.Facade.Controllers.Employee
{
    [RoutePrefix("api/employee")]
    [RequireHttps]
    [BasicAuthorization]
    public class EmployeeController : ApiController
    {
        #region Properties
        private IEmployeeService _employeeService { get; set; }
        #endregion

        #region Constructor
        public EmployeeController()
        {
          //_employeeService = new EmployeeService();
        }

        public EmployeeController(IEmployeeService employeeService)
        {
            _employeeService = employeeService;
        }
        #endregion

        #region Actions
        [HttpPost, Route("add")]
        [ValidateRequest]
        public IHttpActionResult AddEmployee(AddEmployeeRequestDTO request)
        {
            try
            {
                if (request == null)
                    return Content(HttpStatusCode.BadRequest, ErrorCodes.E002);

                var response = _employeeService.AddEmployee(request);
                if (response.OperationResult)
                    return Content(HttpStatusCode.Created, response);

                return Content(HttpStatusCode.InternalServerError, ErrorCodes.E001);
            }
            catch (Exception ex)
            {
#if (DEBUG)
                Logger.Instance.Error(ex);
                throw ex;

#endif
                //Logger.Instance.Error(ex);
                //return Content(HttpStatusCode.InternalServerError, ErrorCodes.E001);
            }
        }
        #endregion
    }
}


texts: Formatting seconds as hours:minutes:seconds

texts:
This is basically my school homework and I want to know what to improve, and what not to do.
The homework basically is this:
You will get a input in seconds, which is supposed to be shown as H:MM:SS where H is hours M is minutes and S is seconds. The formatting is supposed to look like in my example. ( note: In output, 0s from the left will be ignored and replaced with spaces )

Input:
3000
730
308
3967
15
1

Output:
The count of entires: 6
  50:00
  12:10
   5:08
1:06:07
     15
      1

So basically, I did a code based on the example. I haven't got more informations, just that but it is enough and fun.
Here goes my code:

#include <iostream>
#include <fstream>

inline int CountSpaces ( int hod, int min, int sec ){
    int spaces = -1;
    // 1:06:07
    if ( hod )
        return 0;
    if ( min >= 10 )
        return 2;
    if ( min < 10 && min > 0 )
        return 3;
    if ( sec >= 10 )
        return 5;
    if ( sec < 10 )
        return 6;
    // in the case something goes wrong..
    return spaces;
}

// convert time to hour,min,seconds
void CalcTime ( int value, int& hour, int& min, int& sec ){
    hour = value / 3600;
    min = value % 3600 / 60;
    sec = value % 60;
}

// output spaces
void Space ( int* hour, int* min, int* sec ){
    int spaces = CountSpaces ( *hour , *min , *sec );
    if ( !spaces ) return;
    for ( int i = 0 ; i < spaces ; i++ ){
        std::cout << ' ';
    }
}

void Write ( int time ){
    if ( time <= 0 )
        return;

    int hour;
    int min;
    int sec;

    CalcTime ( time , hour , min , sec );
    Space ( &hour , &min , &sec );

    bool bHour = false;
    bool bMin = false;
    if ( hour > 0 ){
        bHour = true;
        std::cout << hour << ':';
    }
    if ( min < 60 && min > 0 ){
        bMin = true;
        if ( bHour ){
            if ( min < 10 ){
                std::cout << '0';

            }
        }
        if ( min > 0 )
            std::cout << min << ':';

    }
    if ( sec < 60 && sec >= 0 ){
        if ( sec < 10 && bMin ){
            std::cout << '0';
        }
        std::cout << sec << std::endl;
    }
}

int main ( ){
    std::ifstream fin ( "in.txt" );

    if ( !fin ) return 1;

    int num;
    int count = 0;
    int arr[100];
    while ( fin >> num ){
        arr [ count++ ] = num;
    }
    std::cout << "The count of entires: " << count << std::endl;
    for ( int i = 0 ; i < count ; i++ ){

        Write ( arr [ i ] );
    }

    return 0;
}


texts:
I've just started a self-learning "course" on Python practical programming for beginners. I found this book online, and decided to go through the chapters.

The book had a half-complete implementation of a Tic-Tac-Toe game, and I was supposed to finish it as an exercise. This is my code so far:

theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
        'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
        'low-L': ' ', 'low-M': ' ', 'low-R': ' '}

def printBoard(board):
    """ This function prints the board after every move """

    print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
    print('-+-+-')
    print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
    print('-+-+-')
    print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

def checkWin(board):
    """
    This functions checks if the win condition has been
    reached by a player
    """
    flag = False
    possibleWins = [['top-L', 'top-M', 'top-R'],
                    ['mid-L', 'mid-M', 'mid-R'],
                    ['low-L', 'low-M', 'low-R'],
                    ['top-L', 'mid-L', 'low-L'],
                    ['top-M', 'mid-M', 'low-M'],
                    ['top-R', 'mid-R', 'low-R'],
                    ['top-L', 'mid-M', 'low-R'],
                    ['top-R', 'mid-M', 'low-L']]

    for row in range(len(possibleWins)):
        temp = board[possibleWins[row][0]]
        if temp != ' ':
            for position in possibleWins[row]:
                if board[position] != temp:
                    flag = False
                    break
                else:
                    flag = True
            if flag:
                return True

    return False

turn = 'X'
for i in range(9):
    printBoard(theBoard)
    print('Turn for ' + turn + '. Move on which space?')
    while True:
        move = input()
        if move in theBoard:
            if theBoard[move] != ' ':
                print('Invalid move. Try again.')
            else:
                break
        else:
            print('Invalid move. Try again.')
    theBoard[move] = turn
    if checkWin(theBoard):
        printBoard(theBoard)
        print('Player ' + turn + ' wins!')
        break
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'

My checkWin function is very "stupid", it detects a win based on predetermined scenarios, and may not be very efficient in that regard as well. What if the board was of an arbitrary size nxn? Is there an algorithm to determine the victory condition without having to rewrite the entire game?


texts: Computing sum and counting matches in an array

texts:
The problem was pretty straightforward and used two simple algorithms from our examples; the one for computing the sum, and the one for counting matches. The array for the problem wasn't provided, but you can easily write a method around it without actually having it, since she gave us the name and type of the array. The code for my solution is this:

 public class Tests

 {

 private double[] grades;

 public int belowAverage() // Creates method for finding scores below the mean

 {

 double total = 0;

 for (double element1 : grades) // Computes total of array 'grades'

 {

  total=total + element1;

 }

  double mean = total / grades.length; //Uses total and the length of the array to computer the mean

  int matches = 0;

  for (double element2 : grades) //Uses mean to compute number of grades that are below the mean and

   {                                               // increases matches for each one that is.

    if (element2 < mean) {matches++;}

 }

 return matches; // Returns the number of matches.

  }

  }

Obviously the third line would change if you had the actual array. That was just kind of a placeholder. I tried to notate the code well enough to see where you get the total, then the mean, then compare each one to the mean to get matches that are less and increase your 'matches' variable for each match. I could have used the same 'element' variable for both loops since they're only used within the loops, but for clarity's sake in this example, I named them differently. I put all of these steps together in one method to solve this problem, but if I were going to write this sort of thing 'for real', I would assume it would probably need to calculate much more than just this small task (different averages, highest/lowest, etc.), so I would probably put each step in its own method so it could be used wherever you needed it.

Can someone comment on this and tell me if I could have done this in another way or an easier way? Maybe I could have used arrays.


texts: Get host ip address behind load balancer or without lb

texts:
Description

Aplication type: WEB API

.NET Framework: 4.5

MVC: 5

I need caller host ip in my custom action filter and then in action. On some enviroments we have configured load balancer which stores caller ip in header "HTTP_X_FORWARDED_FOR". I nedd my code works with LB or without.

CODE

Filter

using System.Collections.Generic;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace FAPTest.TestApp.ActionFilters
{
    public class AccessControlFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string ip = HttpContext.Current.Request.UserHostAddress;

            string sourceIp = HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR");

            string ipAddress = ip;

            if (!string.IsNullOrEmpty(sourceIp))
            {
                ipAddress = sourceIp;
            }

            actionContext.Request.Properties.Add(new KeyValuePair<string, object>("ipAddress", ipAddress));
        }
    }
}

Controller

using System.Web.Http;

namespace FAPTest.TestApp.Controllers
{
    public class TestController : ApiController
    {
        [HttpGet]
        public string Test()
        {
            object o = null;
            string ipAddress = null;

            if (Request.Properties.TryGetValue("ipAddress", out o))
            {
                ipAddress = (string)o;
            }

            return ipAddress;
        }
    }
}

Filter registration:

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FAPTest.TestApp.ActionFilters;

namespace FAPTest.TestApp
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.Filters.Add(new AccessControlFilter());
        }
    }
}

Questions

Is this code safe?

What can I improve?

Are there some pitfals?


texts: Send and receive data code using OpenSSL

texts:
I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it. Here is my first try. Now I need to get review for my new code.

void sslWrite(SSL *ssl, const void *buf, unsigned size)
{
    int writedTotal = 0;
    const char *ccBuf = reinterpret_cast<const char *>(buf);

    while (writedTotal < size) {
        int writedPart = SSL_write(ssl, ccBuf + writedTotal, size - writedTotal);
        if (writedPart < 0) {
            std::string error = "SSL_write error = ";
            error += (std::to_string(writedPart) + ".");
            throw std::runtime_error(error);
        }
        writedTotal += writedPart;
    }
}

std::vector<char> sslRead(SSL *ssl, unsigned size)
{
    std::vector<char> ret(size);
    unsigned readTotal = 0;

    while (readTotal < size) {
        int readPart = SSL_read(ssl, &ret[readTotal], size - readTotal);
        if (readPart < 0) {
            std::string error = "SSL_read error = ";
            error += (std::to_string(readPart) + ".");
            throw std::runtime_error(error);
        }
        readTotal += readPart;
    }

    return ret;
}

void sslWriteSize(SSL *ssl, unsigned size)
{
    if (sizeof(u_long) > 8)
        throw std::runtime_error("Write size error.");

    u_long nlSize = htonl(size);
    sslWrite(ssl, &nlSize, 8);
}

unsigned sslReadSize(SSL *ssl)
{
    if (sizeof(u_long) > 8)
        throw std::runtime_error("Read size error.");

    u_long size = *reinterpret_cast<u_long *>(&sslRead(ssl, 8)[0]);
    size = ntohl(size);
    return size;
}

void sslWrite(SSL *ssl, const std::string &data)
{
    if (data.empty())
        throw std::runtime_error("SSL write error. Data is empty.");

    sslWriteSize(ssl, data.size());
    sslWrite(ssl, &data.at(0), data.size());
}

std::vector<char> sslRead(SSL *ssl)
{
    unsigned size = sslReadSize(ssl);
    return sslRead(ssl, size);
}

Is there a buffering problem as in my old code?


texts:
So I ran into an issue where a client sent me a sample file and the line breaks were not preserved when reading the file using PHP from linux. So I wrote up a little function that should hopefully fix the issue for all platforms.

This is from a larger File class. The function names are pretty self explanatory.

public function fixLineBreaks() {
    $this->openFile();

    // replace all placeholder with proper \r\n
    $contents = str_replace("[%LINEBREAK%]", "\r\n",

                    // replace all double place holder with single
                    // in case both \r and \n was used.
                    str_replace("[%LINEBREAK%][%LINEBREAK%]", "[%LINEBREAK%]",

                        // replace all \n with place holder
                        str_replace("\n", "[%LINEBREAK%]",

                            // replace all \r with placeholder
                            str_replace("\r", "[%LINEBREAK%]",

                                // First, read the file.
                                fread($this->fp, filesize($this->filename))
                            )
                        )
                    )
                );
    $this->closeFile();

    $this->writeOpen();
    fwrite($this->fp, $contents);
    $this->closeFile();
}

EDIT

Okay, to clarify. I received a CSV file that was supposed to be parsed in PHP. Open it up in notepad and everything is on one line. Opening it with fopen and then reading with fgetcsv would also return the contents as one line. However, if you copy and paste the contents from notepad into NetBeans then all the line breaks are there. This made me realize that there are line breaks but they're not the ones that notepad or PHP recognize.

This was the function that I wrote up which essentially re-writes the file with proper line breaks.

I was posting this here to see if anyone possible had a better solution.


texts: Getting all timeDuration from a day which are not in a list of timeDuration in Scala

texts:
I have a list of timestamp tuples of the form List((startTime,endTime)), which are basically denoting periods of time throughout the day.

For example:

(("2016-03-28 14:00:00","2016-03-28 15:00:00"),
 ("2016-03-28 17:00:00","2016-03-28 21:00:00"),
 ("2016-03-28 01:00:00","2016-03-28 13:00:00"))

I want to get a list of the durations which are not included in this list.

So the output should be:

(("2016-03-28 00:00:00","2016-03-28 01:00:00"),
 ("2016-03-28 13:00:00","2016-03-28 14:00:00"),
 ("2016-03-28 15:00:00","2016-03-28 17:00:00"),
 ("2016-03-28 17:00:00","2016-03-28 24:00:00"))

Can anyone suggest a good and efficient way of doing that in Scala?

The naive solution that I've tried so far is as follows:

import java.sql.Timestamp
import scala.collection.mutable.ListBuffer

def comparator(first: (Timestamp,Timestamp), second: (Timestamp, Timestamp)) = first._2.getTime <= second._1.getTime

val data = List((Timestamp.valueOf("2016-03-28 00:00:00"),Timestamp.valueOf("2016-03-28 10:00:00")),
  (Timestamp.valueOf("2016-03-28 12:00:00"),Timestamp.valueOf("2016-03-28 15:00:00")),
  (Timestamp.valueOf("2016-03-28 23:00:00"),Timestamp.valueOf("2016-03-28 23:59:59")),
  (Timestamp.valueOf("2016-03-28 16:00:00"),Timestamp.valueOf("2016-03-28 21:00:00"))
).sortWith(comparator)

var emptySlots = new ListBuffer[(Timestamp,Timestamp)]()
var currTime = Timestamp.valueOf("2016-03-28 00:00:00")
var index = 0
var cond = 0
while(cond == 0){

  if (currTime.compareTo(Timestamp.valueOf("2016-03-28 23:59:59")) < 0 && index >= data.size){
    emptySlots += ((currTime,Timestamp.valueOf("2016-03-28 23:59:59") ))
    cond = 1
  }
  else if(index >= data.size)
  {
    cond = 1
  }
  else if(currTime.compareTo(data(index)._1) < 0) {
    emptySlots += ((currTime, data(index)._1))
    currTime = data(index)._2
    index += 1
  }
  else if(currTime.compareTo(data(index)._1) >= 0 && currTime.compareTo(data(index)._2) < 0 ) {
    currTime = data(index)._2
    index += 1
  }
  else if(currTime.compareTo(data(index)._1) > 0 && currTime.compareTo(data(index)._2) > 0 ) {

    index += 1
  }

}

emptySlots.toList


texts:
I programmed Problem #22 from Project Euler in Python. It works but I want to know if it really is pythonic enough.

  Using names.txt (right click and 'Save Link/Target As...'), a 46K text
  file containing over five-thousand first names, begin by sorting it
  into alphabetical order. Then working out the alphabetical value for
  each name, multiply this value by its alphabetical position in the
  list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN,
  which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the
  list. So, COLIN would obtain a score of 938 × 53 = 49714.

  What is the total of all the name scores in the file?

from itertools import count

FILE = "e022.txt"
CHAR_OFFSET = ord('A') - 1

def parse(file):
    """Return the read in list"""
    with open(file) as fid:
        return fid.read().replace('"',"").split(',')

def score_name(name):
    """Returns the score of a single name"""
    return sum(ord(char) - CHAR_OFFSET for char in list(name))

def score_names(names):
    """Returns the score of the list"""
    return sum(ind*score_name(name) for (ind, name) in zip(count(1),sorted(names)))

if __name__ == "__main__":
    print(score_names(parse(FILE)))

Please feel free to critic me on it. One thing I wasn't sure about: In the file parser, did I need to make the with guard or is this not needed when encapsulated in a function?

Furthermore, the global variable FILE is in a place where it is easy accessible, but let's say we would import it as a module and wouldn't need it. Should I move it down to the main guard and loose a bit of overview?


texts: Creating comma-separated '?' placeholders for SQL query parameters

texts:
I have come up with a code that takes the total number of an array and creates ? for each, then separates them by a comma; leaving me a list like the one below:

?, ?, ?, ?, ?...

I am using this for my sql queries with prepared statements, instead of having to create the prepared statement each time, I want to just have an easily accessible class that does the heavy work.

So far I have a for loop code which I came up with to get the comma-separated question marks. First I create an array of [0] => ? ... based on the total number of the original array and then implode the value and add the comma between each element.

<?php
$arr = array(
    'name' => 'James Bond',
    'age' => 60,
    'hobbies' => 'Saving England',
    'country' => 'England',
    'language' => 'English',
    'children' => 'too many to count'
);

for($i = 0; $i < count($arr); $i++)
{
    $question[$i] = '?';
}
print_r( implode(', ', $question) );
// outputs: ?, ?, ?, ?, ?, ?
?>

Now my question is, is there a more efficient way of achieving this, such as a one-liner that just takes the total array number and creates the number automatically?


texts:
I think DB transaction should be as small as possible, and close it soon.

So I wrote a helper function like 'using' statement in C#.

function transaction($conn, $closure) {
    $conn->beginTransaction();
    try {
        $closure($conn);
        $conn->commit();
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
}

$conn = new PDO('mysql:....');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
transaction($conn, function($conn) {
    $conn->query('insert ....');
    $conn->query('insert ....');
});

but with this pattern:

I have to capture manually any variables with use()
Stack trace will be bit complicated

or, should I write try/catch and begin/commit in every transaction?


texts: Using (templated) function-scope static address as Unique ID

texts:
typedef const bool* const TypeID;
template<typename>
TypeID TypeIdOf() noexcept {
        static const bool idLoc(0);
        return &idLoc;
}

I'm using this function to return from some derived classes to differentiate them at runtime, by returning from this function, templated as the class. ie:
class Object
{
...
        TypeID Type() const = 0;
        template<typename T> bool IsType() const
        { return Type() == TypeIdOf<T>(); }
...
};
class DerivedObject:
public Object
{
...
        TypeID Type() const override { return TypeIdOf<DerivedObject>(); }
...
};

It's worked so far, but it took me a while to decide to use it, and I'm still having some worries about using it in the long-term. So I'm asking my first question here: is this code OK? Is it thread safe? Could this throw any exceptions? Thanks.


texts: Command Pattern: Does my implementation make the point?

texts:
Asking for a review of my implementation of a command pattern. In a Editor, words can be entered and the entering of words can be undone.

General purpose Interface

public interface Command {
    void execute();
}

The concrete write word command

// Command
public class WriteCommand implements Command {

    private Editor editor;
    private String word;

    public WriteCommand(String w, Editor e) {
        this.word = w;
        this.editor = e;
    }

    public String getWord() {
        return this.word;
    }

    public void execute() {
        this.editor.addToWordList(this.getWord());
    }

}

The undo command

public class UndoCommand implements Command {

    private Editor editor;

    public UndoCommand(Editor e) {
        this.editor = e;
    }

    @Override
    public void execute() {
        editor.removeFromWordList();
    }
}

The editor (i.e. receiver, i believe):

// Receiver
public class Editor {

    private List<String> wordList;

    public Editor() {
        wordList = new ArrayList<>();
    }

    public void addToWordList(String w) {
        this.wordList.add(w);
    }

    public void removeFromWordList() {
        this.wordList.remove(this.wordList.size()-1);
    }

    List<String> getWordList() {
        return this.wordList;
    }

}

The invoker keeping the command queue:

public class Invoker {
    private List<Command> undoList;
    private List<Command> redoList;

    public Invoker() {
        undoList = new ArrayList<>();
        redoList = new ArrayList<>();

    }

    public void executeCommand(Command c) {
        undoList.add(c);
        c.execute();
    }
}

The client responsible for creating the commands:

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

        Editor e = new Editor();

        Invoker invoker = new Invoker();

        invoker.executeCommand(new WriteCommand("Hello", e));
        invoker.executeCommand(new WriteCommand("World", e));
        System.out.println(e.getWordList());

        invoker.executeCommand(new UndoCommand(e));
        System.out.println(e.getWordList());

    }
}


texts:
This is part of a class for paginating a Backbone collection.

The paginateTo method is for paginating to a model id. It returns the model if it's already in the collection, otherwise it checks with the server that it exists. If so, it requests subsequent pages until it's loaded into the collection.

How would you refactor this method to make it clearer?

paginateTo: (id, dfd, check) ->
  dfd ?= new $.Deferred
  return dfd.resolve(model) if model = @get(id)
  check ?= @checkModelExists(id)
  check.done =>
    @once 'sync', => @paginateTo(id, dfd, check)
    @fetchNextPage()
  check.fail =>
    dfd.reject()
  dfd.promise()

checkModelExists: (id) ->
  url = @url() + '/' + id
  $.get url

fetchNextPage: ->
  @page += 1
  @fetch { update: true, remove: false, data: { page: @page }}


texts:
I got a Reservation model that has reservation_start and reservation_end.
Then I have the usual date validations (end date cannot be lesser than start date and so on).

The problem is with these two guys:

  def reservation_start_available
    reservations = Reservation.where(["transport_id =?", transport_id])
    date_ranges = reservations.map { |e| e.reservation_start..e.reservation_end }

    date_ranges.each do |range|
      if range.include? reservation_start
        errors.add(:reservation_start, "Start date not available")
      end
    end
  end

  def reservation_end_available
    reservations = Reservation.where(["transport_id =?", transport_id])
    date_ranges = reservations.map { |e| e.reservation_start..e.reservation_end }

    date_ranges.each do |range|
      if range.include? reservation_end
        errors.add(:reservation_end, "End date not available")
      end
    end
  end

This is not even close to the DRY we love so much. How can I pass a parameter to the methods like this?


texts: Python script to renew key from Vault every 30s

texts:
A small Python lib to renew key from Vault every 30s to always get the latest key.

from __future__ import print_function

import hvac
import time
import threading
import os

VAULT_URL = os.environ['VAULT_ADDR']
VAULT_TOKEN = os.environ['VAULT_TOKEN']

class Client:
    def __init__(self, *keys):
        self.keys = keys
        self.data_dict = {}
        self.client = hvac.Client(
            url=VAULT_URL,
            token=VAULT_TOKEN)

        self.__renew()

    def read(self):
        for key in self.keys:
            self.data_dict[key] = self.client.read(key)
        return self.data_dict

    def __renew(self):
        self.client.renew_token()
        threading.Timer(30, self.__renew).start()
        self.read()

if __name__ == '__main__':
    client = Client('secret/key')
    print(client.read())


texts: Get the best rational approximations for any real number in builtin Python

texts:
Best rational approximations is a technical term and not subjective. The best rational approximations are the convergents of a value plus it's semi convergents that are closer to the original value than the previous convergents.

Hi everyone,

I've written some quick code in Python that is my tool for exploring various aspects of music theory, number theory, and my obsession with OEIS. It's currently written to spit out a list of the ratio's themselves. It would be quite easy to tweak to your needs. This may also help anyone exploring the logic of infinite continued fractions and convergents. I use the decimal module here for precision. It's written so you can paste any value you want into the input field - that can easily be tweaked to accept any real number from code. Phasers to stun. I call it my approximilator.

(Python 3)

import decimal
import math

D = decimal.Decimal

def contFrac(x, k):
    """Cont Frac from Real value"""
    cf = []
    q = math.floor(x)
    cf.append(q)
    x = x - q
    i = 0

    while x != 0 and i < k:
        q = math.floor(1 / x)
        if q > k:
            break
        cf.append(q)
        x = 1/x - q
        i += 1

    return cf

def bestra(clist, app):
    """Best Rational Approximation from Cont. Frac"""
    hn0, kn0 = 0, 1
    hn1, kn1 = 1, 0
    """Best Rational Approx Init"""
    ran, rad = 0, 0
    conlist, ralist, finallist = [], [], []

    for n in clist:
        for i in range(1, n+1):
            ran = (hn0 + (i*hn1))
            rad = (kn0 + (i*kn1))
            try:
                if D.copy_abs(app-D(ran/rad)) < D.copy_abs(app-D(hn1/kn1)):
                    ralist.append({'ratio': f'{ran}/{rad}', 'denom' : rad})
            except:
                pass
        hn2 = (n*hn1)+hn0
        kn2 = (n*kn1)+kn0
        conlist.append({'ratio': f'{hn2}/{kn2}', 'denom': kn2})
        hn0, kn0 = hn1, kn1
        hn1, kn1 = hn2, kn2

    for x in sorted(conlist+ralist, key = lambda i: i['denom']):
        finallist.append(x['ratio'])

    return list(dict.fromkeys(finallist))

if __name__ == "__main__":
    value = D(input('Input value to approximate: '))
    prec = len(str(value))*2
    decimal.getcontext().prec = prec
    vc = contFrac(value, prec)
    print(bestra(vc, value))

Some output for Pi to entice:

'3/1', '13/4', '16/5', '19/6', '22/7', '179/57', '201/64', '223/71', '245/78', '267/85', '289/92', '311/99', '333/106', '355/113', '52163/16604', '52518/16717', '52873/16830', '53228/16943', '53583/17056', '53938/17169', '54293/17282', '54648/17395', '55003/17508', '55358/17621', '55713/17734', '56068/17847', '56423/17960'


texts: Enable/Disable Popper.js tooltip if element exists

texts:
I would like to disable the popper.js tooptip if there is an element with a specific class on the page.

Let me explain ... I have a plugin that creates notifications dynamically, these notifications disappear every so often. I would like, that when a notification appears, the tooltip of popper.js will be disabled, and when the notification is closed, the tooltip will be enabled again.

This is what I have implemented so far, it works well, but I was wondering if there was another way a little more elegant.

    new Plugin({
        callbacks: {
            beforeShow: function() {
                $('.navbar-nav [title]').tooltip('disable');
            },
            afterClose: function () {
                if (!$('.notification').length) {
                    $('.navbar-nav [title]').tooltip('enable');
                }
            }
        }
    });