texts:
I have written this simple code for Tic Tac Toe.

#include <iostream>
#include <vector>

void draw_board(const std::vector< std::vector<char> >& vec)
{
    std::cout << "    0   1   2  \n";
    std::cout << "  +---+---+---+\n";
    for (int i = 0; i < vec.size(); i++)
    {
        std::cout << i << " " ;
        for (int j = 0; j < vec[i].size(); j++)
        {
            std::cout << "| " << vec[i][j] << " ";
        }
        std::cout << "|";
        std::cout << '\n';
        std::cout << "  +---+---+---+\n";
    }
}

void enter(int row, int col, char ch, std::vector< std::vector<char> >& vec)
{
    vec[row][col] = ch;
}

bool check(const std::vector< std::vector<char> >& vec)
{
    //to check diagonals
    if ((vec[0][0] == 'X' && vec[1][1] == 'X' && vec[2][2] == 'X')
        || (vec[0][2] == 'X' && vec[1][1] == 'X' && vec[2][0] == 'X'))
        {
            std::cout << "Player X won this game\n";
            return true;
        }
    else if ((vec[0][0] == 'O' && vec[1][1] == 'O' && vec[2][2] == 'O')
             || (vec[0][2] == 'O' && vec[1][1] == 'O' && vec[2][0] == 'O'))
             {
                std::cout << "Player O won this game\n";
                return true;
             }

    //to check horizonatal and vertical
    for (int i = 0; i < vec.size(); i++)
    {
        if ((vec[i][0] == 'X' && vec[i][1] == 'X' && vec[i][2] == 'X')
              || (vec[0][i] == 'X' && vec[1][i] == 'X' && vec[2][i] == 'X'))
              {
                  std::cout << "Player X won this game\n";
                  return true;
              }
        else if((vec[i][0] == 'O' && vec[i][1] == 'O' && vec[i][2] == 'O')
              || (vec[0][i] == 'O' && vec[1][i] == 'O' && vec[2][i] == 'O'))
              {
                  std::cout << "Player O won this game\n";
                  return true;
              }
    }
}

void start(std::vector< std::vector<char> >& vec)
{
    int row, col, res = 0;
    char ch;

    std::vector<int> index = {0, 1, 2};

    for (int i = 0; i < vec.size(); i++)
    {
        for (int j = 0; j < vec[i].size(); j++)
        {
            vec[i][j] = ' ';
        }
    }

    for (int i = 0; i < 9;)
    {
        if (i == 0 || i%2 == 0)
        {
            ch = 'X';
            std::cout << "Chance to enter X\n";
        }
        else
        {
            ch = 'O';
            std::cout << "Chance to enter O\n";
        }
        std::cout << "Enter row number ";
        std::cin >> row;
        std::cout << "Enter column number ";
        std::cin >> col;
        if (vec[row][col] == ' ' || vec[row][col] == ' ')
        {
            enter(row, col, ch, vec);
            draw_board(vec);
            if ( i >= 2)
            {
                res = check(vec);
                if (res == 1)
                {
                    break;
                }
            }
            i++;
        }
        else
        {
            std::cerr << "This position already contains a character\n";
        }

    }
    if (res == 0)
    {
        std::cout << "This game draws\n";
    }
}

int main()
{
    std::vector< std::vector<char> > board(3, std::vector<char>(3));
    draw_board(board);
    start(board);
}


texts: Reusable Unit Of Work Interface / Factory

texts:
Given my IUnitOfWork interface

using System;

public interface IUnitOfWork : IDisposable
{
    void Commit();
}

I then create an abstract factory interface called IUnitOfWorkFactory

using System.Transactions;

public interface IUnitOfWorkFactory
{
    IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel);
}

I then create a default implementation of my IUnitOfWork called TransactionScopeUnitOfWork

using System;
using System.Transactions;

public class TransactionScopeUnitOfWork : IUnitOfWork
{
    private bool disposed = false;

    private readonly TransactionScope transactionScope;

    public TransactionScopeUnitOfWork(IsolationLevel isolationLevel)
    {
        this.transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = isolationLevel,
                    Timeout = TransactionManager.MaximumTimeout
                });
    }

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

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                this.transactionScope.Dispose();
            }

            disposed = true;
        }
    }

    public void Commit()
    {
        this.transactionScope.Complete();
    }
}

I then create the factory to return that implementation called TransactionScopeUnitOfWorkFactory

using System.Transactions;

public class TransactionScopeUnitOfWorkFactory : IUnitOfWorkFactory
{
    public IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel)
    {
        return new TransactionScopeUnitOfWork(isolationLevel);
    }
}

The reason for creating the factory is to allow DI (Dependency Injection) frameworks to use different unit of work implementations depending on configuration.

If TransactionScopeUnitOfWorkFactory was mapped to IUnitOfWorkFactory in a DI container, some sample code for using it in an application could be:

public class Test
{
    private readonly IUnitOfWorkFactory unitOfWorkFactory;

    private readonly IRepository testRepository;

    public Test(
        IRepository testRepository,
        IUnitOfWorkFactory unitOfWorkFactory)
    {
         this.testRepository = testRepository;
         this.unitOfWorkFactory = unitOfWorkFactory;

         using (IUnitOfWork unitOfWork = this.unitOfWorkFactory.GetUnitOfWork(IsolationLevel.Serializable))
        {
            this.testRepository.Delete(1); // Some valid CRUD
            unitOfWork.Commit();
        }
    }

I am asking if this seems like a good implementation.  Am I missing anything?
I want an IUnitOfWork interface that I can use across applications and not worry about maintaining later on.  Any opinions?


texts: Django Model field naming convention for lookup tables

texts:
I'm currently in the process of refactoring a Django app to use Django REST Framework. Within the existing code there are 15 models for lookup tables. The structure of each model is as follows (using gender as an example - there are valid reasons in the context of the application for including a gender model rather than as hardcoded CHOICES on a Person model):
class Gender(models.Model):
    """
    This model stores genders
    """
    name = models.CharField(max_length=64)
    sort = models.IntegerField()

    class Meta:
        ordering = ['sort']

    def __unicode__(self):
        return self.name

(I've already made some changes that are included in the above code to bring it in line with Django's coding style guidelines)
All of the 15 models use the same field names that I am concerned should be more explicit.
My concern with using the name field-name is that it does not explicitly state what data is in the relevant table.
To add to this, I might have the following code in my views:
class PersonByGenderList(generics.ListAPIView):
    """
    This endpoint lists all people by gender
    """
    serializer_class = PersonSerializer

    def get_queryset(self):
        """
        :return: queryset of people restricted by gender.
        """
        queryset = Person.objects.all()
        gender = self.request.QUERY_PARAMS.get('gender', None)
        if gender is not None:
            queryset = queryset.filter(gender__name=gender)
        return queryset

Again, gender__name (for me) is not explicit enough. Also, in a SlugRelatedField the slug name is always slug_name='name'.
So my questions are:

Are there any database design conventions that recommend using name as a generic field name on models, or should I be more explicit (following the Zen of Python) and prefer (albeit with some repetition):
queryset = queryset.filter(gender__gender=gender)
Or is it preferable to use name and be explicit with the model name in the case of gender?

Is the arbitrary integer field used for sorting explicit enough when effectively it will sort by first entry to last? I would think it is generally better to sort by something that is relevant to the use case, but as with question 1 are there any conventions/style guides I should be aware of when naming fields?

Some info on my research:
I've looked for other questions on this site and Stack Overflow, Django's coding style guidelines, PEP8 but not found anything that directly answers this question. A question on Programmer's SE comes closest Should model/table names be as specific as possible. The points I take from the answers are:

naming should be as specific as possible
Table and field names should be descriptive of the domain entity that they capture


texts:
I've created a program for work that checks the status of all our servers quickly. What we use to have to do is ssh into each server manually.

I'm looking for some critique on what I've created here. Any input on it would be greatly appreciated, such as better syntax I can use, better variables, easier ways to perform the rescue, etc. I will be leaving out a couple of things for security purposes.

#!/local/usr/bin/env ruby

require 'rubygems'
require 'net/ssh/gateway'
require 'work/mail/gem'

begin
  def scanning_all_ssh_servers(server_check, cmd)
    check = Net::SSH.start(server_check, @username, :password => @password)
    ping = check.exec!(cmd)
    case
    when ping.include?("1 received, 0% packet loss")
      puts "server online: #{server_check}"
    when ping.include?("0 received, +1 errors")
       puts "SERVER OFFLINE: #{server_check}"
    when check.include?("Connection closed")
      puts "SERVER OFFLINE: #{server_check}"
    else
      raise "Error loading server: #{server_check}. Exiting.."
    end
  end

  @username = "username"
  @password = "password"

  ssh_server_list = %w(these are all the servers that we can ssh too)
  ssh_server_list.each do |server_check|
    cmd = "ping -c 1 #{server_check}"
    scanning_all_ssh_servers(server_check, cmd)
  end
rescue => e
  x = AD::Mail.new
  x.from        = "email@email.email"
  x.to          = "email@email.email"
  x.subject     = "Server Loading Error"
  x.body        = e.message
  x.send
end


texts: Avoid re-initialize values in javascript

texts:
In the below code, variable xAxis is re-initialized multiple times before every push into the array. How can i optimize this code?

var xAxis=1;
            vm.pnLreportingPlotData.push(plotModel.map(function(o){
                    return {x:xAxis++,y:o.PnLreporting};
                })
            );

            var xAxis=1;
            vm.var95PlotData.push(plotModel.map(function(o){
                    return { x:xAxis++, y:o.VaR95Total};
                })
            );

            var xAxis=1;
            vm.var99PlotData.push(plotModel.map(function(o){
                    var xAxis = 1;
                    return  { x:xAxis++, y:o.VaR99Total};
                })
            );


texts:
I have a bit of EF Lambda code which returns a list of data from the db table, then orders by a field called IsDefault

At first, the code was

var listOfData = Db
    .TableName
    .Where(u => u.UserId == userId)
    .OrderBy(u => u.IsDefault)
    .ToList();

Which when writing down, sounds correct. However is wrong as this will order by 0 > 1, and True = 1.

So I changed the statement to;

var listOfData = Db
    .TableName
    .Where(u => u.UserId == userId)
    .OrderBy(u => u.IsDefault ? 0 : 1)
    .ToList();

However, I could have also written this 2 other ways.

.OrderBy(u => !u.IsDefault)

OR

.OrderByDescending(u => u.IsDefault)

Now in my mind, u.IsDefault ? 0 : 1 reads better, and the other two could be misread as the not wanting the default value first.

What is your view on this?


texts:
This is the most Monadic code I have written to date :-) and I'd welcome comments.

I'm also struck how much faster this mutable approach is than the immutable version I first wrote (see end). OK, so QuickSort is pretty much on mutability, but most algorithms seems to involve significant manipulation of elements in the data structure and immutability leads to slowness due to the endless copying of e.g. Arrays.  I'm left wondering whether immutability is practical in the real world?

-- qsort :: Array -> beginning of subsection -> end of subsection
qsort :: (IOArray Int Int) -> Int -> Int -> IO ()
qsort arr min mx =
    if mx - min < 1 then do
        return ()

    else do
        p <- readArray arr min
        --foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
        final_i <- foldM (partitioner p) (min+1) [(min+1)..mx]
        swap min $ final_i - 1
        qsort arr min     (final_i-2)
        qsort arr final_i mx

    where
        swap i j = do
            arr_i <- readArray arr i
            arr_j <- readArray arr j
            writeArray arr i arr_j
            writeArray arr j arr_i

        partitioner p i idx = do
            arr_idx <- readArray arr idx
            if arr_idx > p then
                return i
            else do
                swap i idx
                return $ i+1

I have since made the minor modifications to use an ST Monad (Gist). Not sure which is to be considered better Haskell though.

qsort :: (V.Vector Int) -> Int -> Int -> (V.Vector Int)
qsort v i j
    | len < 2 = v
    | j > len - 1 =
        let
            -- should really switch pivot with last point in < group
            --swap 0 (i-1)
            (less, greater) = V.splitAt i v
            less_sorted = qsort (V.tail less) 1 1
            great_sorted = qsort greater 1 1
        in less_sorted V.++ cons (V.head less) great_sorted
    | vector_j > p =
        qsort v i (j + 1)
    | otherwise =
        qsort (swap i j) (i+1) (j+1)
    where
        len = V.length v
        p = v ! 0
        vector_i = v ! i
        vector_j = v ! j
        swap i' j' = update v $ fromList [(i', v!j),(j', v!i)]


texts: Calling functions with variable functions

texts:
I have some PHP code where I use variable functions to call the right function. I need to build a chart array (for example), and the chart array that comes out has a fixed format. But the data that goes into the chart or table comes from varying places in the underlying objects.

An example:

private function buildChartGroups(PropelCollection $groups, $propertyForDisplay) {
    $groupDisplayFunction = "getSum$propertyForDisplay";

    $chart = array();
    foreach ($groups as $group) {
            $chart[] = array('name' => $group->getName(),
                             'y' => $group->$groupDisplayFunction()
                       );
        }
    }
    return $chart;
}

and then the function gets called something like:

$result = $this->buildChartGroups($groups, "Total");
...elsewhere...
$result = $this->buildChartGroups($groups, "Count");

where $groups is an array of Group objects:

class Group {
   private $name;
   private $sumTotal;
   private $sumCount;

   public function getName() {
       return $this->name;
   }

   public function getSumTotal() {
        return $this->sumTotal;
   }

   public function getSumCount() {
        return $this->sumCount;
   }
}

This works fine and lets me re-use buildChartGroups() which I would otherwise not be able to do. But using variable functions and passing function names as strings always seems a little dirty, even though I'm sure it has its place.

Is there a way to refactor this or is there some pattern I can use to avoid them?


texts: Image to HTML / CSS conversion using pure JS

texts:
Just for fun I wrote some JavaScript that "converts" an image into pure HTML / CSS. The user is able to select a local image. This image is loaded into an invisible canvas in order to extract pixeldata from the image. Using the pixeldata, a structure of 1x1 <div/> elements is created with each element having its background color set to its corresponding pixel color of the image.

The script works perfectly fine on small (width / height) images, but kills the browser on any large image file. I was wondering if there are some things I can do within my code to solve this issue?

document.addEventListener("DOMContentLoaded", function(event) {
 const file = document.getElementById('file');

 file.addEventListener('change', handleFile);

 function handleFile(e){
  // Create canvas
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');

  // Load image
  let img = new Image;
  img.src = URL.createObjectURL(e.target.files[0]);
  img.onload = function() {
   // Draw image to canvas
   ctx.drawImage(img, 0, 0, img.width, img.height);

   let container = document.createElement('div');
   container.id = 'container';
   container.style.Width = img.width;
   container.style.Height = img.height;

   let pixelData = ctx.getImageData(0, 0, img.width, img.height).data;
   let pixel = 0;

   // Loop through each row
   for(let x = 0; x < img.height; x++){
    let row = document.createElement('div');
    row.className = 'row';

    // Loop through each column
    for(let y = 0; y < img.width; y++){
     let col = document.createElement('div');
     col.className = 'col';

     col.style.cssText = 'background: rgba('+pixelData[pixel]+','+pixelData[pixel+1]+','+pixelData[pixel+2]+','+pixelData[pixel+3]+');';
     row.appendChild(col);
        pixel = pixel + 4;
    }
    container.appendChild(row);
   }

   document.getElementById('body').appendChild(container);

   URL.revokeObjectURL(img.src);
  }
 }
});
#container {
 margin-left: 50px;
 margin-top: 50px;
}
.row {
 overflow: auto;
}
.row {
 height: 1px;
}
.col {
 width: 1px;
 height: 1px;
 float:left;
}
<body id='body'>
 <input type='file' id='file'/>
</body>


texts:
Multiple forms make use of the autocomplete of material, which gives a resulting code that is repetitive and difficult to maintain.

The controller is left with pairs of repeated methods [for each controller].

displayFn(option?: Interface): string | undefined {
  return option ? option.Property : undefined;
}

filterAutocomplete(ev: string) {
  if (ev !== '' && ev !== null) {
    // ...
  }
}

The view is based on using the mat-autocomplete with a different template variable for each of them, saving errors.

<mat-form-field>
    <input
      matInput
      [matAutocomplete]="auto"
      (ngModelChange)="filterAutocomplete($event)"
      formControlName="name"
    />
    <mat-autocomplete
      #auto="matAutocomplete"
      [displayWith]="displayAutocomplete"
    >
    <mat-option
      *ngFor="let option of selectionsOption"
      [value]="option"
    >
      {{ option.Property }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

In summary it is an example that would serve me for any context of this type:

List item
Project with multiple forms.
Frequent use of autocompletes in forms
Optional, use of external libraries.


texts: Reading, writing and filtering a CSV file

texts:
I have a CSV with 5+ million rows and I want to filter it:

with open("test1.csv") as csv_file:
    writer =csv.writer(outputfile, delimiter=',')
    for row in csv.reader(csv_file, delimiter=','):
        row = [int(x) for x in row]

        for i in range (1,11):
            if add_i (row) == True:
                break

            elif row not in (row_dup):
                row_dup.append(row)
                writer.writerow(row)

I have many functions, the simplest one being add_i which you can see in the snippet above.

if row[0:3] == range(row[0], row[0] +3 * i, i):
    return True

row_dup = [] is an empty array I use to store duplicates so that they don't get written to the file.

I want to improve the execution time of my script, but it takes hours. According to the calculation of a friend, it takes 530 hours or so. I'm not sure about that but regardless, it is still taking a long time.

How I tried to improve the speed of the script:

Using PyPy but I didn't notice a significant improvement.
Removing row = [int(x) for x in row] but then I'd have to write if [int(x) for x in row[0:4]] == range(int(row[0]), int(row[0]) + 4 * i, i):
it's annoying and there's still a for loop.
Removing for i in range (1,11) but then I would have to write the indexes myself.
Removing for i in range (1,11) and row = [int(x) for x in row] and doing it like so

if (int(row[0]) + 1 == int(row[1])) and int(row[1]) + 1 == int(row[2])
and int(row[2]) + 1 == int(row[3]) and int(row[3]) + 1 == int(row[4]):
    do something

This is a desperate plan and the most annoying. I get rid of two for loops and do everything by hand, increasing the index value from 1 to 11 by copy pasting.
Considered using Hadoop but the VPS I have are so much less powerful than my PC, low end box.
Considered using SQLite instead of CSV but not convinced it would make things much faster.
Considered writing it in C++, and in fact the first version was in C++ but moved to Python since I didn't notice a big difference and because it's easier to plot in Python.

And by the way, I'm on Manjaro 64 bit, filesystem Ext4, Python 2.7, running in virtualenv. I'm only using a CSV module. I have an HP Pavilion G6 laptop, if you want to see the specs of it.

Note that the code is taking that much time, even though I'm only testing with add_i so I didn't even bother testing the complicated function. Who knows how much time it would take then.


texts:
I wrote a small snippet to convert object keys to lowercase. I would like to listen about the ways to improve the following code:

function toLowerCaseKeys(obj) {
  return Object.keys(obj).reduce(function(accum, key) {
    accum[key.toLowerCase()] = obj[key];
    return accum;
  }, {});
}

console.clear();
console.log(toLowerCaseKeys({'Foo': true}).foo);
console.log(toLowerCaseKeys({'FoO': true}).foo);


texts:
I've created a program that will take, a bunch of numbers from a range of 1 - 255, and then put them into 3 different strings(servers) equally. It does this by having a count that starts at 1 and loops to 3, once the count has hit 3 it restarts until three servers have hit a max capacity of 100 numbers within it.

Once that max capacity has been hit, the numbers dump the remaining into a server called failsafe.

I'm looking for better ways to write this, that are cleaner, and will make this, if possible, more readable.

#!/local/usr/bin/ruby

users = (1..255) #<= Amount of users

calculon = " " #<= Random servers to be append into
darth = " "
invader_zim = " "
failsafe = " " #<= Failsafe

count = 1
users.each do |i|
  target_string = case count
   when 1 then calculon #<= Append into server
   when 2 then darth #<= Append into server
   when 3 then invader_zim #<= Append into server
  end

  target_string = failsafe if target_string.length == 100
  target_string << i #<= When amount is reached hits fail safe

  if count == 3
    count = 1
  else
    count += 1
  end
end

puts calculon.length == 1    ? 'No users on server' : calculon.length
puts darth.length == 1       ? 'No users on server' : darth.length
puts invader_zim.length == 1 ? 'No users on server' : invader_zim.length
puts failsafe.length == 1    ? 'No users on server' : failsafe.length

Example of usage:

86
86
86
No users on server

The main objective of this program is to have a script that will equally load three different servers, and if all servers have hit a max capacity, will load into a fail safe server.


texts:
This is my first time using cluster in NodeJS. Can you please let me know if I'm passing the data between the master and the workers according to standard practice?

const cluster = require('cluster');
const numcpus = require('os').cpus().length;
const prompt = require('prompt');

if(cluster.isMaster) {
    // Inputs
    var gridSize = 5000;
    var circleDiameter = 900;
    var n = 1000;
    var iterations = 50;

    // Config
    var worker;
    var results = 0;

    // Getting the data from the user
    prompt.start();
    console.log('------------------------------------------------');
    console.log('Enter custom input or hit enter to use default (5000,900,1000,50)');
    prompt.get(['gridSize', 'circleDiameter', 'n', 'iterations'], function (err, inputs) {
        if (err) { return onErr(err); }

        gridSize = inputs.gridSize || gridSize;
        circleDiameter = inputs.circleDiameter || circleDiameter;
        n = inputs.n || n;
        iterations = inputs.iterations || iterations;

        // If iterations can't be distributed on workers evenly
        if(iterations % numcpus != 0){
            var oddIterations = iterations - (numcpus * Math.floor(iterations/numcpus));
            results += main(gridSize,circleDiameter,n,oddIterations);
            iterations-=oddIterations;
        }

        // Starting workers
        for (let i = 0; i < numcpus; i++) {
            worker = cluster.fork({iterations: iterations/numcpus});
            worker.send({iterations: iterations});
            worker.on('message',function(message){
                results += message.result;
                if(i == numcpus - 1) { // Last worker
                    results = results / numcpus;
                    console.log('Estimated PI',results);
                }
            });
        }

    });

} else {
    process.on('message',function(message){
        process.send({ result: main(5000,900,1000,message.iterations/numcpus) });
    });
}

function main(gridSize,circleDiameter,n,iterations){
    var simulationResults = Array();
    var simulationAvg = 0;
    for(let i = 0; i < iterations; i++){
        var simulationResult = startSimulation(gridSize,circleDiameter,n);
        simulationResults.push(simulationResult);
        simulationAvg+=simulationResult;
    }
    simulationAvg = simulationAvg/iterations;

    return simulationAvg;
}

function startSimulation(gridSize,circleDiameter,n){
    var generateResults = generatePointsAndDistance(gridSize,circleDiameter,n);
    var points = generateResults.points;
    var pointsInCircle = generateResults.pointsInCircle;
    var percentageOfPoints = pointsInCircle/points.length;
    var areaOfCircle = percentageOfPoints*Math.pow(gridSize,2);
    var estimatedPI = areaOfCircle/Math.pow((circleDiameter),2);

    // console.log('points',points);
    // console.log('pointsInCircle:',pointsInCircle);
    // console.log('percentageOfPoints:',(percentageOfPoints*100)+'%');
    // console.log('area of circle by points:',areaOfCircle);
    // console.log('estimated PI:',estimatedPI);
    return estimatedPI;
}

function generatePointsAndDistance(gridSize,circleDiameter,n){
    var points = Array();
    var pointsInCircle = 0;

    for(let i = 0; i < n; i++){
        // Generate Point
        var thisPoint={
            x: Math.floor(Math.random() * gridSize),
            y: Math.floor(Math.random() * gridSize)
        };
        points.push(thisPoint);

        // Calcuate Distance
        if(calculateDistance(thisPoint.x,thisPoint.y,gridSize/2,gridSize/2) < circleDiameter){
            pointsInCircle++;
        }
    }

    return {
        points: points,
        pointsInCircle: pointsInCircle
    };
}

function calculateDistance(x1,y1,x2,y2)
{
    var x = x1 - x2; //calculating number to square in next step
    var y = y1 - y2;
    var dist;

    dist = Math.pow(x, 2) + Math.pow(y, 2);       //calculating Euclidean distance
    dist = Math.round(Math.sqrt(dist));

    return dist;
}


texts: Project Euler # 3 in Haskell: largest prime factor of some number

texts:
The program works, but is extremely slow.

Project Euler problem 3

Problem: What is the largest prime factor of the number 600851475143?

module Problem_3 where

-- find largest prime factor:
findLargestPrimeFactor :: [Int] -> Int
findLargestPrimeFactor []     = 1
findLargestPrimeFactor (n:ns) =
    if (isPrime n)
    then n
    else findLargestPrimeFactor ns

-- Supplementary function definitions:

-- function: listOfFactors n
listOfFactors :: Int -> [Int]
listOfFactors n = [x | x <- [1..n], isFactor x]
    where
        isFactor x = (n `mod` x == 0)

-- function: isPrime p
isPrime :: Int -> Bool
isPrime p = (p >= 2 && listOfFactors p == [1,p])

main = do
          let myGivenNumber = 600851475143
          let largestPrimeFactor = findLargestPrimeFactor (reverse (listOfFactors myGivenNumber))
          print largestPrimeFactor


texts: Find the maximum possible summation of differences of consecutive elements

texts:
Array A contains the elements, \$A_1,A_2, \ldots, A_N\$.
   And array B contains the elements, \$B_1,B_2, \ldots, B_N\$.

  There is a relationship between \$A_i\$ and \$B_i\$: any element \$A_i\$ lies between \$1\$ and \$B_i\$.

  Let the cost S of an array A be defined as:

  $$ S = \sum_{i=2}^N \lvert A_i - A_{i-1} \rvert$$

  Given B, find and print the largest possible value of S.

The problem can be found here

Example:

size of array:5
array: 10 1 10 1 10
output : 36
(since the max value can be derived as |10 - 1| + |1 - 10| + |10 - 1| + |1 - 10|)

Approach:
The only approach I could think of was brute force. I thought I would make an overlapping recursive equation so that I could memoize it, but was not able to.

CODE:

public static void func(int pos,int[] arr,int[] aux,int n)
    {
        /*
         * pos is current index in the arr
         * arr is array
         * aux is temp array which will store one possible combination.
         * n is size of the array.
         * */

        //if reached at the end, check the summation of differences
        if(pos == n)
        {
            long sum = 0;
            for(int i = 1 ; i < n ; i++)
            {
                //System.out.print("i = " + i + ", arr[i] = " + aux[i] + " ");
                sum += Math.abs(aux[i] - aux[i - 1]);
            }
            //System.out.println();
            //System.out.println("sum = " + sum);
            if(sum > max)
            {
                max = sum;
            }
            return;
        }

        //else try every combination possible.
        for(int i = 1 ; i <= arr[pos] ; i++)
        {
            aux[pos] = i;
            func(pos + 1,arr,aux,n);
        }
}

NOTE:
The complexity of this is \$\mathcal{O}(n*2^n)\$


texts: PHP exercise to read or write database values

texts:
I just came up with the code below but I'm wondering if there is room for improvement? I.e. better readability and or performance, better structure, less lines of code?

The script should parse a simple HTTP GET or POST request. The request can contain the following parameters:

action (required, possible values are "read" and "write");
mykey (required)
id (only required when action equals "read")

Depending on a read or write request the script should print an array containing:

status;
id (only after writing / inserting a value into database);
value (in case of a read request);

Sample requests:

api.php?action=write&mykey=12345&value=im%20fine
api.php?action=read&mykey=12345&id=13

The script should also log the content of the request to file. (append)

Code:

<?php
  include("opendb.php");
  $logging = true;
  $log = serialize($_REQUEST) . PHP_EOL;

  $reply = array("id" => null, "status" => null);

  if(isset($_REQUEST["action"]) && isset($_REQUEST["mykey"])) {
    $action = strtolower($_REQUEST["action"]);
    $mykey = $mysqli->real_escape_string($_REQUEST["mykey"]);

    if($action == "read") {
      if(isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"])) {
        $id = $_REQUEST["id"];
        // read message from database
        $sql = "SELECT * FROM data WHERE mykey = '$mykey' AND id = $id";

        if ($result = $mysqli->query($sql)) {
            $row = $result->fetch_assoc();
            $reply["id"] = $id;
            $reply["value"] = $row["value"];
            $reply["status"] = "success";
        } else {
            $log .= $mysqli->error . PHP_EOL;
            $reply["status"] = "error";
        }
      } else {
          $log .= "id missing" . PHP_EOL;
          $reply["status"] = "error (incorrect id)";
      }
    } elseif($action == "write") {
      // write message to database
      $value = $mysqli->real_escape_string($_REQUEST["value"]);

      $sql = "INSERT INTO `data` (`value`, `mykey`) VALUES ('$value', '$mykey')";

      if ($result = $mysqli->query($sql)) {
          $reply["id"] = $mysqli->insert_id;
          $reply["status"] = "success";
      } else {
          $log .= $mysqli->error . PHP_EOL;
          $reply["status"] = "error";
      }
    }
  } else {
      $log .= "invalid querystring" . PHP_EOL;
      $reply["status"] = "error (incorrect action, mykey)";
  }

  print_r($reply);

  if($logging) {
    file_put_contents('log/read_write_exercise.log', date('d-m-Y') . " " . print_r($log, TRUE), FILE_APPEND | LOCK_EX) ;
  }
?>


texts: checks validity of credit card in python (cs50 pset6)

texts:
I'm new to using python and wanted to know how I could improve my program. I'm using the Luhn algorithm, the beginning numbers of the credit cards, and the number of digits in the credit card.
from cs50 import get_string
import re
import sys

number = get_string("NUMBER: ")
check = []

if (len(number)) not in (13,15,16):
    print("INVALID")
    print(len(number))
    sys.exit(1)

for i in range(len(number)): # for the length of the string,
    if i%2 == (-2+len(number))%2: # if a counter is modulo 1
        digits = str(int(number[i])*2) #obtains the value of the multiplication
        for j in range(len(digits)):
            check.append(int(digits[j]))
    else:
        check.append(int(number[i]))

total = str(sum(check))

if re.search("0$", total):
    if re.search("^3(4|7)", number):
        print("AMEX")
    elif number[0] == str(4):
        print("VISA")
    elif re.search("^5(1|2|3|4|5)", number):
        print("MASTERCARD")
else:
    print("INVALID")


texts:
I have written this script to install gcc (here in version 4.9.2) on Centos6.6. I am only interested in C and C++ support.

Please comment if this is any good and can I make it better before I get the packages for those.

#!/bin/bash

LOGFILE=/tmp/gcc_install.log

# $1 - package name
# $2 - status
errorIf(){
if [ $2 -ne 0 ]; then
    echo "Something was wrong with $1"
    exit 1
fi
}

################################################################################
################################# SCRIPT START #################################

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# only one param - gcc's source directory absolute location
if [ $# -ne 1 ]; then
    echo "Please give the gcc source directory as argument"
    exit 1
fi

if [ ! -d "$1" ]; then
    echo "gcc's source directory that you have passed doesn't exist!"
    exit 1
fi

SOURCE_DIR="$1"
SOURCE_DIR_NAME="${SOURCE_DIR##*/}"
cd "$SOURCE_DIR"/contrib/

################################################################################
################################# gmp, mpgr, mpc  ##############################
# this script assumes that you have ran download_prerequisites from gcc's contrib dir
# contrib with downloaded gmp, mpgr, mpc (used download_prerequisites)
if [ ! -d gmp ] || [ ! -d mpfr ] || [ ! -d mpc ]; then
    echo "There is no gmp or mpfr or mpc directory in `pwd`. Please run download_prerequisites."
    exit 1
fi

echo "Installing gcc and dependencies. You can check the status and results in $LOGFILE"

#gmp
cd gmp && ./configure --enable-shared --enable-static --prefix=/usr/local >$LOGFILE 2>&1 && make >$LOGFILE 2>&1 && make check >$LOGFILE 2>&1 && make install >$LOGFILE 2>&1 && cd ..
ret="$?"
errorIf gmp $ret
echo "gmp Installed!:)"

#mpfr
cd mpfr && ./configure --enable-shared --enable-static --prefix=/usr/local --with-gmp=/usr/local >$LOGFILE 2>&1 && make >$LOGFILE 2>&1 && make check >$LOGFILE 2>&1 && make install >$LOGFILE 2>&1 && cd ..
ret="$?"
errorIf mpfr $ret
echo "mpfr Installed!:)"

#mpc
cd mpc && ./configure --enable-shared --enable-static --prefix=/usr/local --with-gmp=/usr/local --with-mpfr=/usr/local >$LOGFILE 2>&1 && make >$LOGFILE 2>&1 && make check >$LOGFILE 2>&1 && make install >$LOGFILE 2>&1 && cd ..
ret="$?"
errorIf mpc $ret
echo "mpc Installed!:)"

echo /usr/local/lib/ >> /etc/ld.so.conf
echo /usr/local/lib64/ >> /etc/ld.so.conf
ldconfig

cd ../../
ulimit -s 32768 # for gcc tests
mkdir -p /usr/share/gdb/auto-load/usr/lib
mkdir -p gcc-build
cd gcc-build

# find mv .py command is due to this ldconfig error (gcc copies some .py files into /usr/local/lib64/)
# ldconfig: /usr/local/lib/../lib64/libstdc++.so.6.0.20-gdb.py is not an ELF file - it has the wrong magic bytes at the start.
../$SOURCE_DIR_NAME/configure --enable-shared --disable-bootstrap --with-system-zlib --enable-languages=c,c++ --enable-libgomp --enable-threads=posix --with-gmp=/usr/local --with-mpfr=/usr/local --with-mpc=/usr/local --with-fpmath=sse --disable-multilib >$LOGFILE 2>&1 && make >$LOGFILE 2>&1 && make install >$LOGFILE 2>&1 && find /usr/local/lib64 -iname "*.py" -exec mv {} /usr/share/gdb/auto-load/usr/lib/ \;  >$LOGFILE 2>&1 && ldconfig >$LOGFILE 2>&1

echo "gcc from $SOURCE_DIR_NAME Installed!:)"


texts:
I tried this spoj problem and solved it using Dynamic Programming, but I was getting Time Limit Exceeded. The challenge is to count the number of occurrences of the subsequence "KEK" in each input string.

Some people in comments stated that they have done in O(n) time. I am getting no idea. can someone give me an idea? Here is my dynamic programming approach.

#include<bits/stdc++.h>
using namespace std;
int dp(string s,int in,int len,int pos){
    if(in == len){
        return 0;
    }
    if(pos == 0){
        if(s[in] == 'K'){
            return dp(s,in+1,len,1)+dp(s,in+1,len,0);
        }
        return dp(s,in+1,len,0);
    }
    if(pos == 1){
        if(s[in] == 'E'){
            return dp(s,in+1,len,2)+dp(s,in+1,len,1);
        }
        return dp(s,in+1,len,1);
    }
    if(pos == 2){
        if(s[in] == 'K'){
            return 1+dp(s,in+1,len,2);
        }
        return dp(s,in+1,len,2);
    }
}
int main(){
    int t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        int l = s.size();
        int k = dp(s,0,l,0);
        cout<<k<<endl;
    }
    return 0;
}


texts:
I'm implementing a basic array data structure with basic functionalities.

#include <iostream>
#include "barray.h"

BArray::BArray(int init_size)
{
    b_array = new int[init_size]();
    array_size = init_size;
}

BArray::BArray(int init_size, int init_val)
{
    b_array = new int[init_size];
    array_size = init_size;

    for(int i = 0; i < init_size; ++i)
        b_array[i] = init_val;
}

BArray::BArray(const BArray & rhs)
{
    array_size = rhs.array_size;
    b_array = new int[array_size];

    for(int i = 0; i < array_size; ++i)
        b_array[i] = rhs[i];
}

BArray::~BArray()
{
    delete [] b_array;
}

int BArray::getSize() const
{
    return array_size;
}

int BArray::operator[](int index) const
{
    return *(b_array + index);
}

int& BArray::operator[](int index)
{
    return *(b_array + index);
}

BArray& BArray::operator=(const BArray& rhs)
{
    if(this == &rhs)
        return *this;

    array_size = rhs.array_size;

    delete [] b_array;

    b_array = new int[array_size];

    for(int i = 0; i < array_size; ++i)
        b_array[i] = rhs[i];

    return *this;
}

std::ostream& operator<< (std::ostream& out, const BArray& arr)
{
    for(int i = 0; i < arr.array_size; ++i)
        out << arr[i] << " ";

    return out;
}

And the header file

#ifndef BARRAY_H
#define BARRAY_H

class BArray
{
public:
    BArray() = delete;                    //Declare the default constructor as deleted to avoid
                                          //declaring an array without specifying its size.
    BArray(const int init_size);
    BArray(int init_size, int init_val);  //Constructor that initializes the array with init_val.
    BArray(const BArray & rhs);           //Copy constructor.
    ~BArray();                            //Destructor.

    int operator[](int index) const;      //[] operator overloading for "reading" index value.
    int& operator[](int index);           //[] operator overloading for "setting" index value.
    BArray& operator=(const BArray& rhs); //Copy assignment operator.

    //Utility functions.
    int getSize() const;

    //Friend functions.
    friend std::ostream& operator<< (std::ostream& out, const BArray& arr);

private:
    int* b_array;
    int array_size;
};

#endif // BARRAY_H

Can you please give me a feedback on what is missing, what is wrong and what is good?
I mean in terms of memory allocation, operators overloading, etc...

Is this is the best way this class can be implemented?

Edit:
This is how I tested the code

#include <iostream>

#include "barray.h"

int main()
{

    //BArray invalid_instance; //Default constructor is deleted.

    BArray barr(5); //Declaring an array of size 5, this initializes all values to zeros.

    std::cout << barr[2] << std::endl;

    barr[2] = 15;   //Setting index 2 to 15.

    std::cout << barr[2] << std::endl; //Reading out value of index 2.

    BArray anotherArray(barr); //Copy constructor.

    std::cout << anotherArray[2] << std::endl;

    anotherArray[3] = 8;

    BArray assignArray = anotherArray; //Copy assignment operator.

    std::cout << assignArray[2] << std::endl;

    std::cout << assignArray; //Printing out array values.

    return 0;
}


texts:
I implemented the atoi() function! Here is my code:

int my_atoi(char* pointer)
{
    int result = 0;
    char* pointer1;
    multiplier = 1;
    char sign = 1;

    if(*pointer == '-')
    sign =- 1;

    pointer1 = pointer;

    while(*pointer != '\0')
    {
        if(*pointer >= '0' && *pointer <= '9')
            multiplier = multiplier * 10;

        pointer = pointer + 1;
    }

    pointer = pointer1;

    while(*pointer != '\0')
    {
        if(*pointer >= '0' && *pointer <= '9')
        {
            result = result + ( (*pointer%48)  * multiplier);
            multiplier = multiplier / 10;
        }

        pointer = pointer+1;
    }

    return (result * sign) / 10;
}

I wonder if there is any way that I can improve my function. I know there is a problem with my function. What if the user wants to convert from char* to int this string: "232-19". What should I do then? Any advice would be really helpful!


texts: Updating a dictionary of trajectories after a step has been made

texts:
I am using a dictionary to save possible trajectories in a game. A trajectory is defined as a list of numbers separated by _. For example '3_7_2_5' is a trajectory of 4 steps. I use a dictionary as I assign a value to each trajectory. The meaning of this value does not matter for the purpose of my question. I also save the trajectories in separated dictionaries if they have different numbers of steps.
I want to update the dictionary in such a way that only the trajectories starting from '1' are preserved. Moreover, I want to remove the '1' from the name, since I don't need to keep listing a step that has already been made.
# here I create the initial dictionaries

pts=[{},{},{}]

for j in range(20):
    k=random.choice(range(3))
    path=str(k)
    for d in range(len(pts)):
        k=random.choice(range(4))
        pts[d][path]=k
        path+='_'+str(k)

print 'initial dictionaries =',pts

# here I make the update

ind=1
new_pts=[{},{},{}]
path=str(ind)
for d in range(len(pts)-1):
    for path in pts[d+1]:
        if path[:len(str(ind))]==str(ind):
            new_pts[d][path[len(str(ind))+1:]]=pts[d+1][path]

pts=new_pts

print 'updated dictionaries =',pts

As you can see, the first element of the old list pts has been discarded. The second element has been used to create the first element of the updated list and so on.
Now, it seems to me that my algorithm is not very efficient. For updating the dictionary I am using a for loop over all keys, even though most of them are going to be discarded.
Is there a better, faster way to do this?


texts: Method on Laravel model to find courses related to a course

texts:
I have a Laravel project that has courses. I want to take the related courses from one.

Should I create the method in the model (the php class) or in the controller?

Currently I have this code in the model:

class Course extends Model {

    public function relatedCourses() {

        $all_courses = new Collection;

        // Similar name
        $words = explode($this->name, " ");
        foreach ($words as $word) {

            $courses = Course::where(function($query) use ($word) {
                $query->where('id', '<>', $this->id)->where('name_es', 'LIKE', "%$word%")->orWhere('name_cat', 'LIKE', "%$word%");
            })->get();

            $all_courses = $all_courses->merge($courses);
        }

        return $all_courses;
    }

}

Should I move it to the controller?


texts: Performing calculations with updated integer

texts:
How could I improve this code to make it shorter and more functional?

#!usr/bin/python
import time
integer = 0
print("The current integer is set at " + str(integer) + ".")
print("\n")
time.sleep(2)
prompt = raw_input("Would you like to change the integer? (Y/N) ")
print("\n")
if prompt == 'y':
    integer = int(raw_input("Insert the new integer here: "))
    print("\n")
    print("You have changed the integer to " + str(integer) + ".")
    print("\n")
    print("\n")
    time.sleep(1)
    print("1. Add / 2. Subtract / 3. Multiply / 4. Divide")
    print("\n")
    new_int = raw_input("What would you like to do with your new integer? (Choose a number) ")
    print("\n")
    if new_int == '1':
        added_int = int(raw_input("What number would you like to add to your integer (" + str(integer) + ") by?"))
        outcome1 = integer + added_int
        print("\n")
        print("The sum of " + str(integer) + " + " + str(added_int) + " is " + str(outcome1))
    if new_int == '2':
        subtracted_int = int(raw_input("What number would you like to subtract your integer (" + str(integer) + ") by?"))
        outcome2 = integer - subtracted_int
        print("\n")
        print("The difference of " + str(integer) + " - " + str(subtracted_int) + " is " + str(outcome2))
    if new_int == '3':
        multiplied_int = int(raw_input("What number would you like to multiply your integer (" + str(integer) + ") by?"))
        outcome3 = integer * multiplied_int
        print("\n")
        print("The product of " + str(integer) + " x " + str(multiplied_int) + " is " + str(outcome3))
    if new_int == '4':
        divided_int = int(raw_input("What number would you like to divide your integer (" + str(integer) + ") by?"))
        outcome4 = integer / divided_int
        print("\n")
        print("The quotient of " + str(integer) + " / " + str(divided_int) + " is " + str(outcome4))
elif prompt == "n":
    print("The integer will stay the same.")
    time.sleep(2)
    print("Press any key to exit...")
else:
    print("Invalid input.")
raw_input()


texts: C# Program that checks on the status of the Capslock with each character insert

texts:
The following is my first successful running C# program.

The lessons that I personally learnt through this include:

The value of asking for help after having tried several times
The advantages of being adaptable about one's methods of reaching an end
The (a?) proper placement of functions in relation to a main program
How to pass information into and out of such functions
How to use a loop to leverage code (doing the same stuff over and over)
How to collect character input from the User & I'm sure there's more...

In any case this code appears to work. I know that it doesn't hold a candle to much of the stuff you guys put up but on the bright side its short and kind of readable (both aims of mine).

Could some much brighter spark than me kindly shine a light on the stuff that could have been done better (or simply provide some advice or suggested direction)? :c)

using System;
namespace CapsChecker
{
    class Program
    {
        static void Main(string[] args)
        {
                //Set up an infinite loop for program to run within
            while (true)
            {
                    //Collection of user input
                Console.Write("Press a key: ");
                char input = (Console.ReadKey().KeyChar);
                    //Check if Capslock is on when key entered. Combined with
                    //the shift button this can result in CapsCheck returning
                    //true even if key entered is lower case.
                if (CapsCheck() == true)
                {
                    CapsNotify(true);
                }
                else
                {
                    CapsNotify(false);
                }
                Console.WriteLine();

                switch (input) //Abandoned '.Key' enum
                {
                    case 'Q':
                        { break; }
                    default:
                        { continue; }
                }
                break; //Afterthoght as it wasn't breaking on capital Q.
            }
            Console.WriteLine("Program ending. Press a key.");
            Console.ReadKey();
        }

        static bool CapsCheck()
        {
                // Check if Capslock is Active
            if (Console.CapsLock == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        static void CapsNotify(bool caps)
        {
                // Notify whether Capslock is Active
            if (caps == true)
            {
                Console.WriteLine(" Capslock is Active.");
            }
            else
            {
                Console.WriteLine(" Capslock is Inactive.");
            }
        }
    }
}


texts:
Solved one of the easiest problems from acm.timus.ru.

1001. Reverse Root
The input stream contains a set of integer numbers Aᵢ (0 ≤ Aᵢ ≤ 10¹⁸).
The numbers are separated by any number of spaces and line breaks.
A size of the input stream does not exceed 256 KB.
For each number Aᵢ from the last one till the first one you should
output its square root. Each square root should be printed in a
separate line with at least four digits after decimal point.

I would like to know why my solution is relatively slow (execution time is 1s) and uses so much memory (7 072 KB)? Compared to C++: 0.093s  and 408 KB of memory.

package main

import "fmt"
import "math"

var a []int64

func main() {
    for {
        var x int64
        k, _ := fmt.Scan(&x)
        if k != 1 {
            break
        }
        a = append(a,x)
    }
    n := len(a)

    for n > 0 {
        n--
        fmt.Printf("%.4f\n", math.Sqrt(float64(a[n])))
    }
}

Is the significantly larger resource consumption due to garbage collection and imported libraries or just my code is inefficient?


texts: Determine if a triangle is equilateral, isosceles, or scalene

texts:
I've been fiddling around with some easy code challenges and there's one about determining if a triangle is equilateral, isosceles, or scalene.

I've come up with a working solution, but I feel this could be greatly improved and/or simplified.

The sides of a triangle come in a list e.g. [2, 2, 2] or [0, 0, 0].

Here's what I've got.

def is_triangle(sides):
    if min(sides) <= 0:
        return False
    if sum(sorted(sides)[:-1]) < sorted(sides)[-1]:
        return False
    return True

def equilateral(sides):
    triangle = is_triangle(sides)
    if triangle:
        x, y, z = sides
        return x == y == z
    else:
        return False

def isosceles(sides):
    triangle = is_triangle(sides)
    if triangle:
        x, y, z = sides
        return x == y or y == z or z == x
    else:
        return False

def scalene(sides):
    if equilateral(sides) or isosceles(sides):
        return False
    return is_triangle(sides)

Also, I'm adding a simple unit test module.

import unittest

from triangle import equilateral, isosceles, scalene

class TestEquilateralTriangle(unittest.TestCase):
    def test_all_sides_are_equal(self):
        self.assertIs(equilateral([2, 2, 2]), True)

    def test_all_zero_sides_is_not_a_triangle(self):
        self.assertIs(equilateral([0, 0, 0]), False)

    def test_third_triangle_inequality_violation(self):
        self.assertIs(isosceles([3, 1, 1]), False)

    def test_sides_may_be_floats(self):
        self.assertIs(equilateral([0.5, 0.5, 0.5]), True)

class TestIsoscelesTriangle(unittest.TestCase):
    def test_last_two_sides_are_equal(self):
        self.assertIs(isosceles([3, 4, 4]), True)

    def test_equilateral_triangles_are_also_isosceles(self):
        self.assertIs(isosceles([4, 4, 4]), True)

    def test_third_triangle_inequality_violation(self):
        self.assertIs(isosceles([3, 1, 1]), False)

    def test_sides_may_be_floats(self):
        self.assertIs(isosceles([0.5, 0.4, 0.5]), True)

class TestScaleneTriangle(unittest.TestCase):
    def test_no_sides_are_equal(self):
        self.assertIs(scalene([5, 4, 6]), True)

    def test_all_sides_are_equal(self):
        self.assertIs(scalene([4, 4, 4]), False)

    def test_third_triangle_inequality_violation(self):
        self.assertIs(isosceles([3, 1, 1]), False)

if __name__ == "__main__":
    unittest.main()

I'd appreciate some feedback on my code.


texts: how to classify tweets in python based on handful of domains

texts:
I am currently working on a project that classifies tweets based on certain categories of information they belong to (7 given categories for his project).

For example, a tweet with the keywords "I think NY should ban smoking" should be classified as a tweet in the "Pollution" category with negative sentiment.

I have been able to get the sentiment analysis to work somewhat, but need some help with getting the category part to work. I am also open to all solutions.

My code so far is the stream.py module. And the following command to get live twitter data into a text file: python stream.py > output.txt:

import oauth2 as oauth
import urllib2 as urllib

api_key = 'xx'
api_secret = 'xx'

access_token_key = 'x-x'
access_token_secret = 'x'

_debug = 0

oauth_token    = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)

signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()

http_method = "GET"

http_handler  = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)

'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''
def twitterreq(url, method, parameters):
  req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                             token=oauth_token,
                                             http_method=http_method,
                                             http_url=url,
                                             parameters=parameters)

  req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)

  headers = req.to_header()

  if http_method == "POST":
    encoded_post_data = req.to_postdata()
  else:
    encoded_post_data = None
    url = req.to_url()

  opener = urllib.OpenerDirector()
  opener.add_handler(http_handler)
  opener.add_handler(https_handler)

  response = opener.open(url, encoded_post_data)

  return response
#locations=-74,40,-73,41
def fetchsamples():
  url = "https://stream.twitter.com/1.1/statuses/filter.json?track=money&locations=-74,40,-73,41"
  parameters = []
  response = twitterreq(url, "POST", parameters)
  for line in response:
    print(line.strip())

if __name__ == '__main__':
  fetchsamples()

The sentiment of a tweet is computed as the sum of the sentiment scores for each term in the tweet. Run: python tweet_sentiment.py AFINN-111.txt tweet_file to get the tweet sentiments.

Here is the link for my upload for AFINN-111.txt.http://s000.tinyupload.com/index.php?file_id=62473255612293859764

Here is the code for tweet_sentiment.py

import sys
import json
import ast
import re

def calcScoreFromTerm(termScoreFile):   # returns a dictionary with term-score values
    scores ={}
    for line in termScoreFile:
        term, score = line.split("\t")
        scores[term] = float(score)
    return scores

def getTweetText(tweet_file):   #returns a list of all tweets
    tweets = []
    for line in tweet_file:
        # print line
        jsondata = json.loads(line)
        if "text" in jsondata.keys():
            tweets.append(jsondata["text"])
    tweet_file.close()
    return tweets

def filterTweet(et):
    # Remove punctuations and non-alphanumeric chars from each tweet string
    pattern = re.compile('[^A-Za-z0-9]+')
    et = pattern.sub(' ', et)
    #print encoded_tweet

    words = et.split()

    # Filter unnecessary words
    for w in words:
        if w.startswith("RT") or w.startswith("www") or w.startswith("http"):
            words.remove(w)

    return words


texts: Best way to replace Urls in .Net application

texts:
I have an application developed in ASP.NET Core C#, where according to a configuration it must replace certain urls of a text when an http request is made and the text must be returned as soon as possible in response, the text can change on each request.

At this moment the code I have is working well, but I would like you to help me check the code to improve the speed of replacement of the urls.

string r = contenidoRespuesta; //contenidoRespuesta can be html, json or javascript content
string dominio="example.com";
int puertoHttp=81,puertoHttps=444;
foreach (var p in grupo.Paginas.Where(p => p.Proxy))
{

    Uri uri = new Uri(p.URL);
    string pattern1 = string.Format("(?<=https://){0}(:(443)(?!\\d+))?(?!:)", uri.Host);//generates a regular expression to replace urls that start with "https"
    string pattern2 = string.Format("(?<=http://){0}(:(80)(?!\\d+))?(?!:)", uri.Host);//generates a regular expression to replace urls that start with "http"
    string pattern3 = string.Format("(?<!%2F|\\.|http(s)?(://)){0}(:((80)|(443))(?!\\d+))?(?!:)", uri.Host);//generates a regular expression to replace urls that start with "//"

    r = Regex.Replace(r, pattern1,uri.Host.Replace(".", string.Empty) + "." +dominio + ":" + puertoHttps, RegexOptions.IgnoreCase);// replace https://www.page.com for https://wwwpagecom.example.com
    r = Regex.Replace(r, pattern2,uri.Host.Replace(".", string.Empty) + "." + dominio + ":" + puertoHttp, RegexOptions.IgnoreCase);// replace http://www.page.com for http://wwwpagecom.example.com
    r = Regex.Replace(r, pattern3, uri.Host.Replace(".", string.Empty) + "." + dominio + ":" +(esquema == "https"? puertoHttps.ToString(): puertoHttp.ToString()));// replace //www.page.com for https://wwwpagecom.example.com
}
return r;//return the responsd with new urls


texts:
Please tell me what the weak spots of this code are (specially in terms of efficiency) and how I can improve it:

def get_word_frequencies(filename):
  handle = open(filename,'rU')
  text = handle.read()
  handle.close()
  MUST_STRIP_PUNCTUATION = ['\n','&','-','"','\'',':',',','.','?','!'\
    ,';',')','(','[',']','{','}','*','#','@','~','`','\\','|','/','_'\
    ,'+','=','<','>','1','2','3','4','5','6','7','8','9','0']
  text = text.lower()
  for char in MUST_STRIP_PUNCTUATION:
    if char in text:
      text = text.replace(char,' ')
  words_list = text.split(' ')
  words_dict = {}
  for word in words_list:
    words_dict[word] = 0
  for word in words_list:
    words_dict[word] += 1
  del words_dict['']
  return words_dict

Some steps sound repetitive to me and it seems that I'm looping on the text many times but I think I'm obliged to take each of those steps separately(unless I'm wrong), for instance, replacing invalid characters should be on multiple separate iterations, or lower casing the whole text must be a separate step, and so on.

Also for creating the dictionary I'm suspicious a way better than words_dict[word] = 0 must exist?


texts:
Introduction:

I have a website where customers can configure and checkout glass products like for example: Shower doors, Mirrors, Kitchen splashbacks, Table tops etc.

What I am trying to do:

I am trying to create a class for calculating the price of this kind of configurable products. All the products have in common that they use square meters to calculate the price and some of the products have the same way of calculating the glasstype price.

The idea:

I have created an abstract class with the methods and properties which the products have in common. The idea is to create a class for each product with their exceptions (own methods and properties).

My question:

Am I doing the right thing or should I approach this differently? For example calling the methods in the constructor in my showerdoor class.

The abstract class:

abstract class ConfigurableProduct {

    public $squareMeters;

    // Stores the prices
    protected $_price = array();

    // Initializes object
    public function __construct( $data = array() ) {

        // Set square meters
        $this->squareMeters = $data['square_meters'];

    }

    // Adds price to _price array
    public function addPrice( $value ) {
        $this->_price[] = $value;
    }

    // Sums prices in _price array
    public function getPrice() {
        return array_sum( $this->_price );
    }

}

Showerdoor class:

class Showerdoor extends ConfigurableProduct {

    // Initializes object
    public function __construct( $data ) {

        // Parent constructor
        parent::__construct( $data );

        // Set glasstype
        if ( isset( $data['glasstype'] ) )
        $this->setGlasstype( $data['glasstype'] );

        // Set coating
        if ( isset( $data['coating'] ) )
        $this->setCoating( $data['coating'] );

        // Set hinges
        if ( isset( $data['hinges'] ) )
        $this->setHinges( $data['hinges'] );

    }

    // Adds the glasstype price to the _price array
    public function setGlasstype( $id ) {

        // Check for part id (so integer)
        if ( isset( $id ) && is_int( $id ) ) {

            // Calculate price
            $value = gtp_wizard_part_price( $id ) * $this->squareMeters;

            // Add price to price array
            $this->addPrice( $value );

        }

    }

    // Adds the coating price to the _price array
    public function setCoating( $id ) {

        // Check for part id (so integer)
        if ( isset( $id ) && is_int( $id ) ) {

            // Calculate price
            $value = gtp_wizard_part_price( $id ) * $this->squareMeters;

            // Add price to price array
            $this->addPrice( $value );

        }

    }

    // Adds the hinges price to the _price array
    public function setHinges( $id, $quantity = 2 ) {

        // Check for part id (so integer)
        if ( isset( $id ) && is_int( $id ) ) {

            // Calculate price (multiply for 2 hinges)
            $value = gtp_wizard_part_price( $id ) * $quantity;

            // Add price to price array
            $this->addPrice( $value );

        }

    }

}

How I create the object:

// Dimensions
$width          = 800;
$height             = 2000;
$square_meters  = $width * $height / 1000000;

// Parts (ids from database)
$glasstype      = 282236;
$hinges         = 282242;
$coating        = 282296;

// Create object
$showerdoor = new Showerdoor(
     array(
        'square_meters'     => $square_meters,
        'glasstype'         => $glasstype,
        'hinges'            => $hinges,
        'coating'       => $coating,
    )
);
// Echo price
echo $showerdoor->getPrice();


texts:
I recently have been very interested in custom allocators, so I decided to make the very basic (this should be faster than malloc) bump allocator. Here is my code in C:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/mman.h>
#include <unistd.h>

#define KB(size) ((size_t) size * 1024)
#define MB(size) (KB(size) * 1024)
#define GB(size) (MB(size) * 1024)
#define HEAP_SIZE GB(1)

typedef intptr_t word_t;
void* free_ptr = NULL;
void* start_ptr;
word_t end_ptr;

void init() {
    free_ptr = mmap(NULL, HEAP_SIZE, PROT_READ | PROT_WRITE,
                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (free_ptr == MAP_FAILED) {
        printf("unable to map memory\n");
        abort();
    }
    start_ptr = free_ptr;
    end_ptr = (word_t) start_ptr + HEAP_SIZE;
}

void* bump_alloc(size_t size) {
    void* new_ptr = free_ptr;
    free_ptr = (char*) free_ptr + size;
    return new_ptr;
}

void free_all_mem() {
    munmap(start_ptr, HEAP_SIZE);
}

int main() {
    init();
    int* x = (int*) bump_alloc(sizeof(int));
    assert(x != NULL);
    *x = 10000;
    printf("x: %d\n", *x);
    free_all_mem();
}

This is my first custom allocator so could I get some tips on optimization, etc.


texts:
Overall, I'm working on a simulator for a modified DnD 3.5 system. Right now, I'm trying to write an enum class that handles the Classes/Professions, and am currently trying to handle the profession modifiers for saving throws.

My issue is that everything is extremely boiler-plate, and I can't figure out a better way of doing it. I was thinking of maybe having a constructor for each profession that used true or false to denote if it was a good saving throw or bad one. That's just really bad though, I think, since it doesn't give any information when reading it. I also thought of having goodSaves and badSaves variables in each and then getGoodSaves() and getBadSaves(), but I can't think of an easy way of getting it working without a literal collection like in other languages.

Does anyone have any advice on how I can make this look better?

public enum ProfessionType {
    BARBARIAN {
        @Override
        public int getWillModifier(int level) {
            return badSaveModifier(level);
        }

        @Override
        public int getFortitudeModifier(int level) {
            return goodSaveModifier(level);
        }

        @Override
        public int getReflexModifier(int level) {
            return badSaveModifier(level);
        }
    },
    BARD {
        @Override
        public int getWillModifier(int level) {
            return goodSaveModifier(level);
        }

        @Override
        public int getFortitudeModifier(int level) {
            return badSaveModifier(level);
        }

        @Override
        public int getReflexModifier(int level) {
            return goodSaveModifier(level);
        }
    },

    /* snip containing all the other professions */

    WIZARD {
        @Override
        public int getWillModifier(int level) {
            return goodSaveModifier(level);
        }

        @Override
        public int getFortitudeModifier(int level) {
            return badSaveModifier(level);
        }

        @Override
        public int getReflexModifier(int level) {
            return badSaveModifier(level);
        }
    };

    private static int goodSaveModifier(int level) {
        return ((level / 2) + 2);
    }

    private static int badSaveModifier(int level) {
        return (level / 3);
    }

    /**
     * Calculates the Profession's Fortitude modifier.
     *
     * @param level Character's current level
     * @return Profession's modifier of the Will save
     */
    abstract int getWillModifier(int level);

    /**
     * Calculates the Profession's Fortitude modifier.
     *
     * @param level Character's current level
     * @return Profession's modifier of the Fortitude save
     */
    abstract int getFortitudeModifier(int level);

    /**
     * Calculates the Profession's Reflex modifier.
     *
     * @param level Character's current level
     * @return Profession's modifier of the Reflex save
     */
    abstract int getReflexModifier(int level);

    @Override
    public String toString() {
        return name().substring(0, 1).toUpperCase() + name().substring(1).toLowerCase();
    }
}


texts:
I am learning from a book, which uses SHA1. I've changed the code to password_hash(), by checking online. Here I query only the password and verify it. I managed get it working, but I feel a bit paranoid about the code. Is the code proper or wrong?

At registration:

//at registration
$p=mysqli_real_escape_string($dbcon, trim($_POST['psword1']));
$hash =  password_hash($p,PASSWORD_DEFAULT);
//stores $hash in db.

At login:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //connect to db
    require ('mysqli_connect.php');
    //validate the email
    if (!empty($_POST['email'])){
       $e = mysqli_real_escape_string($dbcon, $_POST['email']);
       }else {
       $e = FALSE;
       echo '
 You forgot to enter your email.
';
    }
// validate the password
if (!empty($_POST['psword'])){
      $p=mysqli_real_escape_string($dbcon,$_POST['psword']);
   } else {
       $p = FALSE;
       echo '
You forgot to enter your password.
';
     }
      if (!empty($e && $p )){
        //get email info
             $sql = "SELECT  psword FROM users WHERE email = '$e'  LIMIT 1";
             $query = mysqli_query($dbcon,$sql);
             $row = mysqli_fetch_row($query);
             $dbpassword=$row[0];

        //run if email and password got value
        if (password_verify($p,$dbpassword)){
          // Retrieve the user_id, first_name
          $q = "SELECT user_id, fname, user_level,lname,registration_date FROM users WHERE (email='$e')";
          // Run the query and assign it to the variable $result
          $result = mysqli_query ($dbcon, $q);
          // Count the number of rows that match the email/password combination
          if (@mysqli_num_rows($result) == 1) {//if one database row (record) matches
            // Start the session, fetch the record and insert the three values in an array
            session_start();
            $_SESSION = mysqli_fetch_array ($result, MYSQLI_ASSOC);
            // Ensure that the user level is an integer.
            $_SESSION['user_level'] = (int) $_SESSION['user_level'];
            // Use a ternary operation to set the URL
            $url = ($_SESSION['user_level'] === 1) ? 'index.php' : 'members.php';
            header('Location: ' . $url); // Make the browser load either the members’ or the admin page
            exit(); // Cancel the rest of the script
            mysqli_free_result($result);
            mysqli_close($dbcon);
        } else { // No match was made.
            echo '
The e-mail address and password entered do not match our records
Perhaps you need to register, just click the Register button on the header menu
';
          }
          } else { // If there was a problem.
            echo '
Please try again.
';
            }

   }
mysqli_close($dbcon);
}
?>


texts: JavaScript card game and hand evaluation

texts:
I have the following code (it looks long but it's not too bad):

function evaluate_cards(hand){
    var hand_length = hand.length;
    var num_of_sets = 0;
    var num_of_runs = 0;
    var cards_in_run = 0;
    var suit = '';
    var buckets = {
         three_bucket: [],
         four_bucket: [],
         five_bucket: [],
         six_bucket: [],
         seven_bucket: [],
         eight_bucket: [],
         nine_bucket: [],
         ten_bucket: [],
         j_bucket: [],
         q_bucket: [],
         k_bucket: [],
         w_bucket: [] //bucket for wilds
    }

    for(var i = 0; i < hand_length; i++){
        if(hand[0].is_wild){
            buckets.w_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 3){
            buckets.three_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 4){
            buckets.four_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 5){
            buckets.five_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 6){
            buckets.six_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 7){
            buckets.seven_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 8){
            buckets.eight_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 9){
            buckets.nine_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 10){
            buckets.ten_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 11){
            buckets.j_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 12){
            buckets.q_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 13){
            buckets.k_bucket.push(hand.splice(0, 1));
        }
    }

    for(var k in buckets){
        if(buckets.hasOwnProperty(k)){
            if(buckets[k].length >= 3 && buckets[k] != buckets.w_bucket){
                num_of_sets++;
            }else if(buckets.w_bucket.length > 0 && buckets[k].length == 2){
                buckets[k].push(buckets.w_bucket.shift());
                num_of_sets++;
            }else if(buckets[k].length < 3 && buckets.w_bucket.length > 1){
                    for(var i = 0; i < buckets.w_bucket.length; i++){
                        buckets[k].push(buckets.w_bucket.shift());
                    }
                    if(buckets[k].length >= 3){
                        num_of_sets++;
                    }
            }else if(num_of_sets == 0){
                if(buckets[k].length > 0){
                    if(suit == ''){
                        suit = buckets[k][0].suit;
                    }else if(suit == buckets[k][0].suit){
                        cards_in_run++;
                    }else{
                        suit = '';
                    }
                    if(cards_in_run != 0 && cards_in_run < 3 && buckets.w_bucket.length != 0){
                        cards_in_run++;
                    }
                }
                if(cards_in_run >= 3){
                    num_of_runs++;
                    cards_in_run = 0;
                }
            }
        }
    }
    return {'runs':num_of_runs, 'sets': num_of_sets};
}

It's based off of the second answer to this question on game-dev.se. There are two major differences, however.

There are wilds in my game, which makes finding things like runs much more difficult.
Most sets/runs are going to be 3 or four cards but could be up to 5 cards, obviously anything 6 and over can be divided (set or run has to be a minimum of 3 cards).

The following is passed a hand will determine almost all sets of three cards, but only a few runs.

My request is that it be reviewed for optimization and where my logic goes wrong with runs. I'm totally open to any suggestions.


texts:
I'm learning basic algorithms and implementing them in Python. Critiques needed/welcome.

import pudb; pu.db
import random
def selection_sort(list_):
    """Implement selection_sort algorithm: iterate L to R in list, grab value
    if greatest and inserting into correct pos. After each loop, decrement
    length of iterated list by 1"""
    val_list, greatest = list(range(len(list_))), 0
    for num in range(len(list_)):
        greatest = val_list[-1]
        for val in val_list:
            if list_[greatest] < list_[val]:
                greatest = val
        if list_[greatest] > list_[val_list[-1]]:
            list_.insert(val, list_.pop(greatest))
            val_list.remove(val)
    return list_

if __name__ == '__main__':
    unsorted = list(range(9))
    random.shuffle(unsorted)
    assert selection_sort(unsorted) == list(range(9))


texts: Parse weak ciphers out of an nmap.xml report

texts:
I wrote the following code to parse some weak ciphers out of an nmap.xml report. I am wondering if there is a more elegant way to write this code in order to avoid the nested for loops with the double if loops. Also,  I had to create the two queues. There has to be a better way using list comprehension or a generator or something.

from xml.etree import ElementTree

md5Stack = []
shaStack = []
ip = []

with open('nmap.xml', 'rt') as f:
    tree = ElementTree.parse(f)
    for node in tree.getiterator('address'):
        ip = node.attrib.get('addr')
        for node in tree.getiterator('elem'):
            key = node.attrib.get('key')
            if key == "sha1" and ip not in shaStack:
                print ' %s :: %s' % (ip, key)
                shaStack += ip.split(",")
            if key == "md5" and ip not in md5Stack:
                print ' %s :: %s' % (ip, key)
                md5Stack += ip.split(",")

Example XML

<host starttime="1" endtime="1"><status state="up" reason="user-set" reason_ttl="0"/>
<address addr="1.1.1.1" addrtype="ipv4"/>

<elem key="type">md5</elem>
<elem key="bits">56</elem>

<elem key="notBefore">00:00+00:00</elem>
<elem key="notAfter">:00:00+00:00</elem>

<elem key="md5">34lk5jl4k5jlk34j5lk34j5lk</elem>
<elem key="sha1">234lk6j23lk6j2l3kj32lk4j3l4</elem>
<elem key="pem">BEGIN CERTIFICATE;END CERTIFICATE;</elem>
</script></port>
</ports>
<times srtt="98" rttvar="4" to="2"/>
</host>


texts:
Here is my approach.
1. Checking there is no cycle.(Using BFS)
2. All nodes are connected. (visited)

public static boolean isTree(int[][] adjMat) {
    int numVertex = adjMat.length;
    State[] isVisited = new State[numVertex];
    for (int i = 0; i < numVertex; i++) {
        isVisited[i] = State.UNVISITED;
    }

    // use BFS
    Queue q = new LinkedList<>();
    q.add(0);
    isVisited[0] = State.VISITING;
    while (!q.isEmpty()) {
        int current = (int) q.poll();
        if (isVisited[current] == State.VISITED) {
            return false;
        }
        isVisited[current] = State.VISITING;
        for (int i = 0; i < numVertex; i++) {
            if (adjMat[current][i] == 1) {
                q.add(i);
            }
        }
        isVisited[current] = State.VISITED;

    }
    for (int i = 0; i < numVertex; i++) {
        if (isVisited[i] == State.UNVISITED)
            return false;
    }
    return true;

}

public enum State {
    UNVISITED, VISITING, VISITED
}

Any improvements/suggestions please.


texts: Finding minimum scalar product using ST Monad

texts:
Inspired by a Stack Overflow question, I decided to practice my Haskell by taking a crack at the Google Code Jam's Minimum Scalar Product problem:

  Given two vectors \$\mathbf{v_1}=(x_1,x_2,\ldots,x_n)\$ and \$\mathbf{v_2}=(y_1,y_2,\ldots,y_n)\$. If you could permute the coordinates of each vector, what is the minimum scalar product \$\mathbf{v_1} \cdot \mathbf{v_2}\$?

  Constraints:
  \$100 \le n \le 800\$
  \$-100000 \le x_i, y_i \le 100000\$

I'm not claiming any algorithmic awesomeness (this is just a reference implementation for checking correctness later).

This is my first time using Vectors and the ST monad, so what I really want is a sanity check that I'm using both correctly, and that I'm using the correct tools for the job.

module MinimumScalarProduct where

import Control.Monad (replicateM, forM_, (>=>))
import Control.Monad.ST (runST, ST)
import Data.Vector (thaw, fromList, MVector, Vector, zipWith, foldl', length, (!))
import Data.Vector.Generic.Mutable (read, swap)
import Prelude hiding (read, zipWith, length)

-- sequnce of transpoitions to yield all permutations of n elts
-- http://en.wikipedia.org/wiki/Steinhaus-Johnson-Trotter_algorithm
transpositions :: Int -> [(Int, Int)]
transpositions n = runST $ do
          -- p maps index to element
          p <- thaw $ fromList [0 .. n-1]
          -- q maps element to index
          q <- thaw $ fromList [0 .. n-1]
          -- let the prefixes define themselves recursively
          foldr ((>=>) . extend p q) return [2..n] []

extend :: MVector s Int -> MVector s Int -> Int -> [(Int,Int)] -> ST s [(Int,Int)]
extend p q n ts = fmap ((ts++) . concat) . replicateM (n-1) $ do
  -- replace the element in the (n-1)'th position with its predecessor
  a <- read p (n-1)
  i <- read q (a-1)
  swap p (n-1) i
  swap q a (a-1)
  -- replay the earlier transpositions
  forM_ ts $ \(m,j) -> do
    b <- read p m
    c <- read p j
    swap p m j
    swap q b c
  return $ (n-1,i) : ts

-- reference implementation, takes O(n!)
msp :: Vector Int -> Vector Int -> Int
msp u v | length u /= length v = 0
msp u v = runST $ do
  let x = foldl' (+) 0 $ zipWith (*) u v
  let n = length u
  u' <- thaw u
  -- check each permutation of u'
  let steps = map (adjust u' v) $ transpositions n
  fmap minimum . sequence $ scanl (>>=) (return x) steps

-- adjust the current scalar product for the transposition of u
adjust :: MVector s Int -> Vector Int -> (Int, Int) -> Int -> ST s Int
adjust u v (i,j) x = do
  a <- read u i
  b <- read u j
  let c = v ! i
  let d = v ! j
  swap u i j
  return $ x - (a*c + b*d) + (a*d + b*c)


texts:
I'm adding prefixes to headers in markdown using a script. For example, if I have:

# Hello

## World

### Let's add

## Some headers

### Yay!

# Foo

## Bar

I transform it to:

# 1 Hello

## 1.1 World

### 1.1.1 Let's add

## 1.2 Some headers

### 1.2.1 Yay!

# 2 Foo

## 2.1 Bar

I currently have the following working code, but it feels a bit hacky and prone for error. :

preg_match_all('/^(#+)\s(.*)$/m', $markdown, $headers);
$levelCount = [];
$currentLevel = 9999;
foreach ($headers[2] as $idx => $header) {
    $level = strlen($headers[1][$idx]);
    if ($level < $currentLevel) {
        // reset:
        for ($i = $level; $i != $currentLevel; $i += 1) {
            array_pop($levelCount);
        }
    }
    if (!isset($levelCount[$level])) {
        $levelCount[$level] = 1;
    } else {
        $levelCount[$level] += 1;
    }
    $prefix = implode('.', array_values($levelCount));
    $currentLevel = $level;
    $markdown = preg_replace(
        '/' . preg_quote($headers[0][$idx]) . '/',
        $headers[1][$idx] . ' ' . $prefix . ' ' . $header,
        $markdown,
        1
    );
}

What are your thoughts on this?


texts: Root to leaf path with given sum in binary tree

texts:
For a given binary tree and a sum, I have written the following function to check whether there is a root to leaf path in that tree with the given sum.

/*
//A binary tree node
struct Node
{
    int data;
    struct Node* left, * right;
};
*/

bool hasPathSum(Node *node, int sum)
{
    if(!node)
        return sum==0;

    return ( hasPathSum(node->left,  sum-node->data) ||
             hasPathSum(node->right, sum-node->data) );
}

Are there any edge cases in which the code will break? Also, do comment on the code style.


texts: "Can a list of meetings all be scheduled in a conference room?"

texts:
I was given this question at an interview for a position I just got rejected by, so looking to improve and see what better answers there are!

Input: List of meetings

Output: Can conference room fit all the meetings

It was an open ended problem so I was kinda flustered. My first stab at it was probably too much in terms of set up (he was probably just looking for a solution, not so much for a grasp of object oriented principles) and I think I totally diverged from the Output, but still going to paste my answer anyway:

class Meeting
  attr_accessor :start_time
  attr_accessor :end_time

  def does_not_overlap?(start_time, end_time)
    self.start_time < start_time && self.end_time < end_time ||
    self.start_time > start_time && self.end_time > end_time ||
  end
end

class ConferenceRoom
  attr_accessor :meetings

  def initialize
    self.meetings = []
  end

  def bulk_schedule(list_of_meetings)
    currently_scheduled_meetings = self.meetings
    list_of_meetings.each do |meeting|
      self.meetings.each do |scheduled_meeting|
        if currently_scheduled_meetings.does_not_overlap?(meeting)
          schedule(meeting)
        else
          raise "Conference room can't fit all meetings"
        end
      end
    end
  end

  def schedule(meeting)
    self.meetings << meeting
  end
end

My brute force solution was this, which was just to loop through the array of meetings and see if any of them were scheduled at a certain time range when scheduling new meetings. This runs in \$O(n^2)\$ since I have to loop through an array for each element in another array. When he asked how I would optimize it, I said I would use a hash with the time range as keys and loop through those instead. However, thinking back on this I don't think that would improve things at all.

My friend said to sort the array and do binary search on it. However, I don't get how I would do that given the meetings have 2 properties we have to keep in mind (start time and end time), not just one. Can someone shed some light?


texts: Using best practice with complex iteration

texts:
I'm new to Rust so I'm still learning how to use best practice in complex examples.

Below is some code I've used in one of my programs, a simple implementation of a standard neural network.

Here is a the file I'm running: https://pastebin.com/p9ntgWPK

Here is the code snippet I'm particularly interested in (lines 60-72 in the pastebin):

    for x in 0..self.neuron_layers.len() - 1 {
        for y in 0..self.neuron_layers[x+1].len() {
            let mut sum:f64 = 0f64;
            for z in 0..self.neuron_layers[x].len() {
                sum += self.neuron_layers[x][z] * self.connection_layers[x][y][z];
            }
            self.neuron_layers[x+1][y] = sigmoid(sum);
        }
    }

To me this code stinks of inefficiency and bad practice, I just have a gut feeling.

So I wanted to ask 2 things.

How can I improve?
What elements within it are generally considered bad practice?


texts:
This should be relatively simple, but I want to know if I've done the randomness bit correctly.

<?php
function seeded_shuffle(array &$input, int $seed) {
    $rand = function($max) use (&$seed, &$rand) {
        static $rng_a = 0x41C64E6D;
        static $rng_c = 0x00006073;
        // rng_m = 2^32
        // c is odd => m and c are coprime
        // a is odd => a-1 is divisible by all prime factors of m (ie. 2)
        // m%4 = 0 and (a-1)%4 = 0
        // Therefore this is an LCRNG with a full period.

        $seed = ($rng_a * $seed + $rng_c) & 0xFFFFFFFF;
        $mod = $max + 1;
        // Modulo might not divide 2^32, so if it's too high then re-roll
        if( intdiv($seed,$mod) >= intdiv(1<<32,$mod)) {
            return $rand($max); // seed has advanced
        }
        return $seed % $mod;
    };

    // Fisher-Yates shuffle
    for( $i=count($input)-1; $i>0; $i--) {
        $j = $rand($i);
        list($array[$i],$array[$j]) = [$array[$j],$array[$i]];
    }
}

My main concern is that "Modulo might not divide 2^32" bit. I'm trying to avoid modulo bias, but is just re-rolling until we're not in the top-end range good enough?

(Just in case it's relevant, the length of $input is 18 in this use case)


texts: Class with multiple parameters as the object of a WeakReference

texts:
I just read this post on how to avoid memory leaks with AsyncTask. The post proposed using a WeakReference and supplying a TextView as the object of the WeakReference.

In my code, I need to supply multiple parameters to the AsyncTask (not just one as shown in the post). So what I did was create an inner class with the parameters needed in the AsyncTask and use the said class as the object of the WeakReference.

private static class AddBooksToDatabase extends AsyncTask<String, String, String> {
        private final WeakReference<AddBooksDbParams> mReference;
        private String TAG = "TownFragment";
        Context mContext;
        WaveLoadingView waveView;
        TextView infoText;
        String townName;
        File mFile;

        public AddBooksToDatabase(AddBooksDbParams params) {
            this.mReference = new WeakReference<    >(params);
            mContext = mReference.get().mContext;
            infoText = mReference.get().infoText;
            townName = mReference.get().townName;
            mFile = mReference.get().mFile;
            waveView = mReference.get().waveView;
        }

        @Override
        protected String doInBackground(String... strings) {
            TownHelper helper = TownHelper.getInstance(mContext, dbName);
            SQLiteDatabase database = helper.getWritableDatabase();
            int booksSize = getFilesInFolder(mFile).size();
            //Stuffs
            return null;
        }

        @Override
        protected void onPreExecute() {
            if (waveView != null) {
                waveView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected void onPostExecute(String s) {
            if (waveView != null) {
                waveView.setVisibility(View.GONE);
            }
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            Log.d(TAG, "Progress report = " + values[0]);
            infoText.setText(values[0]);
        }

        @Override
        protected void onCancelled() {
            cancel(true);
        }
    }

    //Parameters for AddBooksToDatabase. This is to enable holding of a
    //single object of this class in WeakReference
    private class AddBooksDbParams {
        Context mContext;
        WaveLoadingView waveView;
        TextView infoText;
        String townName;
        File mFile;

        AddBooksDbParams(TextView infoText, Context context, File file,
                         String townName, WaveLoadingView waveView) {
            this.infoText = infoText;
            mContext = context;
            mFile = file;
            this.townName = townName;
            this.waveView = waveView;
        }
    }

When I want to execute the AsyncTask:

AddTownsDbParams params = new AddTownsDbParams(infoText, getActivity(), folder, mShelfLabel, mWave);
addBooksTask = new AddBooksToDatabase(params).execute();

The code is working quite aright but I want to know if I am doing wrong.


texts: Three ways to add pronoun method/property to gendered class in Python

texts:
Say you have a Python class for something that has an optional gender field. You'd like a helper property/method to get the appropriate pronoun for an instance. You'd also like to be able to get the possessive version of the pronoun. The use for these helpers will be in creating human-readable emails and other such messages related to the object.

Below are three ways to do it. Which is best in terms of style and design and why?

Option 1

@property
def pronoun(self):
    return "he" if self.gender == 'male' else "she" if self.gender == 'female' else "they"

@property
def possessive_pronoun(self):
    return "his" if self.gender == 'male' else "her" if self.gender == 'female' else "their"

Option 2

def pronoun(self, possessive=False):
    if possessive:
        return "his" if self.gender == 'male' else "her" if self.gender == 'female' else "their"
    else:
        return "he" if self.gender == 'male' else "she" if self.gender == 'female' else "they"

Option 3

def pronoun(self, possessive=False):
    pronouns = ("he", "his") if self.gender == 'male' else ("she", "her") if self.gender == 'female' \
        else ("they", "their")
    return pronouns[1] if possessive else pronouns[0]

Feel free to suggest an even better fourth option.

P.S. In case you are wondering, I like to use double quotes for strings meant for human consumption, single quotes otherwise.


texts: Google Apps Script for finding empty days on multiple calendars

texts:
I need help with a simple Google Apps Script I've written. The script finds days on which no all-day events have been scheduled, across multiple calendars.

I'm fairly certain the main issue is the fact that I'm making an API call to get all owned calendars, then I'm making 5 API calls on each of these calendars to retrieve each day's (Mon - Fri) events.

Currently, it takes about 60 seconds to run on an account with 11 owned calendars. Is there anything that can be done to optimize?

var one_day = 86400000; //24 * 60 * 60 * 1000
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var startDay = nextMonday(new Date());

// Script-as-app template.
function doGet() {
  var app = UiApp.createApplication();

  var button = app.createButton('Find Blanks').setId('button');
  var loader = app.createImage('http://preloaders.net/preloaders/496/Flip%20Flop.gif').setVisible(false).setId('loader');
  var blanks = app.createHTML().setId('blanksArea').setHTML('Click button to find calendar blanks for week of ' + startDay);

  app.add(button);
  app.add(app.createHTML('
'));
  app.add(loader);
  app.add(blanks);

  var clientHandler = app.createClientHandler().forEventSource().setEnabled(false).forTargets(loader).setVisible(true).forTargets(blanks).setHTML('Processing for week of ' + startDay);
  var handler = app.createServerHandler('serverHandler');

  button.addClickHandler(clientHandler);
  button.addClickHandler(handler);

  return app;
}

function serverHandler(e) {
  var app = UiApp.getActiveApplication();

  var button = app.getElementById('button');
  var blanks = app.getElementById('blanksArea');
  var calendarsWithBlanks = getCalendarsWithBlanks();

  blanks.setHTML(calendarsWithBlanks.length ? calendarsWithBlanks.join('
') : 'There are no blanks');

  app.getElementById('loader').setVisible(false);
  button.setEnabled(true);

  app.close();
  return app;
}

function getCalendarsWithBlanks()
{
  var calendars = CalendarApp.getAllOwnedCalendars();
  var calendarsWithBlanks = [];
  for(var i = 0; i < calendars.length; i++)
  {
    var calendar = calendars[i];
    var calendarName = calendar.getName();
    var blankDays = checkCalendarForBlanks(calendar, startDay);
    if(blankDays.length)
    {
      calendarsWithBlanks.push(calendarName + ' has ' + blankDays.join(', ') + ' blank')
    }
  }
  return calendarsWithBlanks;
}

function checkCalendarForBlanks(calendar, startDay)
{
  var blankDays = [];
  for(var d = 0; d < 5; d++)
  {
    var currDay = new Date(startDay.getTime() + (d * one_day));
    var events = getEventsForDay(calendar, currDay);
    var foundAllDayEvent = false;
    for(var e = 0; e < events.length; e++)
    {
      if(events[e].isAllDayEvent())
      {
        foundAllDayEvent = true;
        break;
      }
    }
    if(!foundAllDayEvent)
    {
      blankDays.push(days[currDay.getDay()]);
    }
  }
  return blankDays;
}

function nextMonday(date)
{
  var today = date;
  today.setUTCHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  today.setMilliseconds(0);
  var day = today.getDay();
  var offset = 8 - day
  var next_monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+offset);
  return next_monday;
}

function getEventsForDay(calendar, date)
{
  /* !!!KLUDGE ALERT!!!
   * This is a kludge. The API method getEventsForDay is wonky: http://stackoverflow.com/questions/11870304/google-apps-script-geteventsforday-returns-invalid-recurring-events
   */

  var startOfDay = new Date(date.getTime());
  startOfDay.setUTCHours(0);
  startOfDay.setMinutes(0);
  startOfDay.setSeconds(0);
  startOfDay.setMilliseconds(0);
  var endOfDay = new Date(startOfDay.getTime() + one_day);

  return calendar.getEvents(startOfDay, endOfDay)
}


texts: Algorithm to transform a string according to occurrence count of each character

texts:
I have this algorithm that counts the frequency of character occurrence in a string, and outputs a new string based on that.

For example,

input = 'aabbcccaaa'
output = 'a5b2c2'

Here is my implementation in python

def compression(string):
    string = string.lower()
    freq_count = {}

    for index, char in enumerate(string):
        if char not in freq_count:
            freq_count[char] = 1
        else:
            freq_count[char] += 1

    return_string = ''
    for key in freq_count:
        return_string += key + str(freq_count[key])
    print(return_string)

    return return_string

compression('aabccccaaa')

My question is, am I making this algorithm less efficient by using dict to memoize values.

Also, I know that creating a new string takes up memory allocation, so is there a way to improve on that?


texts:
The following small function receives a range and returns it with only the cells that contain constants or Nothing if there's none.
Private Function GetConstants(ByVal Cells As Range) As Range
  On Error GoTo ErrHandler
  Set GetConstants = Intersect(Arg1:=Cells.SpecialCells(Type:=xlCellTypeConstants), Arg2:=Cells)
  Exit Function
ErrHandler: If Err.Number <> 1004 Then Err.Raise Number:=Err.Number, Source:=Err.Source, Description:=Err.Description, HelpFile:=Err.HelpFile, HelpContext:=Err.HelpContext
End Function

If there's no constants in the range Cells, the Range.SpecialCells method throws the error:

Run-time error '1004':
Application-defined or object-defined error

The error handler ignores it and returns the default value Nothing.
The use of the Intersect method fixes the issue that occurs when the range is only one cell. It otherwise treats it as the whole sheet.

Question:
Is there any edge case not being handled or not in the best overall way?
Did I miss something, are the names ideal, should I check If Not TypeOf Cells Is Range Then Exit Function, or maybe use another way instead of Intersect and checking Err.Number <> 1004?


texts: Calculate 8 hours business day in a weekdays only

texts:
I am fairly new into asp.net MVC c# I am working on request holiday app where an employee can request holidays. The problem is the app works fine, however,  I am trying to set 8 hours a day when an employee requests a holiday I have scratching my head from 2 days already seen every topic in StackOverflow and here and still can't get to work if anyone has any suggestions it will be much appreciated.
Here is a snippet of the calculation of the working days excluding weekends. Thank you in advance.

 public static class DateHelpers
    {
        public static int DaysBetweenExcludingWeekends(DateTime startDate, DateTime endDate)
        {

            var days = 0;
            while (startDate <= endDate)
            {
                if (startDate.DayOfWeek != DayOfWeek.Saturday && startDate.DayOfWeek != DayOfWeek.Sunday)

                {
                        days++;

                }

                startDate = startDate.AddDays(1);
            }

            return days;
        }

    }