Particle Swarm Optimization algorithm This is part of a Particle Swarm Optimization algorithm, a snippet of a Particle class implementation.

/**
 * Particle class constructor
 * @param p - the position of the particle
 * @param v - the velocity of the particle
 */
Particle::Particle(std::array<double, 30> p, std::array<double, 30> v) {
    bestFitness = fitness = rastriginEvaluation(p);
    bestPosition = position = p;
    velocity = v;
}

// setter methods
void Particle::setFitness(double f) { fitness = f; }
void Particle::setBestFitness(double f) { bestFitness = f; }
void Particle::setPosition(std::array<double, 30> p) { position = p; }
void Particle::setBestPosition(std::array<double, 30> p) { bestPosition = p; }
void Particle::setVelocity(std::array<double, 30> v) { velocity = v; }

Notice the constructor directly accesses member attributes yet I have setter methods. Should I be using the setter methods to initialize attributes? Either is fine, I wonder what is more proper.

For example, instead of:

bestFitness = fitness = rastriginEvaluation(p);
bestPosition = position = p;
velocity = v;

I could do:

setFitness(rastriginEvaluation(p));
setBestFitness(rastriginEvaluation(p));
setPosition(p);
setBestPosition(p);
setVelocity(v);

For this example, rastriginEvaluation() is called twice, when the original code only calls it once. It is therefore slower but what is better practice?

I could also wonder about getter methods in the mix:

setFitness(rastriginEvaluation(p));
setBestFitness(getFitness());
setPosition(p);
setBestPosition(getPosition();
setVelocity(v);

If it makes a difference, all attributes are private.

As a general rule, if the only thing your getters and setters do is contain a single statement, a return or assignment respectively, there is no need to make the variable private and it should be declared public.

Specifically to your question: Neither of your approaches are considered "best" nor "proper" practice. You should be using an initializer list before the constructor's body:

Note: There is no indication of what order the variables were declared in the class declaration. I've made a guess here, but they are initialized in the order they are declared regardless of what order you put them in the list so if I've got it backwards and fitness is declared first things will silently break at run-time.

Particle::Particle(std::array<double, 30> p, std::array<double, 30> v)
: bestPosition(p)
, position(p)
, velocity(v)
, bestFitness(rastriginEvaluation(p))
, fitness(bestFitness)
{
    /* DO NOTHING */
}


CodeIgniter nav/menu insecurities I more or less asked the same questions on stackoverflow.com, but maybe this is more for this forum. I have a hard time getting to grips with how to implement a top navigation (common for the whole site) and a page specific navigation (common for the current controller). I use Colin Williams' Template library.

I have written my own MY_Controller which all page controllers should extend, but I do not know if this is the correct way. The page specific navigation is implemented in the code below.

MY_Controller.php

abstract class MY_Controller extends CI_Controller {
    private $_nav;

    public function __construct() {
        parent::__construct();
    }

    abstract protected function _get_nav();

    protected function _load_nav(array $nav = null) {
        if ($nav === null) {
            $this->_nav = $this->_get_nav();
        } else {
            $this->_nav = $nav;
        }
    }

    protected function _render() {
        if (func_num_args() < 3) {
            return false;
        }

        $args = func_get_args();
        $this->template->write('title', array_shift($args));
        $data = array_pop($args);

        for ($i = 0; $i < count($args); $i++) {
            $this->template->write_view('content', array_shift($args), $data);
        }

        if ($this->_nav === null) {
            $this->_load_nav();
        }

        $this->template->write_view('nav', 'templates/sidebar_nav', array('nav' => $this->_nav));
        $this->template->render();
        return true;
    }
}

collection.php

class Collection extends MY_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('collection_model');
    }

    protected function _get_nav() {
        return $this->config->item('collection_nav');
    }

    public function index() {
        $this->view();
    }

    public function view() {
        $data = array();
        $data['list'] = $this->collection_model->get_list();
        $this->_render('View Collection', 'collection/view', $data);
    }
}

sidebar_nav.php

    <?php foreach ($nav as $item) : ?>
    <?php $class = isset($item['class']) ? ' class="' . $item['class'] . '"' : ''; ?>
    <li<?php echo $class; ?>>
        <a href="<?php echo $item['href']; ?>"><?php echo $item['value']; ?>

    <?php endforeach; ?>

What do you think? Is this the proper way to produce a navigation system?

I'm not familiar with CI, but from what I can tell the concept seems alright. At least, what I am able to glean from your code seems to be. There are some improvements you could make however.

The only reason to abstract the setting of the $_nav property with the _load_nav() method would be so that you could inject different navigation schemes to allow for further expansion. However, you do not inject your navigation into it and instead hardcode it, albeit with another method. If you are always going to use the _get_nav() method to "inject" your navigation then there is no need for the _load_nav() method as it just adds unnecessary abstraction.

//injection
protected function _load_nav( $nav ) {
    $this->_nav = $nav;
}

Another abstraction issue is with the $_nav property itself. Your current implementation creates an associative array container for the navigation array. This is redundant as well as unnecessarily abstract. The only reason to abstract the menu in this way is if you were abstracting submenus and injecting their contents into a main menu container. This is pretty similar to what you are currently doing with your _get_nav() method, though you have combined them all already.

protected function _load_nav( $header, array $nav ) {
    $this->_nav[ $header ] = $nav;
}

In your current implementation of your _render() method you are getting all of the function arguments into an array then, essentially, removing the first element after setting it to the TITLE_REGION. If you use array_shift() to physically remove that first element, then your array will no longer contain that element and you can loop over it more naturally. This also has the added benefit of removing these "magic" numbers from your code.

$title = array_shift( $args );
$this->template->write( self::TITLE_REGION, $title );

$n = count( $args );
for( $i = 0; $i < $n; $i++ ) {

There is no need to explicitly check the $active variable. If it is NULL, then it will not, or rather should not, be set in the $_nav array. Alternatively, if a variable is NULL then it is considered to be not set, so you can use isset() on both variables to simulate an AND comparison, though again, this is unnecessary in this context.

if( isset( $this->_nav[ 'nav' ] [ $active ] ) ) {
//Unnecessary Alternative
if( isset( $active, $this->_nav[ 'nav' ] [ $active ] ) ) {

You might want to think about saving your navigation to a separate file so that if you ever need to change it you wont have to change the code directly to do so. This follows the Separation of Concerns, which helps to make your code more extensible. Another benefit is that it will allow you to implement that abstract method in MY_Controller without losing functionality. One method would be to use JSON. There are many other methods you can use, but JSON is the one I'll show you. The method you choose is up to you.

//JSON file
{ "collection/view" : [
    {
        "href"  : "collection/view",
        "value" : "View collection",
        "class" : "icon-film"
    },
    //etc...
] }

//Importing the JSON
protected function _get_nav( $file ) {
    $json = file_get_contents( $file );
    return json_decode( $json, TRUE );
}

Your index() method is redundant with your view() method. Seeing as how they are both public, having them both is unnecessary. If one were public and the other private then one could be considered the public wrapper, but unless that wrapper was doing something else then it would still be considered redundant and better if you just changed the scope of the other method to public.

You should define your arrays before trying to append to them. Otherwise you could be editing a global. If you meant to edit said global, then you should know that globals are evil and you should never do such a thing. Defining the array before trying to use it, assuming you aren't using globals, ensures that you aren't accidentally manipulating another array defined earlier or accessing a string through the array syntax. The former may not be as noticeable, but the latter will have vastly different results. Another reason not to do this is to avoid PHP issuing warnings, which it should be doing. If you are not seeing these warnings then you should turn up your error reporting so that you can.

$data = array();
$data['list'] = $this->collection_model->get_list();

Instead of rendering your HTML with PHP, you might want to consider using the templating syntax and just rendering the PHP values you need into your HTML. This makes for cleaner, and thus easier read and edit, HTML. For example:

    <?php foreach( $nav AS $item ) : ?>

    <?php $class = isset( $item[ 'class' ] ) ? $item[ 'class' ] : ''; ?>
    <li class="<?php echo $class; ?>">
        <a href="<?php echo $item['href'];?>">

            <?php echo $item[ 'value' ]; ?>

    <?php endforeach; ?>


ReaderWriter Synchronization This code uses a ReaderWriterLockSlim to store data (on a disk or wherever), so that only one thread can write and many threads can read.

All writers should be finished before reading, and the write should not block the caller.

Basically my solution would work, but it doesn't look and feel natural to .NET since 4.0 the Task Parallel Library (TPL) was introduced...

class JsonApplicationContainerDAO : IApplicationContainerDAO
{

    private static volatile IApplicationContainerDAO instance;
    private static object syncRoot = new Object();

    private readonly BlockingCollection<ICollection<IApplicationConfiguration>> itemsToSave = new BlockingCollection<ICollection<IApplicationConfiguration>>();
    private readonly Thread writerThread ;
    private readonly ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();

    public static IApplicationContainerDAO Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new JsonApplicationContainerDAO();
                }
            }
            return instance;
        }
    }

    private JsonApplicationContainerDAO()
    {
        writerThread =  new Thread(WriteItems);
        writerThread.Start();
    }

    private void WriteItems(object obj)
    {
        ICollection<IApplicationConfiguration> item = null;
        while((item = itemsToSave.Take()) != null){
            try
            {
                readerWriterLock.EnterWriteLock();
                //do stream stuff here
            }
            finally
            {
                readerWriterLock.ExitWriteLock();
            }
        }
    }

    public ICollection<IApplicationConfiguration> LoadAll()
    {
        try
        {
            readerWriterLock.EnterReadLock();
            //do stream stuff here
        }
        finally
        {
            readerWriterLock.ExitReadLock();
        }

        return null;
    }

    public void Persist(ICollection<IApplicationConfiguration> items)
    {
        itemsToSave.Add(items);
    }
}

For this:

try
{
    readerWriterLock.EnterWriteLock();
    //do stream stuff here
}
finally
{
    readerWriterLock.ExitWriteLock();
}

EnterWriteLock should be before the try statement.

  Suppose the EnterWriteLock() fails. For whatever reason.
  Then the one thing you shouldn't do is to Exit a lock you never Entered.

Source: C# - Lock question using EnterWriteLock
Please note that singleton nowadays is rather an antipattern. They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with. What is so bad about singletons?


Node exports, architecture My project is written in node JS + Express and has the following architecture:

routes (e.g controllers)
models (stateless functional modules)
app

Models objects only doing SQL queries like this:

exports.setPassword = function (id, password, callback) {
  pg.connect(conString, function (err, client, done) {
    if (err) callback(err);
    else {
      client.query('UPDATE users SET password=$1 WHERE id=$2', [password, id], function (err) {
        done();
        if (err) callback(err);
        else callback(null);
      });
    }
  });
};

exports.setStatus = function (id, status, callback) {
  pg.connect(conString, function (err, client, done) {
    if (err) callback(err);
    else {
      client.query('UPDATE users SET status=$1 WHERE id=$2', [status, id], function (err) {
        done();
        if (err) callback(err);
        else callback(null);
      });
    }
  });
};

exports.getStayInTouch = function (userId, callback) {
  pg.connect(conString, function (err, client, done) {
    if (err) callback(err);
    else {
      client.query('SELECT * FROM stay_in_touch_contacts WHERE user_id=$1', [userId], function (err, results) {
        done();
        if (err) callback(err);
        else callback(null, results.rows[0]);
      });
    }
  });
};

and many many functions connected with the user in that user.js module.
The only thing I can do with that architecture is to place functions to the different module.

I'd appreciate any critiques of that architecture. How can I do better?

That does not look very DRY ( Dont repeat yourself ), not to mention that it does not look good that every function must be aware of the connection string.

For updates, you could do something like this:

exports.setPassword = function (id, password, callback) {
  genericUpdate('UPDATE users SET password=$1 WHERE id=$2', [password, id], callback );
};

exports.setStatus = function (id, status, callback) {
  genericUpdate('UPDATE users SET status=$1 WHERE id=$2', [status, id], callback );
};

function genericUpdate( queryString, parameters, callback )
{
  callback = callback || function(){};
  pg.connect(conString, function (err, client, done) {
    if (err){
      callback(err);
    } else {
      client.query(queryString, parameters, function (err) {
        done();
        callback(err || null);
      });
    }
  });
}

I added curly braces and newlines to your if statements, other than that your code seems fine.

EDIT: some thoughts on selects, you probably want a few generic selection functions, if you create one that is meant for selecting on an id, then you can get away with always returning the first data record if any.

exports.getStayInTouch = function (userId, callback) {
  selectById( 'SELECT * FROM stay_in_touch_contacts WHERE user_id=$1' , userId , callback );
};

function selectById( queryString, id, callback )
{
  callback = callback || function(){};
  pg.connect(conString, function (err, client, done) {
    if (err){
      callback(err);
    } else {
      client.query(queryString, id, function (err,results) {
        done();
        if(err)
          callback(err)
        else
          callback(null, results.rows[0] );
      });
    }
  });
}


Updating a .txt file I'm outputting the results of a query to file.txt in JSON. The file is updated every time I click on 'submit'(form) and depending on the variables it updates the query.

Right now the table only has about 20 records and will probably increase by 2/3 new records everyday.

Is there a better way to updating the file test.txt getting the results from a query?

index.cfm:

  <cfsavecontent variable="mytest">
    [
    <cfoutput query="getimeline">
    <cfif (getimeline.CurrentRow EQ getimeline.RecordCount)>
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"}
    <cfelse>
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"},
    </cfif>

    </cfoutput>
    ]
    </cfsavecontent>

    <cffile action="write" file="C:test.txt"  output="#mytest#">

test.txt:

[

{"title":"Advance pay Rollovers","date":"October 23, 2015"},

{"title":"New Card Ordering Process 1","date":"December 28, 2015"},

{"title":"about about","date":"February 5, 2016"}

]

I don't know sqat about coldfusion, but it seems you could eliminate some duplication:

<cfsavecontent variable="mytest">
    [
    <cfoutput query="getimeline">
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"}<cfif (getimeline.CurrentRow NEQ getimeline.RecordCount)>,</cfif>
    </cfoutput>
    ]
</cfsavecontent>

<cffile action="write" file="C:test.txt"  output="#mytest#">

If you don't mind that the comma will get placed on the next line,
then you can use this more readable writing style:

<cfsavecontent variable="mytest">
    [
    <cfoutput query="getimeline">
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"}
    <cfif (getimeline.CurrentRow NEQ getimeline.RecordCount)>,</cfif>
    </cfoutput>
    ]
</cfsavecontent>

<cffile action="write" file="C:test.txt"  output="#mytest#">


Unnecessary loop in database population I was looking over some code that I wrote years ago (that is still technically working, albeit on a very quiet production server) and I came across this segment of code.
if(isset($array2)){

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

        if((isset($value['coord'])||isset($value['bookedbefore']))&&!isset($value['bookedslot'])){
            echo("
Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot
");
            die();
        }
        $slotcode = $value['bookedslot'];
        !empty($value['bookedbefore']) ? $bookedbefore = 1 : $bookedbefore=0; // not required
        !empty($value['coord']) ? $coord = 1 : $coord=0; // not required

        $valuearray = array($UserID, $slotcode, $bookedbefore, $coord);
        //echo("
debug...
");var_dump($valuearray);
        try{
            $sql =
            ("

                INSERT INTO
                    bookedslot(`FK_UserID`, `FK_SlotCode`, `booked_before`, `coordinator_approv`)
                VALUES
                (
                    :UserID,
                    :slotcode,
                    :bookedbefore,
                    :coord
                );
            ON DUPLICATE KEY UPDATE
            FK_UserID = :UserID,
            FK_SlotCode = :slotcode,
            booked_before = :bookedbefore,
            coordinator_approv = :coord

            ");

            $sth = $dbh->prepare($sql);
            $sth->bindValue(':UserID', $valuearray[0]);
            $sth->bindValue(':slotcode', $valuearray[1]);
            $sth->bindValue(':bookedbefore', $valuearray[2]);
            $sth->bindValue(':coord', $valuearray[3]);

            $sth->execute();
            $sth->closeCursor();
        }

            catch(PDOException $e) {
                $message = (implode($valuearray));
                echo("
Something seems to have gone wrong with your choices.
");
            }

    }
    unset($array2);
}

I am usually loath to touch things that aren't broken, but that foreach loop looks completely unjustified in my mind, or at the very least, surely it is making a large number of unnecessary calls to the database? Was I having a brainfart years ago, or now?

First of all, I don't see any "unnecessary" calls here. Do you need to insert all these lines into the database? Then all there calls are necessary.
However, you can greatly optimize the process, thanks to
Two cornerstone rules for running multiple DML queries

prepare once execute multiple will gain you like 2-5% speed

(however, in order to get that small speed improvement from prepared statements, you have to disable the emulation mode. But in this case you'll be unable to reuse the placeholder name in the same query. Luckily, there is a values() keyword to the rescue)

wrapping all DML queries in a transaction can boost the speed up to 70 times (though depends on the software settings and hardware configuration) and is overall a sensible move. You either want all rows to be inserted or none.

Error reporting
Another issue to address is error reporting which is completely flawed and far from being any helpful in the real life (I have to admit, it's hard to master this skill as your code most of time works as intended) but, unlike what most people think, it's really simple to make it right.
The first thing you have to realize is that there are two kinds of errors that require absolutely different treatment:

userland errors are specific to the application logic and must be conveyed to the user
PHP errors are system errors and a user has no business with them. At the same time, They are vital for the programmer and must be preserved for the future inspection. Luckily, due to their nature, system errors essentially require the uniform treatment which means you can write the handling code once, store it elsewhere, and completely remove any system error handling from your code.

In order to separate these two kinds of errors, validate your data prior the data manipulation. First check if you have all the required data and only then run your inserts. This way you will be able to separate the user interaction errors from the system errors. Be aware that die() is considered a bad practice. It's better to collect all errors into a variable that have to be conveyed to the user in a more convenient fashion.
Regarding the system errors, just like it was said above, write a dedicated error handler once, that would log the error for the programmer and tell the user that something went wrong. I've got a complete working error handler example in my article dedicated to PHP error reporting, you can simply take this file and include it in your script.
Reduce the nesting level
As you may noticed, your code is hard to read because it is constantly shifting to the right side. Hence it's a good idea to remove unneceessary nesting, as most of time it's a sign of the problem code. For example, it makes sense to check outside variables with isset() but internal variables? It's always a good idea to be positively sure whether some variable exists or not. Hence always have your variables initialized before use. Have $array2 initialized at some point and you can drop that outermost condition. Other levels can be removed as well, such as unnecessary try-catch.
Things that indeed could be considered blunders from your beginners days that look rather amusing:

that $valuearray
the way empty() is used. In fact, to get 1 or 0 from a boolean value you can simply cast it as int

So what could we have after all these improvements?
First of all, separate the data validation from the query execution.
Validate all the data first,
$errors = [];
// perform all other validations
foreach($array2 as $value) {
    if ((isset($value['coord']) || isset($value['bookedbefore'])) && isset($value['bookedslot'])) {
        $errors[] = "Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot";
        break;
    }
}

and after that check for errors and if everything is OK then insert all your data, or show the form back to the user with values filled in and errors displayed
if (!$errors) {
    $sql = "INSERT INTO bookedslot(FK_UserID, FK_SlotCode, booked_before, coordinator_approv)
            VALUES (:UserID, :slotcode, :bookedbefore, :coord )
            ON DUPLICATE KEY UPDATE
                FK_UserID = values(FK_UserID),
                FK_SlotCode = values(FK_SlotCode),
                booked_before = values(booked_before),
                coordinator_approv = values(coordinator_approv)";
    $sth = $dbh->prepare($sql);

    $dbh->beginTransaction();
    foreach($array2 as $value) {
        $slotcode = $value['bookedslot'];
        $bookedbefore = (int)!empty($value['bookedbefore']); // not required
        $coord = (int)!empty($value['coord']); // not required

        $sth->bindValue(':UserID', $UserID);
        $sth->bindValue(':slotcode', $slotcode);
        $sth->bindValue(':bookedbefore', $bookedbefore);
        $sth->bindValue(':coord', $coord);
        $sth->execute();
    }
    $dbh->commit();
} else {
    // inform the user
}

What's going on here?
We are implementing all the things mentioned above. Just note that if your application is intended to die in case of a system error, there is no need to wrap your transaction in a try-catch block: it will be rolled back automatically by mysql as soon as the connection will be closed, and PHP always closes all its connections before die.
Just don't forget to configure PDO to throw exception and to disable the emulation mode. Here I've got an example PDO connection code that does all the necessary stuff.


Arcpy script to check for TIFF files and add them to different lists My script goes through sub folders in my main directory and based on a wildcard checks if a tiff file exists or not, if it exists then the file path is appended to the corresponding list. For example, all the tiff files with "*CRP.tif" wildcard, in all the sub folders, go into CRP_List = []. My current code is partially hard-coded, is there a way to make my code more generic? The individual lists i.e. the tiff path names are inputs to a raster mosaic tool which merges all the tiffs/rasters together..

import arcpy, os

#Raster Lists
CRP_List = []
FOR_List = []
INR_List = []
IR_List = []
MO_List = []
PAS_List = []
TCI_List = []
TCT_List = []
TG_List = []
WAT_List = []
WLF_List = []
WLO_List = []
WLT_List = []

arcpy.env.workspace = "D:/A__P6_FINAL_TIFFs"

for folder in arcpy.ListWorkspaces("*"):
    folder_basename = os.path.basename(folder)
    CoName = folder_basename.rsplit('_',1)[0]
    env.workspace = os.path.join("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL")

    for raster in arcpy.ListRasters("*_CRP.tif"):
        if arcpy.Exists(raster):
            CRP_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*FOR.tif"):
        if arcpy.Exists(raster):
            FOREST_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_INR.tif"):
        if arcpy.Exists(raster):
            INR_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_IR.tif"):
        if arcpy.Exists(raster):
            IR_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_MO.tif"):
        if arcpy.Exists(raster):
            MO_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_PAS.tif"):
        if arcpy.Exists(raster):
            PAS_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_TCI.tif"):
        if arcpy.Exists(raster):
            TCI_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_TCT.tif"):
        if arcpy.Exists(raster):
            TCT_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_TG.tif"):
        if arcpy.Exists(raster):
            TG_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WAT.tif"):
        if arcpy.Exists(raster):
            WAT_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WLF.tif"):
        if arcpy.Exists(raster):
            WLF_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WLO.tif"):
        if arcpy.Exists(raster):
            WLO_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WLT.tif"):
        if arcpy.Exists(raster):
            WLT_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

You want to learn what a dictionary is, and store your rasters in it. With Python this is pretty simple, to make a dictionary that when you ask for an apple gives you a 'red apple' you could do:

>>> my_dictionary = {'apple': 'red apple'}
>>> my_dictionary['apple']
'red apple'

From this you want to build this dictionary, to do this you can add a banana to the dictionary:

>>> my_dictionary['banana'] = 'for scale'
>>> my_dictionary['banana']
'for scale'
>>> my_dictionary
{'apple': 'red apple', 'banana': 'for scale'}

After this you want to merge all the for loops together. Using a dictionary like above, we can drastically reduce the amount of code.

rasters = {}
for name, file_ext in [('CRP', '_CRP'), ('FOR', 'FOR'), ...]:
    list = rasters[name] = []
    for raster in arcpy.ListRasters("*" + file_ext + ".tif"):
        if arcpy.Exists(raster):
            CRP_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

Since you also want this to work when you loop through arcpy.ListWorkspaces("*") you can use collections.defaultdict to allow you to remove the need to create a list for each file extension. This would change the above to:

rasters = defaultdict(list)
for name, file_ext in [('CRP', '_CRP'), ('FOR', 'FOR'), ...]:
    list = rasters[name]
    for raster in arcpy.ListRasters("*" + file_ext + ".tif"):
        if arcpy.Exists(raster):
            CRP_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

Going further, you can use arcpy.env.workspace or another constant variable rather than writing "D:/A__P6_FINAL_TIFFs/" three times, this as if you want to change it you would have to do it twice at the moment. I would use str.format to simplify the formatting, so when another person reads it it's not as hard to know what's happening. And finally I would normalize your variable names, pick either CoName or co_name, as it's hard knowing what your variable naming convention is. This can get you:

import arcpy
import os
from collections import defaultdict

WORKSPACE = "D:/A__P6_FINAL_TIFFs"
arcpy.env.workspace = WORKSPACE

rasters = defaultdict(list)
for folder in arcpy.ListWorkspaces("*"):
    co_name = os.path.basename(folder).rsplit('_', 1)[0]
    env.workspace = os.path.join("{}/{}_FINAL".format(WORKSPACE, co_name))

    for name, file_ext in [('CRP', '_CRP'), ('FOR', 'FOR'), ...]:
        list = rasters[name]
        for raster in arcpy.ListRasters("*{}.tif".format(file_ext)):
            if arcpy.Exists(raster):
                list.append("{}{}_Final/{}".format(WORKSPACE, co_name, raster)


Caesar Cipher in Python 3 I've implemented Caesar Cipher with two sample functions, Is my code readable I tried to make it understandable as I can , any comment is appreciated.
I am planning to do a Vigenère Cipher soon.

import string
def cipherencryprt (word , key ):
    word.lower()
    encryptedstring = ""
    for i in word :
        charvalue = ord(i) +key
        if ( charvalue > 122):
            charvalue = ord('a') + (charvalue -123)
            encryptedstring += chr(charvalue)

        else:
            encryptedstring += chr(charvalue)
    return encryptedstring

def cipherdecrypt(word , key ) :
    word.lower()
    decryptstring = ""
    for i in word :
        charvalue = ord(i ) - key
        if ( charvalue < 97 ):
            charvalue = ord('z') - (96-charvalue)
            decryptstring += chr(charvalue)
        else: decryptstring+= chr(charvalue)
    return decryptstring

if __name__ == "__main__" :
    print(cipherencryprt('omar', 4))
    print(decrypt(cipherencryprt('omar', 4),4))

Line spacing is important for readability. leave two spaces before your functions and don't have so many after. be sure to also be consistent about whitespace around operators.
word.lower() does not change the case of word but rather returns a string that is the lowercase equivalent of word.
The following can be simplified using the modulo operator

charvalue = ord(i) +key
if ( charvalue > 122):
    charvalue = ord('a') + (charvalue -123)
    encryptedstring += chr(charvalue)

else:
    encryptedstring += chr(charvalue)

becomes

charvalue = ((ord(i) - ord('a')) + key) % 26 + ord('a')

Your cipherencrypt() function does not currently support negative keys (see #2), but if it did, cipherdecrypt() could be written as:

def cipherdecrypt(word, key):
    return cipherencrypt(word, -key)

In python it is recomendend to do this kind of replacement with a comprehesnion:

def cipherencrypt(word, key):
    return "".join(
        chr(((ord(i) - ord('a')) + key) % 26 + ord('a'))
        for i in word.lower()
    )

Your cipher does not currently support space or any non latin character. If passed a non latin character, like space, your program will not be able to decrypt it. consider expanding your range to all printable characters or adding a special case for space.


Using reflection to connect to an arbitrary backend A little background first - I'm working on a server application that requires the ability to use multiple data access class libraries based on the resources available on the server it is installed on (MySQL, SQL Server, XML, etc.).  The are currently implemented as modular plugins, where the executable is paired with the appropriate class library on the server and interacts with it through a defined interface (IDataAccess).

The following code is the constructor for a singleton class on the server that exposes the backend:

private IDataAccess mDB;

private MudData()
{
    List<String> files = new List<String>(Directory.GetFiles(".", "*.dll"));
    List<Type> accessors = new List<Type>();

    foreach (String file in files)
    {
        try
        {
            Assembly test = Assembly.UnsafeLoadFrom(file);
            System.Type[] types = test.GetTypes();

            //See if any of the located types implement IDataAccess.
            foreach (System.Type candidate in types)
            {
                if (candidate.GetInterface("IDataAccess") != null)
                {
                    accessors.Add(candidate);
                }
            }
        }
        catch
        {
            //Eat this on purpose - still need to check the rest of the matches.
        }
    }

    if (accessors.Count == 0)
    {
        throw new ApplicationException("No supported data access .dll was found.");
    }

    //TODO: Select from multiples if found, but for now just take the first match.
    PropertyInfo target = accessors.First().GetProperty("Instance");
    MethodInfo getter = target.GetGetMethod();

    //Create a delegate for the reflected assembly so any exceptions propagate correctly.
    Func<IDataAccess> dataDelegate = (Func<IDataAccess>)Delegate.CreateDelegate(typeof(Func<IDataAccess>), null, getter);
    Object found = dataDelegate();
    if (found != null)
    {
        mDB = (IDataAccess)found;
    }
    else
    {
        throw new ApplicationException("Attempt to load an instance of IDataAccess failed.");
    }
}

Any exceptions at this point will be fatal, and are trapped and logged in the calling code before a (hopefully) graceful exit. This code is only called once at startup and the object it obtains isn't released until the application exits. I've been having a hard time finding information about the performance implications of using an object reference obtained this way, so I'd especially welcome comments from that direction. My assumption is that the main performance penalty is in obtaining the reference, but I haven't been able to find out whether or not that is true in practice.

I'm mainly looking for feedback on my method of connecting with the back-end, but am certainly open to comments/criticism of code style, practices, etc.

Thoughts?

You're loading every DLL in the directory even if you find what you want in the first one.

I'd guess that loading an assembly is what takes more time and resources than looking for what you want in the assembly-after-it's-loaded.

You code will fail if there's a type which implements IDataAccess but which doesn't have an Instance property.

You might want to load into a different AppDomain if you want to unload the assembly which you loaded.


Implementing a cross-browser event utility as an exercise I am currently learning JavaScript and created this cross-browser event utility as a learning exercise. It was not meant to be used in production code, and I just tried to cover only the cases that I'm aware of, so there might be a lot of edge cases that are not covered.

I'd be happy if you could check it and let me know how it looks and give me suggestions on how to improve it:

var helpers = {
    getOldEventName: function(eventName) {
        if (eventName.lastIndexOf('on', 0) !== 0) {
            return 'on' + eventName;
        }

        return eventName;
    },
    getModernEventName: function(eventName) {
        if (eventName.lastIndexOf('on', 0) !== -1) {
            return eventName.substring(2);
        }

        return eventName;
    },
    isCollection: function(variable) {
        return variable instanceof Array || variable instanceof HTMLCollection || variable instanceof NodeList;
    }
}

var myEvent = {
    addListener: function(element, eventName, callback) {
        var elements = element;
        if (!helpers.isCollection(element))
            elements = [element];
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].addEventListener) {
                elements[i].addEventListener(helpers.getModernEventName(eventName), callback, false);
            } else if (element.attachEvent) {
                elements[i].attachEvent(helpers.getOldEventName(eventName), callback);
            } else {
                elements[i][helpers.getOldEventName(eventName)] = callback;
            }
        }
    },
    removeListener: function(element, eventName, callback) {
        var elements = element;
        if (!helpers.isCollection(element))
            elements = [element];
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].removeEventListener) {
                elements[i].removeEventListener(helpers.getModernEventName(eventName), callback, false);
            } else if (elements[i].detachEvent) {
                elements[i].detachEvent(helpers.getOldEventName(eventName), callback);
            } else {
                elements[i][helpers.getOldEventName(eventName)] = null;
            }
        }
    },
    getEvent: function(event) {
        return event || window.event;
    },
    getTarget: function(event) {
        return (typeof event.target !== 'undefined') ? event.target : event.srcElement;
    },
    stopPropagation: function(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        } else if (typeof event.cancelBubble !== 'undefined') {
            event.cancelBubble = true;
        }
    },
    preventDefault: function(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else if (typeof event.returnValue !== 'undefined') {
            event.returnValue = false;
        }
    }
}

Usage examples:

function myCallback(e) {
    e = myEvent.getEvent(e);
    alert(myEvent.getTarget(e).href);
    myEvent.stopPropagation(e);
    myEvent.preventDefault(e);
}
myEvent.addListener(document.links, 'click', myCallback);

function dynamicDivHandler(e) {
    e = myEvent.getEvent(e);
    var keyCode = e.keyCode;
    var node = document.getElementById('dynamicDiv');

    switch (keyCode) {
        case 37:
            node.style.left = (parseInt(node.style.left) - 5) + 'px';
            break;
        case 38:
            node.style.top = (parseInt(node.style.top) - 5) + 'px';
            break;
        case 39:
            node.style.left = (parseInt(node.style.left) + 5) + 'px';
            break;
        case 40:
            node.style.top = (parseInt(node.style.top) + 5) + 'px';
            break;
    }
}
myEvent.addListener(document, 'keydown', dynamicDivHandler);

P.S.: This exercise is from the book "Object-Oriented JavaScript" by Stoyan Stefanov.

Your code looks ok. Nothing really jumps out at me except these two things:

Event handlers attached via attachEvent are executed in random order (Source: http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx). You might want to create a shim to get older versions of Internet Explorer to execute event handlers in the order they were attached, which is something I believe jQuery does (or did).
Create a function that patches the event object for cross browser compatibility, so your event handlers do not have to constantly call myEvent.getEvent(e). This will prevent repeated code in your handlers.

You could create separate functions to attach events in the three different ways, and use feature detection to determine which one to use:

var myEvent = {
    init: function() {
        if (document.addEventListener) {
            this.addListener = this.addListenerStandard;
            this.removeListener = this.removeListenerStandard;
        }
        else if (document.attachEvent) {
            this.addListener = this.addListenerMSIE;
            this.removeListener = this.removeListenerMSIE;
        }
        else {
            this.addListener = this.addListenerOldSkool;
            this.removeListener = this.removeListenerOldSkool;
        }
    },

    listen: function(elements, event, handler) {
        elements = !helpers.isCollection(elements) ? [elements] : elements;

        for (var i = 0; i < elements.length; i++) {
            this.addListener(elements[i], event, handler);
        }
    },

    stopListening: function(elements, event, handler) {
        elements = !helpers.isCollection(elements) ? [elements] : elements;

        for (var i = 0; i < elements.length; i++) {
            this.removeListener(elements[i], event, handler);
        }
    },

    addListenerStandard: function(element, event, handler) {
        element.addEventListener(event, handler, false);
    },

    addListenerMSIE: function(element, event, handler) {
        element.attachEvent("on" + event, handler);
    },

    addListenerOldSkool: function(element, event, handler) {
        element["on" + event] = handler;
    },

    removeListenerStandard: function(...) { ... },

    removeListenerMSIE: function (...) { ... },

    addListenerOldSkool: function(...) { ... },

    addListener: null,

    removeListener: null
};

myEvent.init();

That way you won't be detecting the proper DOM method on each iteration of your loop.


The right way to get formatted node's body field in Drupal 7 I am wondering am I doing the right "Drupal" way in getting formatted value of node's body field. Here is my code:

$field = field_get_items('node', $node, 'body');
$body = '';
if (isset($field[0]['value'])) {
  $body = check_markup($field[0]['value'], $field[0]['format']);
}

The API has the field_view_value() function which essentially does the same thing as your code, except it applies all of the field/instance settings to the value so you won't need to make changes to your code if you change a field setting.

You can use it like this:

$field = field_get_items('node', $node, 'body');

$body = '';
if (isset($field[0]['value'])) {
  $body = field_view_value('node', $node, 'body', $field[0]);
}

Just in case you want the default HTML wrappers included with the field output, you can use field_view_field() instead.


Counting number of 1's and 0's from integer with bitwise operation Is there a better way of doing this?

// Definition: Count number of 1's and 0's from integer with bitwise operation
//
// 2^32 = 4,294,967,296
// unsigned int 32 bit

#include<stdio.h>

int CountOnesFromInteger(unsigned int);

int main()
{
    unsigned int inputValue;
    short unsigned int onesOfValue;
    printf("Please Enter value (between 0 to 4,294,967,295) : ");
    scanf("%u",&inputValue);
    onesOfValue = CountOnesFromInteger(inputValue);

    printf("\nThe Number has \"%d\" 1's and \"%d\" 0's",onesOfValue,32-onesOfValue);
}

int CountOnesFromInteger(unsigned int value)
{
    unsigned short int i, count = 0;
    for(i = 0; i < 32 ; i++)
    {
        if (value % 2 != 0)
        {
            count++;
        }
        value = value >> 1;
    }
    return count;
}

Yes, there is a better way:

int CountOnesFromInteger(unsigned int value) {
    int count;
    for (count = 0; value != 0; count++, value &= value-1);
    return count;
}

The code relies on the fact that the expression x &= x-1; removes the rightmost bit from x that is set. We keep doing so until no more 1's are removed. This technique is described in K&R.

This approach is superior because it doesn't depend on an integer's size - it's totally portable - and it tests every bit in a fairly efficient way (with the comparison value != 0).

Also, you might want to replace 32 in main() with sizeof(int)*CHAR_BIT so that your code doesn't depend on an integer using 32 bits:

#include <stdio.h>
#include <limits.h>

int CountOnesFromInteger(unsigned int);

int main()
{
    unsigned int inputValue;
    short unsigned int onesOfValue;
    printf("Please Enter value (between 0 to 4,294,967,295) : ");
    scanf("%u",&inputValue);
    onesOfValue = CountOnesFromInteger(inputValue);

    printf("\nThe Number has \"%d\" 1's and \"%zu\" 0's",onesOfValue,sizeof(int)*CHAR_BIT-onesOfValue);
    return 0;
}


The way to realise data access There are a several articles about true data access in MVC. I tried to make the best one according to the architecture flexibility. My way is following:

ADO .NET Entity Data Model (*.edmx from Entity Framework) with default code generation.
Common repository interface

 public interface IGenericRepository<T> where T : class
 {
     T Get(int id);
     void Create(T entityToCreate);
     void Edit(T entityToEdit);
     void Delete(T entityToDelete);
 }

Interface (with particular methods of the current class), class with real implementation of methods. For example

public interface ITestingRepository: IGenericRepository<Testing>
{
    List<dynamic> GetTestingUser(int id);
    List<dynamic> GetNotTestingUser(int idTesting, Guid idCompany);
    List<Testing> List(Guid CompanyId);
}

public class TestingRepository : ITestingRepository
{
   private TestEverybody _entities = new TestEverybody();

   public List<Testing> List(Guid CompanyId)
   {
       return _entities.Testing.Where(t => t.idCompany == CompanyId).ToList();
   }
   public void Edit(Testing productToEdit)
   {
       var originalProduct = Get(productToEdit.id);
       _entities.ApplyCurrentValues(originalProduct.EntityKey.EntitySetName, productToEdit);
       _entities.SaveChanges();
   }
   public void Create(Testing productToCreate)
   {
       _entities.Testing.AddObject(productToCreate);
       _entities.SaveChanges();
   }
   //other methods
}

The following data access method in the controller

 public class TestingController : Controller
 {
   //
   // GET: /Testing/
   private ITestingRepository _repository;
   public TestingController() : this(new TestingRepository()) { }

   public TestingController(ITestingRepository repository)
   {
      _repository = repository;
   }
   [HttpPost]
   public ActionResult Create(Testing newobject)
   {
       _repository.Create(newobject);
       return RedirectToAction("Index");
   }
   [HttpPost]
   public ActionResult Edit(Testing item)
   {
      _repository.Edit(item);
      return RedirectToAction("Index");
   }
 }

Is it a good one? Have I any mistakes there?

Your code seems really good, I would change the ITestingRepository methods to return IEnumerable<> instead of List<>.

Also, I suggest you would add a method signature to your generic repository interface that would let you query your DbContext.

public interface IGenericRepository<T> where T : class
{
    T Get(int id);
    void Create(T entityToCreate);
    void Edit(T entityToEdit);
    void Delete(T entityToDelete);
    IEnumerable<T> Get(Expression<Func<T,bool>> whereClause)
}

Then you can use it this way

//Class example, I don't know what Testing class is
public class Testing
{
    public string PropertyOne { get; set;}
    public string PropertyTwo { get; set;}
}

public class TestingRepository
{
    //Method implementation
    public IEnumerable<Testing> Get(Expression<Func<Testing,bool>> whereClause)
    {
        IQueryable<Testing> result = _entities.Testing;

        if(whereClause != null)
            return result.Where(whereClause);

        return result.ToList();
    }
}

public static void AMethod() //Just to show an example at work!
{
    List<Testing> testings = new TestingRepository().Get(x => x.PropertyOne == "Hello" && x.PropertyTwo == "World").ToList();
}

Finally, you might want to implement a generic repository class that implements your interface (a public class GenericRepository<T> : IGenericRepository<T>, I won't write it down for you but you could check this http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in


Multiple column sorting and arraging algorithm Problem

The goal is to perform the following transformation:

Additionally, if two rows can be merged, they are combined into one:

Code

I wrote the following algorithm to solve this problem:

#include <vector>
#include <iostream>
#include <algorithm>

using Matrix = std::vector<std::vector<int>>;
using Column = std::vector<int>;

Column max_col(const Matrix &v) {
    return *std::max_element(v.begin(), v.end(),
                             [](auto& lhs, auto& rhs)
                             {
                                 return lhs.size() < rhs.size();
                             });
}

bool is_element_in_next_rows(const Matrix &v, int element,int row) {
    for (auto& col : v) {
        if (row >= static_cast<int>(col.size())) continue; // out of range
        if (std::lower_bound(col.begin()+row+1,col.end(),element) !=
            std::upper_bound(col.begin()+row+1,col.end(),element)) {
            return true;
        }
    }
    return false;
}

int min_element_in_row(const Matrix &v, int row) {
    int min_element = max_col(v)[row];
    for (auto& col : v) {
        if (row >= static_cast<int>(col.size())) continue; // out of range
        if (col[row] != 0) min_element = std::min(min_element, col[row]);
    }
    return min_element;
}

void print_elements(const Matrix &v) {
    for (auto& i : v) {
        for (auto& j : i) {
            std::cout << j << " ";
        }
        std::cout << std::endl;
    }
}

void organize_elements(Matrix &v) {
    for (auto& col : v) {
        std::sort(col.begin(),col.end());
    }
    auto current_max_col = max_col(v);
    for (int row{0}; current_max_col.begin()+row!=current_max_col.end(); ++row) {
        int min_element = min_element_in_row(v,row);
        for(auto& col : v) {
            if (row >= static_cast<int>(col.size())) continue; // out of range
            int candidate = col[row];
            if (candidate > min_element) {
                if (is_element_in_next_rows(v,candidate,row)) {
                    col.push_back(0);
                    std::rotate(col.begin()+row,col.end()-1,col.end());
                }
            }
        }
        current_max_col = max_col(v);
    }
}

int main() {

    Column c1 = {5,6,8,11};
    Column c2 = {2,5,3,1,4,6};
    Column c3 = {8,7,2,4,5,3,1};

    Matrix v;
    v.push_back(c1);
    v.push_back(c2);
    v.push_back(c3);

    std::cout << "original: \n";
    print_elements(v);
    organize_elements(v);
    std::cout << "organized: \n";
    print_elements(v);
    return 0;
}

Which produces the following output:

original:
5 6 8 11
2 5 3 1 4 6
8 7 2 4 5 3 1
organized:
0 0 0 0 5 6 8 11
1 2 3 4 5 6
1 2 3 4 5 7 8

Questions

I particularly don't like this part of my code:

auto current_max_col = max_col(v);
for (int row{0}; current_max_col.begin()+row!=current_max_col.end(); ++row) {
    // ....
    current_max_col = max_col(v);
}

I also don't like that I have to do this cast:

if (row >= static_cast<int>(col.size())) continue; // out of range

Is there a way to do this check better?

The fact that I need to declare current_max_col out of the for, and then update it inside the loop. Any idea how to avoid this?

Any other ideas about how to solve this problem? Any other tips? Thank you!

It seems that the transform you are after is a k-way merge in disguise.

In the nutshell, set up a min-heap of pairs <col_id, vector<int>::iterator>. On each iteration construct a vector of values equal to heap head, 0 otherwise; push it to the resulting matrix; remove those entries from heap an pull new values from the respective columns. Sorry if I miss something obvious.

I don't think you shall strive for in-place transform.

I am pretty sure that merging rows deserve a separate pass.

The

                col.push_back(0);
                std::rotate(col.begin()+row,col.end()-1,col.end());

is no better than col.insert(col.begin() + row, 0);

The static_cast<int>(col.size()) suggests that row should not be int, but along the lines of std::vector<int>::size_type.


Parallel scheduler for running actions at designated times I've been trying to learn Haskell on and off for a couple years. I had a project for building a parallel web scraper, and I figured I'd try to use Haskell for it. Here's the part used to schedule tasks: basically, it opens a Chan that can be used to send jobs, which is simply an IO action with the time when it should be run. I'd be thankful for any (constructive) remarks.

Here's the main Scheduler module:

{-|
Module      : Scheduler
Description : Run IO actions at a designated time, in parallel
-}
module Scheduler (startScheduler, InputJobChan, Job(..)) where

import System.Timeout (timeout)
import Control.Concurrent.Chan (Chan, newChan, readChan)
import Control.Concurrent (forkIO)
import Data.Time.Clock.POSIX (getPOSIXTime, POSIXTime)
import qualified Data.PQueue.Min as PQ

-- |Main job type used to describe jobs that are sent to the scheduler.
data Job = Job { action :: InputJobChan -> IO(), time :: POSIXTime }
instance Eq Job where
  (==) j1 j2 = time j1 == time j2
instance Ord Job where
  (<=) j1 j2 = time j1 <= time j2
-- |Queue type used to send jobs to the scheduler
type InputJobChan = Chan [Job]
-- |Internal priority queue used to find the next job to run
type JobPQueue = PQ.MinQueue Job

-- |Start the scheduler and return an input queue used to send jobs
startScheduler :: IO InputJobChan
startScheduler = do
  chan <- newChan
  _ <- forkIO $ processJobs_ chan PQ.empty
  return chan

-- |Internal function doing most of the work
processJobs_ :: InputJobChan -> JobPQueue -> IO()
processJobs_ chan jobs
  -- If we don't have any jobs in queue, wait until we get some
  | PQ.null jobs = do
    returnedJobs <- readChan chan
    print "Got new jobs!"
    processJobs_ chan (PQ.fromList returnedJobs)
  -- otherwise wait until it's time to run the first job
  | otherwise = do
      let (job, others) = PQ.deleteFindMin jobs
      print $ "current: " ++ show (time job) ++ " (" ++ show (PQ.size others) ++ " others in queue)"
      now <- getPOSIXTime
      -- delay in microseconds
      let microsecondTimeout = round $ 1000000 * (time job - now)
      print $ "preparing to wait " ++ show microsecondTimeout ++ " for new messages on the queue..."
      readResult <- timeoutReadChan chan microsecondTimeout
      case readResult of
        Nothing -> do
          print "no new jobs, running current job action..."
          action job chan
          processJobs_ chan others
        Just returnedJobs -> do
          print "Enqueuing new jobs ..."
          let newJobs = PQ.union jobs (PQ.fromList returnedJobs)
          processJobs_ chan newJobs

-- |Listen to a chan at most t microseconds, return Nothing if nothing was read
timeoutReadChan :: Chan a -> Int -> IO (Maybe a)
timeoutReadChan chan t
  | t <= 0    = return Nothing
  | otherwise = timeout t (readChan chan)

And here is some simple test code:

import Scheduler
import System.Random.MWC (createSystemRandom)
import System.Random.MWC.Distributions (exponential)
import Control.Monad
import Data.Time.Clock.POSIX
import Control.Concurrent.Chan (writeChan)
import Control.Concurrent (threadDelay)

-- |Create jobs at random, simulating a poisson process
createRandomJobs :: InputJobChan -> IO ()
createRandomJobs chan = do
  gen <- createSystemRandom
  forM_ [1..15::Int] $ \n -> do
    delay <- exponential 1 gen
    now <- getPOSIXTime
    let job = Job { action = \_ -> putStrLn $ "hello " ++ show n, time = now + 1 }
    writeChan chan [job]
    threadDelay $ round $ 1000000 * delay

main :: IO ()
main = do
  chan <- startScheduler
  createRandomJobs chan

processJobs_ logic

You want to make sure that microsecondTimeout is never negative, since according to the documentation a negative timeout means to wait indefinitely.

To guard against negative timeouts, I would write processJobs_ to have the following logic:

loop:
  if queue is empty:
    call readChan for a new job and add to queue
    goto loop
  else:
    now <- getPosixTime
    if queue minimum <= now:
      fire off all jobs in the queue with a time <= now
      goto loop
    else:
      readResult <- timeoutReadChan ...
      put new job onto the queue
      goto loop

priority queues

You might be interested in this SO question and answers discussing the merits of the various Haskell priority queue packages:

https://stackoverflow.com/questions/6976559/comparison-of-priority-queue-implementations-in-haskell


Python 2.7 Tower of Hanoi game with ASCII graphics The game generates a fixed, "animated" game board via ASCII characters that is reprinted and cleared after each valid move. The format of the input for making moves is described in the script. You select the "difficulty" via a commandline parameter, so the game requires you enter a number (>=3) for the disc count after the filename.

I'm new to classes, so I wasn't sure how to retrieve the latest "top occupied position" on a rod following each addition/removal of a piece besides what I have here and maybe one other way. I'm guessing that I could have had a default self.topindex and self.top for a rod, and then updated this upon each call of the methods add() and remove().

import os
import sys
level = int(sys.argv[1])

class rod:
    def __init__(self,n):
        self.n=n
        if n==1: self.state= list(range(1,level+1))
        else: self.state=[0]*level
    def pos(self, height): #This generates one chunk of the rod and any pieces at that height
        width=self.state[height-1]
        return " "*(level+1-width)+"-"*width+"|"+"-"*width+" "*(level+1-width)
    def topindex(self): #This is meant to return the index of the top occupied position on the rod
        for index,i in enumerate(self.state):
            if i!=0: return index
            elif index==level-1: return index #But if there are no occupied positions (empty rod) it should return the bottom
    def top(self):
        return self.state[self.topindex()]
    def add(self, piece):
        if self.top()==0: self.state[level-1]=piece
        else: self.state[self.topindex()-1]=piece
    def remove(self):
        self.state[self.topindex()]=0

rod1=rod(1) #This seems like a waste of lines
rod2=rod(2)
rod3=rod(3)

gamestate=["Welcome to the game. ", "first"]

def printgame():
    print gamestate[0]+"The objective is to move all the pieces from rod 1 to another rod."
    print "Pieces must be placed in ascending order of size from top to bottom."
    print 'Move pieces by typing "n m" (where n and m denote the numbers of the source and destination rods) when requested.'
    print ""
    for i in range(1,level+1):
        print rod1.pos(i)[1:]+rod2.pos(i)+rod3.pos(i)
    spacing=(level-3)*" " #Add each block of each rod at the same height to one line, then print the line
    print spacing+" Rod 1    "+2*spacing+"Rod 2    "+2*spacing+"Rod 3\n"

def hasdigit(string):
    return any(char.isdigit() for char in string)

os.system("clear")

def movepiece():
    global rod1 #Too many globals here
    global rod2
    global rod3
    global gamestate
    move=raw_input("Which piece will you move {}? ".format(gamestate[1]))
    if " " in move and hasdigit(move.split(" ")[0]) and hasdigit(move.split(" ")[1]):
        gamestate[0]=""
        gamestate[1]="next"
        source=move.split(" ")[0]
        destination=int(move.split(" ")[1])
        piece=eval("rod"+str(source)+".top()")
        if (piece<eval("rod"+str(destination)+".top()") or eval("rod"+str(destination)+".top()")==0) and piece!=0:
            eval("rod"+str(source)+".remove()")
            eval("rod"+str(destination)+".add("+str(piece)+")")
        elif piece==0:
            print "There's nothing to move from rod {}!\n".format(source)
            movepiece()
        else:
            print "You can't move that there!\n"
            movepiece()
    elif move=="exit": gamestate=move
    else:
        print "Please use the specified format: n m (where n and m denote the numbers of the source and destination rods).\n"
        movepiece()

steps = 0
while rod2.state!=list(range(1,level+1)) and rod3.state!=list(range(1,level+1)):
    if gamestate=="exit": break
    printgame()
    movepiece()
    steps+=1
    os.system("clear")

if gamestate!="exit":
    printgame()
    print "Congratulations, you've finished the game in {} steps.".format(steps)

Hi thanks for sharing your code,

You should stick to Python naming conventions, check out the PEP8 style guide.

https://www.python.org/dev/peps/pep-0008/

Based off of this, your rod class should be class Rod: and movepiece should be move_piece

For your global variables, you could fix this by having a Game or Hanoi class.

class Hanoi:

    def __init__(self, rod1, rod2, rod3):
        self.rod1 = rod1
        self.rod2 = rod2
        self.rod3 = rod3
        ...

Watch out for using eval. There are lots of reasons not to use eval, but the one I want to talk about is that here you're relying on the user to know variable names. Variable names should never matter. But here if you were to change a variable name, your program would not function as intended.

If the goal is to call a method on a Rod object based on user input, just do a standard if/elif block

if source == 1:
    piece = self.rod1.top()
elif some_condition:
    ...

If you're using eval to call methods like this, just call the methods instead.

list(range(1,level+1)) if you look at the documentation for the range function, it already returns a list, you can just use range(1,level+1)

There seem to be some unnecessary offsets throughout your code, why use range(1, level + 1) and not just range(level) you can just take the user input value and subtract 1 from it in one place, in Python counting starts from 0 :)

def __init__(self,n): n is a very poor name for a variable, use something like num or number instead, anything to improve readability goes a long way.

in your movepiece() function, you call movepiece again inside, I don't think there's any real benefit to using recursion here, I think it would be simpler to understand a simple loop instead, and it would also be simpler to reason about and leave less room for error.

while !game_over:
    # game loop

This way you don't need to worry about maximum recursion depth exceeded either, not that that would really be a problem here anyway.

This while loop rod2.state!=list(range(1,level+1)) and rod3.state!=list(range(1,level+1) could be a lot simpler.

Try breaking it down into multiple well named boolean values instead.

meaningful_name_for_this = rod2.state!=list(range(1,level+1))
meaningful_name_for_that = rod3.state!=list(range(1,level+1)
while meaningful_name_for_this and meaningful_name_for_that:
    # do your loop code

Make your code as self documenting as possible.

destination=int(move.split(" ")[1])

Avoid magic numbers where possible, whenever you need specific values like this, make them a well named constant instead.

destination=int(move.split(" ")[DESTINATION_INDEX])

especially if you reuse them throughout your code base.

Hopefully some of this was useful to you!

Edit:

Here's an example of what your move_piece method could look like
Here it's a method of some Hanoi or Game object.

def move_piece(self):
    move = INVALID_VALUE  # some constant
    while not self._is_move_valid(move):  # method that checks if a move is okay or not
        move = self._prompt_for_move() # reads user input

    # if we're here, we know that the move is definitely valid
    self._perform_movement(move)  # does the work on the Rod objects

I've made up some methods here, in your code you have the logic to do these actions, so I'll let you fill in those!

Notice now how short this method is, the shorter the method the better, even though it's made up of many calls to other methods, by giving them all good clear names, you should be able to see what the method is doing without looking at the bodies of these other methods.


Project Euler problem #1 solution in C Any suggestions or comments? Is my style any good?

Initially I struggled with this problem as I found that using the "+=" operator gave the wrong results. I also tried a while loop the first time which was a baaaad idea. But what actually worked was using a static accumulator variable.

#include <stdio.h>

static unsigned long total;

int main(void)
{

  total = 0;

  for(unsigned int i = 1; i < 334; i++){

     total  = total + (3*i);

  }

  for(unsigned int j = 1; j < 1000; j++){

    if(j%5==0 && j%3!=0){

      total  = total + j;

    }else{

      total = total + 0;

    }

  }

  printf("Project Euler problem 1 solution = ");
  printf("%lu \n", total);

  return 0;
}

Ref: Euler 1: Multiples of 3 and 5

Your code is very hard to read since there is so much empty space. Even if we don't remove all of them, the following variant is a lot easier to read:

#include <stdio.h>

static unsigned long total;

int main(void)
{
  total = 0;

  for(unsigned int i = 1; i < 334; i++){
     total  = total + (3*i);
  }

  for(unsigned int j = 1; j < 1000; j++){

    if(j%5==0 && j%3!=0){
      total  = total + j;
    }else{
      total = total + 0;
    }
  }

  printf("Project Euler problem 1 solution = ");
  printf("%lu \n", total);

  return 0;
}

It fits even into the code example without any scrollbars.

There is no need to make total global. It should be a local variable.

Your first for loop uses an optimization, your second doesn't. That's asymmetrical. Use the same trick for both loops.

total = total + 0 doesn't change total at all. The compiler will most likely throw that line away, but better don't include it.

The following for loop is easier to understand:

for(unsigned int i = 0; i < 1000; i += 3) {
    total += i;
}

Concerning your comments on +=, did you accidentally use total += total + j? This will give wrong results. Otherwise I cannot reproduce your behaviour.

If you printf a unsigned int, you must use %u, not %lu, since the latter is meant for unsigned long int. Your compiler will warn you mismatching specifiers if you enable warnings.

If you apply those comments above, you end up with

#include <stdio.h>

int main(void)
{
  unsigned int total = 0;

  for(unsigned int i = 0; i < 1000; i += 3){
     total += i;
  }

  for(unsigned int i = 0; i < 1000; i += 5){
    if(i % 3 != 0){
      total += i;
    }
  }

  printf("Project Euler problem 1 solution = %u \n", total);

  return 0;
}


Ruby Mod 11 implementation I wrote this Ruby Mod 11 (perhaps it's a bit generous to call it that) implementation to validate Brazilian CPF documents, which use a Mod 11 algorithm. CPF format is a 9 digit number followed by two checksums. It's often presented in this format 012.345.678-90. Feedback is welcome.

class CPF
  attr_reader :digits

  LENGTH = 11

  def self.valid?(number)
    new(number).valid?
  end

  def self.mask(number)
    new(number).mask
  end

  def initialize(number)
    @digits = number.to_s.gsub(/\D/, '').each_char.map(&:to_i)
  end

  def valid?
    correct_length? && !black_listed? && checksums_match?
  end

  # The `black_listed?` method checks common number patterns.
  #
  # It tests to see if the provided CPF is the same digit repeated n times.
  #
  def black_listed?
    digits.join =~ /^12345678909|(\d)\1{10}$/
  end

  # A valid CPF must be 11 digits long.
  #
  def correct_length?
    digits.size == LENGTH
  end

  # A CPF is only valid if the first and second checksum digits are what they should be.
  #
  def checksums_match?
     first_checksum_matches? && second_checksum_matches?
  end

  # This returns the CPF is a human readable format.
  #
  #     CPF.mask("01234567890")
  #     => "012.345.678-90"
  #
  def mask
    [digits.first(9).each_slice(3).map(&:join).join("."), digits.last(2).join].join('-') if valid?
  end

private

  def first_checksum_matches?
    checksum_one == digits.at(9)
  end

  def second_checksum_matches?
    checksum_two == digits.at(10)
  end

  def checksum_one
    digit = sum_at(10)
    digit = calculate(digit)
    digit = 0 if digit > 9
    digit
  end

  def checksum_two
    digit = sum_at(11) + (2 * checksum_one)
    digit = calculate(digit)
    digit = 0 if digit > 9
    digit
  end

  def sum_at(position)
    digits.slice(0..8).collect.with_index { |n, i| n * (position - i) }.reduce(:+)
  end

  def calculate(digit)
    LENGTH - (digit % LENGTH)
  end
end

Tests

require 'test_helper'

class CpfTest < ActiveSupport::TestCase
  test 'black listed numbers are not' do
    black_list = %w(00000000000 11111111111 22222222222 33333333333 44444444444
                    55555555555 66666666666 77777777777 88888888888 99999999999)
    black_list.each do |number|
      assert_invalid number
    end
  end

  test 'nil is not a valid CPF' do
    assert_invalid nil
  end

  test 'blank is not a valid CPF' do
    assert_invalid ''
  end

  test 'valid CPF' do
    assert_valid '01234567890'
  end

  test 'masked valid CPF' do
    assert_valid '012.345.678-90'
  end

  test 'mask returns a masked CPF when CPF is valid' do
    assert_equal '012.345.678-90', CPF.mask('01234567890')
  end

  test 'mask returns nil when CPF is not valid' do
    assert_nil CPF.mask('0123456789')
  end

private

  def assert_invalid(number)
    refute CPF.valid?(number), "Expected #{number || 'nil'} to be an invalid CPF"
  end

  def assert_valid(number)
    assert CPF.valid?(number), "Expected #{number} to be a valid CPF"
  end
end

Your code looks pretty good, but there is a no-no:

def checksum_one
  digit = sum_at(10)
  digit = calculate(digit)
  digit = 0 if digit > 9
  digit
end

Note thatdigit my have up to three different values in just four lines of code. This makes the code harder to follow. As a rule of thumb, use different variable names. That's how I'd write it:

def checksum_one
  digit = calculate(sum_at(10))
  digit > 9 ? 0 : digit
end


Code to modify DOM element using DOM.style property So, I've a code that is below which works just fine:

<html>
  <head>
    <title> Javascript Practice </title>
  </head>
  <body>
    <div id="myDiv">
    </div>
    <script>
      var a = 0;
      var b = 255;
      var c = 0;
      var color2 = 'RGB(' + a + ',' + b + ',' + c + ')';

      document.getElementById("myDiv").style.backgroundColor = color2;
      document.getElementById("myDiv").style.width = 50;
      document.getElementById("myDiv").style.height = 300;
    </script>
  </body>
</html>

I've got a lot of feedback saying that when accessing DOM style property, I need to set value as strings such as setting DOM.style.width not to a number like I've done here but appending w + "px"

I'm puzzled because I'm using Brackets as a code editor and deploying this on chrome. My code runs just fine and every time I load the HTML page, it initializes a div of the required dimensions. Everyone tells me it won't work which is what's confusing me.

TIA.

Inline style lengths require units. In quirks mode, browsers will assume pixels as the unit, if provided with an integer instead of a length. If you are not sure how the browser will handle the value, specify the units.

  The CSS parser interprets unitless numbers as px (except for line-height and any other properties where they have distinct meaning, and except in shorthands).

Bonus: Here is an extensible version of your script.

const state = {
  color : { r : 0, g : 255, b : 0 },
  dimensions : { width : 50, height : 300 }
}

const applyState = (el, state) => {
  Object.assign(el.style, {
    backgroundColor: `rgb(${state.color.r}, ${state.color.g}, ${state.color.b})`,
    width: `${state.dimensions.width}px`,
    height: `${state.dimensions.height}px`
  })
}

applyState(document.getElementById('my-div'), state)


Formatting data for use in a controller I am using the function inputSetup to prepare an array for a multi-select directive. I am passing in an array with the existing selections ($scope.item.categories), an array with all the available categories, and a string the carries the context of the values "category".

Formatting the array to add the value "ticked" = true; on each object, so that the multi-select understand which options are selected.
Concatenating the arrays.
Sorting the arrays.
Using a for loop to iterate through the array and removing any duplicates that have the same "category" key... then removing the one that has "ticked" = false.

This code feels like it can be improved.

Should the .concat and .sort be chained together?
Should the for loop be replaced with an array.filter()?

$scope.categories = inputCategories($scope.item.categories, $scope.settings.categories, "category");

function inputSet (input, settings, category) {
  var updatedSettings = [];

  angular.forEach(input, function(obj) {
    var setting = { "ticked": true };
    setting[category] = obj;
    updatedSettings.push(setting);
  });

  var list = updatedSettings.concat(settings);

  list.sort(function(a, b) {
    return (a[category] > b[category]) - (a[category] < b[category]);
  });

  for ( var i = 1; i < list.length; i++ ){
    if(list[i-1][category] == list[i][category]) {
      list.splice(i,1);
    }
  }
  return list;
};

Here's my take on your code. Longer, but in my opinion, easier to follow since it is written as a chain of operations on arrays.

In addition, I use array methods, which easily chain together. Their callbacks are moved out for clarity. They're also written in a way that a function doesn't use outside variables. Makes your code more predictable and easily modifiable without dragging along other stuff.

// The first phase of your code is just mapping obj into another form. Use map().
function inputMapper(obj) {
  var setting = {};
  // Using the bracket notation to keep it uniform.
  setting['ticked'] = true;
  setting[category] = obj;
  return setting;
}

// Removing items first will make further operations iterate less.
// Additionally, we use reduce to carry around the data, and the already-found categories
function duplicateCategoryRemover(carry, item) {
  if (!~carry.categoriesFound.indexOf(item.category)) {
    carry.items.push(item);
    carry.categoriesFound.push(item.category);
  }
  return carry;
}

// Nothing special, just your sorter moved out.
function categorySorter(a, b) {
  return (a[category] > b[category]) - (a[category] < b[category]);
}

// Now everything's in place, let's do the magic.
function inputSet(input, settings, category) {
  return input.map(inputMapper)
              .concat(settings)
              .reduce(duplicateCategoryRemover, { items: [], categoriesFound: [] })
              .items
              .sort(categorySorter);
};


Calculate sum of an attribute across multiple repositories I have multiple repositories that contain userId, paidDate and amount attributes like Bills(userId, paidDate, amount) Shoppings(userId, paidDate, amount) etc. I want to get sum of amounts and group them by userId and get something like this {user1: {amount1, amount2, amount3 ..}, user2: {amount4, ..}}

I created a expenseDetails model that contains all of repositories above.

public class ExpenseDetails
{
    public IEnumerable<ApplicationUser> ApplicationUsers { get; set; }
    public IEnumerable<Bill> Bills { get; set; }
    public IEnumerable<Shopping> Shoppings { get; set; }
    public IEnumerable<Rent> Rents { get; set; }
}

And I created a helper method for calculate the sum of amounts with looping every model in expenseDetails.

public static Dictionary<string, List<double>> UsersExpense(ExpenseDetails expenseDetails)
    {
        Dictionary<string, List<double>> TotalCosts = new Dictionary<string, List<double>>();
        List<double> Total = new List<double>();
        double sum = 0;

        foreach (var user in expenseDetails.ApplicationUsers)
        {
            foreach (var item in expenseDetails.Shoppings)
            {
                if (item.ApplicationUserId == user.Id)
                {
                    if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
                    {
                        sum = item.Amount + sum;
                    }
                }
            }

            Total.Add(sum);
            sum = 0;

            foreach (var item in expenseDetails.Bills)
            {
                if (item.ApplicationUserId == user.Id)
                {
                    if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
                    {
                        sum = item.Amount + sum;
                    }
                }
            }

            Total.Add(sum);
            sum = 0;

            foreach (var item in expenseDetails.Rents)
            {
                if (item.ApplicationUserId == user.Id)
                {
                    if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
                    {
                        sum = item.Amount + sum;
                    }
                }
            }

            Total.Add(sum);
            sum = 0;

            TotalCosts.Add(user.Id, Total.ToList());
            Total.Clear();
        }

        return TotalCosts;
    }

But this is not a good one for programming. How can I achive this with best practice? I am using repository pattern by the way.

Some quick remarks:

Why isn't PaidDate a DateTime?
What is a "Shopping"? (I realize that often naming things is hard, but be careful when inventing new English words that do not adequately describe their contents, because the next person to maintain this code will find it harder to do so when they have to first decipher various terms.)
Use descriptive names: item is way too vague.
TotalCosts and Total should be camelCased.
sum = item.Amount + sum; can be shortened to sum += item.Amount;.
Don't do if (item.ApplicationUserId == user.Id), instead use LINQ to extract the relevant records, e.g. expenseDetails.Shoppings.Where(x => x.ApplicationUserId == user.Id). And if PaidDate was a DateTime, you could easily also include that in the LINQ query and immediately calculate the sum.
Why do you do Total.ToList()? How can it be anything else?

But all of that is IMHO just plugging some small holes, while ignoring the massive dam breach elsewhere: surely this logic could be done easily in one SQL query?

On a related note: is there even a point to have a List<double> Total? I wouldn't be surprised if all you did with those is add them up.

And if you're not adding them up and always assume that the first item is the sum of Shoppings etc. and use this to display them elsewhere: please don't. In such cases always use the key-value pair structure, so you'd know that value X is definitely the sum of the Shoppings.


A Simple Word Guessing Game I have just finished learning basic-intermediate Python subjects and wanted to test myself. This word-guessing game is one of the first programs I have written.

import random

def pick_random_word():
    word_list = ["python", "c", "java", "swift", "html", "css", "go", "ruby"]
    random_word = random.choice(word_list)
    return random_word

def make_word_classified(word):
    classified_list = ["_" for i in word]
    return classified_list

def guess():
    word = pick_random_word()
    classified_word = make_word_classified(word)
    print(*classified_word)
    total_attempts = 0

    while True:
        try:
            answer = input("Guess a letter (Write only one letter)>: ").lower()
            if len(answer) > 1:
                raise Exception
        except Exception:
            print("Only one letter at a time!")
            continue
        total_attempts += 1

        if total_attempts >= 7:
            print("Sorry but you lost!")
            try_again = input("Wanna play again? (write y or n) >: ")
            if try_again == 'y':
                guess()
            elif try_again == 'n':
                print("Goodbye!")
                quit()

        for i in range(len(word)):
                if answer == word[i]:
                    classified_word[i] = answer
                if "".join(classified_word) == word:
                    print("You won!")
                    quit()

        print(*classified_word, f"\nTotal attempts left: {7 - total_attempts}")

if __name__ == "__main__":
    guess()

So, what do you think? How can I make it better? What are my mistakes?

General Remarks

For the most part, this code is quite good if it's truly one of the first programs you've written. I've seen experienced coders with a University degree do much worse things. Congrats.
Avoid: while True:, catch Exception, raise Exception in the future. These should only be used in rare cases, and yours wasn't one.
KISS. That try..except block where you raise and catch an exception is just too complex for what can simply be achieved with an if statement.
Consider the control flow. There's a couple of bugs that I found because some of the conditions were incomplete. I've annotated and fixed some of them in the line-by-line review, and will put them rest as "exercises" at the end.
Avoid the use of quit() (or even sys.exit()) and opt for an early return instead.

Personal Remarks and Hints

Consider adopting type hinting. A small program like this is ideal to explore Python type hinting, and tools such as mypy can make your life a lot easier once you get the hang of it.
I would've liked to see some docstrings in your module and functions.
Variable names and functions names were okay for the most part, although there's room for improvement. Always make them indicative of the variable/function's purpose, and avoid confusion.
Consider the visibility of your functions, and mark functions that should not be visible outside of your module as "private" by prefixing them with an underscore. Although unnecessary for this code, it's good practice for the future.

Line-by-Line Review

Without further ado, here's a line-by-line review with some inline comments and personal suggestions for improvement I've made while reading your code.

import random

# EXERCISES:
# - What if I win, but I want to play another round?
# - What happens if I guess the same character twice? What *should* happen?
#   Maybe it's already okay.

# COMMENT: Putting this list in the `pick_random_word` function will constantly
# reconstruct the list, which is redundant. Instead, moving it to the global
# scope will only construct it once.
# NOTE: Putting variables into the global scope is also considered bad
# practice, but in this simple case there's not a lot wrong with it. There's
# other options that I won't go into detail on.
# COMMENT: You removed "javascript" because @Gloweye correctly pointed out a
# bug in your program. We'll instead fix this bug here.
_WORD_LIST = [
        "python", "c", "java", "swift", "html", "css", "go", "ruby",
        "javascript"]

# COMMENT: Magic constants are a bad practice to have in your source code. I've
# extracted the maximum attempts to a global variable, so if you want to
# provide more attempts at a later date, you just have to change this, and not
# search for the number in the code.
_MAX_FAILED_ATTEMPTS = 7

# COMMENT: I've prefixed all function definitions with an underscore. This is
# mostly just a convention to denote names that should be kept internal. In
# case of modules, this signifies a user of the module that this is not a
# function they should be concerned with. In your case, this is probably
# redundant, but it's good practice for the future.
def _pick_random_word():
    # COMMENT: Don't assign and immediately return, instead, return without
    # assignment. This makes your code clearer.
    return random.choice(_WORD_LIST)

def _make_word_classified(word):
    # COMMENT: Again, immediately return instead of assigning to a variable
    # first. Secondly, lists can be "multiplied". This replicates the contents,
    # just like your list comprehension did previously.
    # Note: Mind the brackets so it's a list, not a string. Strings can be
    # multiplied too, but are immutable so won't work for the remainder of the
    # code.
    return ["_"] * len(word)
    # return classified_list

# COMMENT: A better name would be in order here. Something along the lines of
# `play_guessing_game` would be better, but still not ideal. `guess` feels like
# the wrong name to me.
def guess():
    # COMMENT: Confusing variable names are one of my pet peeves, so I changed
    # `word` to `target_word`. This way, when writing the code, you won't get
    # confused.
    target_word = _pick_random_word()
    classified_word = _make_word_classified(target_word)
    print(*classified_word)
    # COMMENT: Let's count the how many attempts are left, since that's what
    # we use more often: In printing as well as (now) the condition of the loop
    attempts_left = _MAX_FAILED_ATTEMPTS

    # COMMENT: I don't like `while True:`, unless it's really necessary.
    # I've changed it to iterate with a condition on the number of attempts
    # instead. This will also simplify our loop body.
    # COMMENT: We could simplify this to `while attempts_left` and use the fact
    # that 0 is equivalent to `False`, but this is more explicit.
    while attempts_left > 0:
        # COMMENT: The `try..except` block is over-engineered, it could've
        # been done with a simple `if` statement.
        answer = input("Guess a letter (Write only one letter)>: ").lower()
        # COMMENT: What happens if I don't enter anything? Should it really be
        # counted as an attempt? Thus I check if there's exactly one character.
        if len(answer) != 1:
            print("Exactly one letter is expected!")
            # COMMENT: I like the use of `continue` instead of an `else` block.
            # Both are viable, but for a large `else` body it gets hard on the
            # eyes. Well done.
            continue
        # COMMENT: Before I forget: You raised and caught `Exception`. In the
        # future, create your own custom exceptions instead, or use a specific
        # exception that's already provided by Python. `Exception` is the
        # superclass of almost all exceptions in Python, and by catching
        # exceptions, you would've suppressed different errors as well, such
        # as `IndexError`, `KeyError`, `AttributeError`, `TypeError`, ...

        # COMMENT: We'll only increment the attempt counter on mistakes, so
        # that words of arbitrary length are possible.
        # total_attempts += 1

        # COMMENT: We don't have to check this anymore, it's already checked
        # in the loop condition. Instead. we'll move the handling of running
        # out of attempts to after the loop.
        # if total_attempts >= _MAX_ATTEMPTS:
        #     print("Sorry but you lost!")
        #     try_again = input("Wanna play again? (write y or n) >: ")
        #     if try_again == 'y':
        #         guess()
        #     elif try_again == 'n':
        #         print("Goodbye!")
        #         quit()

        attempt_correct = False
        # COMMENT: Use enumerate(word) rather than range(len(word)) to get both
        # the value and the index.
        for char_idx, target_char in enumerate(target_word):
            # I've reindented this code to be 4 spaces rather than 8. New
            # blocks should always have 4 spaces.
            if answer == target_char:
                classified_word[char_idx] = answer
                attempt_correct = True

        # We still need to decrement the attempt counter if the attempt was
        # incorrect. This is why we maintain a boolean and set it to True only
        # if the attempt is correct.
        if not attempt_correct:
            attempts_left -= 1

        # COMMENT: Let's move this out of that loop, so we only compare the
        # words once, rather than every time we access a character.
        # COMMENT: Instead of turning the classified word into a string, let's
        # instead check whether it still contains an underscore to check if
        # we're done. This is more elegant.
        if "_" not in classified_word:
            print("You won!")
            # COMMENT: Instead of calling `quit()`, we'll return. I'm
            # `quit()` is not really an elegant way to exit a program,
            # and is not necessary here. Returning early will simply
            # break out of the function (and thus also the loop) and
            # thus stop the game.
            # COMMENT: Exercise for you: What if I wanted to continue
            # to play another round?
            return

        # COMMENT: You could move this to the top of the loop, and do away
        # with the initial print before the loop, and then you'd have the
        # "Total attempts left" from the start.
        print(*classified_word, f"\nTotal attempts left: {attempts_left}")

    # If we reach the end of this loop, we've lost, since if we've won,
    # we'd already have returned from the function.
    print("Sorry but you lost!")
    try_again = input("Wanna play again? (write y or n) >: ")
    # COMMENT: Python makes no distinction between strings and characters, so
    # single quotes and double quotes are equivalent. "y" and "n" here were
    # single quotes while the rest of your strings are double quotes.
    # Be consistent. Choose one and stick with it.
    if try_again == "y":
        # Okay, but what if I play millions of times? It's likely never going
        # to be an issue, but if I play millions of times, this will cause a
        # stack overflow because of the recursion. Prefer iteration (with a
        # `for` or `while` loop) instead. Python does not have tail-call
        # optimization: https://stackoverflow.com/q/13591970/10973209
        guess()
    # We still need the `else` to print the goodbye, otherwise it would print
    # goodbye multiple times if we recursively call ourselves. I've changed it
    # to `else` so that it prints goodbye even if I didn't say 'n'.
    # This would previously cause a bug when it was still in the loop. If I
    # entered 'a', it would just continue the game and I'd have an infinite
    # number of attempts.
    else:
        print("Goodbye!")
        # Now that this is moved outside of the loop, we don't need to return
        # or quit anymore, the function will just end.

if __name__ == "__main__":
    guess()

Exercises

There's still room for improvement, and I'll give you a few pointers on where to start:

Consider the case where I'm forgetful, and I've typed the same character twice. How should this be handled? How is this currently handled? Is that okay?
I've won the game. Now what? I'd like to play again, please and thank you.
I already mentioned in the code the possibility of stack overflow because Python doesn't perform so-called tail-call optimisation. I doubt you'll ever run into issues with this program because of this, but it's still a good exercise to 1) look into what tail-call optimisation is and why your program could crash without it, and 2) fix the program so that it wouldn't have that problem.


Simple JavaScript library for DOM interactions I got this pretty interesting homework assignment, which was to finish off a very simple Javascript library. I couldn't use jQuery.

First, I will show you the raw piece of code that I received, then I will show you my solution and the last piece of code is what I think is the test of all the functions I had to make. I checked it and it worked pretty well- I mean the console output was as expected. I would like to ask you whether my solution is okay or not.

What I was given:

'use strict';

var dom = {
    // TODO: fill in library's API ...

    create: function(tag_name, attrs){

    },

    // Attributes getter / setter
    attr: function(elem, name, value){

    },

    // Append element as last child
    append: function(elem, child){

    },

    // Prepend element as first child
    prepend: function(elem, child){

    },

    // Detach element from dom
    remove: function(elem){

    }
}

What I did:

'use strict';

var dom = {
    // TODO: fill in library's API ...

    create: function(tag_name, attrs){
        var temp = document.createElement(tag_name);
        for(var key in attrs)
            {
            temp.setAttribute(key, attrs[key]);
            }
        return temp;
    },

    // Attributes getter / setter
    attr: function(elem, name, value){
        if(!value) return elem.getAttribute(name);
        elem.setAttribute(name,value);
        return elem;
    },

    // Append element as last child
    append: function(elem, child){
        elem.appendChild(child);
    },

    // Prepend element as first child
    prepend: function(elem, child){
        elem.prepend(child);
    },

    // Detach element from dom
    remove: function(elem){
        var par = elem.parentNode;
        par.removeChild(elem);
    }
}

WHAT I THINK IS A TEST:

'use strict';

describe('Dom library', function () {

  it('should allow to create dom elements', function () {
    var div = dom.create('div');

    expect(div instanceof window.Element).toBeTruthy();
    expect(div.tagName).toBe('DIV');
  });

  it('should allow to create dom elements with attributes', function () {
    var div = dom.create('div',{
        test:'test_value'
    });

    expect(div instanceof window.Element).toBeTruthy();
    expect(div.getAttribute('test')).toBe('test_value');
  });

  it('should allow to append elements', function () {
    var div = document.createElement('div');
    div.innerHTML = '

\

\

';

    var appendee = document.createElement('div');
    dom.append(div, appendee)
    expect(div.children[div.children.length - 1]).toBe(appendee);
  });

  it('should allow to prepend elements', function () {
    var div = document.createElement('div');
    div.innerHTML = '

\

\

';

    var prependee = document.createElement('div');
    dom.prepend(div, prependee)
    expect(div.children[0]).toBe(prependee);
  });

  it('should allow to detach elements', function () {
    var div = document.createElement('div');
    div.innerHTML = '

\

\

';

    var target = div.children[0];
    var detached = dom.remove(target)
    expect(target).toBe(detached);
    expect(div.children[0]).not.toBe(target);
  });

  it('should allow get element attribute', function () {
    var div = document.createElement('div');
    div.setAttribute("test","test_value");

    expect(dom.attr(div, 'test')).toEqual('test_value');
  });

  it('should allow set element attribute', function () {
    var div = document.createElement('div');
    dom.attr(div, 'test', 'test_value');

    expect(div.getAttribute('test')).toEqual('test_value');
  });

});

First off, consider which browsers is this DOM library supposed to support. Then test that it works in all of them.

create()

Plain for-in loop is not safe as it also loops over keys in object prototype.
temp is bad name for a variable.
You're repeatedly testing that return value is window.Element.
window.Element can be written as just Element (or perhaps use HTMLElement for clarity).

attr()

What if the value is 0 or ""?

prepend()

elem.prepend() is not supported by all browsers.

remove()

par is unnecessary abbreviation of parent.

A few general remarks:

Check your code for consistent formatting. You're missing some semicolons and the indentation is inconsistent. Use a tool like ESLint.
Escaping newlines to create multiline strings is not officially supported in ECMAScript.