texts:
I am a new to Eigen, and I implemented a logistic regression model with it. It works but I don't know whether it is implemented in an efficient way.

#include <iostream>
#include <Eigen/Dense>
#include <cmath>

using namespace Eigen;
using namespace Eigen::internal;
using namespace Eigen::Architecture;
using namespace std;

class logistic_regression
{
public:
   VectorXd w;
   double b;
   logistic_regression(int n_in)
   {
      this->w = VectorXd::Random(n_in);
      this->b = 0.0;
   }

   void train(MatrixXd train_datas, double lr)
   {
      VectorXd dw(this->w.rows());
      double db;
      dw = train_datas.rightCols(1) - calc(train_datas.leftCols(this->w.rows()));
      db = dw.mean();
      MatrixXd tmp = train_datas.leftCols(this->w.rows());
      tmp = tmp.array().colwise()*dw.array();
      dw = tmp.colwise().mean();
      w += lr * dw;
      b += lr * db;
   }

   VectorXd predict(MatrixXd inputs)
   {
      return ((1 / (1 + ((-inputs*this->w).array() - b).exp())).array() > 0.5).cast<double>();
   }

   double test_error(MatrixXd datas)
   {
      VectorXd outputs = predict(datas.leftCols(w.rows()));
      /*
      cout << outputs << endl << endl << endl;
      cout << datas.rightCols(1) << endl << endl << endl;
      cout << (outputs - datas.rightCols(1)) << endl;
      cout << ((outputs - datas.rightCols(1)).array() > 1e-5).count() << endl;*/

      return ((outputs - datas.rightCols(1)).array() > 1e-5).count() / (double)outputs.rows();

   }

};

MatrixXd linear_separable_dataset_generator(int n, int dim, VectorXd w, double b)
{
   int n_col = w.rows();
   MatrixXd datas = MatrixXd::Random(n, n_col + 1);

   datas.rightCols(1) = (((datas.leftCols(n_col)*w).array() + b) > 0).cast<double>();
   return datas;
}

void test_logistic_regression()
{
   logistic_regression lr(2);
   VectorXd w(2);
   double b = 0.2;
   w << 0.3, 0.6;
   MatrixXd train_datas = linear_separable_dataset_generator(1000, 2, w, b);
   for (int i = 0; i < 500; i++)
   {
      lr.train(train_datas.topRows(990), 0.1112);
      cout << "epoch:" << i << " error:" << lr.test_error(train_datas) << endl;
   }
   cout << "w:" << lr.w / (lr.b / 0.2) << endl;
   cout << "b:" << lr.b << endl;
   getchar();
   return;
}


texts:
I am trying to teach myself a new language in three weeks. Can you please give me some advice on how to clean my code and make it faster or more reliable? This works fine. I don't "need" any 'free' code, I need the knowledge of what I am doing wrong, and what I am doing right so I can learn.

   Using sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ITCSDatabase.mdf;Integrated Security=True")
        Dim resultVar As String
        sqlCon.Open()
        Dim sqlText = "SELECT appLink FROM appTable WHERE Id = @name"
        Dim cmd = New SqlCommand(sqlText, sqlCon)
        cmd.Parameters.AddWithValue("@name", x)
        resultVar = cmd.ExecuteScalar()
        cmd.ToString()
        If y = 1 Then
            System.Diagnostics.Process.Start(resultVar)
        ElseIf y = 0 Then
            System.Diagnostics.Process.Start("iexplore.exe", resultVar)
        Else
            MsgBox("When calling the appCall Function, an invalid parameter is being sent in.")
        End If
        Dim sqlText2 = "UPDATE appTable SET appClickCount = appClickCount + 1 " & _
        "WHERE Id = @x"
        Dim cmd2 = New SqlCommand(sqlText2, sqlCon)
        cmd2.Parameters.AddWithValue("@x", x)
        cmd2.ExecuteNonQuery()
End Using


texts: Initializing a variable with a function reference (PHP)

texts:
I'm working on an old PHP website, and NetBeans is complaining about an uninitialized variable. I'm seeing some code like this:

$app->soapAPIVersion($apiVersion);
$_SESSION['apiVersion'] = $apiVersion;

The function looks something like this:

function soapAPIVersion(&$apiVersion)
{
    $apiVersion = '';
    $result = false;
    $soapResult = $client->call('getAPIVersion', array('sessionKey' => $sessionKey), $url);

    if (is_string($soapResult))
    {
        $apiVersion = $soapResult;
        $result = true;
    }

    return $result;
}

I believe it's using this line to initialize the $apiVersion variable:

$app->soapAPIVersion($apiVersion);

For better coding practice, should that really be this:

$apiVersion = '';
$app->soapAPIVersion($apiVersion);

Or is it a valid trick?


texts: Fetching all nodes of a directed graph by an id of any node

texts:
Task: Rowset of all reachable(in any direction) nodes from any node in a graph. In other words I need to extract all nodes of a particular graph from a table in the database where graph specified by an id of any one graph node. The final goal is a map in the app.

Table structure of DocumentDependency is simple as:

descendant_id | predecessor_id
-------------------------------
     2857     |      2856
     2858     |      2856
     2859     |      2856
     2859     |      2857
     2860     |      2859
     2861     |      2859

Finally I came up with CTE:

WITH RECURSIVE DocumentGraph AS
(
    SELECT
        CASE WHEN predecessor_id = 2858 THEN descendant_id ELSE predecessor_id END AS anchor_id,
        ARRAY[ROW(predecessor_id, descendant_id)] path,
        1 depth

    FROM
        DocumentDependency

    WHERE
        2858 in (descendant_id, predecessor_id)

    UNION ALL

    SELECT
        CASE WHEN DocumentDependency.predecessor_id = DocumentGraph.anchor_id THEN DocumentDependency.descendant_id ELSE DocumentDependency.predecessor_id END,
        path || ROW(DocumentDependency.predecessor_id, DocumentDependency.descendant_id) path,
        depth + 1

    FROM
        DocumentGraph

    JOIN DocumentDependency ON
        DocumentGraph.anchor_id in (DocumentDependency.predecessor_id, DocumentDependency.descendant_id)
        AND
        ROW(DocumentDependency.predecessor_id, DocumentDependency.descendant_id) <> ALL(path)
)

There are a lot discussions about directed graphs and this is sort of a compilation from stack* and one useful book1, but I'm experiencing an overdose and what I need is criticism.

Maybe this is generally an inappropriate approach? =)
Lightweight? (What if DocumentDependency will have 500k rows?)
Portability? (for now I'm using PostgreSQL12)
Simplicity? (I'm under custom ORM and need to extend for ROWS/ARRAYS/CTE support but probably there is a way to avoid using arrays?)

1Joe Celko's Trees and Hierarchies in SQL For Smarties (highly recommended, btw ;)


texts: Testing a probabilistic prime-testing algorithm that may fail

texts:
I have implemented Pollard's Rho algorithm in Java. Due to the nature of it there is a small chance for it to fail (have not seen it happening yet).

Since I do not want to see my unit tests failing due to this "too often", I set a retry, with which I am not totally satisfied, as you can see here:

@Test
void primeFactorsCalculatedWithPollardsRhoAreCorrect() {
    Operations op = new Operations();
    int remainingAttempts = 5;

    while (true) {
        try {
            assertEquals(5, op.primeFactorsPollardRho(13195));
            break;
        } catch (UnsupportedOperationException e) {
            remainingAttempts -= 1;

            if (remainingAttempts == 0) {
                throw e;
            }
        }
    }
}

I am using jUnit.

Is there a better, more pleasing to the eye, way of doing this?


texts: SPOJ Class Leader using circular linked list

texts:
I have solved a spoj question CLASS LEADER.  For each test case there are n students and a paper will be given to student m and now the game starts, the student m will pass the paper by o positions and the person who gets the paper gets eliminated and the game will be continued until one student is left.

I actually solved the problem by first creating a linked list of size n using struct and then pointed last node to the front which made my list circular then i went to position m and then started the calling recursive call to function which moved by o positions and removed that node. I am unable to improve my code's performance and getting TLE.

#include<iostream>
using namespace std;
struct node {
    int data;
    node* next;
};
node* tail = new node();                    //Global node
void createLL(int n) {                      //adding node at end
    node* t = new node();
    t->data = n;
    t->next = NULL;
    tail->next = t;
    tail = t;
}
int func(node* p, int k) {
    if (p->next == p)return p->data;
    int f = k;
    node* q = new node();
    while (f--) {
        q = p;
        p = p->next;
    }
    q->next = p->next;
    func(q, k);
}
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m, o;
        cin >> n >> m >> o;
        if (n == 1) {
            cout << n << endl;
            continue;
        }
        node* head = new node();
        head->data = 1;
        head->next = NULL;
        tail = head;
        for (int i = 1; i<n; i++) {         //created linked list with values index+1
            createLL(i + 1);
        }
        node* r = head;
        while (r->next != NULL) {           //traverse to the end
            r = r->next;
        }
        r->next = head;                     //created a circular linked list
        m--;
        while (m--) {
            head = head->next;              //going to m'th position
        }
        int ans = func(head, o);            //iterative call
        cout << ans << endl;
    }
    return 0;
}


texts: Importing a report through the enabler4excel add-in

texts:
This connects to Salesforce to import a report through the enabler4excel add-in. The report overwrites what is currently there on the sheet (2016 Incidents Dashboard). The report contains about 55,000 rows and 10 columns each. I also have 8 columns of formulas (nothing complex) off to the right. The next section autofills the Excel formulas from the last row on the right to match that of the report on the left.

This works, but the only problem is that it seems awfully slow: about 2 minutes. How can I do this so it doesn't take forever?

Sub ButtonClick1()

Dim addin As Office.COMAddIn
Dim automationObject As Object
Dim error As String
Dim error1 As String
Dim Result As Boolean
Dim ReportResult As String
Dim LastRowLeft As String
Dim LastRowRight As String
Dim sheetname As String

sheetname = ActiveSheet.Name
For Each addin In Application.COMAddIns
If addin.Description = "Enabler4Excel" Then
Set automationObject = addin.Object
End If
Next addin

Result = automationObject.LogIn("myemail.org", "mypassword",              "https://login.salesforce.com", error)
If Result = False Then
MsgBox error
End
End If

ReportResult = automationObject.RunReport("00Od0000004yulX", error1)

Dim wb As Excel.Workbook
Set wb = ThisWorkbook
Set ws = wb.Sheets("2016 Incidents Dashboard")

With ws.QueryTables.Add(Connection:="TEXT;" & ReportResult,           Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.RefreshStyle = xlOverwriteCells
.Refresh
End With

Result1 = automationObject.LogOut()

Worksheets("2016 Incidents Dashboard").Activate
LastRowLeft = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
LastRowRight = ws.Range("M" & ws.Rows.Count).End(xlUp).Row
Range("M" & LastRowRight & ":U" & LastRowRight).Select
Selection.AutoFill Destination:=Range("M" & LastRowRight & ":U" & LastRowLeft)

ActiveWorkbook.RefreshAll
 Worksheets(sheetname).Activate
End Sub


texts: Few concerns about specific session class

texts:
I am having a few issues about a session class that I found after reading it a lots of times,

Here is the class :

class SessionManager{
static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
session_set_cookie_params($limit, $path, $domain, $https, true);
session_start();
if(self::validateSession())
{

    if(!self::preventHijacking())
    {

        $_SESSION = array();
        $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
        $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
        self::regenerateSession();

    }elseif(rand(1, 100) <= 5){
        self::regenerateSession();
    }
}else{
    $_SESSION = array();
    session_destroy();
    session_start();
}
}

 static protected function preventHijacking()
 {
      if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
           return false;

      if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
           return false;

      if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
           return false;

      return true;
 }
 static function regenerateSession()
 {

      if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true)
           return;

      $_SESSION['OBSOLETE'] = true;
      $_SESSION['EXPIRES'] = time() + 10;
      session_regenerate_id(false);
      $newSession = session_id();
      session_write_close();
      session_id($newSession);
      session_start();
      unset($_SESSION['OBSOLETE']);
      unset($_SESSION['EXPIRES']);
 }
 static protected function validateSession()
 {
      if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
           return false;

      if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
           return false;

      return true;
 }

}

My concerns are:

Security [Fixation,Hijacking] , is the above a bulletproof ?
Usability I am unable to understand how to use the above code in terms of providing the user an authorized access as long not logging out was performed i.e after secure logging should I just keep calling session_start(parameters); and when logging out call session_destroy() [In addition to make the class functions public/protected .. ]; ?
I am unable to convince myself that this will not cause problems when redirecting between pages such as after submitting a form(like when pressing the back button [I am not attending to rely on JavaScript]),disconnecting and reconnecting
How do I integrate secure cookies mechanism with above code while maintaining a complete secure environment and compatibility with SECTION 3
Will the above code be compatible with these settings:

session.cookie_httponly = 1
session.session.use_only_cookies = 1
session.entropy_file = "/dev/urandom"
session.cookie_lifetime = 0
session.cookie_secure = 1

Should I integrate DB functionality to provide more security?,
As for AJAX,the above code is built to response to multiple Sessions requests,are there any related security issues about this ?

Original source http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions

I will be very happy if you could let me know your own thoughts,improvements,concerns about the above code to drive it into maximum security.


texts: Using GeoComplete with RequireJS (with shim config)

texts:
I am using the GeoComplete plugin with RequireJS
It works, but please could someone confirm I've done this correctly, mainly my understanding of shim:

    requirejs.config({
        waitSeconds: 120,
        paths: {
            async: './lib/async',
            jquery: './lib/jquery-1.7.2.min',
            geocomplete: './lib/jquery.geocomplete.min'
        },
        shim: {
            'geocomplete': ['jquery'],
        }
    });

    require(['async!http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false', 'jquery', 'geocomplete'], function () {
        $("#geocomplete").geocomplete({
            map: "#map_canvas"
        });
    }
    );

The way I understand shim, is, GeoComplete doesn't support AMD, but has a dependency on jQuery, so my set up basically says "load geocomplete after jquery"

Is that correct?


texts:
I'm writing a plugin and want it to have no dependencies. I create a form and append it to the page, but the code is really long. Does anyone have any suggestions to clean it up, perhaps shortening it? I feel like there must be a better way!

// Create elements
  var elements = [
      reporter_wrapper                = document.createElement('div'),
      reporter_close                  = document.createElement('button'),
      reporter_title                  = document.createElement('h1'),
      reporter_title_label            = document.createElement('label'),
      reporter_bug_title              = document.createElement('input'),
      reporter_priority_label         = document.createElement('label'),
      reporter_bug_priority           = document.createElement('select'),
      reporter_details_label          = document.createElement('label'),
      reporter_bug_details            = document.createElement('textarea'),
      reporter_user_label             = document.createElement('label'),
      reporter_user                   = document.createElement('input'),
      reporter_submit                 = document.createElement('button')];

  // // Add class names
  reporter_wrapper.className          = 'buggr__reporter';
  reporter_close.className            = 'buggr__reporter-close';
  reporter_title.className            = 'buggr__reporter-title';
  reporter_bug_title.className        = 'buggr__reporter-input';
  reporter_bug_priority.className     = 'buggr__reporter-select';
  reporter_bug_details.className      = 'buggr__reporter-textarea';
  reporter_user.className             = 'buggr__reporter-input';
  reporter_submit.className           = 'buggr__reporter-submit';

  // Input types
  reporter_user.type                  = 'text';
  reporter_bug_title.type             = 'text';

  // Populate title
  reporter_title.innerHTML            = 'Report a bug';

  // Populate label text
  reporter_title_label.innerHTML      = 'Bug title:';
  reporter_priority_label.innerHTML   = 'Bug priority:';
  reporter_details_label.innerHTML    = 'Bug details: <small>(Please include any specific steps to replicate)</small>';
  reporter_user_label.innerHTML       = 'Your name:'

  // Poulate submit button
  reporter_submit.innerHTML           = 'Submit Bug';

  // Populate select with options
  var select_options = ['Low', 'Medium', 'Hard'];
  for(var i = 0; i < select_options.length; i ++) {
    var option = document.createElement('option');
    option.value = select_options[i];
    option.innerHTML = select_options[i];
    reporter_bug_priority.appendChild(option);
  }

  // Create DOM tree
  for(var i = 1; i < elements.length; i ++) {
    reporter_wrapper.appendChild(elements[i]);
  }

  // Add event listeners
  reporter_close.addEventListener('click', this.close);
  reporter_submit.addEventListener('click', this.submit);

  // Append DOM tree
  document.body.appendChild(reporter_wrapper);


texts: IPC with over 100 different methods - viable way to maintain readability

texts:
I have a system with 2 different processes. Process 1 starts process 2 and sets up an AnonymousPipe between the 2. Process 1 needs to run some code and needs to interact with process 2 to get info and commit changes. Process 2 runs on Python with references to C# code (since I'm more familiar with C#) so process 2 has a while(true) loop to listen to process 1.
Process 2 has 3 classes that are "services" to underlying code. A simplified example:
// Runs under Process 2 (Python)
public class LibraryManager
{
   public string GetCategory(string something) // Step 3.1
   {
       return something;
   }
}

// Runs under Process 2 (Python)
public class Agent
{
    public void Run()
    {
        while (true)
        {
            // pipe is the anonymouspipe wrapped in an easy to handle class
            var function = pipe.Read<Command>(); // Step 2 - waits here for a write, halts code but this is ok for me
            switch (function)
            {
                case Command.LibraryManager_Category:
                    pipe.Write(LibraryManager.GetCategory("something"); // Step 3
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

// Runs under Process 1 (C#)
public class LibraryManagerService
{
    public string GetCategory()
    {
        CodesysEngine.Pipe.Write(Command.LibraryManager_Category); // Step 1
        return CodesysEngine.Pipe.Read<string>(); // Step 4 - this halts the code until the Agent does his write, this is ok for me
    }
}

I'm doing this communication now via an enum Command. This works. If I need to send data to Process 2 I can just write 2 things and bases on the Command change the type I read. (I've done some coding under the hood to be able to do this.)
What I'm not 100% satisfied with is the Command I use to tell the Agent which part of code to execute. This example only has 1 method but I see this growing to over 100 which will make it not very readable as it will be a switch with over 100 casees. I was thinking of splitting the enum per service and have a "master" enum with the 3 services as a divider. (First send which service, then send which method, then send any arguments if needed.)
Is there a more standardized way of doing what I want to achieve cause I have the feeling this can get pretty fast too big to handle?


texts: Langton's Ant cellular automaton in Ruby

texts:
I wrote a Langton's Ant cellular automaton simulator in Ruby using object oriented principles. This code works. It requires the drawille library.

I would like to get feedback on what I could do better here, from optimizing the display to cleaning up code. I'm also wondering what I could improve in code quality and style.

#!/usr/bin/env ruby

require 'drawille'

# Langton's Ant
# Draws in terminal

class Direction
    @dir = 0

    def initialize(direction)
        @dir = {up: 0, right: 1, down: 2, left: 3}[direction] || 0;
    end

    def transform_vector
        case @dir
        when 0
            return {x: 0, y: 1}
        when 1
            return {x: 1, y: 0}
        when 2
            return {x: 0, y: -1}
        when 3
            return {x: -1, y: 0}
        end
    end

    def turn_cw
        @dir = (@dir + 1) % 4
    end

    def turn_ccw
        @dir = (@dir + 3) % 4
    end
end

module State
    OFF = 0
    ON = 1
end

class Tile
    @state = State::OFF
    def initialize(state)
        @state = state
    end
    def state
        return @state
    end
    def flip
        if @state == State::OFF
            return @state = State::ON
        else
            return @state = State::OFF
        end
    end
    def bool
        return (@state == State::ON ? true : false)
    end
end

class Screen
    @screen = [];
    @canvas = Drawille::Canvas.new
    @x = 0
    @y = 0

    def initialize(x, y)
        @screen = Array.new(y) { Array.new(x) { Tile.new State::OFF } }
        @canvas = Drawille::Canvas.new
        @x = x
        @y = y
    end

    def inspect
        string = "";
        @screen.each do |i|
            i.each do |j|
                string << (j.bool ? '██' : '  ')
            end
            string << ?\n
        end
        return string
    end

    def screen
        return @screen
    end

    def flip(x, y)
        return @screen[y][x].flip
    end

    def print
        @screen.each_with_index do |row, y|
            row.each_with_index do |cell, x|
                if cell.state == State::ON
                    @canvas.set(x, y)
                else
                    @canvas.unset(x, y)
                end
            end
        end
        puts @canvas.frame
    end

    def x
        @x
    end

    def y
        @y
    end
end

class Ant
    @x = 0
    @y = 0
    @direction = :up
    @screen = nil

    def initialize(x, y, direction, screen)
        @x, @y, @direction, @screen = x, y, direction, screen
    end

    def current_cell
        @screen.screen[@y][@x]
    end

    def step
        if current_cell.state == State::ON
            @direction.turn_cw
        else
            @direction.turn_ccw
        end
        @screen.flip(@x, @y)
        @x = (@x + @direction.transform_vector[:x]) % @screen.x
        @y = (@y + @direction.transform_vector[:y]) % @screen.y
    end
end

def main
    screen = Screen.new(160, 96);
    ant = Ant.new(79, 47, Direction.new(:down), screen);

    loop do
        screen.print
        ant.step
    end
end

main


texts: Discord.py Bot : Sends with the loverate between 2 persons

texts:
I'm creating a Discord Bot and i made a !love command which is testing the love rate between 2 persons or entities.
Example : !love Peignoir Emma
Result: The loverate between Peignoir and Emma is x%
Here's the code :
@bot.command(name="love", aliases=["l"])
async def love(ctx, Personne1, Personne2):
    if ctx.message.channel.id != 763352957579690018:
        printIt = 1
        wordBanList = ['@everyone', '@here', '<@&763489250162507809>','<@&777564025432965121>','<@&822200827347075132>',
                       '<@&763815680306184242>','<@&764422266560839680<','<@&763815728972300338>','<@&763815728972300338>',
                       '<@&763815228323528725>','<@&763815784904261632>','<@&764422166116171806>','<@&764422057353936897>',
                       '<@&804807279043674143>','<@&828664814678179861>','<@&823562218095640646>','<@&823638574809219163>']
        LoveRate = str(random.randrange(0, 100))
        for y in range(len(wordBanList)):
            if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
                printIt = 0

        if(printIt == 0):
            await ctx.send("Tu t'es pris pour qui ?")
            if debug == True:
                print("[DEBUG] !love : Someone tried to use a banned word !")
        else:
            await ctx.send("L'amour entre **"+Personne1+"** et **"+Personne2+"** est de **"+LoveRate+"%** <:flushed:830502924479758356>")
            if debug == True:
                print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))
    else:
        botChannel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
        messageBot = await ctx.send("Va faire cette commande dans "+botChannel.mention+" ou je te soulève <:rage:831149184895811614>")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await messageBot.delete()

I'm pretty sure this code is optimizable, but i don't know how, can somebody help me :) ?


texts:
This is the bare bones of a SNAKE game that I'm working on, the code runs as is, I've taken great care to keep my code clean and readable. I would appreciate feedback on my code. I plan on creating some graphics to greatly improve the presentation and a menu and high scores.

import sys
import random
import pygame

pygame.init()

class Snake:

    RED = (200, 0, 0)
    BLUE = (0, 0, 190)
    BLACK = (0, 0, 0)
    GREEN = (0, 230, 0)

    score = 0
    xpos = 80
    ypos = 16
    direction = (1, 0)
    snake_tail = [[16, 16], [32, 16], [48, 16], [64, 16], [80, 16]]

    keys = {"GO": pygame.KEYDOWN, "UP": pygame.K_UP, "DOWN": pygame.K_DOWN,
            "LEFT": pygame.K_LEFT, "RIGHT": pygame.K_RIGHT
            }

    fps = pygame.time.Clock()

    def __init__(self, width, height):

        self.width = width
        self.height = height
        self.food_x = random.randint(1, width - 1) * 16
        self.food_y = random.randint(1, height - 1) * 16
        self.screen = pygame.display.set_mode((width * 16, height * 16))

    def main_loop(self):

        while True:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == self.keys["GO"] and event.key == self.keys["RIGHT"]:
                    self.direction = (1, 0)
                if event.type == self.keys["GO"] and event.key == self.keys["LEFT"]:
                    self.direction = (-1, 0)
                if event.type == self.keys["GO"] and event.key == self.keys["UP"]:
                    self.direction = (0, -1)
                if event.type == self.keys["GO"] and event.key == self.keys["DOWN"]:
                    self.direction = (0, 1)

            self.move_snake()
            self.fps.tick(12)

    def move_snake(self):

        self.xpos += self.direction[0] * 16
        self.ypos += self.direction[1] * 16
        self.snake_tail.append([self.xpos, self.ypos])
        segment = self.snake_tail.pop(0)

        pygame.draw.circle(self.screen, self.BLACK, (segment[0], segment[1]), 8)

        for segments in self.snake_tail:
            pygame.draw.circle(self.screen, self.BLUE, (segments[0], segments[1]), 8)

        pygame.draw.circle(self.screen, self.GREEN, (self.food_x, self.food_y), 8)
        pygame.draw.circle(self.screen, self.RED, (segments[0], segments[1]), 8)
        pygame.display.update()

        self.kill_snake()

    def kill_snake(self):

        if self.snake_tail[-1] in self.snake_tail[:-1]:
            pygame.quit()
            sys.exit()
        if self.xpos <= 0 or self.xpos >= self.width * 16 or self.ypos <= 0 or self.ypos >= self.height * 16:
            pygame.quit()
            sys.exit()

        self.feed_snake()

    def feed_snake(self):

        if self.xpos == self.food_x and self.ypos == self.food_y:
            self.score += 1
            pygame.display.set_caption(str(self.score))
            self.snake_tail.insert(0, [self.xpos, self.ypos])
            self.food_x = (random.randint(1, self.width - 1)) * 16
            self.food_y = (random.randint(1, self.height - 1)) * 16

Snake(25, 25).main_loop()


texts: Secure math expressions using PHP eval()

texts:
PHP's eval() is general considered insecure with any user input.

However, with filtering of input (i.e. [-+/*0-9]) you can make eval() secure for a small subset of PHP; mathematical expressions.

I've tried to think of a way to extend that by allowing a limited set of math functions and I believe I've found a secure way of doing it.

function expression($expression) {
    static $function_map = array(
        'floor'     => 'floor',
        'ceil'      => 'ceil',
        'round'     => 'round',
        'sin'       => 'sin',
        'cos'       => 'cos',
        'tan'       => 'tan',
        'asin'      => 'asin',
        'acos'      => 'acos',
        'atan'      => 'atan',
        'abs'       => 'abs',
        'log'       => 'log',
        'pi'        => 'pi',
        'exp'       => 'exp',
        'min'       => 'min',
        'max'       => 'max',
        'rand'      => 'rand',
        'fmod'      => 'fmod',
        'sqrt'      => 'sqrt',
        'deg2rad'   => 'deg2rad',
        'rad2deg'   => 'rad2deg',
    );

    // Remove any whitespace
    $expression = strtolower(preg_replace('~\s+~', '', $expression));

    // Empty expression
    if ($expression === '') {
        trigger_error('Empty expression', E_USER_ERROR);
        return null;
    }

    // Illegal function
    $expression = preg_replace_callback('~\b[a-z]\w*\b~', function($match) use($function_map) {
        $function = $match[0];
        if (!isset($function_map[$function])) {
            trigger_error("Illegal function '{$match[0]}'", E_USER_ERROR);
            return '';
        }
        return $function_map[$function];
    }, $expression);

    // Invalid function calls
    if (preg_match('~[a-z]\w*(?![\(\w])~', $expression, $match) > 0) {
        trigger_error("Invalid function call '{$match[0]}'", E_USER_ERROR);
        return null;
    }

    // Legal characters
    if (preg_match('~[^-+/%*&|<>!=.()0-9a-z,]~', $expression, $match) > 0) {
        trigger_error("Illegal character '{$match[0]}'", E_USER_ERROR);
        return null;
    }

    return eval("return({$expression});");
}

It's use would be simple: `$result = expression('floor(3 / 2)') and anything but math/boolean operators, numbers and a limited set of functions should be filtered out.

I can't find a way of hacking this expression() function, but I'd really like to have a second opinion on this.

Is the above expression function secure for user input?


texts: Social network queries for profiles, posts, and followers

texts:
The code below is for a social networking system. The problem is that when there are many posts and many followers, the performance is slow.  Is something wrong with the queries and the script below?

public function __construct($dbo = NULL)
{
    parent::__construct($dbo);
}

public function count()
{
    $count = 0;

    $stmt = $this->db->prepare("SELECT * FROM profile_followers WHERE follower = (:followerId) ORDER BY create_at DESC");
    $stmt->bindParam(':followerId', $this->requestFrom, PDO::PARAM_INT);

    if ($stmt->execute()) {

        while ($row = $stmt->fetch()) {

            $stmt2 = $this->db->prepare("SELECT count(*) FROM posts WHERE fromUserId = (:fromUserId) AND removeAt = 0 ORDER BY createAt DESC");
            $stmt2->bindParam(':fromUserId', $row['follow_to'], PDO::PARAM_INT);
            $stmt2->execute();

            $count = $count + $stmt2->fetchColumn();
        }
    }

    return $count;
}

public function getMaxId()
{
    $stmt = $this->db->prepare("SELECT MAX(id) FROM posts");
    $stmt->execute();

    return $number_of_rows = $stmt->fetchColumn();
}

public function get($itemId = 0)
{
    if ($itemId == 0) {

        $itemId = $this->getMaxId();
        $itemId++;
    }

    $feed = array("error" => false,
                  "error_code" => ERROR_SUCCESS,
                  "itemId" => $itemId,
                  "items" => array());

    $stmt = $this->db->prepare("SELECT * FROM profile_followers WHERE follower = (:followerId) ORDER BY create_at DESC");
    $stmt->bindParam(':followerId', $this->requestFrom, PDO::PARAM_INT);

    if ($stmt->execute()) {

        $items = array();

        while ($row = $stmt->fetch()) {

            $stmt2 = $this->db->prepare("SELECT id FROM posts WHERE fromUserId = (:fromUserId) AND id < (:itemId) AND removeAt = 0 ORDER BY id DESC");
            $stmt2->bindParam(':fromUserId', $row['follow_to'], PDO::PARAM_INT);
            $stmt2->bindParam(':itemId', $itemId, PDO::PARAM_INT);
            $stmt2->execute();

            while ($row2 = $stmt2->fetch())  {

                $items[] = array("id" => $row2['id'], "itemId" => $row2['id']);
            }
        }

        $stmt3 = $this->db->prepare("SELECT id FROM posts WHERE fromUserId = (:fromUserId) AND id < (:itemId) AND removeAt = 0 ORDER BY id DESC");
        $stmt3->bindParam(':fromUserId', $this->requestFrom, PDO::PARAM_INT);
        $stmt3->bindParam(':itemId', $itemId, PDO::PARAM_INT);
        $stmt3->execute();

        while ($row3 = $stmt3->fetch())  {

            $items[] = array("id" => $row3['id'], "itemId" => $row3['id']);
        }

        $currentItem = 0;
        $maxItem = 20;

        if (count($items) != 0) {

            arsort($items);

            foreach ($items as $key => $value) {

                if ($currentItem < $maxItem) {

                    $currentItem++;

                    $item = new post($this->db);
                    $item->setRequestFrom($this->requestFrom);

                    $itemInfo = $item->info($value['itemId']);

                    array_push($feed['items'], $itemInfo);

                    $feed['itemId'] = $itemInfo['id'];

                    unset($itemInfo);
                    unset($item);
                }
            }
        }
    }

    return $feed;
}

public function setRequestFrom($requestFrom)
{
    $this->requestFrom = $requestFrom;
}

public function getRequestFrom()
{
    return $this->requestFrom;
}

}


texts: Simple multithreading and synchronization problems in MFC

texts:
I use a worker thread for some data processing in my MFC project. In the thread-controlling function, it needs to use some parameters (declared as member variables) to the data-processing. I use a sub-dialog (which is triggered by a menu item and contains a few edit controls) to change the values of the parameters, that the user inputs are first stored in a struct, which is then used in the thread controlling function when needed. In order to prevent data-corruption, I also use Mutex to sync the worker thread and main thread, since both of them need to access the shared resource m_structBlkContSimPara (the struct that stores parameter values).

/*the following code is in my MFC Dlg Project head file*/

struct RecExtractParam {
    bool bMod;

    float fSimBlkShpWt;
    float fSimGrPosWt;
    float fSimGrTxtAttWt;
    float fSimGrTypesWt;
    float fDataUnitGroupSimThld;
    float fVertDistThld;

RecExtractParam() {
    bMod = false;
    fSimBlkShpWt = 0;
    fSimGrPosWt = 0;
    fSimGrTxtAttWt = 0;
    fSimGrTypesWt = 0;
    fDataUnitGroupSimThld = 0;
    fVertDistThld = 0;
}};

RecExtractParam m_structBlkContSimPara;

// parameters for some data processing
float m_fSimBlkShpWt;
float m_fSimGrPosWt;
float m_fSimGrTxtAttWt;
float m_fSimGrTypesWt;
float m_fDataUnitGroupSimThld;
float m_fVertDistThld;

CMutex m_Mutex;

afx_msg void OnToolsBlockContentSimilarityThreshold();

static UINT RecExtractThreadCtrlFunc(LPVOID pParam);

UINT DoThreadProc();

// button clicked handler for launching data processing

void CXMLDOMFromVCDlg::OnBnClickedDataRecExtractButton()
{
    // TODO: Add your control notification handler code here

    // some code for other processing
    // start the thread for data record extraction

    AfxBeginThread(RecExtractThreadCtrlFunc, this);

    // some code for other processing
}

// menu item command handler for parameter inputs

void CXMLDOMFromVCDlg::OnToolsBlockContentSimilarityThreshold()
{
    // TODO: Add your command handler code here
    // CBlkContSimThldDlg is a sub-dialog for user input
    CBlkContSimThldDlg dlgBlkContSimThld(this);

    if (dlgBlkContSimThld.DoModal() == IDOK)
    {
        CSingleLock singleLock(&m_Mutex);
        // try to capture the shared resource
        singleLock.Lock();
        m_structBlkContSimPara.bMod = true;
        m_structBlkContSimPara.fDataUnitGroupSimThld =  dlgBlkContSimThld.m_fDlgBlkContSimThld;
        m_structBlkContSimPara.fSimBlkShpWt = dlgBlkContSimThld.m_fDlgGrShpWt;
        m_structBlkContSimPara.fSimGrPosWt = dlgBlkContSimThld.m_fDlgGrPosWt;
        m_structBlkContSimPara.fSimGrTxtAttWt = dlgBlkContSimThld.m_fDlgGrTxtAttWt;
        m_structBlkContSimPara.fSimGrTypesWt = dlgBlkContSimThld.m_fDlgGrContTypeWt;
        m_structBlkContSimPara.fVertDistThld = dlgBlkContSimThld.m_fDlgGrVertDistThld;
        singleLock.Unlock();
   }
}

// thread controlling function

UINT CXMLDOMFromVCDlg::RecExtractThreadCtrlFunc(LPVOID pParam)
{
    CXMLDOMFromVCDlg* pDlg = (CXMLDOMFromVCDlg*)pParam;

    return pDlg->DoThreadProc();
}

UINT CXMLDOMFromVCDlg::DoThreadProc()
{
    // Create object for Single Lock
    CSingleLock singleLock(&m_Mutex);
    // try to capture the shared resource
    singleLock.Lock();
    // use the shared resource m_structBlkContSimPara
    if(m_structBlkContSimPara.bMod)
    {
        m_fSimBlkShpWt = m_structBlkContSimPara.fSimBlkShpWt;
        m_fSimGrPosWt = m_structBlkContSimPara.fSimGrPosWt;
        m_fSimGrTxtAttWt = m_structBlkContSimPara.fSimGrTxtAttWt;
        m_fSimGrTypesWt = m_structBlkContSimPara.fSimGrTypesWt;
        m_fDataUnitGroupSimThld = m_structBlkContSimPara.fDataUnitGroupSimThld;
        m_fVertDistThld = m_structBlkContSimPara.fVertDistThld;
        m_structBlkContSimPara.bMod = false;
    }
    // After we done, let other threads use m_structBlkContSimPara
    singleLock.Unlock();
    /*some code for data processing*/
 }

I am new to multithreading and synchronization.  Is my code correct?  If not, what should I do to improve it?


texts: Extracting ids out of arguments of different types

texts:
I'm building a Ruby API client. My brief is to extract ids out of various inputs and fetch the relevant data. It's working just fine at the moment but I think it's a little clumsy.

My specs (which pass):

shared_examples 'it requests ids' do |resource|
  it 'sends the ids to Foo::Client' do
    Foo.stub(:parse)
    Foo::Client.should_receive(resource).once.with(expected)
    Foo.send(resource, *args)
  end
end

describe Foo do
  describe 'resources have numeric ids only'
    [:accounts, :contacts].each do |resource|
      it_behaves_like 'it requests ids', resource do
        let(:args) { [1, 2] }
        let(:expected) { [1, 2] }
      end

      it_behaves_like 'it requests ids', resource do
        let(:args) { [3, 'jesse-pinkman', 5, {'links' => {resource.to_s => [98, 99]}}] }
        let(:expected) { [98, 99, 3, 5] }
      end
    end
  end

  describe 'resources have numeric and string ids'
    [:clients, :services].each do |resource|
      it_behaves_like 'it requests ids', resource do
        let(:args) { [2,'saul-goodman', 6] }
        let(:expected) { [2, 6, 'saul-goodman'] }
      end

      it_behaves_like 'it requests ids', resource do
        let(:args) { [3, 'saul-goodman', 5, {'links' => {resource.to_s => [202, 234]}}] }
        let(:expected) { [202, 234, 3, 5, 'saul-goodman'] }
      end
    end
  end
end

And my code:

module Foo
  class << self
    [:accounts, :contacts, :clients, :services].each do |resource|
      define_method(resource) do |*args|
        ids = []
        unless args.empty?
          ids += hash_ids(args, resource)
          ids += numeric_ids(args)
          ids += text_ids(args) unless numeric_ids_only?(resource)
        end
        parse(client.send(resource, ids))
      end
    end

    private

    def hash_ids(args, resource)
      args.collect { |arg| arg['links'][resource.to_s] if arg.is_a? Hash }.compact!.flatten!.to_a
    end

    def numeric_ids(ids)
      ids.select { |id| !id.is_a?(Hash) && id.to_i > 0 }
    end

    def text_ids(ids)
      ids.select { |id| id.is_a? String }
    end

    def numeric_ids_only?(resource)
      [:accounts, :contacts].include?(resource)
    end

    def client
      Foo::Client
    end

    def parse(json)
      Foo::Adapter::JSON.parse(json)
    end
  end
end

My particular concern is the ugly concatenating of the ids array and passing all those args around. Any tips?


texts:
I have written my first regex:

static void Main(string[] args)
{
    string phoneNumber= Console.ReadLine();

    Regex pattern = new Regex("(1-)?\\p{N}{3}-\\p{N}{3}-\\p{N}{4}\\b");

    MatchCollection collection = pattern.Matches(phoneNumber);

    Console.WriteLine(phoneNumber + " is " + (collection.Count == 1 && collection[0].ToString() == phoneNumber ? "" : "not ") + "a valid US number.");
}

It needs to match the entire input string, and it can work for any US phone number with or without country code "1-". It can most likely be improved; any suggestions?


texts: Less-repetitive code for document-analyzer

texts:
I've refactored my code such that every function has only one responsibility. Now I'd like like to work on making it DRY.

I'm noticing a lot of duplication in the DocumentAnalyzer class. In nearly every function, I make a reference to @document.

Should my one-statement functions be collapsed into one line?

require 'set'

class Document
    attr_reader :words
    def initialize(words)
        @words = words
    end
end

class DocumentAnalyzer
    def initialize(document)
      @document = document
    end

    def unique_words
        @document.words.to_set
    end

    def unique_words_count
        unique_words.count
    end

  def word_count
    @document.words.size
  end

  def total_characters
    total = 0.0
    @document.words.each { |word| total += word.size }
    total
  end

  def average_word_length
    total_characters / word_count
  end
end

d = Document.new %w(here are some words)
da = DocumentAnalyzer.new(d)


texts: I would like to know if the following code is 'good'

texts:
I would like a serious, blunt and cold judgement on this code.  Would it be considered 'good' code?  In general, is it well written?  Is the design reasonable?

#include <iostream>   // C++ IO library code to include.
#include <string>     // C++ string functions.
using namespace std ; // Use standard C++ names for functions.

//====== class declaration.

class Tpacket_list
{public: // functions that are available to code outside the class.
    // put the command line into the list.
    Tpacket_list(int param_index, string param) ;
    void print_list() ; // print the list.
    Tpacket_list* find( string target) ;
    int    tell_id() ;
    string tell_payload() ;

 protected:                //  Data in a class is normally hidden from other code.
    string payload ;       // C++ strings are classes so this is aggregation.
    int id ;               // Such strings are more powerful and easier to use
    Tpacket_list *next ;   //   than the older C string routines, also slower!
} ;

Tpacket_list *list_head ;  // Start of linked list, set to 1st item.
Tpacket_list *work_ptr ;   // Work pointer to work along list.

//====== Class Body =========================================================

//------ Constructor gets called when the class is created. It puts in the
//       payload and sets up the chain of pointers.All this is hideen from
//       the user of the class.
Tpacket_list::Tpacket_list(int param_index, string param)
{//--- save information for this parameter.
   id = param_index ;
   payload = param ;
   cout << "    Adding parameter # " << id << ", value = " << payload << endl ;
 //--- form list.
   next = list_head ;
   list_head = this ;
}

//------ Print the list.  Note how the function calls the print_list function
//       in the next item in the link list.
//       Function prints from the current link list item to the end.
void Tpacket_list::print_list()
{//---
   cout << "    id = " << id << ",  payload = " << payload << ", length " << payload.length() << " characters."<< endl ;
   if ( next != NULL) // if there is a next item, get it to print itself.
     next->print_list() ;
}

//------ Find item in the list.
Tpacket_list* Tpacket_list::find( string target)
{//---
   if ( payload == target)
      return ( this) ;          // return pointer to current object.
   if ( next == NULL)
      return( NULL) ;           // end of list, not match, return NULL.
   //--- if got here there is a valid next.
   return( next->find( target)) ;
}

//------ Tell of internal data.
int    Tpacket_list::tell_id()
 { return( id) ;
 }

string Tpacket_list::tell_payload()
 { return( payload) ;
 }

//====== Start program here =================================================

int main(int argc, char *argv[]) // argc = number strings on command line.
                                 // argv is array of strings each holding
                                 //   a parameter.

{//--- Initialize link list with command parameters.
   cout << endl << "  Form link list of command line parameters." << endl ;
   list_head = NULL ;
   int i = 1 ;
   while ( i < argc)
    { new Tpacket_list(i, argv[i]) ;
      i++ ;
    }

 //--- print out the list.
   cout << "  Print paramters from head of list the end of list." << endl ;
   if ( list_head != NULL)
        list_head->print_list() ;
   else cout << "   List is empty." << endl ;

 //--- search for parameters
   cout << "  Find first 0 parameter (working last to first parameter, list head to tail)." << endl ;
   Tpacket_list *found ;
   if ( list_head != NULL)
     { found = list_head->find("0") ;
       if ( found != NULL)
            cout << "    Found target on parameter # " << found->tell_id()  << endl ;
       else cout << "    No \"0\" found." << endl ;
     }

   cout << endl ;
   return(0) ;
}

P.S. It's not my code, it's actually the lecturer's.


texts: Python class inheritance - using super() and __str__

texts:
I have been trying out some stuff using inheritance with classes in Python 3.4. In the code below, I use the super() call to return the __str__ from the parent class. Is it correct coding practice to save the information returned by the parent class method in a variable, concatenate the __str__ from the child class to that of the parent class, and return like I did twice below?

Also, what would be best coding practice to convert such output to a string? Would it be better to

Do this also in the parent class.
Also in the child class.
When printing - in this case - Director or Manager?

class Employee:
   def __init__(self, name, salary, position):
      self._name = name
      self._salary = salary
      self._position = position

   def __str__(self):
      return str(self._name) + ' ' + str(self._salary) + ' ' + str(self._position)

class Director(Employee):
   def __init__(self, name, salary, position, mngteam):
      super().__init__(name, salary, position)
      self.managementteam = mngteam

   def __str__(self):
      st = super().__str__() # IS THIS GOOD CODING PRACTICE?
      st += ' ' + str(self.managementteam)
      return st

class Manager(Employee):
   def __init__(self, name, salary, position, supervises):
      super().__init__(name, salary, position)
      self.supervises = supervises

   def __str__(self):
      st = super().__str__() # IS THIS GOOD CODING PRACTICE?
      st += ' ' + str(self.supervises)
      return st

d = Director('DirMax', 100000, 'Director', 5)
print(d)
m = Manager('ManSam', 50000, 'Manager', 10)
print(m)


texts: T-test Independence for a Pandas DataFrame

texts:
I want to calculate the scipy.stats.ttest_ind() for numeric columns in a pandas DataFrame with the binary target variable.
import pandas as pd
from scipy import stats

def calculate_tStatistic(df, target, numeric_cols):

    """
    Calculate the t-test on TWO RELATED samples of scores, a and b.

    This is a two-sided test for the null hypothesis that 2 related or
    repeated samples have identical average (expected) values.

    Params
    =====================================
    df               : dataframe
    target           : target column name(str)
    numeric_cols     : list of numeric columns

    Return
    =======================================
    results_df       : A dataframe with features and t-statistic p-val
    """

    # create an empty dictionary
    t_test_results = {}
    # loop over column_list and execute code
    for column in numeric_cols:
        group1 = df.where(df[target] == 0).dropna()[column]
        group2 = df.where(df[target] == 1).dropna()[column]
        # add the output to the dictionary
        t_test_results[column] = stats.ttest_ind(group1,group2)
    results_df = pd.DataFrame.from_dict(t_test_results,orient='Index')
    results_df.columns = ['t-statistic','t_stat_pval']

    results_df.reset_index(inplace=True)
    results_df.rename(columns = {"index":"x"}, inplace=True)
    return results_df

Sample
import seaborn as sns
titanic = sns.load_dataset("titanic")

calculate_tStatistic(titanic, "survived", ["age", "fare"])

Results
      x       t-statistic     t_stat_pval
0    age        3.479558       0.000630
1    fare      -1.767759       0.078795

Can someone confirm that I'm actually doing it the right way?
Is there a better / more elegant / more accurate way to do this??


texts: Using a navigation menu to help keep material organized

texts:
I'm working on a personal project to keep different snippets/examples/small projects of mine organized. I want to make the most of my page width, so I decided to write a navigation menu that slides out. It works as expected, but the code is kinda big.

I provided the HTML/CSS just in case that helps, but I'm really only looking for help with the JavaScript. I don't need anyone to rewrite the whole thing.

$(document).ready(function() {
 $('#tab').click(function() {
  if($('#main').attr('class') != 'out') {
     $('#main').animate({
      'margin-left': '+=340px',
       }, 500, function() {
       $('#main').addClass('out');
       });

    } else {
      $('#main').animate({
       'margin-left': '-=340px',
        }, 500, function() {
       $('#main').removeClass('out');
        });

     }
    });

    //does the same as above, but when I press ctrl + 1. from /http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/
    $(document).keyup(function (e) {
     if(e.which == 17) isCtrl=false;
      }).keydown(function (e) {
       if(e.which == 17) isCtrl=true;
       if(e.which == 97 && isCtrl == true) {
        if($('#main').attr('class') != 'out') {
           $('#main').animate({
            'margin-left': '+=340px',
             }, 500, function() {
             $('#main').addClass('out');
             });

          } else {
            $('#main').animate({
             'margin-left': '-=340px',
              }, 500, function() {
             $('#main').removeClass('out');
              });

           }
            return false;
           }
    });
   });
#sidebar {
 top: 0;
 left: 0;
 position: relative;
 float: left;
 }

#main {
 width: 320px;
 padding: 10px;
 float: left;
 margin-left: -340px;
 }

#tab {
 width: 30px;
 height: 120px;
 padding: 10px;
 float: left;
 }

.clear { clear: both; }


texts: Selecting users with biopsies in a given country for charting

texts:
I have this monstrosity

    @nation_biopsy =
       User.all.where(country: @nation).group_by{ |u| [u.institute_type, u.biopsy] }
      .map{ |i, o| ["name" => i[0], "y" => User.where(id: o.map(&:id))
      .sum("biopsy")]}.flatten.to_json

What it is doing is finding all the users in my database that belong to a country (@nation) and grouping them according to their "institute_type" and then "biopsy" (both columns for users). Then it is trying to convert it to an array of JSON objects for a "Highcharts" script. It works, but as a newbie I am sure this is very database heavy. Is there a better way?


texts:
Purpose:
Given a 2-Dimensional Array, return a copy of the Array. In VBA, if I just

Set newArray = oldArray

then newArray is simply a pointer to oldArray rather than an independent copy, hence this function.

Method:
Assign Array bounds. Create identically-sized Array. Iterate over Array and copy each element value.

Specific Areas of Interest:
The function feels very generic. The naming even more so. But then again it's supposed to be very generic. Is the naming alright or could it be better?

Function:

Private Function CopyOf2DArray(ByRef targetArray As Variant) As Variant
    '/ Will error if the array contains objects

    Dim LB1 As Long, UB1 As Long
    Dim LB2 As Long, UB2 As Long
    AssignArrayBounds targetArray, LB1, UB1, LB2, UB2

    Dim newArray As Variant
    ReDim newArray(LB1 To UB1, LB2 To UB2)

    Dim i As Long, j As Long
    For i = LB1 To UB1
        For j = LB2 To UB2
            newArray(i, j) = targetArray(i, j)
        Next j
    Next i

    CopyOf2DArray = newArray

End Function


texts: Comparing a string that can hold a numeric value

texts:
I am refactoring a part of big old system developed in Java. I came across a situation where we are migrating some data types, and there will be use of both types. For compatibility, as all the old part will remain using id as an int, I simply overloaded the constructor, and the old getter now parse a integer value.

The thing is, how is the proper way to compare this data? Does this way make any sense, or is there a simpler way to compare it, considering that id can be both, a number or a word.

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

public class SomeItem implements Comparable<SomeItem> {
    private String id;

    public SomeItem(String id) {
        this.id = id;
    }

    public SomeItem(int no) {
        this(String.valueOf(no));
    }

    public String getId() {
        return id;
    }

    public int getNo() {
        return Integer.parseInt(id);
    }

    @Override
    public int compareTo(SomeItem that) {
        if (StringUtils.isNumeric(this.getId()) && StringUtils.isNumeric(that.getId())) {
            return this.getNo() - that.getNo();
        } else {
            return this.getId().compareTo(that.getId());
        }
    }
}


texts: Sending a HttpRequest Message, and retrying in case of unauthorised

texts:
This code simply sends a HttpRequest message and, if it comes back Unauthorized, gets a new login and tries again.

This code is meant to deal with the moment a JSON Web Token goes out of date. In this system the client is notified of this by having its request become Unauthorized, it then picks up a new Token by logging on again. Hiding away that Unauthorized code, it continues to message.

Two things to note:

A HttpRequestMessage has to be recreated every time it is used.
I have a need to recreate the client to pick up the new JWT token

(Edit: Actually can just go in and change some properties for client, I assume it would be worth changing?)

Basically my question is: How unpleasant is my use of delegates and what lengths should I go to change this code, if any?

private async Task<HttpResponseMessage> SendToFooAsync(Func<HttpClient> client, Func<HttpRequestMessage> requestMessage)
{
    var response = await client().SendAsync(requestMessage());

    if (response.StatusCode == HttpStatusCode.Unauthorized)
    {
        //Re-authenticate, recreate client with new token, and retry
        if (await authService.LoginAsync())
        {
            response = await client().SendAsync(requestMessage());
            Log.Log("Unauthorized code received: Re-Authentication attempt succeeded");
        }
        else
        {
            Log.Log("Unauthorized code received: Authentication attempt has failed");
        }
    }
    return response;
}

Simplest code that calls it:

HttpResponseMessage result = await SendToFooAsync(InitialiseHttpClient, () => InitialiseRequest(HttpMethod.Post, path));

Most complex code that calls it

Func<HttpClient> client = () =>
            {
                var httpClient = InitialiseHttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add("some json stuff");
                return httpClient;
            };

HttpResponseMessage result = await SendToFooAsync(client, () =>
{
    var message = InitialiseRequest(HttpMethod.Post, path);
    message.Content = new StringContent("some json stuff");
    return message;
});

Where InitialiseRequest and LoginAsync are my own methods outside the scope of this review. Hopefully their use is obvious here.


texts: How to design shopping cart Java application which satisfy modular, extensible and maintainable

texts:
I am new in Application Design. I have use-case as below

As per the above story I have implemented code as below without any Modularity, Extensible and Maintainable. Could someone share the thoughts how to design below bad code to production grade application ?

Based on this story context, there could be other stories which could build-upon in later.
Example: Introduce new customer types like Gold, Diamond, Platinum, etc and their discounts slabs.

I really appreciate if some one have a look at the code below and let me know the how to design before creating data members, Interfaces and classes of improvements.

public class ShoppingCartDiscount {

    public static void main(String args[]) {
        System.out.println("Price for the premium customer: " + calculatePrice("Premium", 20000));
        System.out.println("Price for the regular customer: " + calculatePrice("Regular", 8000));
    }

    static float calculatePrice(String customerType, float purchaseAmount) {

        float total = 0;
        if (customerType.equalsIgnoreCase("Regular") {

            if (purchaseAmount > 5000 && purchaseAmount <= 10000) {

                float firstSlab = purchaseAmount - 5000;

                firstSlab = firstSlab - (float) (firstSlab * 0.1);

                total = 5000 + firstSlab;
            }

            else if (purchaseAmount > 10000) {

                float secondSlab = purchaseAmount - 10000;

                secondSlab = secondSlab - (float) (secondSlab * 0.2);

                float firstSlab = 10000 - 5000;

                firstSlab = firstSlab - (float) (firstSlab * 0.1);
                System.out.println("firstSlab:" + firstSlab);

                total = 5000 + firstSlab;

                total = total + secondSlab;

            } else if (purchaseAmount <= 5000 && purchaseAmount >= 0) {

                total = purchaseAmount;

            } else {
                return purchaseAmount;
            }

        } else if (customerType.equalsIgnoreCase("premium")) {
            if (purchaseAmount <= 4000) {

                total = purchaseAmount - (float) (purchaseAmount * 0.1);

            }
            if (purchaseAmount > 4000 && purchaseAmount <= 8000) {

                float secondSlab = purchaseAmount - 4000;

                secondSlab = secondSlab - (float) (secondSlab * 0.15);

                float firstSlab = 8000 - 4000;

                total = firstSlab - (float) (firstSlab * 0.1);

                total = total + secondSlab;
            }

            if (purchaseAmount > 8000 && purchaseAmount <= 12000) {

                float thirdSlab = purchaseAmount - 8000;

                thirdSlab = thirdSlab - (float) (thirdSlab * 0.20);

                float secondSlab = 8000 - 4000;

                secondSlab = secondSlab - (float) (secondSlab * 0.15);

                float firstSlab = 8000 - 4000;

                total = firstSlab - (float) (firstSlab * 0.1);

                total = total + secondSlab + thirdSlab;

            }
            if (purchaseAmount > 12000) {

                float fourthSlab = purchaseAmount - 12000;

                fourthSlab = fourthSlab - (float) (fourthSlab * 0.30);

                float thirdSlab = 8000 - 4000;

                thirdSlab = thirdSlab - (float) (thirdSlab * 0.20);

                float secondSlab = 8000 - 4000;

                secondSlab = secondSlab - (float) (secondSlab * 0.15);

                float firstSlab = 8000 - 4000;

                total = firstSlab - (float) (firstSlab * 0.1);

                total = total + secondSlab + thirdSlab + fourthSlab;

            }
        }

        return total;
    }

}


texts:
I have the following sample data:

target <- "Stackoverflow"
candidates <- c("Stackflow", "Stackflow", "Stckoverfow")

I would like to filter the string from candidates that has the lowest (levensthein) distance to the target string.

I decided to use the pipe operator to improve readability. However, i find it suboptimal that adist doesnt return the strings that corresponds to the distances.

My attempts:

Version 1)

library(magrittr)
candidates  %>%
  adist(y = target) %>%
  which.min %>%
  `[`(x = candidates, i = .)

Version 2)

library(dplyr)
candidates %>%
  adist(y = target) %>%
  data.frame(dist = ., candidates = candidates) %>%
  filter(dist == min(dist)) %>% select(candidates)

Goal:

I want to Improve readability. Memory usage or performance do not matter as data
is pretty small. Using additional packages, like dplyr, is also fine.

In version 1 i think
     `[`(...) is bad to read.

Version 2 seems better to me. But it does not seem optimal to me, that i have to add the strings to the data.frame after having applied adist() to them: data.frame(dist = ., candidates = candidates).


texts:
I am implementing a flood fill algorithm using Python and NumPy.  I have written the following fill function which works fine:

def fill(self, data, xsize, ysize, x_start, y_start):

    stack = [(x_start, y_start)]

    while stack:
        x, y, stack = stack[0][0], stack[0][1], stack[1:]

        if data[x, y] == 1:
            data[x, y] = 2
            if x > 0:
                stack.append((x - 1, y))
            if x < (xsize - 1):
                stack.append((x + 1, y))
            if y > 0:
                stack.append((x, y - 1))
            if y < (ysize - 1):
                stack.append((x, y + 1))

I wanted to implement a way that would eliminate the need to re-check a point if it had already been checked. By creating a new list of checked points and then comparing to see if the current point is already in that list, but this ended up making it slower and I wanted to understand if there is a more efficient way to improve upon my existing implementation.


texts: Looking cleaner code of Python Combining Image with PIL

texts:
Please review and help me write better codes.
Combining Pictures
We can use a conditional to copy just the non-white pixels from one picture to another picture. We can take this tiny image of the women and put her by the Eiffel tower in Paris, France. I have modified the code so that the code automatically swaps the image1 and image2; hence, always using the larger image as the canvas and the smaller picture as the insert.
from PIL import Image

image1 = Image.open("lady_tiny.jpg")
image2 = Image.open("eiffel.jpg")

width = min(image1.size[0], image2.size[0])  # (x)
length = min(image1.size[1], image2.size[1])  # (y)

# check if smaller image then use it as insert
if width == image2.size[0] and length == image2.size[1]:
    canvas = image1.load()  # larger pic
    insert = image2.load()  # smaller pic
else:
    insert = image1.load()
    canvas = image2.load()

for col in range(width):
    for row in range(length):
        r, g, b = insert[col, row]  # read each pixel of insert(small)

        # Check if the pixel isn't white
        if r < 250 and g< 250 and b< 250:
            # Copy the color of insert (smaller) onto the canvas(larger)
            canvas[col, row + 130] = r, g, b

if (
    width == image2.size[0] and length == image2.size[1]
):  # if image2 is insert then image 1 is canvas
    image1.show()
else:
    image2.show()


texts:
I'm reading a data structure and algorithm book in C.  I have implemented a generic single linked list in the C programming language, and I want to know your opinion on my implementation:

linked_list.h

#ifndef LINKED_LIST_H_INCLUDED
#define LINKED_LIST_H_INCLUDED

#define list_size(list) (list->size)

#define list_head(list) (list->head)
#define list_tail(list) (list->tail)
#define list_is_head(list, element) (element == list_head(list))
#define list_is_tail(list, element) (element == list_tail(list))

#define list_append(list, data)     list_ins_next(list, list->tail, data)
#define list_preprend(list, data)   list_ins_next(list, NULL, data)

#define list_data(element)  (element->data)
#define list_next(element)  (element->nextElmt)

typedef struct ListElmt_{
    void *data;
    struct ListElmt_ *nextElmt;
} ListElmt;

typedef struct List_{
    ListElmt *head;
    ListElmt *tail;
    size_t size;
    void (*destroy)(void *data);
    int (*cmp)(const void *fdata,const void *sdata);
}List;

List *list_init(void (*destroy)(void *data),
        int (*cmp)(const void *fdata, const void *sdata));
void list_destroy(List *list);
int list_ins_off(List *list, size_t off, void *data);
int list_ins_next(List *list, ListElmt *element, void *data);
int list_drem_next(List *list, ListElmt *element);
int list_rem_next(List *list, ListElmt *element, void ** data);
ListElmt * list_find(List *list, void *data, ListElmt *sElmt);

#endif

linked_list.c

#include <stdlib.h>

#include "linked_list.h"

List * list_init(void (*destroy)(void *data),
        int (*cmp)(const void *fdata, const void *data))
{
    List *rlist;

    if((rlist = malloc(sizeof *rlist)) != NULL) {
        rlist->head = NULL;
        rlist->tail = NULL;
        rlist->size = 0;
        rlist->destroy = destroy;
        rlist->cmp = cmp;
    }

    return rlist;
}

void list_destroy(List *list) {

    ListElmt * el;
    void *data;

    while( (el=list_head(list)) != NULL) {
        list_rem_next(list, NULL, &data);
        list->destroy(data);
    }

    free(list);
}

int list_ins_next(List *list, ListElmt *elmt, void *data) {

    ListElmt *addElmt = malloc(sizeof *addElmt);
    if(addElmt == NULL)
        return -1;

    addElmt->data = data;

    if(elmt == NULL) {
        addElmt->nextElmt = list->head;
        elmt = list->head = addElmt; // using elmt for checking list tail
    }
    else {
        addElmt->nextElmt = elmt->nextElmt;
        elmt->nextElmt = addElmt;
    }

    // updating list->tail if needed
    if(elmt == list->tail)
        list->tail = addElmt;

    list->size++;

    return 0;
}

int list_ins_off(List *list, size_t off, void *data) {
    if(off < 0 || off >= list->size)
        return list_append(list, data);

    size_t i;
    ListElmt *elmt = NULL;

    for(i = 0; i < off; ++i)
        elmt = elmt->nextElmt;

    list_ins_next(list, elmt, data);
    return 0;
}

int list_drem_next(List *list, ListElmt *element) {
    void *data;
    int ret = list_rem_next(list, element, &data);

    if(ret != 0)
        return ret;

    list->destroy(data);
    return 0;
}

int list_rem_next(List *list, ListElmt *element, void **data) {
    ListElmt *remElmt;

    // the list still not contain any element
    if(list->size == 0 || element->nextElmt == NULL)
        return -1;

    *data = element->nextElmt->data;
    remElmt = element->nextElmt;

    element->nextElmt = element->nextElmt->nextElmt;

    if(remElmt == list->tail)
        list->tail = element;

    free(remElmt);
    list->size--;

    return 0;
}

ListElmt * find(List *list, void *data, ListElmt *sElmt) {
    if(list->size == 0 || list->cmp == NULL)
        return NULL;

    sElmt = sElmt ? sElmt : list_head(list);

    while(sElmt && list->cmp(sElmt->data, data))
        sElmt = sElmt->nextElmt;

    return sElmt;
}


texts:
Given an array of integers arr:

Write a function flip(arr, k) that reverses the order of the first k elements in the array arr.
Write a function pancakeSort(arr) that sorts and returns the input array.

You are allowed to use only the function flip you wrote in the first step in order to make changes in the array.

Example:

input:  arr = [1, 5, 4, 3, 2]

output: [1, 2, 3, 4, 5] # to clarify, this is pancakeSort's output

My approach:

import java.io.*;
import java.util.*;

class Solution {

  static int[] pancakeSort(int[] arr) {
    // your code goes here
    int max = -1000,maxpos = 0 ;
    //3 1 2 4 6 5 -->  6 4 2 1 3 5
    for(int i = 0; i < arr.length; i++ )
    {
      max = -1000;
    for( int c = i; c < arr.length; c++ )
      {
        if( max <= arr[c] )
        {
          max = arr[c];
          maxpos = c;
        }
       }
      arr = flip(arr,i,maxpos+1);
    }
    arr = flip(arr,0,arr.length);
   return arr;
  }

  // 3 1 2 4 6 -> 6 4 2 1 3 5
  // k = 5 ->
  static int[] flip(int [] arr,int start , int k)
  {
     int temp;

     for(int i = start, j = k - 1; i < j; i++, j-- )
     {
           temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
     }
     return arr;
   }

  //
   //1 5 4 3  -> 3 4 5 1
//54321

  1 5 4 3 2 --> flip(arr, maxpos) -> 5 1 4 3 2 --> flip(arr,arr.length ) -> 2 3 4 1 5

  public static void main(String[] args) {

  }

}

I have the following questions about my code:

Can I further improve my space and time complexity?
Is there any other alternative, smarter way to attempt this question?
Any grave coding convention that I have violated in my code?

Reference


texts:
I need help with a question my teacher wants us to do by tomorrow. I would love for you to try to help me out with this.

The following functions must be implemented:

A function that initializes all variables
Variables that keep track of which player is currently playing, and which player is next
Variables that keep count of X's and O's played

var currentPlayer = prompt("Who is The Current Player X=1 O=2");

var grid=new Array(3);
grid[0]=new Array(3);
grid[1]=new Array(3);
grid[2]=new Array(3);

for (var i=0; i<=2; i++) {
  for (var j=0; j<=2; j++) {
    grid[i][j]=0;
  }
}

// Checks If Grid Is Already Clicked
function clickCell(x,y) {
  if (grid[x][y]>0) {
    alert("Dont Try To Cheat Bud!!!!!");
  }

// Clicking Of Boxes
  else {
    if (currentPlayer==1) {
      document.getElementById("cell_"+x+"_"+y).style.color="#3F88C5";
      document.getElementById("cell_"+x+"_"+y).innerHTML="X";
      grid[x][y]=1;
      currentPlayer=2;
    } else {
       document.getElementById("cell_"+x+"_"+y).style.color="#E2C290";
       document.getElementById("cell_"+x+"_"+y).innerHTML="O";
      grid[x][y]=2;
      currentPlayer=1;
    }
  }
}

// Reset Game

function reset() {
for (var i=0; i<=2; i++) {
  for (var j=0; j<=2; j++) {
    grid[i][j]=0;
    document.getElementById("cell_"+i+"_"+j).innerHTML="&nbsp;";
  }
}
 currentPlayer=1;
}
h1 {
    text-align: center;
    font-family: 'Indie Flower', cursive;
  font-size: 53px;
}
div {
  text-align: center;
  margin: 0px auto;
    text-align: center;
  margin: auto;
}
body {
    background-color: #02c39a;
}

.cell {
  width:80px;
  height:80px;
  border: 5px solid #000000;
  background: #FFFFFF;
  font-size: 46pt;
  font-family: arial;
  font-weight: bold;
  text-align: center;
  margin: auto;

}

fieldset {
  text-align: center;
  margin: auto;
}

.cell:hover {
  background: #C2DBFC;
  text-align: center;
}

    <meta charset="utf-8" />
    <title>Tic-Tac-Toe</title>
    <link rel="stylesheet" type="text/css" href="tictoe.css">
    <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>

Tic Tac Toe

<fieldset>

Please Reload The Page To Choose Player Who Goes First Again

    &nbsp;
    &nbsp;
    &nbsp;

    &nbsp;
    &nbsp;
    &nbsp;

    &nbsp;
    &nbsp;
    &nbsp;

<input type=button onClick="Javascript: reset();" value="Reset">


texts: In-Memory FileSystem in Java - Is there a better OOP approach?

texts:
I have implemented an in-memory filesystem - this is a design question from LeetCode. Is there a better OOP approach to represent files and directories? The current code uses a boolean flag isDirectory to distinguish between files and directories and I'm not confident that it is the best approach. See the code below. I'll also be happy to get any other comments about the code - readability, variable and method naming, etc.
class FileSystem {

    Inode root;

    public FileSystem()
    {
        root = new Inode("/", true);
    }

    public List<String> ls(String path)
    {
        List<String> listing = new ArrayList<>();

        String[] queries = path.substring(1).split("/");

        Inode node = root;

        for(String query: queries)
        {
            if(query.isEmpty()) // happens when we search root
                break;

            node = node.children.get(query);

            if(node == null)
                return listing;
        }

        if(node.isDirectory)
        {
            node.children.forEach((name, inode) -> {
                listing.add(name);
            });
        }
        else
        {
            listing.add(node.Name);
        }

        Collections.sort(listing);

        return listing;
    }

    public void mkdir(String path)
    {
        String[] subdirs = path.substring(1).split("/");
        Inode node = root;

        for(String dir: subdirs)
        {
            if(dir.isEmpty()) // happens when we search root
                break;

            if(!node.children.containsKey(dir))
                node.children.put(dir, new Inode(dir, true));

            node = node.children.get(dir);
        }

    }

    public void addContentToFile(String filePath, String content)
    {
        String[] subdirs = filePath.substring(1).split("/");
        Inode node = root;

        for(int i=0; i<subdirs.length; i++)
        {
            if(!node.children.containsKey(subdirs[i]))
            {
                if(i < subdirs.length-1)
                    node.children.put(subdirs[i], new Inode(subdirs[i], true));
                else
                    node.children.put(subdirs[i], new Inode(subdirs[i], false));

            }

            node = node.children.get(subdirs[i]);
        }

        node.fileContent.append(content);

    }

    public String readContentFromFile(String filePath)
    {
        String[] subdirs = filePath.substring(1).split("/");
        Inode node = root;

        for(String dir: subdirs)
        {
            node = node.children.get(dir);
        }

        return node.fileContent.toString();
    }

}

// Trie data structure for files and directories

    class Inode
    {
        public String Name;
        public boolean isDirectory=true;
        public StringBuilder fileContent=null;
        public HashMap<String, Inode> children = null;

        public Inode(String name, boolean is_dir)
        {
            this.Name = name;
            this.isDirectory = is_dir;

            if(!is_dir)
                fileContent = new StringBuilder();

            if(is_dir && children == null)
                children = new HashMap<>();
        }

    }


texts:
I have two JS functions that return a total number for me based on some properties. It works fine but feels a bit 'clunky'. Would there be a cleaner way of doing this?

getTotalTrucks: function (data) {
    var noOfTrucks = 0;

    if (data.truck1 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck2 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck3 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck4 == "1") {
        noOfTrucks += 1;
    }
    if (data.truck5 == "1") {
        noOfTrucks += 1;
    }

    return noOfTrucks ;
},

getTotalCars: function (data) {
    var noOfCars = 0;

    if (data.car1 == "2") {
        noOfCars += 1;
    }
    if (data.car2 == "2") {
        noOfCars += 1;
    }
    if (data.car3 == "2") {
        noOfCars += 1;
    }
    if (data.car4 == "2") {
        noOfCars += 1;
    }
    if (data.car5 == "2") {
        noOfCars += 1;
    }

    return noOfCars ;
}


texts: Reduce as many adjacent chars as possible in string

texts:
This code is meant to reduce a given string as much as possible by deleting adjacent characters. Here are some examples:

reduce('aa') = 'Empty String'
reduce('ab') = 'ab'
reduce('abba') = 'Empty String' # remove 'bb' then 'aa'
reduce('bbb') = 'b'  # can only delete 2 chars at a time

This is based off this HackerRank question.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def reduce(s):
    cur_chars = list(s)
    while cur_chars:
        new_chars = do_deletions(cur_chars)
        if new_chars == cur_chars:  # if nothing deleted then return
            new_s = ''.join(cur_chars)
            return new_s
        else:
            cur_chars = new_chars  # do another round of deletions
    return 'Empty String'

def do_deletions(org_chars):
    if len(org_chars) == 1:
        return org_chars

    new_chars = []
    i = 0
    while i < len(org_chars):
        if i == len(org_chars) - 1:
            new_chars.append(org_chars[i])
            i += 1
        elif org_chars[i] == org_chars[i+1]:
            i += 2  # don't include char i and i+1
        elif org_chars[i] != org_chars[i+1]:
            new_chars.append(org_chars[i])
            i += 1
    return new_chars

I was originally going to do deletions using 2 consecutive del commands (O(n)) but then I thought this performance would be too bad for an interview. Instead I opted to not do any deletions and just use appends to create gradually reduced strings. If my original approach would have been fine for an interview then let me know.

I think this algorithm is O(n^2) time and O(n) space. Any suggestions about how I can improve the complexities are welcome.


texts: How would you rate this python code? (Django AJAX)

texts:
This code comes straight out from the example code in a Django book. I find it quite bad, mainly because the use of flags (if ajax then again if ajax) and unnecessarily bigger variable scope (set title='', tags='' and then use these variables in different flows). The function body also seems way too long.
I guess I'll subtract the book title (for the record I find the book in general good).

How would you rate this code, say out of 10 (10=very good, 3 and below being unacceptable)? (I'd rate it a 3)

The reason I ask is, I had rejected similar code in the past during code review and now I'm wondering whether I've been too strict or didn't understand python culture (I'm new to python).

@login_required
def bookmark_save_page(request):
  ajax = 'ajax' in request.GET
  if request.method == 'POST':
    form = BookmarkSaveForm(request.POST)
    if form.is_valid():
      bookmark = _bookmark_save(request, form)
      if ajax:
        variables = RequestContext(request, {
          'bookmarks': [bookmark],
          'show_edit': True,
          'show_tags': True
        })
        return render_to_response(
          'bookmark_list.html', variables
        )
      else:
        return HttpResponseRedirect(
          '/user/%s/' % request.user.username
        )
    else:
      if ajax:
        return HttpResponse(u'failure')
  elif 'url' in request.GET:
    url = request.GET['url']
    title = ''
    tags = ''
    try:
      link = Link.objects.get(url=url)
      bookmark = Bookmark.objects.get(
        link=link,
        user=request.user
      )
      title = bookmark.title
      tags = ' '.join(
        tag.name for tag in bookmark.tag_set.all()
      )
    except (Link.DoesNotExist, Bookmark.DoesNotExist):
      pass
    form = BookmarkSaveForm({
      'url': url,
      'title': title,
      'tags': tags
    })
  else:
    form = BookmarkSaveForm()
  variables = RequestContext(request, {
    'form': form
  })
  if ajax:
    return render_to_response(
      'bookmark_save_form.html',
      variables
    )
  else:
    return render_to_response(
      'bookmark_save.html',
      variables
    )


texts: Active record pattern for a subscription service website

texts:
I just jumped to a new project, which uses the active record pattern. It's a subscription service website.

I have the following User object that extends a framework specific ORM object:

class User extends ORM {

    public function isSubscriber()
    {

        $activeSubscription = $this->subscriptions->where('active','=',1)->find_all();
        return $activeSubscription->count();

    }

}

In client code, I have the following code:

class Test_Controller extends Controller {

    public function test()
    {

        // Framework speific way to get a current user
        // returns User orm
        $user = Auth::instance()->get_user();

        var_dump($user->isSubscriber());

    }

}

As you see, it's very straightforward and easy to understand. What's bothering me is that there's no way to test this simple User object unless I hack it.

The problem is that inside ORM objects, it uses a singleton pattern (something like Database::getInstance()) to get a database object and uses it to query to database, making it impossible to properly mock it.

I extracted isSubscriber() from User to a service like this:

class SubscriberVerificationService {

    public function __construct(SubscriptionRepositoryInterface $subscriptionRepository)
    {

        $this->subscriptionRepository = $subscriptionRepository;

    }

    public function isSubscriber(User $user)
    {

        $subscriptions = $this->subscriptionRepository->findActiveSubscriptionsByUserId($user->id);
        return count($subscriptions);

    }

}

Client code

class Test_Controller {

    public function __construct(SubscriberVerificationService $subscriberVerificationService)
    {
        $this->subscriberVerificationService = $subscriberVerificationService;
    }

    public function test()
    {

        $user = Auth::instance()->get_user();
        var_dump($this->subscriberVerificationService->isSubscriber($user));

    }

}

Now I can properly mock SubscriptionRepositoryInterface and and User objects in my test.

I feel like this is the way to go, but I just want to hear advice from people who use the active record pattern day-to-day.

It doesn't have to be a repository (SubscriptionRepositoryInterface) in the service. It can be a Subscription ORM as long as I can mock it.


texts: Find index of array item starting at a given location

texts:
I've written a lot of C++ but now I'm learning Swift.  I did an exercise, the standard Sieve of Erastosthenes. It works fine, but it seems a bit clunky and I wonder if I'm missing some language features that might streamline it a bit and make it more idiomatic Swift.

Here's the code:

struct Sieve {
    let primes: [Int]
    init(_ maxValue: Int) {
        var numbers = Array<Int?>(repeating: nil, count:maxValue + 1)
        for n in 2...maxValue { numbers[n] = n }
        var start = 2
        while start < maxValue {
            guard let prime = numbers.first(where: {$0 != nil && $0! >= start}) else {break}
            let lo = 2 * prime!
            if lo < maxValue {
                for x in stride(from: lo, to: numbers.count, by: prime!) {
                    numbers[x] = nil
                }
            }
            start = prime! + 1
        }
        primes = numbers.compactMap{$0}
    }
}

With the line starting "guard let prime", I'd like to supply a starting index for the 'find' operation, which would be a lot more efficient and would let me drop the comparison $0! >= start altogether. Something along the lines of

guard let prime = numbers.first(where: {$0 != nil}, start: start) else {break}

I also tried

guard let prime = (start...maxValue).first(where: {index in numbers[index] != nil}) else {break}

and that does work but it seems even more awkward. It does have the advantage of starting the search at the index start instead of index zero each time. What's the preferred way to search an array beginning somewhere in the middle of it?


texts:
I am currently writing mergesort in Python and have implemented it to work. I have noticed, though, that it is very slow compared to the standard sorted() method. I understand it will always be faster but I am open to suggestions in terms of optimization.

def merge(left,right):
    sortedArray=[]
    l_idx,r_idx=0,0 #set index for left and right array
    #compare values of left and right array
    while l_idx<len(left) and r_idx<len(right):
        if(left[l_idx] < right[r_idx]):
            sortedArray.append(left[l_idx])
            l_idx+=1
        else:
            sortedArray.append(right[r_idx])
            r_idx+=1
    if l_idx==len(left):
        sortedArray.extend(right[r_idx:])
    else:
        sortedArray.extend(left[l_idx:])
    return sortedArray

def mergesort(A):
    if len(A)<=1:
        return A
    middle=len(A)//2
    left,right=mergesort(A[:middle]),mergesort(A[middle:])
    return merge(left,right)

Thank you for any feedback


texts:
I'm a novice regarding both C++ and Qt. This class is used in my project to get an image from a web service.
If a new call to StartDownload is made before the previous has finished, the old one can safely be discarded as it won't be needed any more. This is because a new request is made for each resize event, as one of the parameters to the service is the image size (font size in the image is adapted to the image size).
As a result, when a request is canceled, Qt prints an error message: QCoreApplication::postEvent: Unexpected null receiver. This does not interfere with any functionality, but tells me I haven't handled canceling the request properly. Several of these messages are printed as I resize the window and CancelDownload is called.
Aside from that, any general feedback on my design or C++ idiomacy is welcome!
Note: I'm using C++11 and Qt 5.6.
Header
#ifndef DOWNLOADER_H
#define DOWNLOADER_H

#include <QtNetwork/qnetworkaccessmanager.h>
#include <qbytearray.h>
#include <QObject>

class Downloader: public QObject
{
    Q_OBJECT

public:
    Downloader();
    ~Downloader();
    void StartDownload(QUrl url);

private:
    void CancelDownload();

    QNetworkAccessManager mNetworkAccessManager;
    QNetworkReply *mCurrentReply;

signals:
    void DownloadFinished(QByteArray bytes);

private slots:
    void HandleFinishedDownload();
};

#endif // DOWNLOADER_H

Source
#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkreply.h>
#include "Downloader.h"

Downloader::Downloader()
    : mNetworkAccessManager(), mCurrentReply(Q_NULLPTR)
{
}

Downloader::~Downloader()
{
    CancelDownload();
    mNetworkAccessManager.deleteLater();
}

void Downloader::CancelDownload()
{
    if (mCurrentReply != Q_NULLPTR) {
        mCurrentReply->abort();
        mCurrentReply->deleteLater();
        mCurrentReply = Q_NULLPTR;
    }
}

void Downloader::StartDownload(QUrl url)
{
    CancelDownload();

    QNetworkRequest request(url);
    mCurrentReply = mNetworkAccessManager.get(request);
    connect(mCurrentReply, &QNetworkReply::finished, this, &Downloader::HandleFinishedDownload);
}

void Downloader::HandleFinishedDownload()
{
    if (!mCurrentReply) {
        qCritical("Null reply in HandleFinishedDownload");
        return;
    }

    if (mCurrentReply->error() == QNetworkReply::NoError) {
        emit DownloadFinished(mCurrentReply->readAll());
    }
    else if (mCurrentReply->error() != QNetworkReply::OperationCanceledError) {
        qWarning() << "Failed download:" << mCurrentReply->errorString();
    }

    mCurrentReply->deleteLater();
    mCurrentReply = Q_NULLPTR;
}

Update
Although I solved the issue described above in a self-answer, I am still looking for a general review!


texts: Functional Game of Life implementation in Ruby

texts:
We ran a Code Retreat day at Hacker Paradise this Saturday, and I was pretty happy with my eventual solution. It's written in Ruby, but would work reasonably well in JS/CS and is (hopefully) reasonably readable across languages.

module Enumerable
  def bag
    # [1,1,1,1,2,2,3] => {1 => 4, 2 => 2, 3 => 1}
    # similar to python's Counter
    Hash[group_by { |x| x }.map {|k, v| [k, v.count] }]
  end
end

def neighbors_of(location)
  x_range = (location.first-1).upto(location.first+1).to_a
  y_range = (location.last-1).upto(location.last+1).to_a
  x_range.product(y_range) - [location]
end

def will_be_alive(was_alive, neighbors_count)
  if was_alive
    [2,3].include? neighbors_count
  else
    neighbors_count == 3
  end
end

def iterate(old_grid)
  old_grid.flat_map do |loc, _|
    neighbors_of(loc)
  end.bag.select do |loc, alive_near_me|
    will_be_alive(old_grid[loc], alive_near_me)
  end
end

def print(grid)
  system('clear')
  min_x, max_x = grid.keys.map(&:first).minmax
  min_y, max_y = grid.keys.map(&:last).minmax

  result = min_y.upto(max_y).map do |y|
     min_x.upto(max_x).map do |x|
      grid[[x,y]] ? 'X' : ' '
    end.to_a.join("")
  end.to_a.join("\n")

  puts result
end

def new_grid()
  glider = [[1,0], [1, 2], [0,2], [2,2], [2,1]]
  box = [[-3,3], [-3,4], [-4,3], [-4,4]]
  alive_start = glider + box
  Hash[alive_start.map { |k| [k, true] }]
end

grid = new_grid()

until grid.empty? do
  print(grid)
  grid = iterate(grid)
  sleep 1
end


texts:
I recently bought a PSP and wanted to know the best ISO files and wrote a scraper to retrieve games ISOs titles that received a high rating and send them to a csv. Any recommendations as to readability, and/or better code optimizations?

var request = require('request');
var cheerio = require('cheerio');
var json2csv = require('json2csv');
var fs = require('fs');

var url = 'http://goo.gl/cc4HRc';
var pspISOs = [];

request(url, function (error, response, html) {
  if (!error && response.statusCode === 200) {
    var $ = cheerio.load(html);
    $('.gamelist').each(function () {
    var titles = $(this).text();
    var ratings = +parseFloat($(this)
      .parents('tr').find('td')
      .last().text()).toFixed(2);
    pspISOs.push({ title: titles, rating: ratings });
  });
  var topISOs = pspISOs.filter(function (iso) {
    return iso.rating >= 4.81;
  });
  var columns = Object.keys(topISOs[0]);
  json2csv({ data: topISOs, fields: columns }, function (err, csv) {
    if (err) console.log(err);
      fs.writeFile('psp_iso.csv', csv, function (err) {
      if (err) throw err;
        console.log('Saved.');
      });
    });
  }
});


texts: Time-dependent state machine with two outputs

texts:
Given a class BasicDataFeed whose purpose is to feed questions and answers into an artificial neural network, which is tested in a non-negotiable manner as follows:

import numpy as np
import matplotlib.pyplot as plt

dt = 0.001
dims = 4
t_len = 0.1
pause = 0.01
n_items = 4

cor = np.eye(n_items)

def dataset_func(idx, t):
    return cor[idx] * (t*10)

df = BasicDataFeed(dataset_func, np.eye(n_items), t_len, dims, n_items, pause)

t_steps = list(np.arange(0, 2*n_items*(t_len+pause), dt))
df_out = []
ans_out = []

for tt in t_steps:
    df_out.append(df.feed(tt))
    ans_out.append(df.get_answer(tt))

plt.plot(df_out)

plt.gca().set_prop_cycle(None)

plt.plot(ans_out)
plt.show()

With the desired output:

How do I write my state-machine in a more elegant manner? I feel like I'm keeping track of time (and thus the state transitions) incorrectly.

import numpy as np

from random import shuffle

dt = 0.001

class BasicDataFeed(object):

    def __init__(self, dataset, correct, t_len: float, dims: int, n_items: int, pause: float):
        self.data_index = 0
        self.paused = False

        self.time = 0.0
        self.sig_time = 0

        self.pause_time = pause
        self.q_duration = t_len
        self.ans_duration = self.q_duration + self.pause_time

        self.correct = correct
        self.qs = dataset
        self.num_items = n_items
        self.dims = dims
        self.indices = list(range(self.num_items))

    def get_answer(self, t):
        """Signal for correct answer"""
        if self.pause_time < self.time < self.ans_duration:
            return self.correct[self.indices[self.data_index]]
        else:
            return np.zeros(self.num_items)

    def feed(self, t):
        """Feed the question into the network
        this is the main state machine of the network"""
        self.time += dt

        if self.time > self.pause_time and self.sig_time > self.q_duration:

            if self.data_index < self.num_items - 1:
                self.data_index += 1
            else:
                shuffle(self.indices)
                self.data_index = 0

            self.time = 0.0
            self.sig_time = 0.0

        elif self.time > self.pause_time:
            self.paused = False

            q_idx = self.indices[self.data_index]
            return_val = self.qs(q_idx, self.sig_time)
            self.sig_time += dt
            return return_val

        else:
            self.paused = True

        return np.zeros(self.dims)

Note: This is a continuation of my previous question about time-dependent state machine. Also, don't worry about the type annotations, they're just there to help me debug and act as documentation for the code.


texts: Calculating the statistical Mode(s) of a (possibly multi-modal) set of elements

texts:
I am trying to come up with the most performant way of calculating the statistical Modes of a std::vector, obeying two conditions:

1) my function should not duplicate memory usage (which would required for most usually mentioned faster methods of calculating mode);

2) my function should be able to handle multi-modality. It means, it should be able to return more than one mode when apropriate (i.e. in case the elements in the passed vactor have more than one mode).

Here is my function so far. It works, but I have the feeling that it could be further improved and reviewed, so I brought it here:

#include <vector>
#include <math.h>

std::vector<int> Mode(std::vector<int> &myvector)
{
int vectorsize = myvector.size();
int max = 0;
std::vector<int> maxs;
int counter = 1;
std::sort(myvector.begin(), myvector.end());

for (int i = 0; i < vectorsize - 1; i++)
{
    int currentnum = myvector[i];

    if (currentnum == myvector[i + 1])
    {
        counter++;

        if (counter > max)
        {
            if (counter > vectorsize - i) break; //early exit when the mode found so far appears more than the number of elements still to be evaluated
            max = counter;
            if (maxs.size() > 0) maxs.clear();
            maxs.push_back(currentnum);
        }
        else if (counter == max)
        {
            bool alreadyin = false;
            for (int j = 0; j < maxs.size(); j++)
            {
                if (maxs[j] == currentnum)
                {
                    alreadyin = true;
                    break;
                }
            }
            if (alreadyin == false)
                maxs.push_back(currentnum);
        }

    }
    else counter = 1; //reset the counter
}

return (maxs.size() > 0) ? maxs : myvector; //if all elements appear only once, return the whole initial vector; otherwise return the the modes that were found
}

Corrections, improvements an even suggestions of algorithm changes are very welcome.


texts:
I had to make a program to crawl through a bunch of PyPI packages and see how many of them implement custom compare operators (i.e. grep for def __le__ etc). After downloading an HTML file with links to all Python 3.4 packages on PyPI (i.e. the directory page), I wrote this simple crawler to go through all the links, download and unzip each package, and grep them for custom compare definitions. It's rudimentary, but still, what are your comments? This is my first "shell-script" style Python program, i.e. a program where you're not computing stuff but just moving around files and doing networking.

Code:

import sys
assert(sys.version_info >= (3,5))

import re
from requests import get
import subprocess
def run(s):
    return subprocess.run(s,
                          shell=True,
                          stdout=subprocess.DEVNULL,
                          stderr=subprocess.DEVNULL)

directory = open('list.html').read() #download list from Browse Packages ->
                                     #                   Python 3.4 -> Show All

custom = no_custom = failiures = 0
for (package_url, package_name) in \
    re.findall('(https://pypi\.python\.org/pypi/([^/]+)/)', directory):
    print(custom+no_custom+failiures,
          custom,
          no_custom,
          failiures)

    try:
        package_page = get(package_url).text
        (download_url,file_type) = re.search('.+(\.tar\.gz|\.zip)',
                                             package_page).groups()
        print(package_name)
        archive = open('archive', 'wb')
        archive.write(get(download_url).content)
        archive.close()

        run('rm -r package_code')
        run('mkdir package_code')

        if file_type == '.tar.gz':
            run('tar -xzf archive -C package_code')
        if file_type == '.zip':
            run('unzip archive -d package_code')
        return_code = run('grep -Er "def __(le|lt|ge|gt)__" ./package_code').returncode

        if return_code == 0:
            custom += 1
        elif return_code == 1:
            no_custom += 1
        else:
            failiures += 1

    except (KeyboardInterrupt, SystemExit):
        raise
    except Exception as exception: #for when there is no .tar.gz or .zip on PyPI
                                   #or (rarely) when the connection is dropped
        print("FAILIURE:", type(exception).__name__)
        failiures += 1

print("""
Packages that define custom compare operators: %i
Packages that don't define custom operators: %i
Packages that didn't have source on PyPI: %i
""" % (custom, no_custom, failiures))