texts:
I recently started learning C++ and here's a simple program I wrote to demonstrate how multi-threading work. This program simply fetches JSON strings from a whether API for a list of cities read from a text file.
Can you guys take a look? And I really appreciate professionals' views.

#include <iostream>
#include <ctime>
#include <typeinfo>
#include <thread>
#include <mutex>
#include <vector>
#include <fstream>
#include <string>
#include <curl/curl.h>

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp);
void fetchJson(int);
void getCityList();
void fetch_weather_async();

const char *URL_BASE = "https://www.metaweather.com/api/location/search/?query=";
const char *CITY_LIST_FILE = "city_list.txt";
std::vector<std::string> cities;
int current_city = -1;
std::mutex city_counter_lock;
std::time_t start;
std::time_t finish;

int main(void){
    getCityList();
    std::cout << "Read " << cities.size() << " cities from file..." << std::endl;

    std::cout << "Using 2 threads to fetch..." << std::endl;
    std::thread thread_1(&fetch_weather_async);
    std::thread thread_2(&fetch_weather_async);

    start = std::time(nullptr);
    thread_1.join();
    thread_2.join();
    finish = std::time(nullptr);

    std::cout << "Duration " << (finish - start) << "s" << std::endl;

    return 0;
}

void fetch_weather_async(){
    while (current_city + 1 < (int) cities.size()){
        city_counter_lock.lock();
        int city_index = 0;
        if (current_city + 1 < (int) cities.size()) {
            city_index = ++current_city;
        }
        city_counter_lock.unlock();

        std::cout << "requesting " << city_index << std::endl;
        fetchJson(city_index);
        std::cout << "acquired " << city_index << std::endl;
    }
}

void getCityList(){
    std::ifstream idFile(CITY_LIST_FILE);
    std::string currentLine;

    if(idFile.is_open()){
        while(! idFile.eof()){
            getline (idFile, currentLine);
            cities.push_back(currentLine);
        }
    }
    idFile.close();
}

void fetchJson(int i){
    CURL *curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, (URL_BASE + cities[i]).c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        std::cout << i << " : " << readBuffer << std::endl;
    }
}

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

The city list file (city_list.txt) contains:

Adelaide
Amsterdam
Ankara
Athens
Atlanta
Auckland
Baghdad
Bangkok
Beijing
Belfast
Berlin
Blackpool
Bridgeport
Brussels
Bucharest
Budapest
Busan
Cairo
Caracas
Cardiff
Casablanca
Charlotte
Copenhagen
Dallas
Damascus
Dhaka
Dublin
Edinburgh
Glasgow
Helsinki
Jakarta
Kiev
Kinshasa
Lagos
Lahore
Lima
Lisbon
London
Madrid
Manila
Milan
Minsk
Moscow
Nairobi
Newark
Newcastle
Oakland
Oslo
Paris
Philadelphia
Plymouth
Portland
Portsmouth
Prague
Pyongyang
Riyadh
Rome
Santander
Santiago
Santorini
Seoul
Singapore
Sofia
Stockholm
Sunderland
Taipei
Tokyo
Vienna
Warsaw
Wellington
Windhoek
Zagreb


texts: Convenience function to save and load pickle objects

texts:
I want to come up with a simple convenience function to save and load pickle objects. A secondary objective is to simply execute the function without the above function. I have come up with two versions so far. Just want some opinions, which of the following will be better from a software engineering point of view. Or more pythonic. If possible please suggest a still better version, with changed parameter names or something already out there.

def test(filename, func, exec_only=False, ignore_file=False, **kwargs):
    if exec_only:
        obj = func(**kwargs)
    else:
        fname = Path(filename)
        if fname.exists() and not ignore_file:
            obj = jl.load(filename)
        else:
            obj = func(**kwargs)
            jl.dump(obj, fname, compress=True)
    return obj

Another version:

def test2(filename, func, exec_only=False, ignore_file=False, **kwargs):
    if Path(filename).exists() and not ignore_file and not exec_only:
        obj = jl.load(filename)
    else:
        obj = func(**kwargs)
        if not exec_only:
            jl.dump(obj, fname, compress=True)
    return obj

Thanks a lot in advance.

EDIT: I created this function as a machine learning utility, since execution is typically very costly and the decision to execute is dependent on the presence of the file. I will be incorporating some features from Sam's answer. Thanks.


texts: class IMessge - returns user message types | loop similar items

texts:
This class holds message types that are sent to the client which knows what to do with them.  It is basically a small registry pattern where I can consolidate message types. |P| and |F| are read by the client...and I use these for simple data passing when I don't need the complexity of JSON.  The programmer is expected to know which messages types are available.

I've added in a array_key_exists() as a defensive measure against a progammer calling a message that does not exit.  I did this as someone said this is best practice...I'm looking for a second opinion...as in this case it is not a big deal but overall "defensive coding" would increase my library size / efficiency by 10-20%.  Can I take this out?

<?php
class IMessage
{
    private $PASS = '|P|';
    private $FAIL = '|F|';
    private $messages = array();
    public function __construct()
    {
        $this->messages['PASS'] =  $this->PASS;
        $this->messages['name'] =  $this->FAIL . 'name';
        $this->messages['email'] = $this->FAIL . 'email_s';
        $this->messages['pass'] =  $this->FAIL . 'pass';
        $this->messages['url'] =   $this->FAIL . 'url';
        $this->messages['title'] = $this->FAIL . 'title';
        $this->messages['tweet'] = $this->FAIL . 'tweet';
        $this->messages['empty'] = $this->FAIL . 'empty';
        $this->messages['same'] =  $this->FAIL . 'same';
        $this->messages['taken'] = $this->FAIL . 'taken';
        $this->messages['validate'] = $this->FAIL . 'validate';
    }
    public function get( $type )
    {
        if( !array_key_exists($type, $this->messages ) )
        {
            echo "Programmer Error: You called a key that does not exist";
        }
        else
        {
            return $this->messages[ $type ];
        }
    }
}


texts: Responsive / CSS fixed and variable widths

texts:
CSS and responsiveness in multiple columns with fixed and scaleable elements can be done in many ways.

I have created a solution that seems to work, though I have no idea whether this is best practice.

Fiddle

CSS

html, body { margin:0 auto; padding:0;  background: #fff; text-align: center; }

/* Clearfix
============================================================================ */
.CF { display:inline-block;overflow:hidden; }

/* Elements
============================================================================ */
div#container {max-width: 1140px;  min-width: 960px; margin:0 auto; margin-top: 10px; padding:0;  background:#0F9;  position:relative;}
    div#left-menu {width: 100px; background:#F30; position: absolute; top:0; left:0;   }
    div#information {padding: 10px 10px 25px 10px; background:#39C;  margin-left:100px;}
        div#information-wrapper {position:relative; background:#3FF; }
            div#information-left-menu {width: 125px;  background:#C30; position: absolute; top: 0; left:0;}
            div#content {background:#FC0; margin-left: 125px; text-align:left;}

HTML

Left 100px wide

Fixed width of 125px

text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text


texts: Two variants of a picture database initialization routine

texts:
I wonder which of the two snippets is better? In the second one, I extracted two short subroutines.

On the one hand, extraction clearly separate the two tasks
On the other hand, it induces 6 more lines for function prototype

The code is about a simple images database called pictdb_file. The first function contributes to the creation of a new database.

/** this is a helper method for [...] blahblah */
static error_enum
db_create_delegate(const char* db_filename, pictdb_file* new_db_file)
{
    strncpy(new_db_file->header.db_name, CAT_TXT,  MAX_DB_NAME);
    new_db_file->header.db_name[MAX_DB_NAME] = '\0';

    new_db_file->header.num_files = 0;
    new_db_file->header.db_version = 0;

    size_t n1;
    n1 = fwrite(&new_db_file->header, sizeof(pictdb_header), 1, new_db_file->fpdb);
    if (n1 != 1) {
        return ERR_IO;
    }

    size_t n2;
    n2 = fwrite(new_db_file->metadata, sizeof(pict_metadata), new_db_file->header.max_files, new_db_file->fpdb);
    if (n2 != new_db_file->header.max_files) {
        return ERR_IO;
    }
    printf("%lu item(s) written\n", n1 + n2);
    return 0;
}

Compared to:

/** helper method [...] blahblah */
static error_enum
db_create_helper(const char* db_filename, pictdb_file* db_file)
{
    finish_initialization(db_file);
    return write_to_file(db_file);
}
static void
finish_initialization(pictdb_file* new_db_file)
{
    strncpy(new_db_file->header.db_name, CAT_TXT,  MAX_DB_NAME);
    new_db_file->header.db_name[MAX_DB_NAME] = '\0';

    new_db_file->header.num_files = 0;
    new_db_file->header.db_version = 0;
}
static error_enum
write_to_file(pictdb_file* db_file)
{
    size_t n1;
    n1 = fwrite(&db_file->header, sizeof(pictdb_header), 1, db_file->fpdb);
    if (n1 != 1) {
        return ERR_IO;
    }
    size_t n2;
    n2 = fwrite(db_file->metadata, sizeof(pict_metadata), db_file->header.max_files, db_file->fpdb);
    if (n2 != db_file->header.max_files) {
        return ERR_IO;
    }
    printf("%lu item(s) written\n", n1 + n2);
    return 0;
}


texts: Using method chains when rendering a scene

texts:
Is writing Java code in chain like _hud.getStage().getCamera().combined an ugly practice?

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1,0,0,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    _batch.setProjectionMatrix(_hud.getStage().getCamera().combined);
    _hud.getStage().draw();
}

If yes, what would be the pretty way to write the code? And why is it ugly? What are the consequences of this?


texts: Cluster arrays according to similarity of key values

texts:
The below script will compare a set of arrays according to similarities between their key's values. For example, if the first 4 keys values of an array are equal to another array's first 4 keys values, they are equal and consists a cluster. Here is my code:

<?php
$arrays = [
array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4),
array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4),
array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4),
array('a'=>1, 'b'=>2, 'c'=>4, 'd'=>3),
];

$result = [];

//get the keys of a sub-array that is inside $arrays, to be used later
$keys = array_keys($arrays[0]);

for($i=0; $i < sizeof($arrays); $i++){

    $sa = array(); // to store similar arrays indexes

    for($k=$i+1; $k < sizeof($arrays); $k++){

        $similar = false;

        //compare the values of keys in the two arrays. Just compare the first 4 keys (as the user's desire)
        for($j=0; $j < 4; $j++){

            //check if the values are similar, if they are, assign $similar to true, and assign $j=3 to end the loop, (a bit of laziness here)
            ($similar = $arrays[$i][$keys[$j]] == $arrays[$k][$keys[$j]] ? true : false) ? null : ($j=3);
        }

        // check if the key (which represents an index in $arrays) is in $sa or not, if not, push it.
        $similar ? (in_array($i, $sa) ? null : array_push($sa, $i) && in_array($k, $sa) ? null : array_push($sa, $k)) : null;
        //if $similar is true, make $i jumps to the $k index (saving time)
        $similar ? $i=$k : null;
    }

    //if $sa not empty, push it to $result
    empty($sa) ? null : ($result[] = $sa);
}

/*
// at this stage, $result includes all the similar arrays
// so we need another loop to push the unique arrays to $result
// just check if an index of $arrays is in an sub-array of $result, if not, push it as an array of one record
*/

for($j=0; $j < sizeof($arrays); $j++){
    $f = false;
    for($i=0; $i < sizeof($result); $i++){
        in_array($j, $result[$i]) ? $f = true : null;
    }
    if(!$f){
        $sa = array();
        array_push($sa, $j);
        array_push($result, $sa);
    }
}

If the result was as follows:

array(2) {
    [0]=> array(3) {
            [0]=> int(0)
            [1]=> int(1)
            [2]=> int(2)
    },
    [1]=> array(1) {
            [0]=> int(3)
    }
}

this means that $arrays has two clusters of sub-arrays, where $arrays[0], $arrays[1], and $arrays[2] are similar (cluster 1), then $arrays[3] is unique (cluster 2).

Does this code have vulnerabilities? Could it be optimized?


texts:
I am creating a CMS for a website, so I've added most of the functions that will fetch data from the database to a separate class. The code doesn't seem to have any bugs(Since I've tested it) but I don't like the way how it's looking, I feel like it can be improved but I don't know how. The other concern I have is whether using object orientation will be in this case better (speed etc) than simple functional way.

    <?php

class getResources{

    private $rowId;
    private $tableName;
    private $rowRes;
    private $limInit, $limEnd;
    private $direction;

    private function sqlFetcher(){

        $selectPosts = "select * from {$this->tableName} where post_id='{$this->rowId}'";

        $run_posts = mysql_query($selectPosts);
        if(!$run){
           die('Could not retreive data: "'.mysql_error().'"');
       }
        $row = mysql_fetch_array($run_posts);

        return $row;
    }

    private function fetchAllData(){
       $query = "SELECT * FROM {$this->tableName} ORDER BY {$this->rowRes} {$this->direction} LIMIT {$this->limInit},{$this->limEnd}";
       $run = mysql_query($query);
       if(!$run){
           die('Could not retreive data: "'.mysql_error().'"');
       }

       return $run;
    }
    /**************sqlFetcher Getters****************/
    function getContent($rowId, $tableName){
        $this->rowId = $rowId;
        $this->tableName = $tableName;

        $post_content = $this->sqlFetcher();

        return $post_content['post_content'];
    }

    function getTitle($rowId, $tableName){
        $this->rowId = $rowId;
        $this->tableName = $tableName;

        $post_title = $this->sqlFetcher();

        return $post_title['post_title'];
    }

    function getAuthor($rowId, $tableName){
        $this->rowId = $rowId;
        $this->tableName = $tableName;

        $post_author = $this->sqlFetcher();

        return $post_author['post_author'];
    }

    function getKeywords($rowId, $tableName){
        $this->rowId = $rowId;
        $this->tableName = $tableName;

        $post_keywords = $this->sqlFetcher();

        return $post_keywords['post_keywords'];
    }

    function getPicture($rowId, $tableName){
        $this->rowId = $rowId;
        $this->tableName = $tableName;

        $post_picture = $this->sqlFetcher();

        return $post_picture['post_picture'];
    }

    function getDate($rowId, $tableName){
        $this->rowId = $rowId;
        $this->tableName = $tableName;

        $post_date = $this->sqlFetcher();

        return $post_date['post_date'];
    }

    /*****************fetchAllData Getter********************/

    function getFetchedData($tb, $rR, $lI, $lE, $direction="ASC"){
        $this->tableName = $tb;
        $this->rowRes = $rR;
        $this->limInit = $lI;
        $this->limEnd = $lE;
        $this->direction = $direction;

        $row1 = $this->fetchAllData();

        return $row1;
    }

}

?>


texts: Optimizing a Solution to an Overdetermined System

texts:
Hearthstone is a collectible card video game similar to Magic: The Gathering, where players play cards with certain values of "attack" and "health" for certain "mana" costs. After being introduced to some of the basics of R, I decided that I would find some of the "values" of these characteristics by finding the best solutions to an overdetermined system, as demonstrated here.

Let a card's mana cost, attack, health, and card value* be represented as the vector (m,a,h,v). Three cards are (1,1,2,1), (2,3,2,1), (4,4,5,1), and (7,9,5,1). This corresponds to the overdetermined system a+2h+v=1, 2a+3h+v=2, 4a+5h+v=4, 9a+5h+v=7. The below code would find values of a, h, and v that minimize the sum of the squared differences between the LHS and RHS of the four equations (more cards are shown than the example).

*Card value is the inherent value in having a card to play, as opposed to not having a card to play

numberOfCards = 9
numberOfEffects = 3 # Must be less than or equal to numberOfCards

# Mana, Attack, Health, Card Value

allCards = matrix(
    c(1,2,1,1),                       # Murloc Raider
    ncol = numberOfEffects + 1,
    byrow = TRUE
    )
allCards = rbind(allCards,c(2,2,3,1)) # River Crocolisk
allCards = rbind(allCards,c(2,3,2,1)) # Bloodfen Raptor
allCards = rbind(allCards,c(3,5,1,1)) # Magma Rager
allCards = rbind(allCards,c(4,2,7,1)) # Oasis Snapjaw
allCards = rbind(allCards,c(4,4,5,1)) # Chillwind Yeti
allCards = rbind(allCards,c(6,6,7,1)) # Boulderfist Ogre
allCards = rbind(allCards,c(7,7,7,1)) # War Golem
allCards = rbind(allCards,c(7,9,5,1)) # Core Hound

coefficientsMatrix = matrix(
    NA,
    nrow = numberOfEffects,
    ncol = numberOfEffects,
    byrow = TRUE)
for(i in 1:numberOfEffects) {
    for(j in 1:numberOfEffects) {
        coefficientsMatrix[i,j] = sum(allCards[,i+1] * allCards[,j+1])
    }
}

constantsVector = vector(mode = "integer", length = numberOfEffects)
for(i in 1:numberOfEffects) {
    constantsVector[i] = sum(allCards[,1] * allCards[,i+1])
}

effectValues = solve(coefficientsMatrix, constantsVector, tol = 1e-9)
cat(effectValues, "\n\n") # For demonstration of values of each effect

cardValueMatrix = allCards[,-1]

cardValues = vector(mode = "integer", length = numberOfCards)
for(i in 1:numberOfCards) {
    cardValues[i] = round(sum(cardValueMatrix[i,] * effectValues), digits = 3)
    cat("Card ", i, ": ", cardValues[i], "\n", sep = "")
}

I know of a couple things that could be improved in this code. The most glaring improvement that needs to be made is the creation of coefficientsMatrix; I've read that making a matrix of the correct size and filling it with NA only to fill in its values later is very memory-intensive. Additionally, I am unsure if the way I create the allCards matrix with rbind is the best way to do this.


texts:
I am creating a sort of Sales Report for an Invoicing System.

I have an extremely complex MySQL Query that takes a very long time to execute (usually about 10 - 15 seconds). It involves multiple tables (containing hundreds or even thousands of rows) in a database that an even more complex system is built upon.

At this stage in development, it doesn't seem to me that it would be beneficial to change the structure of the database tables for this one query since everything else is working very fast.

If you care to review my query and give me advice on how to optimize my code to achieve the quickest possible time in terms of speed, I would be more than grateful.

I am using PHP with MySQLi.

SELECT `u`.`first`, `u`.`last`,
    `i`.`id`, IFNULL(`i`.`vendor`, `d`.`unattached_vendor`) AS `vendor`, IFNULL(`i`.`originalskunumber`, `d`.`skunumber`) AS `skunumber`,
    `d`.`date_sent`, `d`.`document_type`, `d`.`document_id`, `d`.`description`, `d`.`qty`, `d`.`triage_notes`, `d`.`status`, `d`.`arrival_date`, `d`.`id` AS `document_row`
    FROM `documents` AS `d`
        LEFT JOIN `inventory` AS `i`
            ON (CASE
                WHEN `d`.`document_type` = 'Invoice'
                    THEN `i`.`skunumber` = `d`.`skunumber`
                WHEN `d`.`document_type` = 'Purchase Order'
                    THEN `i`.`originalskunumber` = `d`.`skunumber`
            END)
        INNER JOIN `users` AS `u`
            ON `u`.`uid` = `d`.`customer_id`
        WHERE `d`.`document_type` <> 'Quote'
            AND `d`.`header_item` = '0'
            AND `d`.`active_document` = '1'
            AND `d`.`active_item` = '1'
            AND (CASE
                WHEN `d`.`document_type` = 'Invoice' AND `d`.`skunumber` IS NOT NULL
                    THEN (`d`.`document_id`, LEFT(`d`.`skunumber`, 3)) NOT IN (SELECT `trailing_doc`, LPAD(`vendor_code`, 3, '0') AS `vendor_code` FROM `documents` WHERE `active_document` = '1' AND `active_item` = '1' AND `trailing_doc` IS NOT NULL AND `vendor_code` IS NOT NULL)
                WHEN `d`.`document_type` = 'Purchase Order'
                    THEN 1
                ELSE 1
            END)
            AND (CASE
                WHEN `d`.`document_type` = 'Invoice'
                    THEN `d`.`document_id` IN (SELECT DISTINCT `document_id` FROM `payments` WHERE `active_payment` = '1' AND `payment_amount` > 0)
                WHEN `d`.`document_type` = 'Purchase Order'
                    THEN 1
            END)
            AND (CASE
                WHEN `i`.`id` IS NULL AND `document_id` IN (SELECT DISTINCT `trailing_doc` FROM `documents` WHERE `document_type` = 'Purchase Order' AND `active_document` = '1' AND `active_item` = '1' AND `trailing_doc` > '')
                    THEN 0
                ELSE 1
            END)
    GROUP BY `d`.`document_id`, `i`.`originalskunumber`

As requested, here's my EXPLAIN:

id  select_type         table       type    possible_keys   key     key_len     ref                     rows    Extra
1   PRIMARY             d           ALL     NULL            NULL    NULL        NULL                    2298    Using where; Using temporary; Using filesort
1   PRIMARY             u           eq_ref  PRIMARY         PRIMARY 4           example.d.customer_id   1       Using where
1   PRIMARY             i           ALL     NULL            NULL    NULL        NULL                    77418   Using where
4   DEPENDENT SUBQUERY  documents   ALL     NULL            NULL    NULL        NULL                    2298    Using where; Using temporary
3   DEPENDENT SUBQUERY  payments    ALL     NULL            NULL    NULL        NULL                    14      Using where; Using temporary
2   DEPENDENT SUBQUERY  documents   ALL     NULL            NULL    NULL        NULL                    2298    Using where


texts:
I was told I'm using factories wrong, but I'm not so sure. Any ideas? (I know I should be using GET; I've only just noticed that)

app.factory('apiFactory', ['$http', function($http){
    var apiFactory = {};

    apiFactory.initUser = function(){
        return  $http({
            method: "POST",
            url: "api/new_user.php",
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
        });
    };

    apiFactory.hostOrClient = function(session){
        return $http({
            method: "POST",
            url: "api/sessionhostclient.php",
            data: $.param({"session":session}),
            headers:{"Content-Type": "application/x-www-form-urlencoded"}
        });
    };

    apiFactory.hasPlayerJoined = function(session){
        return $http({
            method: "POST",
            url: "api/sessionstatus.php",
            data: $.param({"session":session}),
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
        });
    };

    apiFactory.sendMessage = function(session, message){
        return $http({
            method: "POST",
            url: "api/addmessage.php",
            data: $.param({"message":message, "session":session}),
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
        });
    };

    apiFactory.checkMessages = function(session, id){
        return $http({
            method: "POST",
            url: "api/getmessages.php",
            data: $.param({"session":session, "id":id}),
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
        });
    };

    apiFactory.getAllMessages = function(session) {
        if(session == null){
            return;
        }

        return $http({
            method:"POST",
            url:"api/getallmessages.php",
            data: $.param({"session":session}),
            headers:{"Content-Type": "application/x-www-form-urlencoded"}
        });
    } ;

    apiFactory.getMessagesFrom = function(session, id){
        return $http({
            method: "POST",
            url: "api/getmessages.php",
            data: $.param({"session":session, "id":id}),
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
        });
    };

    return apiFactory;
}]);


texts:
I've been working in a small page with some easy CRUD. The data I get from the database is getting shown on the page. But the way how I show the data feels a bit off. I guess it can be done in a much cleaner way, and really want to know how.

I do it as follows:

First: I require the necessary class, and call the function the the HTML file:

<?php
require 'classes/vacatureData.php';

$db = new database();
$db->listAllVacatures();

require 'templates/head.php';
require 'templates/vacatureOverzicht.php';
require 'templates/footer.php';

In my class I got a public variable public $listAllVacatures;, which I use to store all the values which I retrieve from the database.

The method to retrieve the data from the database looks as following:

public function listAllVacatures() {
    $sql = 'SELECT * FROM vacatures';
    $stmt = $this->db->prepare($sql);

    if($stmt->execute()) {
        $vacatures = $stmt->fetchAll();

        foreach($vacatures as $vacature){
            $this->listAllVacatures .= "
";
            $this->listAllVacatures .= "$vacature[1]";
            $this->listAllVacatures .= " - delete";
            $this->listAllVacatures .= " - Edit";
            $this->listAllVacatures .= "
";
        }
    } else {
        $e = $stmt->errorInfo();
        echo $e[2];
    }

    $this->db = null;
}

As you can see I use a foreach to fill $listAllVacatures with data, but also some HTML (Which i feel shouldn't be there, but right now I'm not quite sure how to organise this properly).

Then I got the template file which uses $listAllVacatures:

Vacatures:

    <?php echo $db->listAllVacatures ?>

This all works fine, but like I said, it doesn't feel right to do it this way. But for now it's the best way I know.


texts:
When coding I noticed I started to get into a habit of not using if-else statements when the else block only has one line of code. For example, if I have code that can be solved like this:

public Person(int initialAge) {
    if(initialAge < 0){
        System.out.println("Age is not valid, setting age to 0.");
        age = 0;
    }
    else{
        age = initialAge;
    }
   }

I will instead remove the else statement entirely to cut down on a few lines of code. This results in my code looking more like this:

public Person(int initialAge) {
    age = initialAge;
    if(initialAge < 0){
        System.out.println("Age is not valid, setting age to 0.");
        age = 0;
    }
   }

I'm wondering if this is a bad coding habit to get into and if I should break out of this coding habit or if it'll be fine to continue doing this. Would doing this be a bigger issue down the line when I get onto more complex programs?

Edit: Just wanted to give some more information for why part of the code is written the way it is. The snippet provided is part of a coding challenge where one of the requirements is to set any negative number inputted to 0.


texts: Find first questions with answers posted within 24 hours

texts:
So, sᴉɔuɐɹɥԀ suggested I write a SEDE query to find first questions with answers posted within 24 hours, and here it is:

WITH QData(OwnerId, CDate)
AS
(
  SELECT
  Q.OwnerUserId [OwnerId]
  ,MIN(Q.CreationDate) [CDate]
  FROM Posts Q
  WHERE Q.PostTypeId = 1 AND Q.OwnerUserId IS NOT NULL
  GROUP BY Q.OwnerUserId
),

FirstQs(QCreationDate, QPostId, QUserId)
AS
(
  SELECT
  CDate [QCreationDate]
  ,Q.Id [QPostId]
  ,OwnerId [QUserId]
  From QData JOIN Posts Q On (Q.CreationDate = CDate AND Q.OwnerUserId = OwnerId)
  WHERE Q.PostTypeId = 1
  GROUP BY OwnerId, Q.Id, CDate
),

FirstQsA(ACreationDate, APostId, AParentId)
AS
(
  SELECT
  MIN(p.CreationDate) [ACreationDate]
  ,MIN(p.Id) [APostId]
  ,p.ParentId [AParentId]
  FROM Posts p, FirstQs
  WHERE (p.PostTypeId = 2 AND p.ParentId = QPostId)
  GROUP BY p.ParentId
)

SELECT QUserId [User Link]
,MIN(QCreationDate) [QCreationDate]
,MIN(ACreationDate) [ACreationDate]
,QPostId[Post Link]
,APostId[Post Link]
FROM
  FirstQs JOIN FirstQsA ON QPostId = AParentId
  WHERE DATEDIFF(HOUR, QCreationDate, ACreationDate) <= 24
GROUP BY QUserId, QPostId, APostId
ORDER BY QUserId

The query can be found here: First Questions with Answers Posted Within 24 Hours.


texts:
I have the following (extremely simplified) database structure:

Table: Competitions

Id: string, unique

Table: Persons

Id: string, unique
Gender: string

Table: Results

CompetitionId: string, references Id on the Competitions table
PersonId: string, references Id on the Persons table
EventId: string
RoundId: string
Average: int

Any Competition may hold n Results. Each Result is assigned to one Person.

I would like to get all Results (filtered for Average > 0, EventId == "333", RoundId == "f", such that it is the one with the lowest Average within the other Results having the same CompetitionId. Furthermore, I only want to get the Results of which the according person is female (gender == "f").

I currently use a weird mixed LINQ construct that is both, ugly and inefficient. The query takes around 3 minutes on my machine (local MySQL database, Results row count is something close to 200k).

I know there are elegant and efficient ways to use one LINQ query, creating temporary tables, joining and such. I am not that much into it, thus I coded this ugly piece:

var femalePersonIds =
    from p in Persons
    where p.Gender == "f"
    select p.Id;

var results333 =
    from r in Results
    where (r.Average > 0) && (r.EventId == "333") && (r.RoundId == "f")
    orderby r.Average
    select r;

foreach (var c in Competitions) {
    var results =
        from r in results333
        where (r.CompetitionId == c.Id)
        select r;
    if (results.Count() > 0) {
        var bestCompResult = results.First();
        if (femalePersonIds.Contains(bestCompResult.PersonId)) {
            bestCompResult.Dump();
        }
    }
}

(This is LINQPad 4 compliant)

I would love to see any efficiency, elegance and shortening hints, in case you have some.


texts:
Just trying out my T-SQL foo.

Wrote a script to get the average time (in seconds) to first answer for a specified language.

-- Could not get this so that the user entered
-- the language in a box at the bottom working.
-- so you have to edit the code here.
declare @Language nvarchar(20) = 'php' -- ##LanguageTag##

declare @AnswerTime table (Id int, CreationDate date, AnswerTime date, Elapse bigint, Slot int )

insert @AnswerTime
Select Q.Id,
       max(Q.CreationDate) AS CreateTime,
       min(A.CreationDate) AS AnswerTime,
       DATEDIFF(second, max(Q.CreationDate), min(A.CreationDate)) AS Elapse,
       Year(max(Q.CreationDate))*12+Month(max(Q.CreationDate)) AS Slot
From   Posts Q, Posts A
Where  Q.PostTypeId = 1
  and  Q.Id = A.ParentId
  and  CHARINDEX(@Language, Q.Tags) != 0
Group by Q.Id, Q.Tags
Order by Elapse

Select min(CreationDate),
       count(*)         as [Count of Tickets],
       -- min(Elapse)   as [Min Time to Answer],
       -- max(Elapse)   as [Max Time to Answer],
       avg(Elapse)    as [Average time to first Answer]
From   @AnswerTime
Group by Slot

Here it is running.


texts:
I know that there is a function bsearch present in stdlib.h but still I want to implement this.

This is my code for binary search. Any and all reviews are welcome.

#include<stdio.h>
#include<stdlib.h>

int compare (const void * a, const void * b)
{
    return (*(int*)a - *(int*)b);
}

int bin_search(int arr[], int min_index, int max_index, int element)
{
    /*
    Searches for an element in the array arr
    Returns fist index of element if present else returns -1
    */
    if (min_index > max_index){
        return -1;
    }
    else
    {
        //Don't change this assignment of mid_point. It avoids overflow
        int mid_point = min_index + (max_index - min_index)/2;

        if (arr[mid_point] > element){
            return bin_search(arr, min_index, mid_point - 1, element);
        }
        else if (arr[mid_point] < element){
            return bin_search(arr, mid_point + 1, max_index, element);
        }
        else{
            return mid_point;
        }
    }
}

int main()
{
    int length;
    while (1)
    {
        printf("Enter a positive length: ");
        scanf("%d", &length);
        if (length > 1){
            break;
        }
        else{
            printf("You entered length = %d\n\n", length);
        }
    }

    int *arr = malloc(sizeof(int) * length);
    if (arr == NULL)
    {
        perror("The following error occurred");
        exit(-1);
    }

    for (int i = 0; i < length; i++){
        scanf("%d", &arr[i]);
    }

    int element;
    printf("\nEnter the element to be searched: ");
    scanf("%d", &element);

    qsort(arr, length, sizeof(int), compare);
    int index = bin_search(arr, 0, length - 1, element);

    if (index == -1){
        printf("\nElement not in the array");
    }
    else{
        printf("\nIndex of element is %d", index);
    }

    free(arr);
    return 0;
}


texts: Recognizing elements and doing event handling for repeating templates

texts:
This fiddle has an ADD button when you click it a Chat window is added.  When there are more than 1 windows the message from one window is reflected across all the windows.

Say you have templates (in above case "Chat Window") which will repeat in DOM (i.e. append and removal will happen dynamically):

var html="
Chat Window

<textarea rows='4' cols='50'>  </textarea>
<input type='button' value='send'>
";

The above template keeps repeating in the DOM i.e. when you click on the ADD button they are added inside:

I have an event handler which listens to the clicks in its innerHTML:

  var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
 var chatWindows=document.getElementsByTagName('p');
if(event.target.value=="send"){
    for(var i=0;i<chatWindows.length;++i){
        chatWindows[i].innerHTML+= "Chat window {index} says: "+ event.target.previousElementSibling.value+"
";
    }
    event.target.previousElementSibling.value=null;
}
},false);

I have a couple of questions regarding it:

Say each of the template has an event with it and a respective handler so say I add this template 10 times in DOM (i.e. click add button in the fiddle 10 times) then I want to do event handling for each of them, possible ways:

I append event handler to each of this template by giving the elements ID so I will have 10 event handlers which I feel is inefficient.
I have one event handler on the parent of these chat windows and then use event.target to extract the particular values (like I have done in fiddle as shown above). But its side effect is that it also listens to click events other then on the SEND button.

Which strategy to use from above?

I want to know that SEND button of which chat window was pressed i.e. chat window of what index but Ii don't want to give ID to my templates then how do I do it?
this will help me to display that message is coming from which chat window:

  Chat window {index} says: " check the above fiddle

You want to recognize individual/particular group of elements in JavaScript DOM the known ways are:

Provide ids to the elements dynamically before appending in DOM
Provide class names
Provide name attribute or any of your own attributes with some values

Among above which is most recommended?  Or if there is any other way too, then please specify.

In the Fiddle provided above, when you add more than one Chat window and then you type a msg and press SEND, I select all elements with P tag and replace their innerHTML to show message across all windows. As shown above in the handler and Fiddle.

But I know it is unsafe as, if there are other P tags in the page then they too will be screwed.  Can you suggest the best strategy for this?  How can I make sure that only P tags meant to display the chat message have their content changed?


texts:
A challenge from Code Fights; a function that takes a number no less than 10 and that will always have an even number of digits and determines if the sum of the first half of the digits equals the sum of the second half of digits. The function returns a Boolean. Maximum execution time is 4000 milliseconds.

Here is the function:

// tickets are lucky when sum of first half equals sum of second half
const isLucky = n => {
  // min is 10 and we know it's false
  if (n === 10) return false;
  // store digits in an array
  const digitCorral = [];
  // use modulo, division and Math.trunc
  while (n > 0) {
    // push reverses the order but that doesn't matter
    // since the sum of each half will still be the same
    digitCorral.push(n % 10);
    n /= 10;
    n = Math.trunc(n);
  }
  // get sum of first half of array
  const firstHalf = digitCorral
    .slice(0, digitCorral.length / 2)
    .reduce(function(a, b) {
      return a + b;
    });
  // get sum of second half of array
  const secondHalf = digitCorral
    .slice(digitCorral.length / 2, digitCorral.length)
    .reduce(function(a, b) {
      return a + b;
    });
  // return a boolean
  return firstHalf === secondHalf;
};

The function passes all tests, however, I wonder if there is an even more efficient way write it--would recursion be faster? Can the speed of this algorithm be improved?


texts: A tool to extract all links from a web-page in Python

texts:
I'm starting writing in Python and is tasked with writing a simple tool that opens a web-page, collects all the URLs (both complete like http://mail.com and relative ones like /mail/inbox) and returns a list of them prefixed with the domain name. The code is below.

Could someone take a look and advise on what could've been better in terms of the code style, readability, general coding principles and code quality?

Appreciate your help!

import sys, requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse

def main(argv):
    ''' Main '''
    links = []

    try:
        if len(argv) != 3:
            raise IndexError("Not enough arguments.")

        url = argv[2].rstrip('/')
        scheme = urlparse(url).scheme

        if argv[1].upper() in ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE']:
            method = argv[1]
        else:
            raise ValueError("Method %s is not supported." % argv[1])

        r = requests.request(method, url, verify=False) # get the response
        url = r.url.rstrip('/') # if there was a redirect - acquire the URL from the response

        print('[+] Retrieving '+url)
        raw_html = r.content

        soup = BeautifulSoup(raw_html, "html.parser")

        # neat print headers
        print("[+] Received the response HTTP %d" % r.status_code)
        for header in r.headers:
            print(header + ':', r.headers[header])

        # gathering a list of hrefs and srcs
        for script in soup.find_all('script'):
            if not script == None:
                links.append(script.get('src'))
        for anchor in soup.find_all('a'):
            if not anchor == None:
                links.append(anchor.get('href'))
        for link in soup.find_all('link'):
            if not link == None:
                links.append(link.get('href'))
        for form in soup.find_all('form'):
            if not form == None:
                links.append(form.get('action'))

        links = list(filter(None, links)) # removing None src's

        links = [link for link in links if
                 not link[0] == '#' and
                 not urlparse(link).scheme in ['mailto', 'skype'] and
                 not link == '/'] # removing bookmarks, emails and skype and '/'

        links = [scheme + '://' + link[2:] if link[0:2] == '//' else
                 link if urlparse(link).scheme in ['http', 'https'] else
                 url + link if link[0] == '/' else
                 url+'/'+link for link in links] # appending URL value

    except Exception as e:
        print("[-] Something went wrong: %s" % e)

    except KeyboardInterrupt as e:
        print("[x] Exiting by user command")

    print("\n[+] %d Links extracted:" % len(links))
    for link in links:
        print(link)
    return links

if __name__ == "__main__":
    print('[*] Starting the main module')
    main(sys.argv)


texts:
I have written a function splitAtPredicate that splits the list at element x satisfying p, dropping x and returning a tuple.
-- | 'splitAtPredicate', applied to a predicate @p@ and a list @xs@,
-- splits the list at element @x@ satisfying @p@, dropping @x@.
splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])
splitAtPredicate p = splitAtPredicateAcc p []
  where
    splitAtPredicateAcc p left right@(x : xs')
      | null right = (left, right)
      | p x = (left, xs')
      | otherwise = splitAtPredicateAcc p (left ++ [x]) xs'

It works, but I'm new to Haskell, so I'm unsure how idiomatic and performant this is. In addition, I'm not too happy with the name splitAtPredicateAcc. Any suggestions are more than welcome.


texts:
I have a component that I want to render with certain styling based upon the props that it will receive. I'm currently defaulting the prop types, and then creating the styling at render as such:

 getDefaultProps: function(){
  return{
    size: "small",
    shape: "rounded"
  };
},
statics : {

  function getShape(shape){
    if(shape === "rounded"){
      return "59px";
    }else{
      return "2px";
    }
  },
  function getSize(size){
    if(size === "large"){
      return "136px";
    }else if(size==="medium"){
      return "68px";
    }else{
      return "34px";
    }
  }
},
render: function(){

  var borderpx = Avatar.getShape(this.props.shape);
  var imgpx = Avatar.getSize(this.props.size);
  return(
    <img src={this.props.img}  style={{"border-radius" : borderpx, height: imgpx}}  />
  );
}

What I'm trying to figure out:

Is this the correct way to "dynamically" render the style in React?
Is there anything in my code that I could do better?


texts: Generating all possible combinations of a string using iteration

texts:
I am generating all possible combinations from a string concatenated. I have a \$O(n*2^n)\$ solution.

public static String[] combinations(String[] array) {
    String[] res = new String[(1 << array.length) - 1];
    int k = 0;
    int x = 1;
    for (int i = array.length - 1; i >= 0; --i) {
        res[k++] = array[i];
        for (int j = 1; j < x; ++j) {
            res[k++] = array[i] + res[j - 1];
        }
        x *= 2;
    }
    return res;
}

How can this be improved?


texts:
The code does the following:

Gets an array of objects and filters them according to some properties
Returns the array of objects with the filtered data

I'm using the following code which is working and I wonder if there is a way to write it better.

By the way, I can use LodashJS if it's helpful here.

filterNullUndefinedOrRejected: function(oData) {
    if (oData && oData.length > 0) {
        var aNewExtendedObjects = [];
        for (var i = 0; i < oData.length; i++) {
            if (oData[i].va === null || oData[i].val === undefined || oData[i].state === "rejected") {
                if (oData[i].state === "rejected") {
                      console.log(oData[i].error);
                }
                oData.splice(i, 1);
                i--;
            }
            else{
                aNewExtendedObjects.push(oData[i].val);
            }
        }
        return aNewExtendedObjects[0];
    }
    return oData;
},


texts:
Hi I am trying to get into Rust by implementing a small library for vector calculations.

I am mainly asking to point out whether I chose a valid approach. I also am interested in comments on the overall details I might have missed or got the wrong way.

So for my Vec3 implementation I basically declared a custom type which is an array of length 3. Afterwards I am simply implementing Traits for this type. For now I only implemented it for f32.

pub type Vec3<T = f32> = [T; 3];

pub trait Vector3<T> {
    /// Creates a new Vec3 with its values initialized to `[0.0, 0.0, 0.0]`.
    fn new() -> Self;

    /// Creates a new `Vec3` based on the given `x`, `y` and `z` values.
    fn from_values(x: f32, y: f32, z: f32) -> Vec3<T>;

    /// Calculates the scalar dot product of two `Vec3`'s.
    fn dot(a: Vec3<T>, b: Vec3<T>) -> f32;

    /// Performs multiplication between two `Vec3`.
    fn multiply(self, a: Vec3) -> Vec3;

    /// Calculates the sum of two `Vec3` components.Vec3
    fn add(self, a: Vec3) -> Vec3;

    /// Scales a `Vec3` by a scalar value.
    fn scale(self, x: f32) -> Vec3;
}

impl Vector3<f32> for Vec3<f32> {
    /// Creates a new Vec3 with its values initialized to `[0.0, 0.0, 0.0]`.
    ///
    /// ```
    /// use glMatrix_rs::vec3::*;
    ///
    /// let result = Vec3::new();
    /// assert_eq!([0.0, 0.0, 0.0], result);
    /// ```
    fn new() -> Vec3<f32> {
        [0.0, 0.0, 0.0]
    }

    /// Creates a new `Vec3` based on the given `x`, `y` and `z` values.
    ///
    /// ### Arguments
    ///
    /// * `x` - The first vector component.
    /// * `y` - The second vector component.
    /// * `z` - The third vector component.
    ///
    /// ```
    /// use glMatrix_rs::vec3::*;
    ///
    /// let result = Vec3::from_values(0.0, 1.0, 2.0);
    /// assert_eq!([0.0, 1.0, 2.0], result);
    /// ```
    fn from_values(x: f32, y: f32, z: f32) -> Vec3 {
        [x, y, z]
    }

    /// Calculates the scalar dot product of two `Vec3`'s.
    ///
    /// ### Arguments
    ///
    /// * `a` - The first vector for `dot` calculation.
    /// * `b` - The second  vector for `dot` calculation.
    ///
    /// ```
    /// use glMatrix_rs::vec3::*;
    /// let a = Vec3::from_values(2.0, 2.0, 2.0);
    /// let b = Vec3::from_values(2.0, 2.0, 2.0);
    /// assert_eq!(12.0, Vec3::dot(a, b));
    /// ```
    fn dot(a: Vec3, b: Vec3) -> f32 {
        a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
    }

    /// Performs multiplication between two `Vec3`.
    ///
    /// ### Arguments
    ///
    /// * `a` - Vector by which `self` will be multiplied.
    ///
    /// ```
    /// use glMatrix_rs::vec3::*;
    /// let mut out = Vec3::new();
    /// let a = Vec3::from_values(1.0, 2.0, 3.0);
    /// let b = Vec3::from_values(2.0, 2.0, 2.0);
    /// assert_eq!([2.0, 4.0, 6.0], a.multiply(b));
    /// ```
    fn multiply(self, a: Vec3) -> Vec3 {
        [self[0] * a[0], self[1] * a[1], self[2] * a[2]]
    }

    /// Calculates the sum of two `Vec3` components.Vec3
    ///
    /// ### Arguments
    ///
    /// * `a` - Vector which will be added to `self`.
    ///
    /// ```
    /// use glMatrix_rs::vec3::*;
    /// let x = Vec3::from_values(1.0, 2.0, 3.0);
    /// let a = Vec3::from_values(3.0, 2.0, 1.0);
    /// assert_eq!([4.0, 4.0, 4.0], x.add(a));
    /// ```
    fn add(self, a: Vec3) -> Vec3 {
        [self[0] + a[0], self[1] + a[1], self[2] + a[2]]
    }

    /// Scales a `Vec3` by a scalar value.
    ///
    /// ### Arguments
    ///
    /// * `x` - Scalar value by which the vector will be scaled.
    ///
    /// ```
    /// use glMatrix_rs::vec3::*;
    /// let a = Vec3::from_values(1.0, 2.0, 3.0);
    /// assert_eq!([2.0, 4.0, 6.0], a.scale(2.0));
    /// ```
    fn scale(self, x: f32) -> Vec3 {
        [self[0] * x, self[1] * x, self[2] * x]
    }
}

You can clone, build and test it any time from my GitHub repository.


texts: Using Bluebird with fs to read a file within each of an (variable length) array of directories

texts:
I'm reading an array (of unknown length) of modules package.json files in order to extract the "style" property and store it in an array of its own:

var gulp = require('gulp')
  , path = require('path')
  , Promise = require('bluebird')
  , fs = Promise.promisifyAll(require('fs-extra'));

let components = [
    'comp1',
    'comp2',
    'comp3'
];
let npmScope = '@myscope';
gulp.task('getstyle', () => {
    let componentsBaseLocation = path.join(__dirname, 'node_modules', npmScope);
    Promise.map(components, (componentName) => {
        return fs.readFileAsync(path.join(componentsBaseLocation, componentName, 'package.json'), 'utf8')
    })
    .spread((...packageData) => {
        return packageData.map((packageDatum, i) => {
            packageDatum = JSON.parse(packageDatum);
            tempName = packageDatum.name.match(new RegExp(`${NpmScope}\/(.*?)$`))[1]
            tempStyle = path.join(componentsBaseLocation, tempName, packageDatum.style);
            return {
                name: tempName,
                style: tempStyle
            };
        });
    })
    .then(components => {
        console.log(JSON.stringify(components, null, 2));
    });
});

This works, but I wonder if there are smarter, better, more appropriate ways to use bluebird or promises in general.


texts:
I am building an ad-hoc text-editor. I have two functions which use a cache, provideHover and provideCompletionItems.

"use strict";

import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
const $ = require("jquery");
const urlResolve = require("url-resolve");

const AUTOCOMPLETE_ENDPOINT = "http://localhost:7000/";
const LRU = require("lru-cache");

const options = {
    max: 500,
    length: (suggestions, key) => { return suggestions.length }
};

const cache = new LRU(options);
const definition_cache = new LRU(options);

(function () {
    // create div to avoid needing a HtmlWebpackPlugin template
    const div = document.createElement('div');
    div.id = 'root';
    div.style = 'width:800px; height:600px; border:1px solid #ccc;';
    document.body.appendChild(div);
})();

monaco.editor.create(
    document.getElementById('root'),
    {
        value: ``,
        language: 'python',
        theme: 'vs-dark'
    }
);

const getCompletions = (text) => {
    return $.ajax({
        url: urlResolve(AUTOCOMPLETE_ENDPOINT, "suggestion"),
        type: 'GET',
        "data": {
            "text": text
        }
    });
};

const getDocumentation = (cursorInfo) => {
    const line = cursorInfo.line;
    const column = cursorInfo.column;
    const text = cursorInfo.text;
    return $.ajax({
        url: urlResolve(AUTOCOMPLETE_ENDPOINT, "documentation"),
        type: 'GET',
        "data": {
            "line": line,
            "column": column,
            "text": text,
            "highlighted": cursorInfo.highlighted
        }
    });

}

monaco.languages.registerHoverProvider("python", {
    provideHover: async (model, position) => {
        const lineNumber = position.lineNumber;
        const snippet = model.getWordAtPosition(position);
        const text = model.getValueInRange({ startLineNumber: 1, startColumn: 1, endLineNumber: position.lineNumber, endColumn: snippet.endColumn });
        if (definition_cache.has(text)) {
            console.log("hit");
            return {
                contents: [{ value: definition_cache.get(text) }]

            }
        }

        const response = await getDocumentation({ "line": lineNumber, "column": snippet.endColumn, "text": text, "highlighted": snippet.word });
        definition_cache.set(text, response.documentation);
        return {
            contents: [{ value: response.documentation }]
        }
    }
});

monaco.languages.registerCompletionItemProvider('python', {
    provideCompletionItems: async (model, position) => {
        const text = model.getValueInRange({ startLineNumber: 1, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column });
        if (cache.has(text)) {
            const suggestions = cache.get(text);
            return {
                "suggestions": suggestions
            };

        }

        const completions = await getCompletions(text)
        const suggestions = completions.map(c => ({
            label: c.name,
            insertText: c.name
        }));

        cache.set(text, suggestions)

        return {
            "suggestions": suggestions
        };

    }
});

As it stands, the introduction of the cache makes the code quite ugly (in my opinion). I'd like to refactor it so that I have only one cache usage that applies in both situations -- something like a Python decorator.

How do I make the code cleaner?


texts:
This command line program applies defined labels along with Monday's date to a directory of images.

The script has to handle not being run on a Monday. Others are asking for the script so I cleaned it up as much as I could. I want to make it as friendly and as cross-platform as possible.

Labels should be applied just above where the white border region ends. I couldn't guarantee that the border region would always be white, nor how big the border region could be.

Any tips on making it shorter, more elegant, more user-friendly or more resilient would be helpful. I'm considering moving the conditions and text of the actual labels to a separate text file for more flexibility.

import os
import datetime
from datetime import timedelta
import argparse
import glob
import PIL
from PIL import Image, ImageFont, ImageDraw

path_sep = os.path.sep

def get_date_string(optionalArg):
    #return date of most recent Monday
    # or optional date param given by user.
    if optionalArg is not None:
        return optionalArg
    else:
        today = datetime.datetime.today()
        if today.weekday() == 0:
            t = today
        else:
            t = today - timedelta(days=today.weekday())
        return t.strftime("%m/%d/%Y")

def significant_difference(v, previous_v):
    return abs(sum(v) - sum(previous_v)) > 200

def find_v_border(png):
    h = png.height
    png_ims = png.load()
    x = png.width/2
    last_v = png_ims[x,h-1]
    # walk up image from bottom, one pixel at a time.  when color changes, identify that as the place to write text:
    for y in range(h-1,0,-1):
        v = png_ims[x,y]
        if significant_difference(v,last_v):
            return y
        last_v = v

def find_left_border(png,bottom_border):
    png_ims = png.load()
    last_v = png_ims[1,bottom_border]
    for x in range(1,png.width/2):
        v = png_ims[x,bottom_border]
        # when big difference between v and last v, then return x
        if significant_difference(v,last_v):
            return x
        last_v = v

def draw_on_image(raw_img, new_img,date_text):
    global path_sep
    font_size = 16
    png = Image.open(raw_img)
    offset = font_size + 3
    bottom_border = find_v_border(png) - offset
    right_border = find_left_border(png,bottom_border) + 3
    fg="#000000"
    ttfpath = os.path.dirname(PIL.__file__)

    fnt = PIL.ImageFont.truetype(ttfpath + path_sep +'OpenSans-Bold.ttf',font_size)
    draw = PIL.ImageDraw.Draw(png)
    draw.text((right_border,bottom_border), date_text,font=fnt, fill=fg)
    del draw
    png.save(new_img, "PNG",quality=100)

# accept arguments for image file directory and optional date string
parser = argparse.ArgumentParser(description='Process given image.')
parser.add_argument('-p', help='path in which to find images to mark up...', required=True)
parser.add_argument('--d', help='optional to add date you want displayed')
args = parser.parse_args()
image_path = args.p

#path references start from current directory
image_path = os.path.abspath(os.curdir) + path_sep + image_path

image_date = get_date_string(args.d)

    # read all the png files in image_path:

all_files = glob.glob(image_path + path_sep +'*.png')
for file_name in all_files:
    #parse file name to determine text ("Server, Desktop, or All")
    if "server" in str.lower(file_name):
        text = " Server Systems"
        new_file_name =  "labelled_server.png"
    elif "desktop" in str.lower(file_name):
        text = " Desktop Desktop"
        new_file_name = "labelled_Desktop.png"
    else:
        text = " All Systems"
        new_file_name = "labelled_all.png"

    img_text = image_date + text
    new_file_name = image_path + path_sep +new_file_name

    draw_on_image(os.path.join(image_path,file_name),new_file_name,img_text)

print("{0} files labelled with {1}".format(len(all_files),image_date))


texts:
I have two style of code but don't know which is better or maybe you could recommend the better one.

The good part of first one is every if else branches return something and the process will stop at there but the bad part is even the Captcha is invalid I still need to query the DisalbeUser() and BlackList()

        bool isValidateCaptcha = ValidateCaptcha();

        bool isDisableUser = DisableUser();

        bool isInblackList = BlackList();

        if (isValidateCaptcha)
        {
            return Ok(new
            {
                IsSuccess = false,
                InvalidCode = LoginInvalidCode.CaptchaInvalid
            });
        }
        else if (isDisableUser)
        {
            return Ok(new
            {
                IsSuccess = false,
                InvalidCode = LoginInvalidCode.DisableAccountAndInDisableGroup
            });
        }
        else if (isInblackList)
        {
            return Ok(new
            {
                IsSuccess = false,
                InvalidCode = LoginInvalidCode.InLoginBlackList
            });
        }
        else
        {
            return Ok(new
            {
                IsSuccess = true,
            });
        }

And the second style is like below

        bool isValidateCaptcha = ValidateCaptcha();

        if (isValidateCaptcha)
        {
            return Ok(new
            {
                IsSuccess = false,
                InvalidCode = LoginInvalidCode.CaptchaInvalid
            });
        }

        bool isDisableUser = DisableUser();

        if (isDisableUser)
        {
            return Ok(new
            {
                IsSuccess = false,
                InvalidCode = LoginInvalidCode.DisableAccountAndInDisableGroup
            });
        }

        bool isInblackList = BlackList();

        if (isInblackList)
        {
            return Ok(new
            {
                IsSuccess = false,
                InvalidCode = LoginInvalidCode.InLoginBlackList
            });
        }

        return Ok(new
        {
            IsSuccess = true,
        });


texts:
The hard drive in my dev box is running out of space so I wrote this little script to try and free up space until I get a new drive.

My Concerns

Is the code pythonic?
Does the code go against any best practices?

import glob
import os
import psutil
import shutil

PATHS = ['/var/log/*', '/tmp/*', '/home/ricky/Downloads/']

USAGE = psutil.disk_usage('/').percent

if os.geteuid() != 0:
    exit("You need to have root privileges to run this script.")

def flatten(alist):
    if alist == []:
        return []
    elif type(alist) is not list:
        return [alist]
    else:
        return flatten(alist[0]) + flatten(alist[1:])

if __name__ == '__main__':
    for path in flatten(map(glob.glob, PATHS)):
        if os.path.isfile(path):
            os.remove(path)
        if os.path.isdir(path):
            shutil.rmtree(path)

    print "Usage Before {}\nUsage After {}".format(USAGE, psutil.disk_usage('/').percent)

Example Output:

ricky@ricky-OptiPlex-330:~/Projects/Python
$ sudo python cleanup.py
Usage Before 83.5
Usage After 82.1


texts: Simple Tic-Tac-Toe game in Javascript (NO A.I.)

texts:
After some hours of coding trying to implement "algorithms" to make a Tic-Tac-Toe game, I came up with something I'm not really proud of.

Here's the code:

const TicTacToe = (function(){

    const grids = document.querySelectorAll(".box");
    const winning_combinations = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    let turn = 'X';
    let marks = 0;
    let currPos = void 0;

    for(let i = 0, len = grids.length; i < len; ++i)
        grids[i].addEventListener("click", () => mark( (currPos=i) )  );

    function mark(pos){
        if(grids[currPos].textContent != '')
            return alert("grid taken!");

        grids[currPos].textContent = turn;

        if(!foundWinner())
            turn = (turn === 'X') ? 'O' : 'X';
        else
            win();

    }

    function foundWinner(){

        for(let currSet = 0, len = winning_combinations.length; currSet < len; ++currSet){

            winning_combinations[currSet].forEach(pos => {
                if(grids[pos].textContent == turn){
                    marks++;
                }
            });

            if(marks == 3){
                return true;
            }
            else{
                marks = 0;
            }
        }

        return false;

    }

    function win(){
        return alert(turn + " won!");
    }

    return{
        reset: function(){
            // todo
        }
    }

}) ();

The issue is that I am pretty sure this code has O(n log n) time complexity, and I would love to make it at least O(n). I've tried creating possible combinations based on what grid the player pressed—opposed to trying all the winning combinations—but no avail.

If there is any way I can better this code or make it more efficient, please let me know!


texts:
I've created a singleton by means of an interface. I don't want to make a thing with getInstance() etc because I don't care about inheritance, and it's redundant and non-declarative.

Are there downsides of doing it this way? Any redundancy I can remove? Is there a cleaner/more consise way to do this? I like doing it this way because methods are first class because I can pass them to map etc (e.g: map(Dog.sleep, someListOfNumbers)) and it supports currying if you have functions like F<Pair<X,Pair<Y,Z>>>.

Note the F interface is declared elsewhere, I just inlined it here to have less files.

package a;
import static a.Dog.State.*;
public interface Dog {
    interface F<X,Y> {
        Y f(X x);
    }

    static final class State {
        protected static boolean dead;
        protected static String name = "leo";
        protected static Integer age = 0;
    }

    F<Void,String> getName = new F<Void,String>() {
        public String f(Void _) {
            return name;
        }
    };

    F<Void,Void> die = new F<Void,Void>() {
        public Void f(Void _) {
            System.out.println("X_X");
            dead = true;
            return null;
        }
    };

    F<Void,Void> woof = new F<Void,Void>() {
        public Void f(Void _) {
            if (dead)
                throw new IllegalStateException("cannot woof when dead");
                System.out.println("woof");
            return null;
        }
    };

    F<Integer,Void> sleep = new F<Integer,Void>() {
        public Void f(Integer years) {
            if (dead)
                throw new IllegalStateException("cannot sleep when dead");
            age += years;
            return null;
        }
    };

    F<Void,Integer> getAge = new F<Void,Integer>() {
        public Integer f(Void _) {
            return age;
        }
    };
}

A test:

import a.Dog;
class Main {
    public static void main(String[] args) {
      System.out.println(
          "The dog's name is " + Dog.getName.f(null) +
          " and is " + Dog.getAge.f(null) + " years old"
      );
      Dog.sleep.f(2);
      System.out.println(
          "The dog's name is " + Dog.getName.f(null) +
          " and is " + Dog.getAge.f(null) + " years old"
      );
      Dog.woof.f(null);
      Dog.die.f(null);
      Dog.woof.f(null);
    }
}


texts:
I would like to see if the working code below can be written more elegantly. I am assuming there is a way to parse out the "r" and "h" to condense it down into a function. Any help is much appreciated for learning purposes. There are no parent/sibling relationships in the ID's.

    $('#r1_1').hoverIntent(function(){
        $('#h1_1').toggleClass('vis');
    });
    $('#r1_2').hoverIntent(function(){
        $('#h1_2').toggleClass('vis');
    });
    $('#r1_3').hoverIntent(function(){
        $('#h1_3').toggleClass('vis');
    });
    $('#r1_4').hoverIntent(function(){
        $('#h1_4').toggleClass('vis');
    });
    $('#r1_5').hoverIntent(function(){
        $('#h1_5').toggleClass('vis');
    });
    $('#r2_1').hoverIntent(function(){
        $('#h2_1').toggleClass('vis');
    });
    $('#r2_2').hoverIntent(function(){
        $('#h2_2').toggleClass('vis');
    });
    $('#r2_3').hoverIntent(function(){
        $('#h2_3').toggleClass('vis');
    });
    $('#r2_4').hoverIntent(function(){
        $('#h2_4').toggleClass('vis');
    });
    $('#r2_5').hoverIntent(function(){
        $('#h2_5').toggleClass('vis');
    });
    $('#r3_1').hoverIntent(function(){
        $('#h3_1').toggleClass('vis');
    });
    $('#r3_2').hoverIntent(function(){
        $('#h3_2').toggleClass('vis');
    });
    $('#r3_3').hoverIntent(function(){
        $('#h3_3').toggleClass('vis');
    });
    $('#r3_4').hoverIntent(function(){
        $('#h3_4').toggleClass('vis');
    });


texts:
In PHP exists a function array_diff (http://php.net/manual/de/function.array-diff.php) which returns the difference of two arrays.
I have tried the implement my own version in JavaScript.

Any feedback is welcome. :)

function getArrayDiff(a, b) {
  var ret = [],
      merged = [];

  merged = a.concat(b);

  for (var i = 0; i < merged.length; i++) {
    // When the element is contained ONLY
    //   one time then the search from
    //   left returns the same value as
    //   the search from the right.
    if (merged.indexOf(merged[i]) ==
        merged.lastIndexOf(merged[i])) {
      // ... in that case the element
      // is pushed to the result array.
      ret.push(merged[i]);
    }
  }

  return ret;
}

// -- Test ----------
a = [2, 4, 8, 16, 32];
b = [2, 4, 32, 64, 128, 256];

console.log(getArrayDiff(b, a));

Live Demo on CodePen:
http://codepen.io/mizech/pen/GpVMEd


texts:
My application has two parts -- a client and a server.  Within this, there are different versions for different platforms.  The user specifies this in the args, i.e. "make PLATFORM=x11".

However, I feel like I'm separating the client and server build operations in a very inefficient way, and that I have too many variables.  It works, but I'm not sure how to improve it.

Any suggested improvements would be much appreciated!

CC=gcc
CFLAGS=-c -Wall
LDFLAGS=
BUILD_DIR = ../build/
OBJ_DIR = $(BUILD_DIR)obj/
LIBS=

CLIENT_NAME_DIR = client/
CLIENT_SRC_FILES := $(wildcard $(CLIENT_NAME_DIR)*.c)
CLIENT_PLATFORM_DIR = $(PLATFORM)/
CLIENT_SRC_FILES += $(wildcard $(CLIENT_NAME_DIR)$(CLIENT_PLATFORM_DIR)*.c)
CLIENT_OBJ_DIR = $(OBJ_DIR)$(CLIENT_NAME_DIR)
CLIENT_OBJ_FILES := $(addprefix $(CLIENT_OBJ_DIR),$(notdir $(CLIENT_SRC_FILES:.c=.o)))
CLIENT_LIBS = $(LIBS) -lX11
CLIENT_EXECUTABLE_NAME = outcast-client
CLIENT_EXECUTABLE=$(BUILD_DIR)$(CLIENT_EXECUTABLE_NAME)

SERVER_NAME_DIR = server/
SERVER_SRC_FILES := $(wildcard $(SERVER_NAME_DIR)*.c)
SERVER_OBJ_DIR = $(OBJ_DIR)$(SERVER_NAME_DIR)
SERVER_OBJ_FILES := $(addprefix $(SERVER_OBJ_DIR),$(notdir $(SERVER_SRC_FILES:.c=.o)))
SERVER_LIBS = $(LIBS)
SERVER_EXECUTABLE_NAME = outcast-server
SERVER_EXECUTABLE=$(BUILD_DIR)$(SERVER_EXECUTABLE_NAME)

all: clean client server

client: $(CLIENT_SRC_FILES) $(CLIENT_EXECUTABLE)

server: $(SERVER_SRC_FILES) $(SERVER_EXECUTABLE)

$(CLIENT_EXECUTABLE): $(CLIENT_OBJ_FILES)
    $(CC) $(LDFLAGS) $(CLIENT_OBJ_FILES) -o $@ $(CLIENT_LIBS)

$(CLIENT_OBJ_DIR)%.o: $(CLIENT_NAME_DIR)$(CLIENT_PLATFORM_DIR)%.c
    $(CC) $(CFLAGS) -c -o $@ $<

$(CLIENT_OBJ_DIR)%.o: $(CLIENT_NAME_DIR)%.c
    $(CC) $(CFLAGS) -c -o $@ $<

$(SERVER_EXECUTABLE): $(SERVER_OBJ_FILES)
    $(CC) $(LDFLAGS) $(SERVER_OBJ_FILES) -o $@ $(SERVER_LIBS)

$(SERVER_OBJ_DIR)%.o: $(SERVER_NAME_DIR)%.c
    $(CC) $(CFLAGS) -c -o $@ $<

clean:
    rm -rf $(BUILD_DIR)
    mkdir -p $(CLIENT_OBJ_DIR)
    mkdir -p $(SERVER_OBJ_DIR)


texts:
I have written a program that calculates the "cost" of transforming one string into another. I would like you to review it.

public class EditDistance {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String source="COTI",destination ="CAT";
        System.out.println(getEditDistance(source,destination));
    }

    /**
     * This function finds out the cost of transforming one string to
     * another
     * any change made to the string costs 1
     * @param sourceString
     * @param destinationString
     * @return
     */
    public static int getEditDistance(String sourceString, String destinationString) {

if (sourceString == null || destinationString == null){
            throw new IllegalArgumentException("String cannot be null");
        }

        int distance = 0;
        int sourceLength = sourceString.length() , destLength = destinationString.length();

        for ( int i=0 ;i < sourceLength && i < destLength ; i++){
            //how can I optimize loop condition, 3 conditions are checked on
            //every iteration
            if (sourceString.charAt(i) != destinationString.charAt(i)){
                //if characters are unequal and increment the distance
                distance++;
            }
        }
        if (destLength !=  sourceLength ){
            distance += Math.abs(sourceLength - destLength);
        }
        return distance;
    }
}

However, I would like to optimize the loop condition. Currently, 3 operations are done.

What can I do to speed it up or make it more elegant?


texts:
I'm implementing a stack by C++ and here I think it has memory leakage problem: in Stack::peek() and Stack::pop(), where I created heap space and returned pointer to function caller.

Users who call these two functions may perform deletion on returned pointer, which will recycle heap space once done. I am wondering what is a better approach to my current leakage prone approach.

Header file:

// this is the header file of stack data structure.

#ifndef MY_STACK_H
#define MY_STACK_H

class Node
{
private:
    int number;
    Node * next;

public:
    Node(){number = 0; next = NULL;}

    Node(int initialNumber, Node * initialNext = NULL)
    {
        number = initialNumber;
        next = initialNext;
    }

    // copy constructor
    Node(Node & copyFromNode)
    {
        this->number    =   copyFromNode.getNumber();
        this->next      =   copyFromNode.getNext();
    }

    // setters & getters
    int getNumber() {return number;}
    Node * getNext()    {return next;}
    void setNumber(int newNumber)   {number = newNumber;}
    void setNext(Node * newNext)    {next = newNext;}
};

class LinkedList
{
private:
    Node * head;

public:
    LinkedList(){head = NULL;}

    // very similar to Stack::push()
    void addFirst(Node *newNode)
    {
        newNode->setNext(head);
        head = newNode;
    }

    // somehow similar to Stack::pop()
    void deleteFirst()
    {
        if (head == NULL)
            return;
        else
        {
            Node * temp = head;
            head = head->getNext();
            delete temp;
        }
    }

    bool isEmpty()      {return (head == NULL);}
    Node * getHead()    {return head;}

    // there is no setter to head
    // since head should be maintained by addFirst() & deleteFirst() only.
};

class Stack
{
private:
    Node * top;
    LinkedList ll;
public:
    Stack(){top = NULL; }

    // push new node to the stack
    // new node will become the new top of stack
    void push(Node * newNode);

    // it checks if the stack is empty or not.
    bool isEmpty();

    // it copies the top node on stack,
    // without deleting it.
    Node * peek();

    // it copies the top node on stack,
    // and deletes the node from stack.
    Node * pop();
};

#endif

.cpp file:

// implementation for the stack

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

using namespace std;

void Stack::push(Node * newNode)
{
    ll.addFirst(newNode);
    top = ll.getHead();
}

bool Stack::isEmpty()
{
    if(top == NULL)
        return true;
    else
        return false;
}

Node * Stack::peek()
{
    // make a copy, erase next link and return
    // copy is made by calling copy construtor
    Node * copy = new Node(*top);   // ?? asks for reference but pointer is given

    return copy;
}

Node * Stack::pop()
{
    if (isEmpty())
        return NULL;
    else
    {
        Node * copy = new Node(*top);
        ll.deleteFirst();
        top = ll.getHead();
        return copy;
    }
}

int main()
{
    Stack stack;

    Node * nd1 = new Node(100);
    Node * nd2 = new Node(200);

    // test push()
    stack.push(nd1);
    stack.push(nd2);

    // test isEmpty()
    cout<<"Test: isEmpty(): "<< stack.isEmpty()<<endl;

    // test peek()
    cout<<"Test: peek(): "<<stack.peek()->getNumber()<<endl;

    // test pop()
    cout<<"Test: pop()"<<stack.pop()->getNumber()<<endl;
    cout<<"Test: pop()"<<stack.pop()->getNumber()<<endl;

    cout<<"Test: isEmpty(): "<<stack.isEmpty()<<endl;

    return 0;
}


texts: Getting the lengths of each word in its String parameter

texts:
Is this a smart method?

public static ArrayList<Integer> getWordLengths( String s )
{

    String str = " " + s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    for ( int i = 0; i < str.length(); i++ )
    {
        if ( str.charAt(i) == ' ' )
        {
            for ( int j = i+1; j < str.length() ; j++)
            {
                if ( str.charAt(j) == ' ')
                {
                    list.add( j - i - 1 );
                    j = str.length();
                }
            }
        }
    }
    return list;
}

Sample output:

System.out.println( getWordLengths("This is really easy"));

[4, 2, 6, 4]

so it worked.

We are only allowed to use length and charAt from the String class.


texts: Finding the names of students with the second-lowest score

texts:
I'm teaching myself programming.

I would like to know how I could make this Python3 could more flexibile, for example if I wanted to find students with the 3rd lowest grade, or the lowest, or any other value. Based on this piece of code (that it took me awhile to fathom out) I'm not convinced Python is the best tool for this task.
It uses the data structure it does because the task brief I was working on requested that I use nested lists.

#! /usr/bin/env python3

# Number of student records to expect
n = int(input())

# Take inp of n student records, store in format [[name, score], [name, score], ...]
students = [[input(), float(input())] for studentrecord in range(n)]

# Sort records by score, ascending. Using float else defaults to lexicographical order.
students.sort(key=lambda studentrecord: float(studentrecord[1]))

# Get the lowest mark achieved
lowest_mark = students[0][1]

# Get ind of second lowest scoring student
ind = 0
while students[ind][1] == lowest_mark:
    ind += 1

# Get the second lowest mark achieved
second_lowest_mark = students[ind][1]

second_lowest_scoring_students = []

# Accumulate list of second lowest scoring students.
while students[ind][1] == second_lowest_mark:
    second_lowest_scoring_students.append(students[ind][0])
    ind += 1
    if ind == n: # If iteration reaches the end of the list of records, end.
        break

# Sort name/s alphabetically.
second_lowest_scoring_students.sort()

# Send results to stdout.
for student_name in second_lowest_scoring_students:
    print(student_name)


texts: Resizing and recoloring a logo using PHP GD Library

texts:
I have the following code, that works very well. However I'm about to launch it to 5000 users and will no doubt take a beating early on. I want to ensure that if there are any opportunities to streamline so the code executes better or faster, that I do not miss them.

I've only pasted the PHP GD portion of the code, as the rest of my page is fine (some basic HTML)

$position = strpos($size, 'x');
$width = substr($size,0,$position);
$height = substr($size,$position+1);

$logo_image = imagecreatefrompng($image);
imagealphablending( $logo_image, false );
imagesavealpha( $logo_image, true );

$logo_width = imagesx($logo_image);
$logo_height = imagesy($logo_image);

if(($width>=601)&&($width<=1080)) {
    $percent = $width/$logo_width;
} elseif($width>=1081) {
    $percent = 1.2;
    $font_size = 28;
}

$logo_new_width = $logo_width*$percent;
$logo_new_height = $logo_height*$percent;

$base_image = imagecreatetruecolor($width, $height);

$logo_x = (($width/2)-($logo_new_width/2));
$logo_y = (($height/2)-($logo_new_height/2));

$text_box = imagettfbbox($font_size,$angle,$font,$text);
$text_width = $text_box[2]-$text_box[0];
$text_height = $text_box[3]-$text_box[1];

$x = ($width/2) - ($text_width/2);
if($height==768) {
    $y = (($height/2)+($logo_new_height/2));
} else {
    $y = (($height/2)+($logo_new_height));
}

//set overall background color here based on user selection
if($theme=='plum') {
    $fill_color = imagecolorallocate($base_image, 93, 62, 93);
} elseif($theme=='black') {
    $fill_color = imagecolorallocate($base_image, 0, 0, 0);
} elseif($theme=='white') {
    $fill_color = imagecolorallocate($base_image,255,255,255);
} elseif($theme=='gray') {
    $fill_color = imagecolorallocate($base_image,149,150,153);
} elseif($theme=='charcoal') {
    $fill_color = imagecolorallocate($base_image,78,80,84);
} elseif($theme=='warm') {
    $fill_color = imagecolorallocate($base_image,255,79,31);
}

//Set the Text Color
if($textC=='black') {
    $text_color = imagecolorallocate($base_image,0,0,0);
} elseif($textC=='red') {
    $text_color= imagecolorallocate($base_image,255,79,31);
} elseif($textC=='white') {
    $text_color = imagecolorallocate($base_image,255,255,255);
} elseif($textC=='plum') {
    $text_color = imagecolorallocate($base_image, 93, 62, 93);
} elseif($textC=='gray') {
    $text_color = imagecolorallocate($base_image,78,80,84);
}

imagefill($base_image, 0, 0, $fill_color);
imagesavealpha($base_image, TRUE);

//set text color here
imagettftext($base_image,$font_size+1,0,$x,$y,$text_color,$font,$text );

imagecopyresampled($base_image, $logo_image, $logo_x, $logo_y, 0, 0,$logo_new_width, $logo_new_height, $logo_width, $logo_height);

$num_str = "";
$charsRand = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<6;$i++)
    $num_str.=substr($charsRand,rand(0,strlen($charsRand)),1);

$filename_create = substr($text,0,strpos($text, ".")).'_'.$num_str.'.png';
imagepng($base_image,'images_created/'.$filename_create,1);
$file_size = filesize('images_created/'.$filename_create);

Did I do anything that will cause me grief? Any tips for me to optimize this portion of the code ?

Look forward to any and all comments. This was my first go around with GD.


texts: Listing all the chars in a given UnicodeBlock

texts:
I want to visually inspect all the characters that Java thinks are in any given UnicodeBlock. The following method, as far as I can tell, does the task. But, it sure feels like awful design.

public static void displayUnicodeBlock(Character.UnicodeBlock block) {
    int maxCharVal = (int) Math.pow(2, 16);
    for(int cInt = 0; cInt <= maxCharVal; cInt++) {
        char c = (char) cInt;
        if(Character.UnicodeBlock.of(c) == block) {
            System.out.println("_" + c + "_");
        }
    }
}

Would reflection be the ideal solution?
Can reflection actually show every character in a UnicodeBlock? How?
My solution is stupid because it is inefficient?
My solution is stupid because it is hardwired with 2^16?


texts: A static Java method for multi-indexing a collection

texts:
I have this small utility for selecting from a collection via multiple indices at one method invocation:

MultiIndexUtils.java

package net.coderodde.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public final class MultiIndexUtils {

    private MultiIndexUtils() {}

    public static <T> List<T> multiIndex(Collection<T> collection,
                                         Collection<Integer> indices) {
        List<T> indexedElements = new ArrayList<>(indices.size());
        T[] array = (T[]) collection.toArray();
        indices.forEach((Integer index) -> {
            indexedElements.add(array[index]);
        });
        return indexedElements;
    }

    public static <T> List<T> multiIndex(Collection<T> collection,
                                         Integer... indices) {
        return multiIndex(collection, Arrays.asList(indices));
    }

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("A", "B", "C", "D", "E", "F");
        System.out.println(multiIndex(strings, 1, 0, 3, 2, 0, 5, 4));
    }
}

Critique request

I would like to hear anything that comes to mind.


texts: Implementation of a linear congruential generator

texts:
Here's a simple LCG that I've made to learn a bit more about pseudo random number generation.

Is this implementation correct, and if so, how can I improve it further?

The following code is self contained and it should run without problems.

#include <chrono>
#include <iostream>
#include <map>

namespace Random {
    class LCG {
        static constexpr uint64_t const A = 0x5851F42D4C957F2D;
        static constexpr uint64_t const C = 0x14057B7EF767814F;
        static constexpr uint64_t const M = 0xFFFFFFFFFFFFFFFF;

        uint64_t this_seed;

        auto now() noexcept {
            using namespace std::chrono;
            auto const output = high_resolution_clock::now();
            return output.time_since_epoch().count();
        }

    public:
        LCG() noexcept
            : this_seed(now()) {
        }

        LCG(uint64_t const value) noexcept
            : this_seed(value) {
        }

        void seed() noexcept {
            this_seed = now();
        }

        void seed(uint64_t const value) noexcept {
            this_seed = value;
        }

        // [0, 2 ^ 64 - 1)
        auto next() noexcept {
            this_seed = (this_seed * A + C) & M;
            return this_seed;
        }

        void discard(uint64_t const amount) noexcept {
            for (uint64_t i = 0; i != amount; ++i) {
                next();
            }
        }

        // [0, 1)
        double get() noexcept {
            return static_cast<double>(next()) / M;
        }

        // x - 0 == (-1 | 0 | 1) ? 0 : x > 0 ? [0, x) : (x, 0]
        int64_t get(int64_t const x) noexcept {
            return static_cast<int64_t>(get() * x);
        }

        // b - a == (-1 | 0 | 1) ? 0 : b > a ? [a, b) : (b, a]
        int64_t get(int64_t const a, int64_t const b) noexcept {
            return a + static_cast<int64_t>(get() * (b - a));
        }
    };
}

int main() {

    Random::LCG lcg(0);
    std::map<int64_t, uint64_t> buckets;
    for (uint64_t i = 0; i != 1000000; ++i) {
        ++buckets[lcg.get(10)];
    }
    for (auto const [a, b] : buckets) {
        std::cout << a << '\t' << b << '\n';
    }

    return 0;
}


texts:
I write this program that checks if a file is executable, and if so, to check if it is an ELF binary or a shell script.
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>

int Search_in_File(char *fname, char *str);

int main(int argc, char **argv)
{
    if(argc < 2){
        printf("The path to the file is\n");
        return 1;
    }

    struct stat fileStat;

    if(stat(argv[1],&fileStat) < 0){
        printf("error\n");
        return 1;
    }

    if(S_ISREG(fileStat.st_mode)){
        if(fileStat.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
        {
            printf("The file is executable ");
            Search_in_File(argv[1], "#!");
            Search_in_File(argv[1], "ELF");
        }
        else
        {
            printf("The file is not executable.\n");
        }
    }
    else
        printf("Not a file\n");
    return 0;
}

int Search_in_File(char *fname, char *str) {
    FILE *fp;
    char temp[512];

    if((fp = fopen(fname, "r")) == NULL) {
        return(-1);
    }

    while(fgets(temp, 512, fp) != NULL) {
        if((strstr(temp, str)) != NULL) {
            if(strcmp(str, "#!")==0)
                printf("shell type.");
            else if(strcmp(str, "ELF")==0)
                printf(" ELF.");
        }
    }
    printf("\n");
    if(fp) {
        fclose(fp);
    }
    return(0);
}


texts:
I am solving the well known problem Remove Nth Node From End of List:

  Given a linked list, remove the n-th node from the end of list and
  return its head. Assume that n is between 0 and the length of the list.

  Example:

Given:  1->2->3->4->5, and n = 2
Return: 1->2->3->5.

This is my solution:

public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || n == 0)
            return head;
        ListNode slow = head;
        ListNode fast = head;
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode pre = newHead;
        int steps = 1;
        while(steps <= n){
            fast = fast.next;
            steps++;
        }
        if(fast == null)
            return head.next;
        while(fast.next != null){
            pre = pre.next;
            slow = slow.next;
            fast = fast.next;
        }
        if(slow.next != null)
            slow.next = slow.next.next;
        else // slow.next = null, i.e. I have to remove the last node
            pre.next = null;
        return head;
    }

and this is the definition of ListNode class:

public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }

What I don't like in my code is that I handle every edge case separately. Is there more sophisticated way to deal with the edge cases? Also the following code fragment:

       while(steps <= n){
            fast = fast.next;
            steps++;
        }

Is this the right condition for traversing the list? This definitely works, but is it better to rewrite my code in terms of

      while(steps < n){
            fast = fast.next;
            steps++;
      }


texts:
I was going through the Project Euler problem #3 and made a program to solve it. The problem is as follows:

  The prime factors of 13195 are 5, 7, 13 and 29. What is the largest
  prime factor of the number 600851475143 ?

My code is as follows:

#include<iostream>
#include<vector>
using std::cout;
using std::endl;
using std::vector;
typedef long long int llint;

vector<llint> computeFactors(llint);
vector<llint> computePrimeFactors(vector<llint>&);
llint getLargestPrimeFactor(const llint);
bool isPrime(const llint);

int main() {
   llint num = 600851475143;
   llint prime;
   cout<<"The number to factorize is : "<<num<<endl;
   //call the function getLargestPrimeFactor to get the factor
   prime = getLargestPrimeFactor(num);
   cout<<"The largest prime factor is : "<<prime<<endl;
   return 0;
}

//////////////////////////////////////////////////////////////
////////// GET THE LARGEST PRIME FACTOR BY MAGIC /////////////
//////////////////////////////////////////////////////////////

llint getLargestPrimeFactor(const llint n) {
   vector<llint> list, primeList;

   list = computeFactors(n);
   //if n itself is prime then return n;
   if(list.size()==2) {
      return *(primeList.end());
   } else {
      primeList = computePrimeFactors(list);
   }
   for(vector<llint>::iterator i=primeList.begin(); i<primeList.end(); i++) {
      cout<<*i<<endl;
   }
   vector<llint>::iterator i = primeList.end() - 1;
   return *i;
}

//////////////////////////////////////////////////////////////
/////////// GET THE FACTORS  /////////////////////////////////
//////////////////////////////////////////////////////////////

vector<llint> computeFactors(llint n) {
   vector<llint> list;
   //iterate through every number in the range
   for(llint i=1; i<=n; i++) {
      //find out whether any of the number divides n
      if(n%i==0) {
         //if it does push it into the vector
         list.push_back(i);
         n=n/i;
      }
   }
   return list;
}

//////////////////////////////////////////////////////////////
/////////// GET THE PRIME FACTORS ////////////////////////////
//////////////////////////////////////////////////////////////

vector<llint> computePrimeFactors(vector<llint>& factorList) {
   vector<llint> prime;
   //iterate through every number in the vector
   for(vector<llint>:: iterator i=factorList.begin();
                               i<factorList.end();
                               i++)
   {
      //check whether each of the element is prime
      if(isPrime(*i)) {
         prime.push_back(*i);
      }
   }
   return prime;
}

//////////////////////////////////////////////////////////////
/////////// WHETHER A PRIME NUMBER ///////////////////////////
//////////////////////////////////////////////////////////////

bool isPrime(const llint n) {
   int count = 0;
   for(llint i=1; i<=n; i++) {
      if(n%i==0) {
         count++;
      }
   }
   if(count == 2) {
      return true;
   } else {
      return false;
   }
}

My doubts start from here:

I called a single function from main() that gives me the result.
Now that function calls other functions from itself rather than in main().
Those sub-functions call other functions to achieve the task.

So now while designing the program, I just had to think about a single function that gave me the result. Now I decompose the function into different parts.

So when I call the getLargestPrimeFactor(), others are implicitly called.

But what I could have done is that I could have called each function explicitly in main().

Is there a difference in between the two approaches ? Does it really matter ? In what cases thinking like this can be harmful ? I have studied a bit about cohesion and coupling. I just want to get the habits right from the beginning.


texts: Efficiently working out the nearest weekend

texts:
Is this an efficient way to do this?

the code is designed to find the nearest friday, without passing Sunday. If it is already past Friday, the start date should equal now.

function get_weekend(){
        $start = time();
        $day = date('w',$now);

        //find friday, without going past Sunday
        while ($day < 5 && $day > 0){
            $start = $start + 86400;
            $day = date('w',$start);
        }

        //find nearest sunday to start date
        $end = $start;
        while ($day != 0){
            $end = $end + 86400;
            $day = date('w',$end);
        }
        $weekend['StartDate']=date("d-F-Y",$start);
        $weekend['EndDate'] = date("d-F-Y",$end);
        return $weekend;

    }


texts: Breadth-first tree traversal using STL list

texts:
I am writing code for breadth-first search of a tree with C++'s STL.  Please help as I am new to the STL.

#include<iostream>
#include<malloc.h> //on llvm we don't need this
#include<list>
using namespace std;
typedef struct Node{
    int val;
    struct Node* left;
    struct Node* right;
}node;
void push(node** root,int val)
{
    if(!(*root))
    {
        node* temp=(node*)malloc(sizeof(node));
        temp->val=val;
        temp->right=temp->left=NULL;
        *root=temp;
    }
    else if(val<(*root)->val)
        push(&((*root)->left),val);
    else
        push(&((*root)->right),val);
}

void printout(node* head)
{
    node* temp;
    temp=head;
    list<node*>qu;

    //using bfs here
    while(temp!=NULL)
    {
        cout<<temp->val<<endl;
        if(temp->left!=NULL)
            qu.push_back(temp->left);
        if(temp->right!=NULL)
            qu.push_back(temp->right);

        free(temp);
            if (qu.empty())
            {   break;
            }

        temp=qu.front();
        qu.pop_front();
    }
}

int main()
{
    node* root=NULL;
    push(&root,3);
    push(&root,4);
    push(&root,1);
    push(&root,10);
    push(&root,2);
    printout(root);
}

The output is:

3
1
4
2
10


texts: Custom iOS chat interface design & functionality

texts:
Preamble

So, as most of you have likely also noticed, chat components, at least at a basic level, are becoming very common with lots of apps.  I found myself tweaking and redesigning the interface from my last project all the time, so I decided to just create an easy to drop in solution.  I'd love to get some second opinions on the code, the design, the class interface, or whatever else you've got to say about it!

Full Project Here

 Usage

ViewController.h

#import <UIKit/UIKit.h>

#import "ChatController.h"

@interface ViewController : UIViewController <ChatControllerDelegate>

@property (strong, nonatomic) ChatController * chatController;

@end

Launch With This:

if (!_chatController) _chatController = [ChatController new];
_chatController.delegate = self;
_chatController.chatTitle = @"Simple Chat";
_chatController.opponentImg = [UIImage imageNamed:@"tempUser.png"];
[self presentViewController:_chatController animated:YES completion:nil];

Receive Message (Delegate):

- (void) sendNewMessage:(NSString *)messageString {
    NSLog(@"Received msg: %@", messageString);
}

Add Message:

It receives a dictionary with the message set as a content key.  We use the dictionary within the controller so we can pass additional information like userId's, to see who sent the message, or timestamps.  This is just a demo.

NSMutableDictionary * newMessageOb = [NSMutableDictionary new];
newMessageOb[kMessageContent] = @"Some Message To Send";

// Add Message Right To Collection
[_chatController addNewMessage:newMessageOb];

You'll also have to go into the controller and add some logic to assign who sent the message. Right now it's random just so you can see how it looks and works:

int sentByNumb = arc4random() % 2;
message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:(sentByNumb == 0) ? kSentByOpponent : kSentByUser];

You can put whatever logic you'd want there, likely something similar to:

NSString * sentById = message[@"sentById"];
if ([sentById isEqualToString:currentUserId]) {
    message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:kSentByUser];
}
else {
    message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:kSentByOpponent];
}

 Design


texts:
I am doing the 100 Doors problem as an exercise to practice user input and loops. I do understand the problem can be solved by outputting every square number up to the maximum number, but it defeats the purpose of the exercise. The 100 Doors problem goes like this:

  \$N\$ doors are closed. In the first pass, I open all of them. In the second pass, I toggle every second door. In the third pass, I toggle every third door. I continue this until I have completed the \$N\$th pass. Find all the doors that will remain open after \$N\$ passes.

Here is the code:

import java.io.IOException;
import java.util.Scanner;

public class hundredDoors {
    static boolean hasNum = false;

    public static void main(String[] args) throws IOException {
        while (!hasNum) {
            Scanner input = new Scanner(System.in);
            int numOfDoors = 0;

            System.out.print("Please enter the number of doors: ");
            if (input.hasNextInt()) {
                hasNum = true;
                numOfDoors = input.nextInt();
                if (numOfDoors < 1) {
                    hasNum = false;
                    System.out.println("Please enter an integer.");
                    continue;
                }
                boolean[] doors = new boolean[numOfDoors];

                for (boolean door : doors) {
                    door = false;
                }

                for (int index = 1; index <= numOfDoors; index++) {
                    for (int door = index - 1; door <= numOfDoors - 1; door += index) {
                        doors[door] = !doors[door];
                    }
                }

                String output = "Doors still opened: \n";
                int loops = 0;
                for (int door = 0; door <= numOfDoors - 1; door++) {
                    if (loops == 10) {
                        output += "\n";
                        loops = 0;
                    }
                    if (doors[door]) {
                        output += (door + 1 + " ");
                        loops += 1;
                    }
                }
                input.close();
                System.out.println(output);
            }

            else {
                System.out.println("Please enter an integer.");
            }
        }
    }
}

One note for this program is that \$N\$ is supplied by the user. The other is that for formatting sakes, each line will have a maximum of 10 numbers (# of door).

My question here isn't how to make it more efficient (the most efficient method is to output every square since they have an odd number of factors as explained here) but rather if the code can be more clean/clear (ie, names of indentifiers, loops can be shortened, input validation check can be better, etc).


texts:
Is there any better way of doing this?

function getRandomColor() {
    var chars = '0123456789ABCDEF'.split('');
    var hex = '#';
    for (var i = 0; i < 6; i++) {
        hex += chars[Math.floor(Math.random() * 16)];
    }
    return hex;
 }


texts: Using a single for loop to load multiple images in a canvas

texts:
Is there a better way to do this? If I ever have to worry about earlier images not being loaded before the later images, i.e. image[3] being loaded after image[21]. I have to load about 100 images at the start.

for (var i = 0; i < 22; i++) {
   images[i] = new Image();
   images[i].src = whatever[i] + ".png";
    if (i == 21) {
        images[21].onload = function() {
            for (var j = 0; j < 22; j++) {
            context.drawImage( images[j], (test * 60), (240 + ((Math.floor(j * 0.25)) * 70)) );
            }
            test ++;
            if(test > 4) {
                test = 1;
            }
        }
    }
}