texts:
This is my first relevant code in OpenCL. Please, let me know if I'm doing something wrong in a logical level (i.e., I guess it can crash in situations?) or accounting for performance (bottlenecks, bad use of resources, misunderstanding some concepts, etc).

void accumulatedSum(
    volatile __global u32* completeBlocks,
    volatile __global u32* input,
    volatile __global u32* output,
    __local u32* loc) {
    // Receives an input such as:    [1, 3, 0, 0, 4,  7,  0,  0,  3,  4,  1,  1]
    // Computes the accumulated sum: [1, 4, 4, 4, 8, 15, 15, 15, 18, 22, 23, 24]
    // Always call it with global_work_size = num_of_elements / 2
    // Works like this: http://imgur.com/3lm3CAq
    unsigned int k, a;
    int lid          = get_local_id(0);
    int gid          = get_global_id(0);
    int groupId      = get_group_id(0);
    int localPasses  = get_local_size(0);
    int globalPasses = get_num_groups(0)*2;
    loc[lid*2]       = input[gid*2];
    loc[lid*2+1]     = input[gid*2+1];
    barrier(CLK_LOCAL_MEM_FENCE);
    for (a=0; localPasses>>=1; ++a){
        k = (lid >> a << (a+1)) + (1<<a);
        loc[k + (lid&((1<<a)-1))] = loc[k - 1] + loc[k + (lid&((1<<a)-1))];
        barrier(CLK_LOCAL_MEM_FENCE);
    };
    output[gid*2] = loc[lid*2];
    output[gid*2+1] = loc[lid*2+1];
    for (; globalPasses>>=1; ++a){
        barrier(CLK_GLOBAL_MEM_FENCE);
        while (*completeBlocks != 0);
        if (lid == 0) atomic_inc(completeBlocks);
        while (*completeBlocks < get_num_groups(0));
        if (lid == 0 && gid == 0) atomic_xchg(completeBlocks,0);
        k = (gid >> a << (a+1)) + (1<<a);
        output[k + (lid&((1<<a)-1))] = output[k - 1] + output[k + (gid&((1<<a)-1))];
    };
};

If you have clever ideas in how to make it more readable please let me know, although that is not the focus.


texts: Compact a file of 'Compound binary file format'

texts:
I am working on a modelling application written in C++ and MFC. The generated model is saved as a compound file. For various reasons, I need to compact the compound file therefore I decided to write a function for doing this.
The function should take as inputs the path of the original uncompacted file and the path of the output file. Note that there is no need to worry about source and destination paths being the same, they are guaranteed to be different. Here is the function I wrote.

bool CompactCompoundFile(LPCTSTR sourcePath, LPCTSTR destinationPath)
{
    ASSERT(sourcePath != nullptr);
    ASSERT(destinationPath != nullptr);
    ASSERT(lstrcmp(sourcePath, destinationPath) != 0);

    bool success = false;
    LPSTORAGE sourceStorage = nullptr;
    LPSTORAGE destStorage = nullptr;

    try
    {
        const CStringW sourcePathStr(sourcePath);
        const CStringW destPathStr(destinationPath);
        SCODE sc;

        sc = ::StgOpenStorage(sourcePathStr.GetString(),  NULL, STGM_READ | STGM_TRANSACTED, 0, 0, &sourceStorage);
        if ( !FAILED(sc) && sourceStorage != NULL )
        {
            sc = ::StgCreateDocfile(destPathStr.GetString(),
                                    STGM_READWRITE|STGM_TRANSACTED|STGM_SHARE_DENY_WRITE|STGM_CREATE, 0, &destStorage);

            if (sc == S_OK)
            {
                if (sourceStorage->CopyTo(0, 0, 0, destStorage) == S_OK)
                {
                    if (destStorage->Commit(STGC_DEFAULT) == S_OK)
                    {
                        success = true;
                    }
                }
            }
        }
    }
    catch(...)
    {
        success = false;
    }

    if (sourceStorage!=nullptr)
        sourceStorage->Release();

    if (destStorage!=nullptr)
        destStorage->Release();

    return success;
}

My code seems to work, but because I am not very familiar with compound files, I would mostly like to know if you see something wrong with the above way of compacting the file, any cases that the code will fail. Of course any other comments are also welcome.


texts: Cleaning up get/set functions in Node export

texts:
So currently I'm working on cleaning up a recently developed project and notice a lot of potentially un-needed code; whereas I create separate functions for very minimal stuff..

Here's an example of a module export I've done:

//MemCache
const Cache = require('memcached-promisify');
const cache = new Cache();

module.exports = {

    suppression_times: function(key) {
        let times = {
            bm_notices: this.secs('1 hour')
        };
        return times[key];
    },

    suppression_get: async function(_id, key, cb) {
        let mem_key;
        if (!this.suppression_times[key]) {
            return cb(new Error('Suppression key `' + key + '` does not exist'));
        }
        mem_key = [_id, key].join(':');
        const result = await cache.get(mem_key);
        if (result !== undefined) {
            return cb(null, result);
        }
        return cb(result);
    },

    suppression_set: async function(_id, key, cb) {
        let mem_key, secs, time;
        if (!(secs = suppression_times[key])) {
            return cb(new Error('Suppression key `' + key + '` does not exist'));
        }
        mem_key = [_id, key].join(':');
        const result = await cache.set(mem_key, (time = this.time()), secs);
        if (result !== undefined) {
            return cb(null, time);
        }
        return cb(result);
    },

    secs: function(str) {
        let result;
        result = require('english-time-mirror')(str);
        return Math.round(parseInt(result / 1000));
    },

    time: function() {
        let d = new Date().getTime() / 1000;
        return Math.round(d);
    }

}

How could I go about improving this?


texts: React App with external route table and cookie-based routing

texts:
This is a small frontend frame for a React app that is built then served statically.
Because the app uses React-Router for browser-based routing but the server doesn't know anything about the app I added some code to the backend that reads the list of routes the app uses from a json file and creates dummy handlers for each that place a redirect=/path cookie and redirect to the main page. That code is left out for brevity and to focus on the frontend.
Meanwhile, the Javascript React frontend in this question sets ups the app's React-Router routes based on the same external json file. The main page checks whether there is a redirect cookie set by the server and if so sends the user to that page.
The overall effect between the frontend and backend is that a user can go directly to app.com/widget/4 and without them knowing the server bounces them to the main page to start the browser-routing session and then back to the correct url
routes.json:
{
  "routes": [
    {"path":"/widget/:widgetId", "component": "WidgetContainer", "redirect": true},
    {"path":"/", "component": "MainPageContainer", "exact": true}
  ]
}

index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from "react-router-dom";

import  ParseRoutes from "./Utils/ParseRoutes"
import { routes } from "./routes.json"

function AppContainer() {
  const routeProps = ParseRoutes(routes)

  return (
    <Router>
     {routeProps.map((props, i) => (<Route key={i} {...props} /> ))}
    </Router>
  )
}

ReactDOM.render(<AppContainer />, document.getElementById("root"))

ParseRoutes.js:
import  MainPageContainer from "../Components/MainPage"
import  WidgetContainer from "../Components/Widget"

const stringToComp = {
    MainPageContainer: MainPageContainer,
    WidgetContainer: WidgetContainer
}

const ParseRoutes = (routes) => (
    routes.map((props) => ({...props, component: stringToComp[props.component]}))
)

export default ParseRoutes

RedirectIfRequested.js:
import React from "react"
import { Redirect } from "react-router-dom"

const getCookieValue = (a) => {
    var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)')
    return b ? b.pop() : ''
  }

const RedirectIfRequested = () => {
    const redirectTo = getCookieValue("redirect")

    if ( redirectTo ) {
        document.cookie = "redirect=''; max-age=-1"
        return <Redirect to={redirectTo} />
    }

    return null
}

export default RedirectIfRequested

MainPage.js:
import React from "react"

import RedirectIfRequested from "../Utils/RedirectIfRequested.js"

export default function MainPageContainer(props) {
    const redirect = RedirectIfRequested()

    return redirect ? redirect : <MainPage />
}

function MainPage(props) {
    return
Main Page

}

Widget.js:
import React from "react"

import { useParams } from "react-router-dom"

export default function WidgetContainer(props) {
    const id = useParams().widgetId

    return
 Widget {id} accessed via react-router

}


texts: Using separate functions for Project Euler 1

texts:
I started programming with Java and C++, so I'm used to having a 'main' function that calls other functions that do the actual work. At university I was always told that doing actual computation in the main function is bad practice. I'm currently playing around with Python, and I have trouble figuring out how to write a nice 'main' function, especially since I'm doing small stuff that doesn't need separate classes.

What do you think about the following code? Is the main function necessary, or would  you just write everything without functions? Is there a general consent on this in the Python world?

# Finds sum of all multiples of 3 and 5 from 0 to 999

def find_multiples():
    global numbers

    for i in range(0,1000):
       if i%3==0 or i%5==0:
           numbers.append(i);

numbers = []

if __name__ == '__main__':
    find_multiples()
    print sum(numbers)


texts:
https://leetcode.com/problems/search-a-2d-matrix/

  Write an efficient algorithm that searches for a value in an m x n
  matrix. This matrix has the following properties:

  Integers in each row are sorted from left to right. The first integer
  of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true
Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

Please review for performance. maybe there are better solutions but this is how my brain worked on this question.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/search-a-2d-matrix/
    /// </summary>
    [TestClass]
    public class SearchA2DMatrixTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            int[][] matrix =
            {
                new[] {1, 3, 5, 7},
                new[] {10, 11, 16, 20},
                new[] {23, 30, 34, 50}
            };
            int target = 3;
            Assert.IsTrue(SearchMatrix(matrix, target));
        }

        [TestMethod]
        public void FailedTest()
        {
            int[][] matrix =
            {
                new[] {1},
                new[] {3},
            };
            int target = 3;
            Assert.IsTrue(SearchMatrix(matrix, target));
        }

        [TestMethod]
        public void FailedTest2()
        {
            int[][] matrix =
            {
                new[] {1,3,5,6},
                new[] {10,11,16,20},
                new[] {23,30,34,50},
            };
            int target = 11;
            Assert.IsTrue(SearchMatrix(matrix, target));
        }
        public bool SearchMatrix(int[][] matrix, int target)
        {
            if (matrix == null || matrix.Length == 0 || matrix[0].Length == 0)
            {
                return false;
            }
            if (target < matrix[0][0] || target > matrix[matrix.Length - 1][matrix[0].Length - 1])
            {
                return false;
            }
            int top = matrix.Length - 1;
            int bottom =0;
            int mid = 0;
            while (bottom <= top)
            {
                mid = ((top - bottom) / 2) + bottom;
                if (matrix[mid][0] == target)
                {
                    return true;
                }
                if (matrix[mid][0] > target)
                {
                    top = mid - 1;
                }
                else
                {
                    bottom = mid + 1;
                }
            }

            //if the first cell of the curr row(mid)
            // is bigger than the target,
            // the target is in the previous row
            if (matrix[mid][0] > target)
            {
                mid--;
            }

            int left = 0;
            int right = matrix[0].Length - 1;
            int cm;
            while (left <= right)
            {
                cm = ((right - left) / 2) + left;
                if (matrix[mid][cm] == target)
                {
                    return true;
                }
                if (matrix[mid][cm] > target)
                {
                    right = cm - 1;
                }
                else
                {
                    left = cm + 1;
                }
            }
            return false;
        }
    }
}


texts: Oh my goodness: How many selfies have I taken?

texts:
The title is a joke on how some people take a lot of selfies pictures

Recently, in The 2nd Monitor, there was a brief discussion on selfie answers, starting with this post.

At one point, a user said this:

  I don't know how many selfies I have :s

I immediately thought: this is the perfect opportunity for an SEDE query!

Try it out!

DECLARE @QuestionId INT = (SELECT Id FROM PostTypes WHERE Name = 'Question');
DECLARE @AnswerId INT = (SELECT Id FROM PostTypes WHERE Name = 'Answer');

DECLARE @UserAnswers TABLE (AnswerId INT, ParentId INT);
DECLARE @UserQuestions TABLE (QuestionId INT);

INSERT INTO @UserAnswers
SELECT Id, ParentId
FROM Posts
WHERE OwnerUserId = ##UserId## AND PostTypeId = @AnswerId;

INSERT INTO @UserQuestions
SELECT Id
FROM Posts
WHERE OwnerUserId = ##UserId## And PostTypeId = @QuestionId;

SELECT AnswerId
FROM @UserAnswers
JOIN @UserQuestions
ON ParentId=[@UserQuestions].QuestionId;

The above query takes the user's ID and returns a list of all their selfie answers that they have posted.

This is my first time ever writing any form of SQL and I'm still trying to get used to the overall flow of it, so I'm really open to any recommendations.

However, here are a few things I had in mind:

Is it good that I stored the posts in tables, or is it unnecessary?
Am I following good SQL practices/conventions?
I was really confused on how I should break up the SQL into multiple lines, so, after much trial and error, it seemed to me having one instruction per line was the cleanest. However, if this is not recommended, I am open to change.
Am I missing indentation anywhere?
To me, reading SQL is just like reading English. Therefore, writing documentation seemed redundant. However, I am not familiar with good documentation and SQL, so is there anything documentation-wise that I should add?


texts: Where to put hidden fields when displaying entities properties in a table?

texts:
Let's say that I have a view, whose purpose is to show a table with some information about a person entity. The view contains a form with an input element that the user can use to add a new person to the table by entering its name.

My question is: In this scenario, is there a convention about where to put hidden fields that are needed to retrieve the data in the server again?

In my code, I put them in the table definition; but maybe it's best to put all those fields together inside a div or something. Maybe it just doesn't matter where you put those as long as the code works. I'm just curious because I like to generate the best HTML possible.

I understand that this type of operation is very expensive to archive using a full post-back to the server, and an Ajax request will be better in this scenario, but still the question remains valid.

This is the model for the view:

class IndexViewModel
{
    public string Query { get;set; }

    public IList<Person> People { get;set; }
}

And the view:

<form action="home/index">
    <input id="query" name="query"/>
    <input type="submit" value"Add"/>

                Name

            @for (int i = 0; i < Model.People.Count; ++i)
            {

                        @Html.HiddenFor(m=>m.People[i].Id)
                        @Html.ActionLink(Model.People[i].Name, "Details", "Person", new { id = Model.People[i].Id }, null)

                        @Html.ActionLink("Remove", "RemovePerson", "Home", new { id = Model.People[i].Id }, null)

            }

</form>

In the Action I receive the model and get the list of people again from the database and add the new person.

[HttpPost]
public ActionResult Index(IndexViewModel model)
{
    // Here I load again all people in the view and add the new that was queried.
    for (int i = 0; i < model.People.Count; ++i)
        model.People[i] = db.FindById(model.People[i].Id);

    var newPerson = db.FindByName(model.Query);
    if (newPerson != null)
        model.People.Add(newPerson);

    return View(model);
}


texts:
I have a GET method that handles paging, filtering, and sorting. Development has been fairly rapid and I'm not completely sold on some of the implementation. A few assumptions have to be made for this method: I'm using System.Dynamic.Linq. I want to put as much work as possible on SQL Server. The page will make use of both the resulting record set after filtering and paging have been applied, as well as the count of the filtered record set before paging is applied. I have full control of the entity definitions, and each has a [Key] attribute on only one property. Currently, I'm only interested in seeing the IsActive records.

Any thoughts on improvements are welcome. Thanks in advance.

    public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties, out int recordCount, Dictionary<string,string> filter, bool filterExact,
    string orderBy = null, bool orderByAsc = true, int pageNumber = 0, int perPage = 10)

    {
        //IQueryable that will eventually contain the record set
        IQueryable<TEntity> query = _context.Set<TEntity>();
        //IQueryable that will get the count of post-filter, but pre-page records
        IQueryable<TEntity> countQuery = _context.Set<TEntity>();
        List<TEntity> page;

        //countQuery mirrors query through the filter assignments
        query = query.Where("IsActive = true");
        countQuery = countQuery.Where("IsActive = true");

        if (filter.Count > 0)
        {
            string _template = filterExact ? "{0}.ToString().Equals(@0)" : "{0}.ToString().Contains(@0)";
            string _clause = "";
            foreach (KeyValuePair<string, string> entry in filter)
            {
                _clause = string.Format(_template, entry.Key);
                query = query.Where(_clause, entry.Value);
                countQuery = countQuery.Where(_clause, entry.Value);
            }
        }
        //countQuery's job is finished at this point
        recordCount = countQuery.Count();

        if (includeProperties != null)
        {
            foreach (var include in includeProperties)
            {

                query = query.Include(include);
            }
        }

        if (orderBy != null)
        {
            query = query.OrderBy(orderBy + ((orderByAsc) ? " ascending" : " descending"));
        }
        else
        {
            //Using reflection to find the [Key] attribute to use as a default ordering because Skip/Take requires an ordered set
            Type entityType = typeof(TEntity);
            var keyField = entityType.GetProperties()
                .Single(p => Attribute.IsDefined(p, typeof(KeyAttribute)));
            query = query.OrderBy(keyField.Name);
        }

        if (pageNumber > 0)
        {
            int _start = (pageNumber - 1) * perPage;
            query = query.Skip(_start);
            query = query.Take(perPage);
        }

        page = query.ToList();

        return page;
    }


texts: Greasemonkey script to auto fill the values of a form on a specified page

texts:
I created a Greasemonkey script to allow me to quickly fill a specific form on a specific URL, for testing/dev purposes. If the current URL matches any of the urls found in the formsDefault array a button is added to the page that allows the user to auto fill with the default values.

This is my first time using arrow functions in JS.

/*jshint esversion: 6 */

(function($) {
    'use strict';

    var formDefaults = [
        {
            urlPattern : '/profile/user',
            valueSet : [
                { selector : '#username', value : 'bill' },
                { selector : '#lastname', value : 'miller' },
                { selector : '#auth_pin', value : '1234' },
            ]
        },
        {
            urlPattern : '/profile/company',
            valueSet : [
                { selector : '#companyname', value : 'bill' },
                { selector : '#state', value : 'washington' },
            ]
        },
    ];

    var formFiller = {
        valueSet : null,

        run(formDefaults) {
            var valueSetObj = this.tryEachPattern(this);
            if (valueSetObj !== null) {
                this.valueSet = valueSetObj.valueSet;
                this.showFormFillButton(this);
            }
        },

        tryEachPattern : (_this) => {
            var valueSetObj = null;
            for (var i = formDefaults.length - 1; i >= 0; i--) {
                valueSetObj = formDefaults[i];
                var matched = _this.matchUrl(_this, valueSetObj.urlPattern);
                if (matched === true)
                {
                    break;
                }
            }
            return valueSetObj;
        },

        matchUrl : (_this, urlPattern) => {
            var matched = !!location.href.match(urlPattern);
            return matched;
        },

        fillForm : (_this) => {
            var valueSet = _this.valueSet;
            for (var i = valueSet.length - 1; i >= 0; i--) {
                var value = valueSet[i];
                $(value.selector).val(value.value);
            }
        },

        showFormFillButton : (_this) => {
            var button = $('<button type="button" style="position: absolute; right: 10px; bottom: 10px">Auto Fill</button>');
            button.on('click', function(event) {
                event.preventDefault();
                _this.fillForm(_this);
            });
            $('body').append(button);
        },
    };

    // Ready, set, go
    formFiller.run(formDefaults);

})(jQuery);


texts: Project Euler Problem #4 - Palindromic number

texts:
The problem is as follows:

  A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

Using Project Euler to stretch my C# learning, I solved problem #4 with the code below. I ran this in a console app to get the answer. How can I improve my code?

class PalindromNumber
{
    public string GetPalindromeNumber(int maxNumber = 999)
    {
        bool breakOut = false;
        int test=0;
        int left = 0;
        int right = 0;
        int biggestNumber = 0;
        string returnString=string.Empty;
        for (left=maxNumber; left >= 0; left--)
        {
            for(right=maxNumber; right >= 0; right--)
            {
                test = left * right;

                string testNumberAsString = Convert.ToString(test);
                string reverse = string.Empty;
                for (int index = testNumberAsString.Length; index > 0; index--)
                {
                    reverse += testNumberAsString[index-1];
                }

                breakOut = (testNumberAsString == reverse && Convert.ToString(left).Length == 3 && Convert.ToString(right).Length == 3);

                if (breakOut )
                {
                    break;
                }
            }

            if (test>biggestNumber)
            {
                biggestNumber = test;
                returnString = $"Palindrome: {test}, Left: {left}, Right: {right}";
            }
        }

        return returnString;
    }
}


texts: Matchmaking system - sorting musicians by skills, genres, and location

texts:
I'm making a matchmaking system using PHP and MySQL which allows users to search through a list of musicians so that they can find people with the right skills and interests who are near them. It works but it's extremely messy, and I'd like to learn how I can clean it up and eliminate as many bad habits as possible. I've been trying to learn OOP but it feels more like I'm just writing procedural code and putting it into methods.

The search form:

The database:

When the form is submitted, the find_users method is called from my database class.

class DB
{
protected $conn;

public function __construct($config)
{
    try {
        $conn = new PDO('mysql:host='. $config['host'] . ';
            dbname=' . $config['db'],
            $config['username'],
            $config['password']);

        $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $this->conn = $conn;
    } catch (Exception $e) {
        return false;
    }
}

public function query($query, $bindings = [])
{
    try {
        $stmt = $this->conn->prepare($query);
        $stmt->execute($bindings);
        return ($stmt->rowCount() > 0)
        ? $stmt :
        false;
    } catch (Exception $e) {
        var_dump($e);
    }
}

public function get($tableName, $limit = 24)
{
    try {
        $result = $this->conn->query("SELECT * FROM $tableName LIMIT $limit");
        return ( $result->rowCount() > 0)
        ? $result->fetchAll(PDO::FETCH_OBJ)
        : false;
    } catch (Exception $e) {
        die($e);
    }
}

public function get_user_by_username($username)
{
    $result = $this->query("SELECT * FROM users where username = :username LIMIT 1", array(
        "username" => $username
        ));

    return $result->fetch(PDO::FETCH_OBJ);
}

public function find_users($username = '', $skill = '', $tag = '', $lat = 1, $lng = 1, $distance)
{

    $sql = "SELECT DISTINCT
    users.username, ( 3959 * acos( cos( radians($lat) ) * cos( radians( latitude ) )
            * cos( radians( longitude ) - radians($lng) ) + sin( radians($lat) ) * sin(radians(latitude)) ) ) AS distance
    FROM
    users
    INNER JOIN
    user_skills ON users.user_id = user_skills.user_id
    INNER JOIN
    skills ON user_skills.skill_id = skills.skill_id
    INNER JOIN
    user_tags ON users.user_id = user_tags.user_id
    INNER JOIN
    tags ON user_tags.tag_id = tags.tag_id
    WHERE users.availability = 'Yes'";

    $bindings = array();

    if ($username) {
        $sql .= " AND users.username LIKE :username";
        $bindings['username'] = "%" . $username . "%";
    }

    if ($skill) {
        $sql .= " AND skills.skill_name = :skill";
        $bindings['skill'] = $skill;
    }

    if ($tag) {
        $sql .= " AND tags.tag_name = :tag";
        $bindings['tag'] = $tag;
    }

    $sql .= " HAVING distance < $distance ";
    $sql .= " ORDER BY distance";

    $result = $this->query($sql, $bindings);

    return ( $result )
    ? $result->fetchAll(PDO::FETCH_OBJ)
    : false;
}
}

Like I mentioned earlier, it's seriously messy but I'm not sure how to tidy it up. Accepting 6 parameters feels really wrong but I need them so that I can sort users using the specified criteria.


texts:
Here are some snippets I coded and I would like some feedback on my way of handling this:

I have a utility class, as a singleton, that provides me with a method named randomColor which returns a (UIColor*):

-(UIColor*)randomColor
{
    float l_fRandomRedColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f];
    float l_fRandomBlueColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f];
    float l_fRandomGreenColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f];

    return [UIColor colorWithRed:l_fRandomRedColor
                    green: l_fRandomGreenColor
                    blue: l_fRandomBlueColor
                           alpha: 255];
}

Now, I know the object return by this method is autoreleased.

I store the returned value in another class and I would like to keep this value for a while, so I proceed like this:

[self setMpCurrentPieceColor:[[GraphicsUtility instance] randomColor]];

Which calls the following property:

- (void)setMpCurrentPieceColor:(UIColor*)_newColor
{
    [_mpCurrentPieceColor release];
    [_newColor retain];

    // Make the new assignment.
    _mpCurrentPieceColor = _newColor;
}

Question A)

My instance variable is released in the dealloc method. Is a the correct way to go?

Question B)

Now, let's imagine I have an array, like this:

UIColor* mBoardColors[WIDTH][HEIGHT];

I want to store the previous instance variable into the array:

[mBoardColors[l_iBoardXIndex][l_iBoardYIndex] release];
[_color retain];
mBoardColors[l_iBoardXIndex][l_iBoardYIndex] = _color;

Is it correct?

Question C)

What if I want to move a color from a cell to another (moving, not copying), is it correct to do it like that?

[mBoardColors[l_iBoardXIndex][l_iBoardYIndex] release];
mBoardColors[l_iBoardXIndex][l_iBoardYIndex] = mBoardColors[l_iBoardXIndex][l_iBoardYIndex - 1];
mBoardColors[l_iBoardXIndex][l_iBoardYIndex - 1] = nil;

Thank in advance for your precious comments and advices!


texts: Who needs clean configuration? Swapping server.xml

texts:
So I'm working on a project that sometimes requires me to switch my server configuration. This is due to some circumstances with database drivers and names that are "too expensive to fix" ...

That made me think though: "Why do I always copy these files around manually?"

I decided I won't and wrote this small script to help me:

#!/bin/bash

if [ $# != 1 ]
    then
    echo "you must provide a configuration to switch to"
    exit
fi;

if [ -a $TOMCAT_HOME/conf/server_$1.xml ]
    then
    rm $TOMCAT_HOME/conf/server.xml
    cp $TOMCAT_HOME/conf/server_$1.xml $TOMCAT_HOME/conf/server.xml
else
    echo "given configuration was not found. did not make any changes."
fi;

exit 0

Usage is dead simple: I made this available system-wide and can just call:

switch-config postgres

or

switch-config firebird

To make changes happen.

This is built for my personal convenience, so please ignore the incredibly bad error messages, also the (nonexistent) directory structure is for simple convenience. Comments like "move the different configurations somewhere else" don't help me.

In any case, what can I improve?


texts: Fetching data from nested JSON using jQuery and displaying in table

texts:
I'm displaying JSON data in a tabular format on a html page using jQuery.

In the function I'm looping the resp.DATA once to get the key names so it can be displayed as the headings in the table, and a second time to get the values of the keys for all customers.

Can this be done in a way that I only have to loop the resp.DATA once?

JSON data:

    var resp= {
    "ERROR": [],
    "DATA": [{
        "CustomerID": "234",
        "BranchID": "1",
        "LocationID": "26",
        "FirstName": "Lakshmi "
    }, {
        "CustomerID": "235",
        "BranchID": "1",
        "LocationID": "6",
        "FirstName": "Arora "
    }, {
        "CustomerID": "236",
        "BranchID": "1",
        "LocationID": "68",
        "FirstName": "S.K.Raman "
    }, {
        "CustomerID": "237",
        "BranchID": "1",
        "LocationID": "38",
        "FirstName": "Vidya Rao "
    }, {
        "CustomerID": "238",
        "BranchID": "1",
        "LocationID": "18",
        "FirstName": "Raju "
    }, {
        "CustomerID": "239",
        "BranchID": "1",
        "LocationID": "49",
        "FirstName": "K.B.Hebbar "
    }],
    "META": {
        "currentPageNumber": "1",
        "totalPages": "11",
        "rowcountCurrentPage": "10",
        "rowcountTotal": "107"
    }
}

Code:

            var content = '
';
            var heading = "
";
            var data = "";
            $.each(resp.DATA[0], function(ke, va) {
                heading += '' + ke + '	';
            });
            $.each(resp.DATA, function(key, value) {

                data += "
";
                $.each(value, function(k, v) {
                   data += '' + v + '	';
                });
                data += "
";
            });
            heading += "
";
           content += heading + data + "
";
            $('#data').append(content);

HTML file:

<!DOCTYPE html>

    <title>COnsuming rest webservice</title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Consuming REST api

    </script>

You can see a working example here.


texts: Finding pair in an array with the OO approach

texts:
Description:

I am trying to solve algorithmic problems mixing them with Object oriented design as part of my interview preparation. So, the question is given an array of integers find the pair of index which satisfy the given sum hence, given:

  arr = [1, 2, 3, 4, 5] , sum = 6, answer = (2, 4) or (1, 5)

Code:

class Solution {
    static final class Pair {
        public final int i;
        public final int j;

        public Pair() {
            i = -1;
            j = -1;
        }

        public Pair(int i, int j) {
            this.i = i;
            this.j = j;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            return "(" + i + ", " + j + ")";
        }
    }

    static final class PairSum {
        private Pair p;

        public PairSum(int[] arr, int sum) {
            // validation here
            int n = arr.length;
            boolean found = false;
            for (int i = 0; i < n; i++) {
                if (found == true) break;
                for (int j = i + 1; j < n; j++) {
                    if (arr[i] + arr[j] == sum) {
                        p = new Pair(i, j);
                        found = true;
                    }
                }
            }
            if (p == null) // no pair found
                p = new Pair();
        }

        public Pair get() {
            return p;
        }
    }

    static final class PairSumFast {
        private Pair p;

        public PairSumFast(int[] arr, int sum) {
            // validation here
            Map<Integer, Integer> map = new HashMap<>();

            for (int i = 0; i < arr.length; i++) {
                int diff = sum - arr[i];
                if (map.containsKey(diff)) {
                    p = new Pair(map.get(diff), i);
                    break;
                }
                else
                    map.put(arr[i], i);
            }
            if (p == null) p = new Pair();
        }

        public Pair get() {
            return p;
        }
    }

    public static void main (String[] args) throws java.lang.Exception {
        PairSum p = new PairSum(new int[]{1, 2, 3, 0, 4}, 4);
        System.out.println(p.get()); // (0, 2)

        p = new PairSum(new int[]{1, 2, 3, 0, 4}, 5);
        System.out.println(p.get()); // (0, 4)

        p = new PairSum(new int[]{1, 2, 3, 0, 4}, 10);
        System.out.println(p.get()); // (-1, -1)

        PairSumFast p2 = new PairSumFast(new int[]{1, 2, 3, 0, 4}, 4);
        System.out.println(p2.get()); // (0, 2)

        p2 = new PairSumFast(new int[]{1, 2, 3, 0, 4}, 5);
        System.out.println(p2.get()); // (0, 4)

        p2 = new PairSumFast(new int[]{1, 2, 3, 0, 4}, 10);
        System.out.println(p2.get()); // (-1, -1)
    }
}

Given the time constraint I am not sure if its a good approach but I think it should a good impression. I would like to hear if my code could be improved further?


texts: Calculate and plot expected value involving summations and products

texts:
I wrote a code to calculate a series of summations and products for a maths assignment I'm doing. The equation is shown below.

$$E(\sigma)=[1-(P(\text{$1^{st}$ rejects}) \times P(\text{$2^{nd}$ rejects}) \times \ldots \times P(\text{$n^{th}$ rejects}))] \times \frac{\frac{n(n+1)}{2} - \frac{(n-j)(n-j+1)}{2}}{j}$$

where

$$P(\text{$x^{th}$ rejects})=1-\left[\frac{j}{n} \times\left(\frac{n-1}{n}\right)^{j-1} \times \prod_{y=2}^{x-1}\sum_{k=0}^{j-1} (\binom{j-1}{k}(\frac{n-1}{n})^{j-1-k}(\frac{1}{n})^k(1-\prod_{i=0}^{Y-1} P(i^{th} rejects))) \times \\ \sum_{k=0}^{j-1}(\binom{j-1}{k}(\frac{n-1}{n})^{j-1-k}(\frac{1}{n})^k \sum_{i=0}^{k}(\frac{1}{1+i}\binom{k}{i}(1-\prod_{i=0}^{x-1} P(i^{th} rejects))^{k-i}(\prod_{i=0}^{Y-1} P(i^{th} rejects))^i)))\right]$$

The code calculates \$E(\sigma)\$ for all values of \$j\$ for \$1\le j\le n\$ for all values of \$n\$ for \$3\le n\le a\$. The code finds the value of \$j\$ which produces the highest value of \$E(\sigma)\$ for each \$n\$ and expresses this as a percentage of \$n\$. Then it plots the graph of this percentage versus \$n\$

The thing is it requires many loops and the computation for \$a=100\$ seems like it's taking forever. Is there a way to reduce the computation time? If not, if I leave the computer running for a few hours will it eventually compute successfully? I'm really new to programmming so please excuse the messy code.

\$P(\text{$1^{st}$ rejects})\$ and \$P(\text{$2^{nd}$ rejects})\$ are not calculated in the same loop as the rest of \$P(\text{$x^{th}$ rejects})\$ but rather separately as prob1r and prob2r respectively as putting them in the same loop creates some problems (such as for y in 2:1).

Edit: I looked around and discovered the magic of parallelization. By simply changing my for loop to a paralllelized foreach loop, time taken decreased from Time difference of 58.93389 secs to Time difference of 16.01991 secs for \$n=40\$. Still, help will be appreciated if further reduction can be achieved as I want to calculate to as high a value of \$n\$ as possible.

a=as.numeric(a)

registerDoParallel(cores=3)
z=matrix(nrow=1, ncol=a)

y=(foreach(n=3:a, .combine='c') %dopar%
{
  q=matrix(nrow=1,ncol=n)
  for(j in 1:n)
  {
    m=matrix(nrow=1,ncol=n)
    prob1r=0
    for (k in 0:(j-1))
    {
      prob1r=prob1r+(((dbinom(k,(j-1),(1/n))))*(1/(k+1)))
    }
    m[1,1]=1-((j/n)*prob1r)
    prob2r=0
    for(k in 0:(j-1))
    {
      probir=0
      for (i in 0:k)
      {
        probir=probir+((dbinom(i,k,m[1,1])))*(1/(1+i))
      }
      prob2r=prob2r+((dbinom(k,j-1,(1/n))))*probir
    }
    m[1,2]=1-((j/n)*(((n-1)/n)^(j-1))*prob2r)
    for(h in 3:n)
    {
      prob1=1
      for(y in 2:(h-1))
      {
        prob=0
        proby1=1
        for(k in 1:(y-1))
        {
          proby1=proby1*m[1,k]
        }
        for(k in 0:(j-1))
        {
          prob=prob+((dbinom(k,j-1,(1/n))))*((1-proby1)^k)
        }
        prob1=prob1*prob
      }
      prob2=0
      for(k in 0:(j-1))
      {
        probrej=1
        for (g in 1:(h-1))
        {
          probrej=probrej*(m[1,g])
        }
        probi=0
        for (i in 0:k)
        {
          probi=probi+((dbinom(i,k,probrej)))*(1/(1+i))
        }
        prob2=prob2+((dbinom(k,j-1,(1/n))))*probi
      }
      m[1,h]=1-((j/n)*(((n-1)/n)^(j-1))*prob1*prob2)
    }
    probno=1
    for(p in 1:n)
    {
      probno=probno*(m[1,p])
    }
    q[1,j]=(1-probno)*((((n*(n+1))/2)-(((n-j)*(n-j+1))/2))/j)
  }
  z[1,n]=((which.max(q))/n)*100
})
x=3:a
lm.r=lm(y~x)

plot(x,y)
abline(lm.r)


texts: Get a map containing elements which are present in unordered map A but are not present in unordered map B

texts:
I would like to create a function which returns a map containing differences between two unordered maps. Here is the code:

std::map<std::string, int> getDiff(const std::unordered_map<std::string, int>& unordered_mapA,
                                   const std::unordered_map<std::string, int>& unordered_mapB)
{
    std::map<std::string, int> mapA(unordered_mapA.begin(), unordered_mapA.end());
    std::map<std::string, int> mapB(unordered_mapB.begin(), unordered_mapB.end());;
    std::map<std::string, int> diffMap;

    std::set_difference(mapA.begin(), mapA.end(), mapB.begin(), mapB.end(), std::inserter(diffMap, diffMap.end()));

    return diffMap;
}

Edit:

A result should contain elements which are present in mapA but are not present in mapB.


texts:
I have used the following code for a stack implementation. The top keeps track of the topmost node of the stack. Now since top is a data member of the node function, each node created will have a top member, which ideally we wouldn't want.

Is this good approach to coding?
Will making top as static make it a better coding practice?
Should I have a global declaration of top?

#include<iostream>
using namespace std;
class node
{
    int data;
    node *top;
    node *link;
    public:
    node()
    {
       top=NULL;
       link=NULL;
    }
    void push(int x)
    {
        node *n=new node;
        n->data=x;
        n->link=top;
        top=n;
        cout<<"Pushed "<<n->data<<endl;
    }
    void pop()
    {
        node *n=new node;
        n=top;
        top=top->link;
        n->link=NULL;
        cout<<"Popped "<<n->data<<endl;
        delete n;
    }
    void print()
    {
        node *n=new node;
        n=top;
        while(n!=NULL)
        {
            cout<<n->data<<endl;
            n=n->link;
        }
        delete n;
    }
};

int main()
{
    node stack;
    stack.push(5);
    stack.push(7);
    stack.push(9);
    stack.pop();
    stack.print();
}

Any other suggestions welcome. I have also seen codes where there are two classes, where the second one has the top member. What about this?


texts: Recursive implementation of integer partition without re-arrangement

texts:
Problem: Integer partition without re-arrangement

Input: An arrangement S of nonnegative numbers {s1, . . . , sn} and an integer k.

Output: The largest job from partitioning S into k or fewer ranges, to minimize the maximum sum over all the ranges, without reordering any of the numbers. Also the indexes of the partition dividers.

'use strict';

var sum = function(p, c) {
    return p + c;
};

var integerPartitionRec = function(n, k, S, divider_indexes) {
    if (divider_indexes === undefined) divider_indexes = [];
    if (i === 1) return [S[0], divider_indexes];
    if (k === 1) return [S.slice(0, n).reduce(sum), divider_indexes];

    var cost, prefix, min_cost = Number.MAX_VALUE,
        min_divider_indexes = [];
    for (var i = 1; i < n; i++) {
        prefix = integerPartitionRec(i, k - 1, S, divider_indexes.concat(i));
        cost = Math.max(prefix[0], S.slice(i, n).reduce(sum));
        if (cost < min_cost) {
            min_cost = cost;
            min_divider_indexes = prefix[1];
        }
    }

    return [min_cost, min_divider_indexes];
};

// define M[n,k] to be the minimum possible cost over all partitionings of {s1 , . . . , sn }
// into k ranges, where the cost of a partition is the largest sum of elements in one of its parts.
// O(kn^2) time

var integerPartitionDp = function(S, k) {
    var n = S.length;
    var cache = [
        [0]
    ];

    /* Dividers */
    var d = []

    /* Prefix Sums */
    var p = [0];

    for (var i = 1; i <= n; i++) {
        p[i] = p[i - 1] + S[i - 1];
    }

    for (i = 1; i <= n; i++) {
        cache[i] = [0, p[i]];
    }

    for (var j = 1; j <= k; j++) {
        cache[0][j] = 0
        cache[1][j] = S[0];
    }

    for (i = 2; i <= n; i++) {
        for (j = 2; j <= k; j++) {
            cache[i][j] = Number.MAX_VALUE;

            var cost;
            for (var x = 1; x < i; x++) {
                cost = Math.max(cache[x][j - 1], p[i] - p[x]);
                if (cost < cache[i][j]) {
                    cache[i][j] = cost;
                    if (d[i] === undefined) d[i] = [];
                    d[i][j] = x;
                }
            }
        }
    }

    var dividers = [];
    var curr = d[n][k];
    var count = k;
    while (curr !== undefined) {
      dividers.push(curr);
      curr = d[curr] ? d[curr][--count]: undefined;
    }

    return [cache[n][k], dividers];
}

var run = function() {
    var test = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    console.log('S', test);

    console.log(integerPartitionRec(test.length, 3, test));
    console.log(integerPartitionDp(test, 3));
};

run();


texts: Algorithm to find bucket and item indices from power of two bins?

texts:
So this is building off of Algorithm for dividing a number into largest "power of two" buckets?. Here is a slight modification of the answer from there:

let numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201]
numbers.forEach(n => console.log(`${n} =`, split(n).join(', ')))

function split(number) {
  const result = [0, 0, 0, 0, 0, 0]
  let unit = 32
  let index = 5
  while (unit > 0) {
    while (number >= unit) {
      result[index]++
      number -= unit
    }
    index -= 1
    unit >>= 1
  }
  return result
}

The split function creates "power of two" buckets from an overall array of items of length n. That is, it divides a single large array into multiple small arrays. The result array is 6 items long, accounting for buckets of sizes [1, 2, 4, 8, 16, 32]. Each item in the array is how many buckets of that size need to exist.
Given that, the goal is to then take an index i, and return the bucket and bucket index where you will find that corresponding item. So for example, here are some outputs, and here is my attempt at an algorithm:

let numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201]
numbers.forEach(n => {
  const [c, i] = getCollectionIndexAndItemIndex(n, 300)
  console.log(`${n} = ${c}:${i}`)
})

function getCollectionIndexAndItemIndex(i, size) {
  const parts = split(size).reverse() // assume this is memoized or something
  let j = 0
  let last = 0
  let map = [1, 2, 4, 8, 16, 32].reverse()
  let k = 0
  let bucket = 0
  main:
  while (k <= i) {
    let times = parts[j]
    while (times--) {
      let value = map[j]
      last = 0
      while (value--) {
        k++
        if (value > 0) {
          last++
        } else {
          last = 0
          bucket++
        }
        if (k == i) {
          break main
        }
      }
    }
    j++
  }

  return [ bucket, last ]
}

function split(number) {
  const result = [0, 0, 0, 0, 0, 0]
  let unit = 32
  let index = 5
  while (unit > 0) {
    while (number >= unit) {
      result[index]++
      number -= unit
    }
    index -= 1
    unit >>= 1
  }
  return result
}

That outputs this:
1 = 0:1
2 = 0:2
3 = 0:3
4 = 0:4
5 = 0:5
6 = 0:6
7 = 0:7
30 = 0:30
31 = 0:31
32 = 1:0
33 = 1:1
20 = 0:20
25 = 0:25
36 = 1:4
50 = 1:18
100 = 3:4
201 = 6:9

So basically, for index i == 1, we go to the first bucket (bucket 0), second index (i == 1), represented as 1 = 0:1. For the 32nd index i == 32, that is the 33rd item, so we fill up 1 32-item bucket, and spill over 1, so index 0 in the second bucket, represented 32 = 1:0. For index 201, equals 6:9, which you can calculate as ((32 * 6) - 1) + 10 == 192 - 1 + 10 == 201.
The problem is, this algorithm is O(n), it counts k++ for every item up to k == i. I think there might be a way to optimize this so it can do larger jumps (32, 16, 8, 4, 2, 1 jumps), and cut out a lot of the iterations, I'm just not sure how. Can you find a way to maximally optimize this to the fewest number of steps, using only primitive operations and values (i.e. not fancy array.map and such, but just low-level while or for loops, and bitwise operations)? Basically, how can you optimize the getCollectionIndexAndItemIndex operation, and also simplify it so it's easier to follow.
The size parameter is set to 300, but that is the size of the array. But it could be any size, and we would then want to find the corresponding index within that array, jumping to the appropriate bucket and offset.


texts: Project Euler 22: Names scores by Loki 2

texts:
Alternative to Project Euler 22 solution.

Project Euler 22

Slightly more brittle than the original. This code depends on the input stream being exactly as specified. But on the other side of the coin it's slightly easier to read because you don't have to wonder about std::locale and code that uses facets like std::ctype<> (which few people understand how to use).

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

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

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

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <set>
#include <numeric>

long scoreName(std::string const& name)
{
    return std::accumulate(std::begin(name), std::end(name), 0L,
                           [](long v1, char x){return v1 + x - 'A' + 1;});
}

struct FirstName
{
    // Read a name from a stream.
    // Each name is quoted and separated with comma.
    // There are no extra spaces on the stream.
    //  Sample: "DEBBIE","APRIL","LESLIE","CLARA","LUCILLE","JAMIE"
    std::string name;

    // Read the next name from the input.
    // Note does not remove quotes.
    friend std::istream& operator>>(std::istream& s, FirstName& data)
    {
        return std::getline(s, data.name, ',');
    }

    // When we convert this object to a std::string
    // we remove the quotes around the name. In the code
    // below this happens as the iterator is de-reference into the set.
    operator std::string() const
    {
        return name.substr(1, name.size() - 2);
    }
};

Thus leaving a very simple main.

int main()
{
    std::ifstream   data("euler/e22.data");

    std::set<std::string> names{std::istream_iterator<FirstName>(data),
                                std::istream_iterator<FirstName>()};

    long    score   = 0;
    long    loop    = 1;
    for(auto name: names) {
        score += (loop * scoreName(name));
        ++loop;
    }
    std::cout << score << "\n";
}


texts:
I have this CSS selector:

.img + *{
}

Which, from my understanding, will make the browser look for all the elements and then select only those which follow an element with the class img. Is there a better way of writing this selection to improve performance?

Relevant HTML structure:

    <random-element>content is here</random-element>


texts: Putting a matrix from a text file into a list

texts:
I'm trying to read a text file with matrix and put it in a list, but I am using two loops here and I want my function to be faster.

def read_file(path_to_file):
    mylist=[]
    for eachLine in open(path_to_file,'rt'):
        mylist.append([int(eachRow) for eachRow in eachLine.split()])
    return mylist


texts: C++ overloading += operator in custom string class better implementation

texts:
I am trying to learn C++, so I started coding a custom string class (using only c-style strings) to get familiar with concepts like operator overloading etc. in the case we have a pointer attribute. I wanted to know if there is a smarter/better/neater way to implement the += operator (or the others).
So I am basically defining a private char pointer to store the c-style string, two constructors (empty, char* arg), a copy constructor, a move constructor, a destructor (to deallocate the allocated space from the heap) and two operators (to concatenate strings).
mystring.h
#include <iostream>
#include <cstring>

class mystring
{
private:
    char* str;

public:
    mystring();
    mystring(char* str);
    mystring(const mystring &s);
    mystring(mystring &&s) noexcept;
    ~mystring();

    mystring& operator=(const mystring &s);
    friend std::ostream& operator<<(std::ostream &out, const mystring &s);

    mystring operator+(const mystring &s);
    mystring& operator+=(const mystring &s);
};

mystring.cpp
#include "mystring.h"

mystring::mystring() : mystring(nullptr) {};

mystring::mystring(char* str) : str{nullptr}
{
    if(str == nullptr){
        this->str = new char;
        this->str = '\0';
    }else {
        this->str = new char[strlen(str) + 1];
        strcpy(this->str, str);
    }
}

// Deep copy
mystring::mystring(const mystring &s) : str{nullptr}
{
    if(str == nullptr){
        this->str = new char;
        *(this->str) = '\0';
    }else {
        this->str = new char[strlen(s.str) + 1];
        strcpy(this->str, s.str);
    }
}

// Move constructor
mystring::mystring(mystring &&s) noexcept : str{s.str} { s.str = nullptr; }

mystring::~mystring() { delete [] str; }

mystring& mystring::operator=(const mystring &s){
    if(this != &s){
        this->str = new char[strlen(s.str) + 1];
        strcpy(this->str, s.str);
    }

    return *this;
}

std::ostream& operator<<(std::ostream &out, const mystring &s){
    out << s.str;
    return out;
}

mystring mystring::operator+(const mystring &s){
    mystring concat;
    concat.str = new char[strlen(this->str) + strlen(s.str) + 1];
    strcpy(concat.str, this->str);
    strcat(concat.str, s.str);
    return concat;
}

mystring& mystring::operator+=(const mystring &s){

    // temp save "this" string to other
    mystring other {new char(strlen(this->str) + 1)};
    strcpy(other.str, this->str);

    // allocate space for the concatenated string
    this->str = new char[strlen(this->str) + strlen(s.str) + 1];

    // move "this" and input strings to "this"
    strcpy(this->str, other.str);
    strcat(this->str, s.str);

    return *this;
}


texts: Project Euler Problem 8 - Largest product in a series


texts: Running xinput to change touchpad settings

texts:
I am looking for some feedback on the code below, mainly for efficiency or mechanism correctness (like eval vs. subprocess). I am also curious if .find() is the best mechanism to use here. I am not familiar with regex, so my crutch (or benefit, depending) is using .find() over learning a sublanguage like regex.

import subprocess

get_device_id = subprocess.Popen(["xinput", "list", "SynPS/2 Synaptics TouchPad"], stdout=subprocess.PIPE)
gdi_str = str(get_device_id.stdout.read())
gdi_id_find = (gdi_str[gdi_str.find('id='):])
gdi_len = 3
gdi = (gdi_id_find[gdi_len:5])
if gdi.isdigit():
    device_id = gdi
else:
    pass

get_prop_id = subprocess.Popen(["xinput", "list-props", "15"], stdout=subprocess.PIPE)
r = str(get_prop_id.stdout.read())

if "2 Synaptics TouchPad" in r:
    b = (r[r.find('libinput Tapping Enabled ('):])
    bLen = len('libinput Tapping Enabled (')
    b = (b[bLen:b.find(')')])
    if b.isdigit():
        prop_id = b
    else:
        pass

subprocess.run(["xinput", "set-prop", device_id, prop_id, "1"])

This code parses the output of:

xinput list SynPS/2 Synaptics TouchPad

to get a numerical device ID, in this case 15:

SynPS/2 Synaptics TouchPad                      id=15   [slave  pointer  (2)]

The code then runs:

xinput list-props 15   # 15 is our parsed id

and parses this output:

Device 'SynPS/2 Synaptics TouchPad':
Device Enabled (147):   1
Coordinate Transformation Matrix (149): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
libinput Tapping Enabled (300): 0
libinput Tapping Enabled Default (301): 0
libinput Tapping Drag Enabled (302):    1
libinput Tapping Drag Enabled Default (303):    1
libinput Tapping Drag Lock Enabled (304):       0
libinput Tapping Drag Lock Enabled Default (305):       0
libinput Tapping Button Mapping Enabled (306):  1, 0
libinput Tapping Button Mapping Default (307):  1, 0
libinput Natural Scrolling Enabled (282):       0
libinput Natural Scrolling Enabled Default (283):       0
libinput Disable While Typing Enabled (308):    1
libinput Disable While Typing Enabled Default (309):    1
libinput Scroll Methods Available (286):        1, 1, 0
libinput Scroll Method Enabled (287):   1, 0, 0
libinput Scroll Method Enabled Default (288):   1, 0, 0
libinput Click Methods Available (310): 1, 1
libinput Click Method Enabled (311):    1, 0
libinput Click Method Enabled Default (312):    1, 0
libinput Middle Emulation Enabled (291):        0
libinput Middle Emulation Enabled Default (292):        0
libinput Accel Speed (293):     0.000000
libinput Accel Speed Default (294):     0.000000
libinput Left Handed Enabled (298):     0
libinput Left Handed Enabled Default (299):     0
libinput Send Events Modes Available (267):     1, 1
libinput Send Events Mode Enabled (268):        0, 0
libinput Send Events Mode Enabled Default (269):        0, 0
Device Node (270):      "/dev/input/event10"
Device Product ID (271):        2, 7
libinput Drag Lock Buttons (284):       <no items>
libinput Horizontal Scroll Enabled (285):       1

for the purposes of getting the prop-id for "libinput Tapping Enabled", in this case 300:

libinput Tapping Enabled (300): 0

Once the value is established, the code does a basic check for .isdigit() and if True, presents the values to:

subprocess.run(["xinput", "set-prop", device_id, prop_id, "1"])

Which ultimately sets the value to 1:

libinput Tapping Enabled (300): 1


texts: Adding augmented maps to a vector based on regex text grabbing

texts:
This is my latest brain child for clojure, could it be done with less code, cleaner, or in a more re applicable way? I am at a pretty early stage in my clojure learning so an in depth explanation of how and why my code is faulty would help me get a handle on what I am doing wrong so I do not build bad habits.

(def next-apendage
  #(hash-map :name (clojure.string/replace (:name %1) #"[0-9]" (str (+ 1 %2 (read-string (re-find #"[0-9]" (:name %1))))))))

(defn add-apendages
  [times part]
  (loop [done 0
         final-apendages [part]]
    (if (= done times)
      final-apendages
      (recur
       (inc done)
       (conj final-apendages
             (next-apendage part done))))))

(add-apendages 2 {:name "tentacle-3"})
;;OUTPUT->[{:name "tentacle-3"} {:name "tentacle-4"} {:name "tentacle-5"}]

That really ugly looking first function takes two arguments a map and a number. The number is added (with a compensation for done starting at 0) to the :name string of the map. The second function condenses the new appendages along side the original into a list. The third section is a call to the second function.


texts: Counting Monday and Friday from a Date Range

texts:
How can I get Monday and Friday from a date range (start and end date)?

Example:

startdate - 03/24/2014
enddate - 04/01/2014

Result should be:

Monday - 2
Friday - 2

I tried this code:

Monday = CountDays(DayOfWeek.Monday, startDate, endDate);
Friday = CountDays(DayOfWeek.Friday, startDate, endDate);

static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
    TimeSpan ts = end - start;
    int count = (int)Math.Floor(ts.TotalDays / 7);
    int remainder = (int)(ts.TotalDays % 7);
    int sinceLastDay = (int)(end.DayOfWeek - day);
    if (sinceLastDay < 0) sinceLastDay += 7;

    if (remainder >= sinceLastDay) count++;

    return count > 0 ? count : 0;
}

And this code works!  Is there any other way to simplify this code?


texts: Time complexity of common ancestor algorithm

texts:
I have an algorithm here to find the common ancestor of two nodes in a binary tree.

def commonAncestor(self, nodeA, nodeB, root):
            #checking if nodeB is a descendant of nodeA
            checkLeft = self.checkSubtree(nodeA, nodeB, root.leftChild)
            checkRight = self.checkSubtree(nodeA, nodeB, root.rightChild)
            if checkLeft == 1 and checkRight == 1:
                return root
            else:
                if checkLeft == 2:
                    # pdb.set_trace()
                    result = self.commonAncestor(nodeA, nodeB, root.leftChild)
                if checkRight == 2:
                    result = self.commonAncestor(nodeA, nodeB, root.rightChild)
                else:
                    raise ValueError("One of the values you have entered is not in the binary tree")

            return result

def checkSubtree(self, nodeA, nodeB, node):
            res = 0 #res is being initialized as a separate variable each time
            if node is None:
                return 0
            if node is nodeA or node is nodeB:
                res += 1
            res += self.checkSubtree(nodeA, nodeB, node.leftChild)
            res += self.checkSubtree(nodeA, nodeB, node.rightChild)
            return res

I think that the runtime of this algorithm is \$O(\log^2 n)\$. The first algorithm will run \$O(\log n)\$ times because it recurses through the binary tree, touching every node, and it subsequently calls the second function on each recursion which again recurses \$O(\log n)\$ times, correct?

I know this is a not an efficient algorithm, so how do I go about improving this? Specifically, I want to know how to approach the problem of thinking about how to improve this versus just seeing the code of the improved version.

Definition of node class

class TreeNode():
    def __init__(self, val, left=None, right=None):
        self.value = val
        self.leftChild = left
        self.rightChild = right

    def insertLeftChild(self, val):
        self.leftChild = val

    def insertRightChild(self, val):
        self.rightChild = val

    def hasLeftChild(self):
        return self.leftChild is not None

    def hasRightChild(self):
        return self.rightChild is not None


texts:
I want to add a parent reference to a tree like structure. The structure can be seen in the first code snippet, which also is how I would use my code, for example inside an angular controller.

$scope.tree = Tree.parentize({
    title: 'root',
    children: [{
        title: 'child one',
        children: [{
            title: 'leaf one',
            children: []
        }, {
            title: 'leaf two',
            children: []
        }, {
            title: 'leaf three',
            children: []
        }]
    }, {
        title: 'child two',
        children: [{
            title: 'leaf four',
            children: []
        }, {
            title: 'leaf five',
            children: []
        }]
    }]
});

This is how I implemented the parentize() function.

'use strict';

var Tree = (function () {
    var parentize = function(tree) {

        angular.forEach(tree.children, function(value, key) {
            this.children[key].parent = function() {
                return tree;
            };
            parentize(value);
        }, tree);
        return tree;
    };

    return {
        parentize: parentize
    };
})();

I chose to use a function, to still be able to use JSON.stringify() without need for the replacer argument. It works as expected. But is it the right approach? Is instantiation of a function for each node to heavy? The tree will probably not have more than 500 nodes.

I tried to follow the module pattern. Did I do anything wrong here? Also I'm not sure about "not polluting the global namespace". Is it wrong for Tree to be global? Should Tree be provided via angular as a service, or factory?

(jsHint warns about 'Tree' is not defined in my controller.js. However adding Tree to the predef list, it warns about Redefinition of 'Tree' in my tree.js.)


texts:
I recently decided to try my hand at this problem of calculating the number of days between two given dates including leap years in the calculation. I chose to do it in C++ as it is the language I feel most comfortable with and was wondering about the quality of my code.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

typedef struct Date{
    int day;
    int month;
    int year;

    Date(int d, int m, int y):day(d), month(m), year(y)
    {
    }

    bool operator== (const Date& rhs)
    {
        return day==rhs.day && month==rhs.month && year==rhs.year;
    }
}Date;

vector<int> splitBy(string input, char delimiter)
{
    vector<int> output;
    int startDayIndex = 0;
    int endIndex = 0;
    int length = input.length();
    while(input.find(delimiter, startDayIndex)!=string::npos)
    {
        endIndex = input.find(delimiter, startDayIndex);
        output.push_back(stoi(input.substr(startDayIndex,endIndex)));
        startDayIndex = endIndex+1;

    }

    output.push_back(stoi(input.substr(startDayIndex,length)));
    return output;
}

int NextMonth(int currentMonth)
{
    if(currentMonth == 12) return 1;
    return currentMonth+1;
}

int NextYear(int month, int currentYear)
{

    return month==1?currentYear+1:currentYear;
}

bool isLeapYear(int year)
{
    if(year%4!=0) return false;
    else if(year%100!=0) return true;
    else if(year%400!=0) return false;
    else return true;
}

int DaysInMonth(int month, int year)
{
    vector<int> days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if(isLeapYear(year)) days[1] = 29;
    return days[month-1];

}

bool errorCheck(Date start, Date end)
{

    if(start.year>end.year) return true;
    else if(start.month>end.month && start.year==end.year) return true;
    else if(start.day>end.day && start.month==end.month && start.year==end.year) return true;
    return false;
}

int start(string firstDate, string endDate)
{
    vector<int> initDate = splitBy(firstDate, '/');
    vector<int> finDate = splitBy(endDate, '/');
    Date startDay(initDate[0], initDate[1], initDate[2]);
    Date endDay(finDate[0], finDate[1], finDate[2]);
    if(errorCheck(startDay,endDay)) return -1;
    int count = 0;
    int days = DaysInMonth(startDay.month, startDay.year);

    while((startDay==endDay)!=1)
    {
        while(startDay.day<days)
        {
            startDay.day = startDay.day + 1;
            count++;
            if((startDay==endDay)==1)
            {
                return count;
            }
        }
        count++;
        startDay.day = 1;
        startDay.month = NextMonth(startDay.month);
        startDay.year = NextYear(startDay.month,startDay.year);
        days = DaysInMonth(startDay.month, startDay.year);
    }
    return count;

}

int main()
{
    cout << "Enter date in format DD/MM/YYYY\n";
    string startDayDate;
    string endDate;
    cout << "Enter first date\n";
    cin >> startDayDate;
    cout << "Enter second date\n";
    cin >> endDate;
    int result = start(startDayDate, endDate);
    result==-1?cout << "Invalid input\n":cout << "The number of days are: " << result << endl;

    return 0;

}

I know off the bat that using namespace std is an issue, are there any other issues with regards to readability, efficiency, etc.? Does the code I have written to accomplish this task qualify as "good" code?


texts:
I profiled a library I'm writing that uses vector transposes and found that I am spending a good bit of time doing the following transpose. I am using a std::vector of std::vector<double>s to represent the column vectors.

What are some ways to optimize this function?

std::vector<double> transpose_vector(const std::vector<std::vector<double>> &column_vec) {
  // take a column vector:
  // |x1|
  // |x2|
  // |x3|
  // and return a row vector |x1, x2, x3|
  std::vector<double> row_vector;
  for (auto c : column_vec) {
    for (auto r : c) {
      row_vector.push_back(r);
    }
  }
  return row_vector;
}


texts:
This is part of the Construct library. Rebuffered is used to turn a seekless/tellless stream like from a socket or pipe into a seekable/tellable one like a BytesIO or a file.

If tailcutoff is provided, only that amount of bytes is kept counting from the end of last read write operation backwards. Otherwise entire stream is cached.

class RebufferedBytesIO:
    __slots__ = ["substream","offset","rwbuffer","moved","tailcutoff"]

    def __init__(self, substream, tailcutoff=None):
        self.substream = substream
        self.offset = 0
        self.rwbuffer = b""
        self.moved = 0
        self.tailcutoff = tailcutoff

    def read(self, count):
        startsat = self.offset
        endsat = startsat + count
        if startsat < self.moved:
            raise IOError("could not read because tail was cut off")
        while self.moved + len(self.rwbuffer) < endsat:
            newdata = self.substream.read(128*1024)
            self.rwbuffer += newdata
            if not newdata:
                sleep(0)
        data = self.rwbuffer[startsat-self.moved:endsat-self.moved]
        self.offset += count
        if self.tailcutoff is not None and self.moved < self.offset - self.tailcutoff:
            removed = self.offset - self.tailcutoff - self.moved
            self.moved += removed
            self.rwbuffer = self.rwbuffer[removed:]
        if len(data) < count:
            raise IOError("could not read enough bytes, something went wrong")
        return data

    def write(self, data):
        startsat = self.offset
        endsat = startsat + len(data)
        while self.moved + len(self.rwbuffer) < startsat:
            newdata = self.substream.read(128*1024)
            self.rwbuffer += newdata
            if not newdata:
                sleep(0)
        self.rwbuffer = self.rwbuffer[:startsat-self.moved] + data + self.rwbuffer[endsat-self.moved:]
        self.offset = endsat
        if self.tailcutoff is not None and self.moved < self.offset - self.tailcutoff:
            removed = self.offset - self.tailcutoff - self.moved
            self.moved += removed
            self.rwbuffer = self.rwbuffer[removed:]
        return len(data)

    def seek(self, at, whence=0):
        if whence == 0:
            self.offset = at
            return self.offset
        elif whence == 1:
            self.offset += at
            return self.offset
        else:
            raise ValueError("seeks only with whence 0 and 1")

    def seekable(self):
        return True

    def tell(self):
        return self.offset

    def tellable(self):
        return True

    def cachedfrom(self):
        return self.moved

    def cachedto(self):
        return self.moved + len(self.rwbuffer)


texts: Classifying and counting database entries using Scala map and flatMap

texts:
I am new to Spark and Scala and I have solved the following problem. I have a table in database with following structure:

     id       name      eid        color
     1        John      S1         green
     2        Shaun     S2         red
     3        Shaun     S2         green
     4        Shaun     S2         green
     5        John      S1         yellow

And now I want to know how many times a person is red, green or yellow. So the result should be like this

   name     red       yellow        green
   John     0           1             1
   Shaun    1           0             2

I have written this code and it solves the problem, But I am not sure is this the best way to do it. It think my code is large for this small problem and it can be done with smaller code and with best practice. I need some guidance

  val rdd = df.rdd.map {
  case Row(id: Int, name: String, eid: String, color: String) => ((eid),List((id, name, eid, color)))
}.reduceByKey(_ ++ _)
val result = rdd.map({
  case (key, list) => {
    val red = list.count(p => p._4.equals("red"))
    val yellow = list.count(p => p._4.equals("yellow"))
    val green = list.count(p => p._4.equals("green"))
    val newList = list.map(x => (x._2, red, yellow, green))
    (key, newList.take(1))
  }
}).flatMap {
  case ((eid), list) =>
    list.map {
      case (name, red, yellow, green) =>
        (eid, name, red, yellow, green)
    }
}
import SparkConfig.sc.sqlContext.implicits._
val rDf = result.toDF("eid", "name", "red", "yellow", "green");
rDf.show()


texts: Quickest way of finding the largest integer n such that n! has length of m bits

texts:
Factstone Benchmark

  Amtel has announced that it will release a 128-bit computer chip by
  2010, a 256-bit computer by 2020, and so on, continuing its strategy
  of doubling the word-size every ten years. (Amtel released a 64-bit
  computer in 2000, a 32-bit computer in 1990, a 16-bit computer in
  1980, an 8-bit computer in 1970, and a 4-bit computer, its first, in
  1960.)

  Amtel will use a new benchmark – the Factstone – to advertise the
  vastly improved capacity of its new chips. The Factstone rating is
  defined to be the largest integer \$n\$ such that \$n!\$ can be represented as an unsigned integer in a computer word.

  Given a year \$1960\le y\le 2160\$, what will be the Factstone rating of Amtel's most recently released
  chip?

  Input

  There are several test cases. For each test case, there is one line of
  input containing \$y\$. A line containing \$0\$ follows the last test case. >

  Output

  For each test case, output a line giving the Factstone rating.

  Sample Input 1

1960
1981
0

  Sample Output 1

3
8

import math
n = int(input())
while n != 0:
    n = (n - 1960) / 10 + 2
    m = pow(2,n)
    i = 1
    while m > 0:
        m -= math.log(i,2)
        i += 1
    print(i - 2)
    n = int(input())

Can someone please help me time optimize this code? I'm doing it for a site that checks my code but I always fail at the time check.


texts:
I am quite new to D3 and JavaScript in general, so I'm sure there is a way to write the following in a lot less code:

function CalculatePeriodReturns(){
    periodReturns = [];
    [...]
    periodReturns.push({
        length: [...],
        mean: [...],
        pctile50: [pctile(0.25),pctile(0.75)],
        pctile90: [pctile(0.05),pctile(0.95)],
        pctile99: [pctile(0.005),pctile(0.995)],
        min: [...],
        max: [...]
    });
}

function DrawChart(){
    var margin = {top: 20, right: 100, bottom: 30, left: 100},
        width = $("#multiperiod_chart").width() - margin.left - margin.right,
        height = $("#multiperiod_chart").height() - margin.top - margin.bottom;

    var svg = d3.select("#multiperiod_chart").append("svg")
        .datum(periodReturns)
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .attr("id", "multiperiod_chart_svg")
        .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

    var x = d3.scaleLinear().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);

    x.domain(d3.extent(periodReturns, d=>d.length));
    y.domain([d3.min(periodReturns, d => d.min),
        d3.max(periodReturns, d => d.max)]);

    var area99 = d3.area()
        .x(d=>x(d.length))
        .y0(d=>y(d.pctile99[0]))
        .y1(d=>y(d.pctile99[1]))

    svg.append("path")
        .attr("class", "area")
        .attr("id", "area99")
        .attr("fill", "#565A68")
        .attr("d", area99);

    var area90 = d3.area()
        .x(d=>x(d.length))
        .y0(d=>y(d.pctile90[0]))
        .y1(d=>y(d.pctile90[1]))

    svg.append("path")
        .attr("class", "area")
        .attr("id", "area90")
        .attr("fill", "#7B7F8B")
        .attr("d", area90);

    var area50 = d3.area()
        .x(d=>x(d.length))
        .y0(d=>y(d.pctile50[0]))
        .y1(d=>y(d.pctile50[1]))

    svg.append("path")
        .attr("class", "area")
        .attr("id", "area50")
        .attr("fill", "#A1A3AA")
        .attr("d", area50);

    [...]

}

For a start, is there a way to create an accessor area(y0,y1) that takes the two d.pctileXX properties as attributes or similar? Maybe I can combine the three svg.append's as well?


texts: Python class to save objects into MongoDB

texts:
I am new in Python, and I am writing a Python class representing a calendar entry, each entry contains 2 properties: the date and its type, which can be weekday/weekend/legal holiday/paid holiday/unpaid holiday. The objects can be serialized into JSON format, saved into a MongoDB collection and loaded back into memory.

The serialization and deserialization are implemented with Marshmallow. The problem is that MongoDB uses field _id as primary key, but I want to make the class property entry_date primary key, so I have to do it manually by adding line: serialized['_id'] = serialized['entry_date'].

Here is the complete source code.

#!/usr/bin/python
# -*- coding: utf-8 -*-

from marshmallow import Schema, fields, post_load
from pymongo import MongoClient
from datetime import date

ENTRY_WEEKDAY = 0
ENTRY_WEEKEND = 1
ENTRY_LEGAL_HOLIDAY = 2
ENTRY_PAID_HOLIDAY = 3
ENTRY_UNPAID_HOLIDAY = 4

class CalendarEntry(object):
    def __init__(self, entry_date, entry_type):
        self.entry_date = entry_date

        iso_format = self.entry_date.isoformat()

        if self.entry_date.weekday() in range(5) and entry_type == ENTRY_WEEKDAY:
            raise ValueError('{0} is already a weekday.'.format(iso_format))
        else:
            if entry_type == ENTRY_WEEKEND:
                raise ValueError('{0} is already a weekend day.'.format(iso_format))
            elif entry_type == ENTRY_UNPAID_HOLIDAY:
                raise ValueError('{0} is a weekend day, cannot be an unpaid holiday.'.format(iso_format))

        self.entry_type = entry_type

    def __getattribute__(self, item):
        if item == 'year':
            return object.__getattribute__(self, 'entry_date').year
        elif item == 'month':
            return object.__getattribute__(self, 'entry_date').month
        elif item == 'day':
            return object.__getattribute__(self, 'entry_date').day
        return object.__getattribute__(self, item)

    def serialize(self):
        schema = CalendarEntrySchema()
        output = schema.dump(self)
        return output.data

    @classmethod
    def make_instance(cls, data):
        schema = CalendarEntrySchema()
        result = schema.load(data)
        return result.data

class CalendarEntrySchema(Schema):
    entry_date = fields.Date(required=True)
    entry_type = fields.Integer(required=True)

    @post_load
    def make_entry(self, data):
        return CalendarEntry(**data)

if __name__ == '__main__':
    entry = CalendarEntry(date(2018, 1, 14), ENTRY_WEEKDAY)
    serialized = entry.serialize()
    print 'Serialized:', serialized

    # Manually add _id field for MongoDB.
    serialized['_id'] = serialized['entry_date']
    print 'Serialized with _id:', serialized

    clnt = MongoClient()
    collection = clnt.hrm.calendar_setting
    result = collection.insert_one(serialized)
    print 'Entry saved, inserted ID:', result.inserted_id

The output:

Serialized: {u'entry_type': 0, u'entry_date': '2018-01-14'}
Serialized with _id: {u'entry_type': 0, '_id': '2018-01-14', u'entry_date': '2018-01-14'}

The code works, but with duplicated fields, _id and entry_date contain exactly the same value.

Any suggestions and critiques please?


texts:
I've actually been struggling with painting with VB.Net for a few weeks. All I know is that I shouldn't use CreateGraphics if I can avoid it, so I've done just that. One of the community-challenge questions comes from a CodeGolf challenge that requires users to draw sprockets.

This is only my beginning of that. I've never displayed anything I haven't drawn in excel. At first I tried a Class of sprockets, but it wouldn't fill my List properly, so I've boiled it down to

populating an array
passing that array to the form
Painting my circles.

Essentially I read the input, convert it to integer array, send that to the form and draw the circles. I've probably made it way too complicated, but like I said, I've struggled for a few weeks, which is why I'm here. Parsing the input was pretty tricky to me, actually.

Input

Comes in the form of (sets of) 3 integers (x-position, y-position, radius) e.g.

(0, 0, 16),  (100, 0, 16),  (100, 100, 12),  (50, 50, 24),  (0, 100, 12)

Output

Standard Module

Option Explicit On
Option Strict On
Option Infer On
Option Compare Text
Imports System.IO
Module Module1
    Const INPUT_PATH As String = "C:\Temp\gearinput.txt"
    Public delimiter() As String = {"),"}
    Sub Main()
        Dim inputData() As String
        inputData = GetInput()
        Dim sprocketData() As String = Custom_Split(inputData(0))
        Dim paintingdata(,) As Integer = StringToIntArray(sprocketData)
        Dim targetForm As New Form1
        targetForm.Visible = True
        targetForm.DrawSprockets(targetForm, paintingdata)
    End Sub
    Private Function Custom_Split(ByVal stringToSplit As String) As String()
        stringToSplit = stringToSplit.Replace("(", String.Empty)
        stringToSplit = stringToSplit.Replace(" ", String.Empty)
        Dim stringArray() As String = stringToSplit.Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
        stringArray(stringArray.Length - 1) = stringArray(stringArray.Length - 1).Replace(")", String.Empty)
        Return stringArray
    End Function
    Private Function StringToIntArray(ByVal sprocketdata() As String) As Integer(,)
        Dim firstDimensionSize As Integer = sprocketdata.GetUpperBound(0)
        Dim integerArray(firstDimensionSize, 2) As Integer
        Dim tempString() As String
        For i As Integer = 0 To firstDimensionSize
            tempString = sprocketdata(i).Split(","c)
            For j = 0 To 2
                integerArray(i, j) = Convert.ToInt32(tempString(j))
            Next
        Next
        Return integerArray
    End Function

    Private Function GetInput() As String()
        Return File.ReadAllLines(INPUT_PATH)
    End Function
End Module

Form Code

Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Const BUFFER As Integer = 20
 Dim xValue As Integer
    Dim yValue As Integer
    Dim pRadius As Integer
    Dim paintData(,) As Integer
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load

    End Sub
Public Shared Sub DrawSprockets(ByVal myForm As Form1, ByVal dataArray(,) As Integer)
        myForm.paintData = dataArray
        For i As Integer = 0 To myForm.paintData.GetUpperBound(0)
            myForm.paintData(i, 0) += 10
            myForm.paintData(i, 1) += 10
        Next
        myForm.Refresh()
    End Sub

    Private Sub Form1_Paint(ByVal sender As Object, e As PaintEventArgs) Handles MyBase.Paint
Dim myPen As Pen

        myPen = New Pen(Brushes.Black)

        For i As Integer = 0 To paintData.GetUpperBound(0)
            e.Graphics.DrawEllipse(myPen, New Rectangle(paintData(i, 0), paintData(i, 1), paintData(i, 2), paintData(i, 2)))
            e.Graphics.FillEllipse(Brushes.Black, New Rectangle(paintData(i, 0), paintData(i, 1), paintData(i, 2), paintData(i, 2)))

        Next

    End Sub

End Class


texts: Improving a filter array function, to match elements and conditions

texts:
I have to do some check/match elements with conditions.
A have a list of conditions, each with a specific ID.
I've put for each of my elements an array with the ids of their respective affirmative conditions.
Some elements can share a condition. The goal is to, everytime a condition is "checked" by the user, the code filter the array with all elements, showing only the ones that attend the conditions.
I've made this function. But I don't know if its the "best" way..
this.selectedConditions is already maped by ID
Any help?

private filterElements(){

    let filtered: any[] = [];

    originalArray.forEach( item => {

      let isPossibility: boolean = true;

      for (let i = 0; i < this.selectedConditions.length; i++) {

        if( item.condition_matrix.indexOf( this.selectedConditions[i] ) === -1 ){
          isPossibility = false;
          break;
        }
      }

      if( isPossibility ){
        filtered.push(item);
      }

    });

    this.outputArray = filtered;

    if(this.outputArray.length === 0){
      this.outputArray.push( { <a_filler_object> } );
    }
}

Elements list example:
elements: [
    {
        name: 'el1',
        condition_matrix: [1,2]
    },
    {
        name: 'el2',
        condition_matrix: [2,3]
    },
    {
        name: 'el3',
        condition_matrix: [2,1]
    }
]

Conditions list example:
conditions: [
    {
        id: 1
        name: 'cond1'
    },
    {
        id: 2
        name: 'cond2'
    },
    {
        id: 3
        name: 'cond3'
    }
]


texts: How to use this jQuery search filter more effective?

texts:
This is my code:

function search() {
    $("#myInput").keyup(function() {
        var value = this.value.toLowerCase();

        $("table").find("tr").each(function(index) {
            if (index === 0) return;
            var id = $(this).find("td").first().text().toLowerCase();
            $(this).toggle(id.indexOf(value) !== -1);
        });
    });
}

function searchFilt(value) {
    $("table").find("tr").each(function(index) {
        if (index === 0) return;
        var id = $(this).find("td").first().text();
        $(this).toggle(id.indexOf(value) !== -1);
    });
};

However I have used:

$("table").find("tr").each(function(index) {
            if (index === 0) return;
            var id = $(this).find("td").first().text().toLowerCase();
            $(this).toggle(id.indexOf(value) !== -1);
        });
    });

twice, and I am sure there would be a more effective way to do this. However I am not sure how to go about doing so - any advice?


texts: Generic queries and handlers without reflection

texts:
I'm trying to implement generic queries and handlers so that I can make requests with simple syntax, like this:

var query = new HelloQuery("hi");
var result = processor.Process(query);

This post explains a brilliant technique for accomplishing this, but it uses reflection and dynamic to resolve handlers for queries.  I came up with an alternative using generics.

The central idea is the IQuery:

public interface IQuery<TSelf, TResult>
    where TSelf : IQuery<TSelf, TResult>
{
}

One such implementation could be:

public class HelloQuery : IQuery<HelloQuery, string>
{
    public HelloQuery(string message)
    {
        this.message = message;
    }

    private readonly string message;
    public string Message
    {
        get { return this.message; }
    }
}

The TSelf type argument is the key difference between my technique and the other post's technique.  It allows us to avoid reflection in the HandlerResolver:

public interface IHandlerResolver
{
    IQueryHandler<TQuery, TResult> GetHandlerFor<TQuery, TResult>()
        where TQuery: IQuery<TQuery, TResult>;
}

public class HandlerResolver : IHandlerResolver
{
    private readonly IContainer container;

    public HandlerResolver(IContainer container)
    {
        this.container = container;
    }

    public IQueryHandler<TQuery, TResult> GetHandlerFor<TQuery, TResult>()
        where TQuery : IQuery<TQuery, TResult>
    {
        var handler = this.container.Get<IQueryHandler<TQuery, TResult>>();
        return handler;
    }
}

You would register handlers at the composition root.  Here's the interface for a handler, and an implementation for HelloQuery:

public interface IQueryHandler<TQuery, TResult>
    where TQuery : IQuery<TQuery, TResult>
{
    TResult Handle(TQuery request);
}

public class HelloQueryHandler : IQueryHandler<HelloQuery, string>
{
    public string Handle(HelloQuery request)
    {
        var response = string.Format("Well \"{0}\" yourself!", request.Message);
        return response;
    }
}

And finally, the actual query processor:

public interface IQueryProcessor
{
    TResult Process<TQuery, TResult>(IQuery<TQuery, TResult> request)
        where TQuery : IQuery<TQuery, TResult>;
}

public class QueryProcessor : IQueryProcessor
{
    private readonly IHandlerResolver handlerResolver;

    public QueryProcessor(IHandlerResolver handlerResolver)
    {
        this.handlerResolver = handlerResolver;
    }

    public TResult Process<TQuery, TResult>(IQuery<TQuery, TResult> request)
        where TQuery : IQuery<TQuery, TResult>
    {
        var handler = this.handlerResolver.GetHandlerFor<TQuery, TResult>();
        var response = handler.Handle((TQuery)request);
        return response;
    }
}

The interfaces would be simpler without the queries' TSelf type argument, but then the C# compiler can't infer the types, and you end up having to spell out the full Process() call like processor.Process<HelloQuery, string>(query).  I'm trying to avoid this ugliness.

My question is:  Is the TSelf type argument a code smell?  Is there a better alternative that doesn't require falling back on reflection?


texts:
Can the following code be simplified/ improved? (NOTE: I am yet to learn OOP/ def functions). I have not used OOP and def functions on purpose, as I am yet to learn this aspect of Python. I have listed some things I would like to improve on below.

Could/ Should I implement for loops?
Is the structure of the code of a good standard?
How can I simplify the code (using less loops/ less code in general)?

# Python 3.4.3 // MacOS (Latest)

import random

WORD = ('apple', 'oracle', 'amazon', 'microsoft')
word = random.choice(WORD)
correct = word
clue = word[0] + word[(len(word)-1):(len(word))]
letter_guess = ''
word_guess = ''
store_letter = ''
count = 0
limit = 5

print('Welcome to "Guess the Word Game!"')
print('You have 5 attempts at guessing letters in a word')
print('Let\'s begin!')
print('\n')

while count < limit:
    letter_guess = input('Guess a letter: ')

    if letter_guess in word:
        print('yes!')
        store_letter += letter_guess
        count += 1

    if letter_guess not in word:
        print('no!')
        count += 1

    if count == 2:
        print('\n')
        clue_request = input('Would you like a clue?')
        if clue_request == 'y':
            print('\n')
            print('CLUE: The first and last letter of the word is: ', clue)
        if clue_request == 'n':
            print('You\'re very brave!')

print('\n')
print('Now its time to guess. You have guessed',len(store_letter),'letters correctly.')
print('These letters are: ', store_letter)

word_guess = input('Guess the whole word: ')
while word_guess:
    if word_guess.lower() == correct:
        print('Congrats!')
        break

    elif word_guess.lower() != correct:
        print('Unlucky! The answer was,', word)
        break

print('\n')
input('Press Enter to leave the program')


texts: Efficient way of flat mapping a range of a multidimensional random access collection

texts:
I've recently answered a question about reading elements from an array of arrays. A way it could be interpreted is that the OP wanted to read a range that could span over multiple subarrays of the 2D array like so :

let a = [["5", "3", ".", ".", "7", "."],
         ["6", ".", ".", "1", "9", "5"]]

a.lazy.flatMap{$0}[1..<7] ["3", ".", ".", "7", ".", "6"]

This way of reading a range would need to at least flatMap all the previous arrays to the lower bound of the range. Which would be wasteful.

A more natural way would be to only read the needed elements from the original array:

func get<T>(_ range: Range<Int>, from array2d: [[T]]) -> [T]? {
    var result: [T] = []
    result.reserveCapacity(range.upperBound - range.lowerBound)

    var count1 = 0

    //Get the index of the first element
    guard var low = array2d
            .firstIndex(where: {
                 count1 += $0.count
                 return range.lowerBound < count1 }),
          count1 != 0
    else { return nil }

    let before = count1 - array2d[low].count
    var count2 = before

    //Get the index of the last element in the range
    guard let high = array2d[low..<array2d.endIndex]
            .firstIndex(where: {
                 count2 += $0.count
                 return range.upperBound <= count2
            }),
          count2 != 0
    else { return nil }

    //Append the elements in the array with the low index
    for i in (range.lowerBound - before)..<min(range.upperBound - before, array2d[low].count) {
        result.append(array2d[low][i])
    }

    //If the range spans over multiple arrays
    if count1 < count2 {
        low += 1

        //Append the elements in the arrays with an index between low and high
        while low < high {
            result.append(contentsOf: array2d[low])
            low += 1
        }

        //Append the elements in the array with the high index
        for i in 0..<(range.upperBound - count2 + array2d[high].count) {
            result.append(array2d[high][i])
        }
    }

    return result
}

Which could be used like so :

let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]

get(5..<11, from: a) //Optional(["5", "6", "7", "8", "9", "10"])
get(7..<9, from: a) //Optional(["7", "8"])

To me, the above code feels.. on the border of sanity/maintainability...

What I'd like to do is to make it more generic, maybe as an extension to RandomAccessCollection, and making the flattening process recursive for arrays/collections of arbitrary dimensions. I'm stuck here and not sure if this is the appropriate network to ask such a question.

Feedback on all aspects of the code is welcome, such as (but not limited to):

Efficiency,
Readability,
Naming.


texts: Redacting everything in a string except a particular word

texts:
I am working through the Coding Bat exercises for Java. Here is one I have just completed:

  Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

And here is my solution:

public String plusOut(String str, String word){

    String s = "";
    String n = str + "  ";

    int i = 0;
    while(i < str.length()) {

        if (!(n.substring(i, i + word.length()).equals(word))) {
            s += "+";
            i++;
        } else {
            s += word;
            i += word.length();
        }
    }

    return s;
}

As you can see, I concatenated two spaces on the original string and used that to test the substrings. This was to avoid out of bounds exceptions.

What I want to do is optimise my solution, because I don't like how I added two spaces just to avoid errors. I want to change the if statement so that it tests the substrings of str rather than n, and get rid of n entirely. I have tried but I can't seem to find a way of doing it. How can I do this? What else needs optimising?


texts: A function for batch backpropagation of weight errors in a dense neural network layer

texts:
I'm switching my neural network library over to using ArrayFire for performance.

One of the features I am losing moving from ndarray is ndarray_einsum_beta, as such I need to write my own function to carry out what I was using einsum for.

This function needs to be as fast as possible.

This is the function:

fn arrayfire_weight_errors(errors:arrayfire::Array<f32>,activations:arrayfire::Array<f32>) -> arrayfire::Array<f32> {
    let rows:u64 = errors.dims().get()[0];

    let er_width:u64 = errors.dims().get()[1];
    let act_width:u64 = activations.dims().get()[1];
    let dims = arrayfire::Dim4::new(&[act_width,er_width,rows,1]);

    let temp:arrayfire::Array<f32> = arrayfire::Array::<f32>::new_empty(dims);

    for i in 0..rows {
        let holder = arrayfire::matmul(
            &arrayfire::row(&activations,i),
            &arrayfire::row(&errors,i),
            arrayfire::MatProp::TRANS,
            arrayfire::MatProp::NONE
        );
        arrayfire::set_slice(&temp,&holder,i);
    }
    return temp
}

How could I improve this to make it better? (and hopefully faster)

(Apologies for using arrayfire:: everywhere, this is a test project which uses a few other linear algebra libraries, so it's best to specify)

ndarray approach:

fn ndarray_einsum(errors:ndarray::Array2<f32>,activations:ndarray::Array2<f32>) -> ndarray::ArrayD<f32> {
    return ndarray_einsum_beta::einsum("ai,aj->aji", &[&errors, &activations]).unwrap();
}


texts: Pick a two different random elements from a given closed range

texts:
I wrote a function which picks a two different random elements from a closed  range of ints and returns them as a tuple.

I would like to take a your feedback, if the solution is a "Clever", "Best practice" or "non of them"

func pickTwoRandomElementsFromRange(_ range: ClosedRange<Int>) -> (Int, Int)? {
    guard range.count >= 2 else { return nil }

    let firstElement = range.randomElement()
    var secondElement = range.randomElement()

    while firstElement == secondElement  {
        secondElement = range.randomElement()
    }
    if let firstElement = firstElement, let secondElement = secondElement {
        return (firstElement, secondElement)
    }

    return nil
}


texts:
Below's some code I knocked up to escape the account name to be used in creating an ADSI reference to an account (e.g. escaping $sAmAccountName before using in [ADSI]"WinNT://$Domain/$sAmAccountName,user"

function ConvertTo-LdapEscapedString {
    param (
        [Parameter(Mandatory,ValueFromPipeline)]
        [string]$InputString
    )
    process {
        $InputString -replace '([,\\#+<>;"=])','\$1' -replace '(?<=^ *) ','\ ' -replace '(?= *$) ','\ '
    }
}
ConvertTo-LdapEscapedString '   this, is a demo\example #1 showing escaping of ,\#+<>;"= characters   '

This replaces the following characters with an escaped (i.e. prefixed with a forward-slash) version:

,
\
#
+
<
>
;
"
=
Leading Spaces
Trailing Spaces

Questions that led me to post this here:

Is there an existing function which could do this work that I should call instead of rolling my own?
Have I covered off all characters?
Have I made any other oversights?