texts:
I have a table which has tasks with several statuses, user can use filter check-boxes to show and hide rows based on these status filters.

 function toggleRows(checkBox, img) {
    var show = $("#" + checkBox).prop("checked");
    var rows = $('tr img[src="../_layouts/15/images/' + img + '.png"]').closest('tr')

    if (show) {
        rows.show();
    }
    else {
        rows.hide();
    }
}

Implementation can be,

toggleRows("taskFinishedCb", "finished");

I would put table's code too but I am not allowed to touch that and only code above needs to be improved.


texts:
I'm looking for a way to optimize this piece of code in Python.

all_users holds all the Twitter users and friends_ids is an array of IDs.

g = Graph(directed=True)
all_users = users.find({}, { 'id_str' : 1, 'friends_ids' : 1}) # This is from MongoDb

names = []
edges = []
print 'Processing first 1000 batch'
for idx, user in enumerate(all_users):
    if idx % 1000 == 0 and idx != 0:
        print 'Processing ' + str(idx) + ' batch'
    names.append(str(user['id_str']))
    for friend_id in user['friends_ids']:
        edges.append((user['id_str'], str(friend_id)))
        if not str(friend_id) in names:
            names.append(str(friend_id))

print len(names)
print len(edges)

all_users has 4k records but each of the user has at least 10k of friends_ids. In order to create a graph I need a list of nodes which I have in names and list of edges edges.

The format of edges would be [(node1, node2), (node2, node3), ...], which means that node1 connects to node2 and node2 connect to node3. I'm not sure why but this script takes almost full 10 min to run. So, I'm looking for a way to optimize this.


texts:
I wrote a python program to find if a matrix is a magic square or not. It works, but I can't help feeling like I may have overcomplicated the solution. I have seen other implementations that were a lot shorter, but I was wondering how efficient/inefficient my code is and how I could improve it and/or shorten it to achieve the result I am looking for.
def main():

    matrix = [[4,9,2],
              [3,5,7],
              [8,1,6]]

    result = loShu(matrix)

    print(result)

def loShu(matrix):

    i = 0
    j = 0

    for i in range(0, len(matrix)):
        for j in range(0, len(matrix[j])):
            if ((matrix[i][j] < 1) or (matrix[i][j] > 9)):
                return ("This is not a Lo Shu Magic Square - one of the numbers is invalid")

    row1 = matrix[0][0] + matrix[0][1] + matrix[0][2]
    row2 = matrix[1][0] + matrix[1][1] + matrix[1][2]
    row3 = matrix[2][0] + matrix[2][1] + matrix[2][2]

    ver1 = matrix[0][0] + matrix[1][0] + matrix[2][0]
    ver2 = matrix[0][1] + matrix[1][1] + matrix[2][1]
    ver3 = matrix[0][2] + matrix[1][2] + matrix[2][2]

    diag1 = matrix[0][0] + matrix[1][1] + matrix[2][2]
    diag2 = matrix[0][2] + matrix[1][1] + matrix[2][0]

    checkList = [row1,row2,row3,ver1,ver2,ver3,diag1,diag2]

    temp = checkList[0]

    for x in range (0, len(checkList)):
        if checkList[x] != temp:
            return ("This is not a Lo Shu Magic Square")

    return ("This is a Lo Shu Magic Square")

main()


texts: Computing bezier curves of degree n with recursive functions

texts:
I have been looking at homemade CNC and have been wondering how curves are drawn, so I looked into it and found this cool article. I then decided to try coming up with a bezier curve algorithm in C. It seems to work ok, and while I haven't tried plotting points with this exact implementation, it seems to match up with results from a previous implementation that I did plot points with.

#include <stdint.h>

static long double bbezier(long double t, long double p0, long double p1){
    return ((p1 - p0) * t) + p0;
}

long double bezier(long double t, uint64_t *points, uint64_t n){
    long double p0 = points[0], p1 = points[1];
    if(n == 1) return bbezier(t, p0, p1);

    long double q0 = bezier(t, points, n - 1),
        q1 = bezier(t, points + 1, n - 1);
    return bbezier(t, q0, q1);
}

I then quickly wrote this test program in C++.

#include <iostream>

extern "C" long double bezier(long double, uint64_t *, uint64_t);

uint64_t pointsx[] = {
    0, 40, 100, 200
};
uint64_t pointsy[] = {
    0, 150, 60, 100
};

int main(){
    for(uint64_t i = 0; i <= 10000; ++i){
        long double ii = i;
        long double j = ii/10000;

        long double x = bezier(j, pointsx, 3);
        long double y = bezier(j, pointsy, 3);

        std::cout << "X: " << x << ", Y: " << y << '\n';
    }
    return 0;
}

I wrote an implementation running in javascript from a lightly modified w3 schools canvas tutorial here to understand how bezier curves work but it only supports 3rd degree curves. It does plot the points though, and that's what I based the above implementation on.

It doesn't make any checks to ensure t is between 0 and 1 and n != 0 but I'm not too worried. The only thing I'm worried about is segfaults in cases where n is so high that you get a stack overflow but that will be a pretty crazy curve. Anyway, how does it look?


texts: Log visitor info like latitude, longitude to a database

texts:
I am collecting each visitor information like ip, lat, longitude, referrer and language and save it into db, then in db I have column in table with counter that increment if user revisits the web site (counter increments when visiting from different domain).

My flask app renders the template index.html which contains javascript functions that collect lat, long and pass it to this Flask endpoint registerVisitor:

@app.route("/regVisitor", methods=["POST"])
def registerVisitor():
    data = request.get_json()
    if not data:
        return jsonify({"status": "No data to process."}), 201

    visitorInfo = collectVisitorInfo(data)

    if bool(visitorInfo.get("increment", False)):
        if str(visitorInfo["referrer"]).find("searchCity") != -1 or visitorInfo["referrer"].endswith("newmsg"):
            return jsonify({"status": "coming from newmsg or SearchCity found"}), 200
        try:
            updateOrInsertToTable(request.user_agent, visitorInfo)
            return jsonify({"status" : "success"}), 200
        except Exception, er:
            return jsonify({"status": "fail:{}".format(er.message)})
    return jsonify({"status": "fail"}), 200

def collectVisitorInfo(data):
    visitorInfo = {}
    url = data.get("referrer") # coming from javascript
    visitorInfo["clientIP"] = request.access_route[0]
    visitorInfo["increment"] = data.get("increment")
    visitorInfo["coord_errorcode"] = data.get("coord_errorcode")
    visitorInfo["referrer"] = unquote(url) if url else request.referrer
    visitorInfo["cl_lat"] = data.get("lat", request.cookies.get("cl_lat", 0.0))
    visitorInfo["cl_lng"] = data.get("long", request.cookies.get("cl_lng", 0.0))
    visitorInfo["language"] = data.get("language")
    visitorInfo["visitorId"] = request.cookies.get("unique_visitor")
    return visitorInfo

The javascript function that makes call to this end point from index.html is here:

function getLocation() {
    nIntervId = setInterval(getcitydateTime, 60000)
    sendData = {
        language : window.navigator.userLanguage || window.navigator.language,
        referrer :  document.referrer || "/",
        increment : 1
    };
    $.ajax({
        type: "POST",
        url: $SCRIPT_ROOT + '/regVisitor',
        contentType: "application/json",
        data: JSON.stringify(sendData),
        dataType: "json",
        success: function(response) {
            if (navigator.geolocation) {
                try {
                    navigator.geolocation.getCurrentPosition(showPosition, showError);
                }
                catch(err) {
                    console.log(err);
                }
            } else {
                console.log("Geolocation is not supported by this browser.");
            }
        },
        error: function(err) {
            console.log(err);
        }
    });
    return false;
}

… then passes the latitude and longitude to the same endpoint:

function showPosition(position) {

    $.post($SCRIPT_ROOT + '/regVisitor', {
        lat: position.coords.latitude,
        long: position.coords.longitude,
      }, function(data) {
        console.log("ok it was " + data.status);
      });
    setCookie("cl_lat", position.coords.latitude, 365)
    setCookie("cl_lng", position.coords.longitude, 365)
    return false;
}

The reason why I do not pass lat, long at the same time as user may reject sharing geocordinates in that case some error may occur and other info won't be get passes to flask app via endpoint, so I have separated both these to two different function as you see above.

Is this the correct approach? I am doubting because most of the time the in db lat, long is not punched.

I also do not want to use google analytics as I want to map ip with lat, long of visitor and I couldn't find if google analytics provide a way of providing ip with respect to geo coordinates of visitor.


texts:
I have developed the following script to zip and then remove all files with "*.log" extension in the file name that were modified yesterday. It's definitely not 100% at the moment. For example, it misses files from yesterday that have a modified time of 00:00.

#!/bin/bash

yest=$(date --date="yesterday" +"%m_%d_%Y")

find /path/to/dir/ -daystart -name "*.log" -type f -mtime 1 -print | zip /path/to/dir/"logbackup-$yest.zip" -@
if [ $? -eq 0 ]; then
    find /path/to/dir/ -daystart -name "*.log" -type f -mtime 1 -exec rm -f {} \;
fi

It seems that using -daystart OR using mtime exclusively are not returning the correct results for me. Only files "c" and "a" should be returned.

[user@computer log]$ ls -lart
drwxr-xr-x 23 user user     4096 Sep  5 22:27 ..
-rw-rw-r--  1 user user        0 Nov 18 14:00 d
-rw-rw-r--  1 user user        0 Nov 19 00:00 c
-rw-rw-r--  1 user user        0 Nov 19 12:30 a
-rw-rw-r--  1 user user        0 Nov 20 12:30 b
drwxr-xr-x  2 user user    16384 Nov 20 12:32 .
[user@computer log]$ find . -mtime 1 -type f | xargs ls -lart
-rw-rw-r-- 1 user user 0 Nov 18 14:00 ./d
-rw-rw-r-- 1 user user 0 Nov 19 00:00 ./c
-rw-rw-r-- 1 user user 0 Nov 19 12:30 ./a
[user@computer log]$ find . -daystart -mtime 1 -type f | xargs ls -lart
-rw-rw-r-- 1 user user 0 Nov 19 12:30 ./a


texts: Every node in binary tree = sum of subtree

texts:
I wrote this in Java (I know that the brackets don't exactly follow the standard way of doing it in Java - so it looks a bit like C#). But I was wondering how this algorithm is percieved. I have seen some iterative ways of solving the problem - but I thought recursion improves readability here.

Every node in a Binary Tree, has to have the value of it's subtree.

   8
  /  \
 3    2
/ \
1  2

Would be an example of such a tree. (1+2 = 3 at the bottom, and 1 + 2 + 3 + 2 = 8 at the top). An empty tree is considered 'valid'.

public boolean isValid()
{
    return isValid(root);
}

public boolean isValid(BinaryNode<E> node)
{
    if (node == null)
        return true;

    int sum = sumOfSub(node.getLeft()) + sumOfSub(node.getRight());

    if (node.getLeft() != null && node.getRight() != null)
    {
        if ((Integer) node.getData() != sum)
        {
            return false;
        }
    }
    else
        return true;

    return isValid(node.getLeft()) && isValid(node.getRight());
}

private int sumOfSub(BinaryNode node)
{
    if (node == null) return 0;
    int value = (Integer) node.getData();
    return value + sumOfSub(node.getLeft()) + sumOfSub(node.getRight());
}


texts: Count the ways to partition an array into two equal sets

texts:
I need to count the number of ways to partition an array into two contiguous arrays such that those arrays contain exactly same set of items.

Suppose A = [4, 1, 1, 2, 4, 2, 4, 1]. If you pass this array to the function, it needs to return 2. (Those subarrays are  [4, 1, 1, 2] & [4, 2, 4, 1] and [4, 1, 1, 2, 4] & [2, 4, 1].)

Suppose A = [1, 5, 1]. If you pass this array to the function, it needs to return 0.

My code given below. Is there any better way to do this?

def solve(A):
    count = 0
    for i in range(1, len(A)-1/2):

        left = A[:i]
        right = A[i:]

        left[:i].sort()
        right[i:].sort()

        if set(left) == set(right):
            count += 1
    return count


texts: Accessing Data inside Presentation Layer from API: Laravel 5.2.27

texts:
I wrote the code to fetch the JSON Data. For that I tried to do this in 2 projects.

  First Laravel project which has API code for database interaction only.

Sample code in API controller

class CountryAPI extends Controller
{
    public function AllCountries() {
        return response()->json(['CountryList' => \App\Models\CountryModel::all()]);
    }
}

  Second Laravel project which is a Presentation Layer that has code to access data from an API. So, Database is not exposed directly in this
  layer, instead a URL is being used to access data.

Sample code in the Presentation Layer

class CountryController extends Controller {

    public function AllCountries() {
        $url = "http://localhost/API/public/Countries";
        $json = file_get_contents($url);
        $json_data = json_decode($json, true);
        return view('Country.List', array("Countries" => $json_data["CountryList"]));
    }
}

Then inside the View it is like below.

@foreach($Countries as $Country)

        {{$Country["Country"]}}
        {{$Country["CountryCode"]}}

@endforeach

This is just a beginning to learn how to isolate the database code from Presentation Layer.

Question: Is there problem in below points?

  Code Quality
  Approach to fetch data in Presentation layer from API.
  As website users will send request to website and then website will send request to Database server through an API. So each requests will have one in direct additional request. Is that good?

Reason I asked this because Data has to be accessed from Android as well as from Website


texts: Mini HttpClient json post by Action parameter

texts:
This is an implementation of HttpClient Json Post by Action parameter.

Logic:

  It is mainly convenient to pass the url and object (automatically converted to json by Json.Net), and can use Action as a parameter to customize function.
  default timeout is 15 sec , if you want to change the time , it could change timeout parameter value.

Code:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class Program
{
    public static void Main(string[] args)
    {
        Test().Wait();
    }

    public static async Task Test()
    {
        //SuccessExecute
        await Execute("https://jsonplaceholder.typicode.com/posts", new { value = "ITWeiHan" }); //Result : {"value": "ITWeiHan","id": 101}
        //ErrorExecute
        await Execute("https://jsonplaceholder.typicode.com/error404", new { value = "ITWeiHan" }); //Result : Error 404
    }

    public static async Task Execute(string url, object reqeustBody)
    {
        await HttpClientHelper.PostByJsonContentTypeAsync(url, reqeustBody
            , successFunction: responsebody =>
            {
                //Your Success Logic
                Console.WriteLine("Success");
                Console.WriteLine(responsebody);
            }, errorFunction: httpRequestException =>
            {
                //Your Error Solution Logic
                Console.WriteLine("Error");
                Console.WriteLine(httpRequestException.Message);
            }
        );
    }
}

public static class HttpClientHelper
{
    public static async Task PostByJsonContentTypeAsync(string url, object reqeustBody, Action<string> successFunction, Action<HttpRequestException> errorFunction, int timeout = 15)
    {
        var json = JsonConvert.SerializeObject(reqeustBody);

        using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(timeout) })
        using (var request = new HttpRequestMessage(HttpMethod.Post, url))
        using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
        {
            request.Content = stringContent;
            try
            {
                using (var httpResponseMessage = await client.SendAsync(request))
                {
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                    successFunction(responseBody);
                }
            }
            catch (HttpRequestException e)
            {
                errorFunction(e);
            }
        }
    }
}


texts:
I literally spend all day working on PHP and I think I figured it out, but I need some reviews in order to make my code secure & okay. I am asking you about functionality here. The code below works.

index.php

<form action="upload.php" method="post" enctype="multipart/form-data">

        <input name="images[]" multiple type="file" id="file[]"/>

        <input type="submit">

</form>

upload.php

$target = "upload/";

$uploadit = 1; // I will change it with extension checker.
$checksize = // will check file size

foreach($_FILES['images']['name'] as $key => $value){
    $path = $_FILES['images']['name'][$key];
    $ext = pathinfo($path, PATHINFO_EXTENSION);

    $name = md5($name);
    $generate1 = md5(date('Y-m-d H:i:s:u'));
    $randomizer = uniqid($name);
    $name = $name . $generate1 . $randomizer;
        if ($uploadit == 1) {
               if (move_uploaded_file($_FILES['images']['tmp_name'][$key], $target.$name.".".$ext)){
                echo "".$value ."Your files have been upload successfully
\n";
            }
        } else {
            echo "Failed";
        }


texts: Creating an iOS form with many similar text field cells

texts:
I'm using multiple instances of an object creating a form:

{...
BPFormInputTextFieldCell *nameCell = [[inputTextFieldClass alloc] init];
    nameCell.backgroundColor = cellBgnd;
    nameCell.textField.placeholder = @"business_name";
    nameCell.mandatory = YES;
    nameCell.textField.delegate = self;
    nameCell.customCellHeight = 40.0f;

    BPFormInputTextFieldCell *addressCell = [[inputTextFieldClass alloc] init];
    addressCell.backgroundColor = cellBgnd;
    addressCell.textField.placeholder = @"contact_name";
    addressCell.mandatory = YES;
    addressCell.textField.delegate = self;
    addressCell.customCellHeight = 40.0f;

    BPFormInputTextFieldCell *dobCell = [[inputTextFieldClass alloc] init];
    dobCell.backgroundColor = cellBgnd;
    dobCell.textField.placeholder = @"address";
    dobCell.mandatory = YES;
    dobCell.textField.delegate = self;
    dobCell.customCellHeight = 40.0f;

    BPFormInputTextFieldCell *sexCell = [[inputTextFieldClass alloc] init];
    sexCell.backgroundColor = cellBgnd;
    sexCell.textField.placeholder = @"city";
    sexCell.mandatory = YES;
    sexCell.textField.delegate = self;
    sexCell.customCellHeight = 40.0f;

    BPFormInputTextFieldCell *contexturaCell = [[inputTextFieldClass alloc] init];
    contexturaCell.backgroundColor = cellBgnd;
    contexturaCell.textField.placeholder = @"region";
    contexturaCell.mandatory = YES;
    contexturaCell.textField.delegate = self;
    contexturaCell.customCellHeight = 40.0f;

    self.formCells = @[@[nameCell, addressCell, dobCell, sexCell, contexturaCell, pesoCell, estaturaCell, actividadCell, deseoCell, cuantosKilosCell, cuantoTiempoCell, ...];
 ...}

As you can see, I need to refactor this badly.  The objects should also go into the array.  What is the best approach?


texts: HttpClient Wrapper supports ignoring invalid/self-signed certs

texts:
I'm using the following as a wrapper for the HtptClient because it doesn't implement an interface -- which makes mocking more difficult. This logic also supports invalid and self-signed certs.

public class HttpClientWrapper : IHttpClient
{
    private readonly HttpClient _client;

    public Uri BaseAddress
    {
        get
        {
            return _client.BaseAddress;
        }

        set
        {
            _client.BaseAddress = value;
        }
    }

    public HttpRequestHeaders DefaultRequestHeaders
    {
        get
        {
            return _client.DefaultRequestHeaders;
        }
    }

    public HttpClientWrapper()
    {
        bool ignoreCertificateErrors = ConfigurationManager.AppSettings["IgnoreCertificateErrors"].ToBool();
        string environmentName = ConfigurationManager.AppSettings["EnvironmentName"];

        _client = new HttpClient();

        // If ignoreCertificateErrors config value is true,
        // the setting ignores all Certificate validation errors in AppDomain,
        // in every environment but PRODUCTION.
        if (ignoreCertErrors && environmentName.ToUpper() != "PRODUCTION")
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        }
    }

    public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, String userOrProcessName)
    {
        IUnityContainer container = UnityCommon.GetContainer();
        ILogService logService = container.Resolve<ILogService>();

        logService.Log(ApplicationLogTypes.Debug, JsonConvert.SerializeObject(request), userOrProcessName);

        return _client.SendAsync(request);
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing && _client != null)
            {
                _client.Dispose();
            }

            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
    #endregion
}

using the following for interface:

public interface IHttpClient : IDisposable
{
    Uri BaseAddress { get; set; }

    HttpRequestHeaders DefaultRequestHeaders { get; }

    Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, String userOrProcessName);
}

Any suggestions?


texts:
I have an autofiltered table in Excel. I have to copy/paste values based on certain conditions and I also have to perform this on all visible cells in a particular column. I have written the code and it works well but the only thing is that it takes a lot of time as there are many rows. Can anyone please help me how to thrash time required? Here's the code. Thanks!

Sub FilterAndCopy()

Windows("Epson Itemcodes.xlsm").Activate
    Range("A" & i).Select
    Selection.Copy

Windows("Epson ASINs.xlsx").Activate
    Range("U1048576").End(xlUp).Offset(0, -12).Select

If ActiveCell.Value <> "Itemcode" Then

If ActiveCell.Value = "" Then
    ActiveSheet.Paste

    Else

    If ActiveCell.Value = Workbooks("Epson Itemcodes.xlsm").Sheets("Sheet1").Range("A" & i).Value Then
    ActiveSheet.Paste

    Else
    ActiveCell.Value = "Conflct"

    End If
    End If

Else
Windows("Epson Itemcodes.xlsm").Activate
Range("I" & i).Value = "No match found"

End If

If ActiveCell.Value <> "Itemcode" Then

With ActiveSheet
Do

ActiveCell.Offset(-1, 0).Activate
Do While ActiveCell.EntireRow.Hidden = True
ActiveCell.Offset(-1, 0).Activate
Loop

If ActiveCell.Value <> "Itemcode" Then

If ActiveCell.Value = "" Then
    ActiveSheet.Paste

    Else

    If ActiveCell.Value = Workbooks("Epson Itemcodes.xlsm").Sheets("Sheet1").Range("A" & i).Value Then
    ActiveSheet.Paste

    Else

    ActiveCell.Value = "Conflct"

    End If
    End If

Else
Exit Do

End If

Loop
End With

End If

End Sub


texts:
This function adds a number of hours to a 24 hour clock:

/**
 * @param {Integer} now The current hours
 * @param {Integer} add The number of hours to add
 */
function addHours(now, add){
    var h = (now + add) % 24;

    return h < 0 ? 24 + h : h;
};

addHours(2, 5) //7
addHours(23, 5) //4
addHours(23, -5) //18
addHours(72, 3) //3
addHours(0, 0) //0

The output should always be an integer in the range of 0 - 23.

I can't see any problem with it, but maybe you can. Please let me know if it can be improved or if there are any bugs.


texts:
I am doing a program for my APCS class in Node.js to practice node, but I am unsure if I did everything the best way possible.

The assignment is to take the number and base as user input and then perform the conversion and print it out.

Here is the code:

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const BASE_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/=";

exports.pa11 = function() {
    rl.question("Enter number: ", number => {
        rl.question("Enter base: ", base => {
            if (base <= 1) throw "Base must be greater than 1";
            else if (base > 64) throw "Base must be less than or equal to 64";

            const numberOriginal = number, baseOriginal = base;

            const negative = number < 0;
            if (negative) number = -number;

            let x = "";

            while (number > 0) {
                let digit = number % base;
                number -= digit;
                number /= base;
                x = BASE_CHARACTERS.charAt(digit) + x;
            }

            if (negative) x = "-" + x;

            console.log(numberOriginal, "in base", baseOriginal, "is", x);

            rl.close();
            process.exit();
        });
    });
};


texts: C++ Single instance application with interrupt of main instance

texts:
I am writing an application using Qt5.7.1 which suppose to run as single instance application.

One of the requirements is whenever user launches second instance of application, this instance should notify original one and exit.

To achieve that I wrote a class below (based off the SO question on similar topic).

However I am unhappy with warning QEventLoop: Cannot be used without QApplication and the fact that it may trigger interruptedCallback() multiple times. Any improvement suggestions?

runguard.h

#ifndef RUNGUARD_H
#define RUNGUARD_H

#include <QObject>
#include <QSystemSemaphore>
#include <QThread>

class RunGuardChecker: public QObject
{
    Q_OBJECT
public:
    RunGuardChecker(QSystemSemaphore *sem);
    ~RunGuardChecker();
    bool couldAcquireLock = false;
    bool check();
private:
    QSystemSemaphore *memLock;
    QThread checkThread;
    bool closeThread = false;
public slots:
    void checkFunc();
signals:
    void doneChecking();
};

class RunGuard: public QObject
{
    Q_OBJECT
public:
    RunGuard(const char *key);
    ~RunGuard();

    bool isAnotherRunning();
    void lock();

private:
    QSystemSemaphore memLock;

    QThread lockThread;
    bool shouldTerminateLock = false;

    RunGuardChecker checker;

private slots:
    void lockLoop();

signals:
    void interrupted();
};

#endif // RUNGUARD_H

runguard.cpp

#include "RunGuard.h"
#include <QMessageBox>

RunGuard::RunGuard(const char *key)
    : QObject(NULL)
    , memLock(key, 0, QSystemSemaphore::Create)
    , checker(&memLock)
{
    memLock.release(1);
}

RunGuard::~RunGuard()
{
    shouldTerminateLock = true;
    lockThread.terminate();
    while (lockThread.wait(100) == false) {
        memLock.release();
    }
}

bool RunGuard::isAnotherRunning()
{
    return checker.check();
}

void RunGuard::lock()
{
    // Ensure flag is set correctly
    shouldTerminateLock = false;

    // Start lock thread
    moveToThread(&lockThread);
    connect(&lockThread, SIGNAL(started()), this, SLOT(lockLoop()));
    lockThread.start();
}

void RunGuard::lockLoop()
{
    while(shouldTerminateLock == false) {
        memLock.acquire();
        if (shouldTerminateLock == false) {
            emit interrupted();
        }
    }
}

RunGuardChecker::RunGuardChecker(QSystemSemaphore *sem)
    : QObject(NULL)
{
    this->memLock = sem;
}

bool RunGuardChecker::check()
{
    bool result = true;
    // Start check function in another thread
    moveToThread(&checkThread);
    connect(&checkThread, SIGNAL(started()), this, SLOT(checkFunc()));
    checkThread.start();
    // Wait 100 milliseconds
    QThread::msleep(100);
    // Check if we acquired the lock
    // If we acquired, we should release,
    // if we did not acquire:
    // then we should send interrupt (release [1]),
    // release [2] (so that we acquire)
    // and then release again.
    memLock->release();
    if (this->couldAcquireLock == true) {
        result = false;
    }

    // Close thread safely
    checkThread.terminate();
    while (checkThread.wait(100) == false) {
        memLock->release();
    }
    return result;
}

void RunGuardChecker::checkFunc()
{
    bool result = memLock->acquire();
    if (result) {
        this->couldAcquireLock = result;
    }
    return;
}

RunGuardChecker::~RunGuardChecker()
{

}

Use like follows:

main.cpp

#include <QMainWindow>
#include "application.h"
#include "runguard.h"

int main(int argc, char *argv[])
{
    RunGuard guard("app");
    if (guard.isAnotherRunning() == true) {
        return 0;
    }
    guard.lock();

    // Application class implements custom slot "interruptedCallback()"
    Application app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    QMainWindow window;
    window.show();

    app.window = &window;

    app.connect(&guard, SIGNAL(interrupted()), &app, SLOT(interruptedCallback()));

    return app.exec();
}


texts:
I am trying to solve the following Codewars kata.
We are given a list as
seq = [0, 1, 2, 2]
We will have to write a function that will, firstly, add elements in the list using the following logic.
if n = 3 and as seq[n]=2, the new list will be seq = [0, 1, 2, 2, 3, 3]
if n = 4 and as seq[n]=3, the new list will be seq = [0, 1, 2, 2, 3, 3, 4, 4, 4]
if n = 5 and as seq[n]=3, the new list will be seq = [0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5] and so on.
Then the function will return the n-th element of the list.
Some elements of the list:
[0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19,
20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21]
Constraint for Python:
0 <= n <= 2^41
My code runs successfully in my system for any value of n, including n=2^41 (within 2.2s). But it times out in Codewars. Can anyone help me in optimizing my code? Thanks in advance.
My code:
def find(n):
    arr = [0, 1, 2, 2]
    if n <= 3:
        return arr[n]
    else:
        arr_sum = 5
        for i in range(3, n+1):
            arr_sum += i * arr[i]
            if arr_sum >= n:
                x = (arr_sum - n) // i
                return len(arr) + arr[i] - (x+1)
            else:
                arr += [i] * arr[i]


texts: Filewatcher compiler for watching different files

texts:
I'm trying to create a filewatcher program that can watch different files. The files might have subfiles that are being imported into the main file, which is being represented by the file object. I'm feeling the code is a little messy and I would like to know how I can improve it.

The input_watcher() is not there to stay, it is being replaced by a GUI eventually, but it's just there for testing.

import multiprocessing
import threading
import os
import time

file_lock = threading.Lock()
update_interval = 0.1

class FileMethods(object):
    def a_import(self):
        # do some sort of file manipulation

    # all different kinds of filewatching / compiling types
    # will be added as methods and also added to the compiler_methods

class FileObject(FileMethods):
    def __init__(self, full_name, compiler):

        self.full_name = os.path.abspath(full_name)
        self.file_name = os.path.basename(self.full_name)
        self.path_name = os.path.dirname(self.full_name)

        name, exstention = os.path.splitext(full_name)
        self.concat_name = name + '-concat' + exstention

        self.compiler = compiler
        self.compiler_methods = {'aImport': self.a_import}

        self.last_updated = os.path.getatime(self.full_name)

        self.subfiles = []
        self.last_subfiles_mod = {}

    def exists(self):
        return os.path.isfile(self.full_name)

    def mod_check(self):
        if self.last_updated < os.path.getmtime(self.full_name):
            self.last_updated = os.path.getmtime(self.full_name)
            print '%s updated' % self.file_name
            return True
        else:
            return False

    def sub_mod_check(self):
        for s in self.subfiles:
            if self.last_subfiles_mod.get(s) < os.path.getmtime(s):
                self.last_subfiles_mod[s] = os.path.getmtime(s)
                return True

        return False

files = []

def input_watcher():
    while True:
        input_file = os.path.abspath(raw_input('Input file name: '))
        compiler = raw_input('Choose compiler: ')

        if os.path.isfile(input_file):

            obj = FileObject(input_file, compiler)

            with file_lock:
                files.append(obj)

            print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler)
        else:
            print 'File does not exists'

def file_manipulation():
    for f in files:
        p = multiprocessing.Process(target=f.compiler_methods.get(f.compiler)())
        p.start()

def file_watcher():
    while True:
        with file_lock:
            file_manipulation()
        time.sleep(update_interval)

if __name__ == '__main__':
    iw = threading.Thread(target=input_watcher)
    fw = threading.Thread(target=file_watcher)

    iw.start()
    fw.start()


texts: Bad practice to have try / catch in constructor?

texts:
I have a constructor which sets a member variable. The setting of this variable throws an exception. Should I be throwing the exception in the contructor or enclosing the try/catch like below. Is below snippet an example of code smell ?

private NewManager newManager;

    public Save(final TheManager manager, final String str) {
        this.manager = manager;

        try {
            this.newManager = manager.getManager(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


texts:
I apologise if the title is not very descriptive. If someone can recommend a clearer one I'll edit it. I have an exercise question as:

  The language L={anbn} where n ≥ 1, is a language of all words with
  the following properties:

  The words consist of strings of a’s followed by b’s.
  The number of b’s is equal the number of a’s.
  Examples of words that belong to L are:

  ab, where n=1;

  aabb, where n=2;

  aaabbb, where n=3;

  aaaabbbb, where n=4.

  One way to test if a word w belong to this language L is to use a
  stack to check if the number of a’s balances the number of b’s. Use
  the following header and write a function isInLanguageL2 that
  uses a stack to test if any word belongs to L. If w belongs to L
  then the isInLanguageL2 should return true otherwise
  isInLanguageL2 should return false.

  bool isInLanguageL(string w);

  Note the following:

  Only words belonging to L should be accepted.
  The word bbaa does not belong to L.
  Do not count the number of a’s or b’s.

I've written the following code which solves the problem.

bool isInLanguageL2(string w){

    linkedStackType<string> wordStack;

    int size = w.length();
    int a = 0;
    int b = 0;

    if(size % 2 != 0)   //word length must be an equal number
        return false;
    else{
        //read first half of word
        for(int i = 0; i < size/2; i++){    //check if the first half consists of A's
            if(w[i] != 'a' && w[i] != 'A')
                return false;
            else
                wordStack.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid
        }

        //read second half of word
        for(int i = size/2; i < size; i++){     //check if the second half consists of B's
            if(w[i] != 'b' && w[i] != 'B')
                return false;
            else
                wordStack.push(string(1, w[i]));    //convert char to string and push to stack if the letter is valid
        }
    }

    //check number of A's and B's in the stack
    while(!wordStack.isEmptyStack()){
        if(wordStack.top() == "b" || wordStack.top() == "B"){
            b++;
            wordStack.pop();
        }
        else{
            a++;
            wordStack.pop();
        }
    }

    //check if number of B's is equal to number of A's
    if(b==a)
        return true;

}

However, since the question says "Do not count the number of a’s or b’s.", I've instead created two stacks and just compared their lengths. Is there a way to do this using a single stack since the question mentions using a stack without explicitly counting the A's and B's to test the word.

bool isInLanguageL2(string w){

    linkedStackType<string> wordStackA, wordStackB;

    int size = w.length();
    int a = 0;
    int b = 0;

    if(size % 2 != 0)   //word length must be an equal number
        return false;
    else{
        //read first half of word
        for(int i = 0; i < size/2; i++){    //check if the first half consists of A's
            if(w[i] != 'a' && w[i] != 'A')
                return false;
            else
                wordStackA.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid
        }

        //read second half of word
        for(int i = size/2; i < size; i++){     //check if the second half consists of B's
            if(w[i] != 'b' && w[i] != 'B')
                return false;
            else
                wordStackB.push(string(1, w[i]));    //convert char to string and push to stack if the letter is valid
        }
    }

    //check if number of B's is equal to number of A's
    if(wordStackA.length() == wordStackB.length());
        return true;

}

Also, I have a follow up to this question. A sort of extension. Should I add it here or create a new question for it as it might make this question rather long.


texts: Implement String's valueOf function, code review request


texts: Is it a bad programming practice to declare variable in a loop?

texts:
Today, I came across a code example like the following:

Option Explicit

Sub MySub()
    Dim iCount As Integer

    For iCount = 0 To 100
        Debug.Print "Arbitrary Code Here"
        If iCount Mod 2 = 0 Then

            Dim myString As String 'This is the line I'm curious about

            myString = iCount
            Debug.Print myString
        End If
    Next iCount
End Sub

Once a variable goes in scope in VB6 and/or VBA, it stays in scope throughout the procedure.

So, is it a bad programming practice to declare a variable in a loop?  Is it better to declare myString either at the top of the procedure or, at the very least, above the FOR LOOP?


texts: Bash manual page selection menu (version 2)

texts:
This is update to a previously asked question Bash manual page selection menu. This script generates a menu for the user to select which manual page he/she would like to read.

#!/bin/bash

# Mac OS X specific function to clear completely clear the screen.
# Seems to work well for the purposes of this script
clear(){
    osascript -e \
    'set theApp to (get the path to the frontmost application) as text
    set this_app to the name of application theApp
    activate application this_app
    tell application "System Events" to keystroke "k" using command down'
}
clear
COLUMNS=80
while true
do
    printf 'Man Pages: main menu\n¯¯¯¯¯¯¯¯¯\n'
    PS3=$'\nMake a selection: '
    select dir in $(ls -d ${PATH//:/ })
    do
        case $REPLY in
            [0-9]*) ls $dir; break 1;;
            *) echo "Exiting" && exit 1;;
        esac
    done
    clear
    printf "Man Pages: $dir"$'\n¯¯¯¯¯¯¯¯¯\n'
    PS3=$'\n(B)ack to main menu\n(Q)uit\n\nMake your selection: '
    while true
    do
        select file in $(ls ${dir} | column -t)
        do
            case $REPLY in
                [0-9]*) man $file; clear; break 1;;
                [bB]) clear; break 2;;
                [qQ]) echo "Exiting" && exit;;
                   *) echo "Exiting" && exit 1;;
            esac
        done
    done
done

I wanted to make it so that any programs without a manual page wouldn't be listed in the menu. But to do so would require checking to see if every command found in the user's PATH had a manual page associated with it and then creating a database of commands with manual pages. As it is, if a command does not contain a manual page, the user is directed back to the previous menu page to choose another selection.

I realize there is already a clear command in most user's terminals. But the clear command in my system clears the screen but still allows the user to scroll up past where the screen was just cleared. I made the clear function to completely clear the screen to enhance the overall aesthetic when running the script. It's not really necessary but I think it looks nice.

I think this script does what I intended it to do. So now I'd like other's opinions on it. Is there anything I could do to improve it?


texts: Simplify splitting a String into alpha and numeric parts

texts:
Requirement:  Parse a String into chunks of numeric characters and alpha characters.  Alpha characters should be separated from the numeric, other characters should be ignored.

Example Data:

Input           Desired Output
1A              [1, A]
12              [12]
12G             [12, G]
12ABC-SFS513    [12, ABC, SFS, 513]
AGE+W#FE        [AGE, W, FE]
-12WE-          [12, WE]
-12- &%3WE-     [12, 3, WE]

Question:

The code below accomplishes this.  However, I am looking for any suggestions as to a better way to accomplish this (maybe a crazy regex using String.split()? ) or any changes that could make this code more readable/easy to follow.

Code:

private static String VALID_PATTERN = "[0-9]+|[A-Z]+";

private List<String> parse(String toParse){
    List<String> chunks = new LinkedList<String>();
    toParse = toParse + "$"; //Added invalid character to force the last chunk to be chopped off
    int beginIndex = 0;
    int endIndex = 0;
    while(endIndex < toParse.length()){
        while(toParse.substring(beginIndex, endIndex + 1).matches(VALID_PATTERN)){
            endIndex++;
        }
        if(beginIndex != endIndex){
            chunks.add(toParse.substring(beginIndex, endIndex));
        } else {
            endIndex++;
        }
        beginIndex = endIndex;
    }
    return chunks;
}


texts: Nearest point using 2D tree, static variable for the closest point so far

texts:
This is a problem from a Coursera class:

  Write a data type to represent a set of points in the unit square (all points have x- and y-coordinates between 0 and 1) using a 2D tree to support efficient nearest neighbor search (find a closest point to a query point).

I implemented the class with pre-setup API. The problem for me was to efficiently realize the pruning rule:

  To find a closest point to a given query point, start at the root and recursively search in both subtrees using the following pruning rule: if the closest point discovered so far is closer than the distance between the query point and the rectangle corresponding to a node, there is no need to explore that node (or its subtrees).

So I need to store statically best tuple (closest point, minimum distance) so far. For this purpose I think static variable of class is not the best choice (it is needed only for one this method). I also don't like my solution for this: I made nested static class, pointDist, with static variables. What is a more optimal/elegant decision?

public class KdTree {

    private Node root;
    private int size;

    public KdTree() {
        root = null;
        size = 0;
    }

    // ... other class methods

    private static final class pointDist {
        private static Point2D p; // closest point
        private static double d; // min distance

        private static void begin() {
            p = null;
            d = Double.POSITIVE_INFINITY;
        }
    }

    private void nearest(Point2D p, Node x) {
        if (x == null) return;
        // code with p, x, pointDist.p and pointDist.d variables
        // ...
    }

    public Point2D nearest(Point2D p) {
        assert size() > 0;
        pointDist.begin();
        nearest(p, root);
        return pointDist.p;
    }

    private static class Node {

        private Point2D p; // the point
        private RectHV rect; // the axis-aligned rectangle corresponding to this node
        private Node lb; // the left/bottom subtree
        private Node rt; // the right/top subtree

        public Node(Point2D pp, Node prevN, int caseCut) {
            p = pp;
            lb = null;
            rt = null;
            // root case
            if (caseCut == -1) rect = new RectHV(0, 0, 1, 1);
            else {
                RectHV prevR = prevN.rect;
                // the rest of the code here is to define rect based on values of
                // caseCut variable: 0,1,2,4 - cuts from left, right, bottom and top
                // ...
            }
        }
    }
}


texts:
Currently I am trying to teach myself more about functions with parameters and return values that connects with one to another.

In this code I created a square object with graphics.py that moves to a direction in loop whenever you press an arrow key.

from graphics import *
import keyboard, time
width = 200
height = 200
win = GraphWin("MOVEMENTS", width, height)
win.setBackground(color_rgb(25,25,25))

key = ""

def movement(key):
    if keyboard.is_pressed("Right"):
        key = "d"
    if keyboard.is_pressed("Left"):
        key = "a"
    if keyboard.is_pressed("Down"):
        key = "s"
    if keyboard.is_pressed("Up"):
        key = "w"
    return key

def horizontal_movement(x):
    global key
    key = movement(key)
    if key == "d":
        x += 20
    elif key == "a":
        x -= 20
    return x

def vertical_movement(y):
    global key
    key = movement(key)
    if key == "s":
        y += 20
    elif key == "w":
        y -= 20
    return y

def main():
    x = 0
    y = 0
    radius = 10
    player = Rectangle(Point((width/2)-radius+x,(height/2)-radius+y), Point((width/2)+radius+x, (height/2)+radius+y))

    while(True):
        player.undraw()
        player = Rectangle(Point((width/2)-radius+x,(height/2)-radius+y), Point((width/2)+radius+x,(height/2)+radius+y))
        player.setFill("green")
        player.setWidth(2)
        player.draw(win)

        x = horizontal_movement(x)
        y = vertical_movement(y)

        update(10)

main()

I want to know if there is a better code design that can move the movement(key) function into the horizontal_movement(x) and vertical_movement(y) function because right now I feel like I have typed some unecessary coding (the movement function and global key) into the script and I want it be as efficient as possible.

If there is an alternative that makes the script more efficient or perform better, please let me know so I can improve further.


texts: AngularJS recursive function call with $timeout

texts:
I have created a recursive function call in AngularJS and just wonder if is there a better way to solve this problem? The code works perfectly.

My code is the following:

function getLocation(query, map, object, delay) {
    var deferred = $q.defer();
    var service = new google.maps.places.PlacesService(map);
    service.textSearch({ query: query }, function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            var loc = results[0].geometry.location;
            object.lang = loc.lng();
            object.lat = loc.lat();
            deferred.resolve(object);
        } else {
            if (status === "OVER_QUERY_LIMIT") {
                delay += 100;
                deferred.resolve($timeout(function () {
                    var deferred = $q.defer();
                    getLocation(query, map, object, delay).then(function (object) {
                        deferred.resolve(object);
                    });
                    return deferred.promise;
                }, delay));
            } else {
                deferred.reject(status);
            }
        }
    });
    return deferred.promise;
}

I have already tried to replace the following section:

deferred.resolve($timeout(function () {
    var deferred = $q.defer();
    getLocation(query, map, object, delay).then(function (object) {
        deferred.resolve(object);
    });
    return deferred.promise;
}, delay));

with:

$timeout(getLocation(query, map, object, delay).then(function (object) {
    deferred.resolve(object);
}), delay);

but it didn't work (perform the recursive call without timeout).

Could you give me some advice to build a less ugly function to solve this recursive call?


texts:
I have coded up an implementation of Conway's Game of Life and I have a performance bottleneck in it which I wish to be optimized. The main logic is in the Universe class. I have omitted all code which is not applicable here for brewity:

public class Universe {

    private static final int FLIP_INDEX = 0;
    private static final int FLOP_INDEX = 1;
    private final boolean[][][] universeDoubleBuffer;
    private final int height;
    private final int width;
    private int flipFlopIndex = FLIP_INDEX;

    public Universe(boolean[][] universeState) {
        height = universeState.length;
        width = universeState[0].length;
        universeDoubleBuffer = new boolean[2][height][width];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                universeDoubleBuffer[FLIP_INDEX][y][x] = universeState[y][x];
            }
        }
    }

    public boolean[][] recalculateUniverseState() {
    int newFlipFlopIndex = (flipFlopIndex == FLIP_INDEX ? FLOP_INDEX : FLIP_INDEX);
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int liveNeighbors = countLiveNeighbors(x, y);
            boolean isLiving = universeDoubleBuffer[flipFlopIndex][y][x];
            if (!isLiving && liveNeighbors == 3) {
                universeDoubleBuffer[newFlipFlopIndex][y][x] = true;
            } else if (isLiving && (liveNeighbors == 2 || liveNeighbors == 3)) {
                universeDoubleBuffer[newFlipFlopIndex][y][x] = true;
            } else {
                universeDoubleBuffer[newFlipFlopIndex][y][x] = false;
            }
        }
    }
    stampPatterns();
    logger.info("Old:" + Arrays.deepToString(universeDoubleBuffer[flipFlopIndex]));
    logger.info("New:" + Arrays.deepToString(universeDoubleBuffer[newFlipFlopIndex]));
    flipFlopIndex = newFlipFlopIndex;
    return universeDoubleBuffer[flipFlopIndex];
}

    private int countLiveNeighbors(int x, int y) {
        int result = 0;
        for (CellNeighbor neighbor : CellNeighbor.values()) {
            try {
                boolean isLiving = universeDoubleBuffer[flipFlopIndex][y + neighbor.getYOffset()][x + neighbor.getXOffset()];
                if (isLiving) {
                    result++;
                }
            } catch (IndexOutOfBoundsException e) {
                logger.info("Cell's neighbor was off the grid.", e);
            }
        }
        return result;
    }
}

Here is the code for CellNeighbor:

public enum CellNeighbor {

    TOP_LEFT(-1, 1), TOP(0, 1), TOP_RIGHT(1, 1), RIGHT(1, 0), BOTTOM_RIGHT(1, -1), BOTTOM(0, -1), BOTTOM_LEFT(-1, -1), LEFT(-1, 0);

    private int xOffset;
    private int yOffset;

    private CellNeighbor(int xOffset, int yOffset) {
        this.xOffset = xOffset;
        this.yOffset = yOffset;
    }

    public int getXOffset() {
        return xOffset;
    }

    public int getYOffset() {
        return yOffset;
    }
}

My problem is that if I create a world big enough (I tested with 5000 * 5000 for example) life really slows down and the time spent in recalculateUniverseState() reaches almost a second (with an 5000 * 5000 universe the average was 766ms).

I have tried without a double buffer (swapping new boolean[][] arrays) and without the try/catch block but it yielded no significant performance improvements.

My question is that how can I optimize the above code to be faster?


texts: Counting paths in an n-dimensional grid that stay within the boundaries

texts:
Problem Statement

  You are situated in an N dimensional grid at position (x1, x2, …, xN).
  The dimensions of the grid are (D1, D2, …, DN). In one step, you can
  walk one step ahead or behind in any one of the N dimensions. (So
  there are always 2×N possible different moves). In how many ways can
  you take M steps such that you do not leave the grid at any point? You
  leave the grid if at any point xi, either xi ≤ 0 or xi > Di.

  Input Format

  The first line contains the number of test cases T. T test cases
  follow. For each test case, the first line contains N and M, the
  second line contains x1, x2, …, xN and the 3rd line contains D1, D2, …, DN.

  Output Format

  Output T lines, one corresponding to each test case. Since the answer
  can be really huge, output it modulo 1000000007.

  Constraints

  \$1 \le T \le 10\$

  \$1 \le N \le 10\$

  \$1 \le M \le 300\$

  \$1 \le D_i \le 100\$

  \$1 \le x_i \le D_i\$

  Sample Input

1
2 3
1 1
2 3

  Sample Output

12

Code

I have applied dynamic programming, but am exceeding the time limit in most cases. How can I make it faster? I am also eager to know if there is any other method to memoize because these types of grid problems are asked more often.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;

public class Grid_Walking {
    private static String[] n;
    private static int moves;

    private static HashMap<String, Integer> hm;
    private static BufferedReader br;

    private static String[] s;

    private static int dimen;
    private static int[] present;
    private static int[] dimlen;

    public static void main(String args[]) throws IOException {

        br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        while (t > 0) {
            n = br.readLine().split(" ");
            dimen = Integer.parseInt(n[0]);
            present = new int[dimen];
            dimlen = new int[dimen];
            moves = Integer.parseInt(n[1]);

            s = br.readLine().split(" ");
            for (int i = 0; i < dimen; i++) {
                present[i] = Integer.parseInt(s[i]) - 1;
            }
            s = br.readLine().split(" ");
            for (int i = 0; i < dimen; i++) {
                dimlen[i] = Integer.parseInt(s[i]);
            }
            hm = new HashMap<String, Integer>();
            System.out.println(solve(present, moves) % 1000000007);
            t--;
        }

    }

    private static int solve(int[] x, int moves) {
        // TODO Auto-generated method stub
        int result = 0;
        String s = Arrays.toString(x) + moves;
        if (hm.containsKey(s)) {
            return hm.get(s);
        }
        if (moves == 0) {
            return 1;
        }
        for (int i = 0; i < dimen; i++) {
            // System.out.println("fjfvnfjbv");
            if (x[i] > 0) {
                x[i] = x[i] - 1;
                result = result + solve(x, moves - 1);
                x[i] = x[i] + 1;
            }
            if (x[i] < dimlen[i] - 1) {
                x[i] = x[i] + 1;
                result = result + solve(x, moves - 1);
                x[i] = x[i] - 1;
            }
        }
        hm.put(s, result % 1000000007);
        return result % 1000000007;
    }
}


texts:
This is the problem statement for Insertion Sort - Part 2.

In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array?

Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that
in the first step, when you consider an element with just the first element - that is already "sorted" since there's nothing to its left that is smaller
than it.

In this challenge, don't print every time you move an element. Instead, print the array every time an element is "inserted" into the array in (what is
currently) its correct place. Since the array composed of just the first element is already "sorted", begin printing from the second element and on.

Actually just an insertion sort implementation with ints and vector. How can I make this code faster? How can I improve this code?

#include <vector>
#include <iostream>

void print(const std::vector<int>& v) {
    for (auto x : v) {
        std::cout << x << ' ';
    }
    std::cout << '\n';
}

int main() {
    int s;
    std::cin >> s;
    std::vector<int> sorted(s);
    int i = 0;
    while (std::cin && i != s) {
        std::cin >> sorted[i++];
    }
    for (std::size_t i= 1; i < sorted.size(); ++i) {
        std::size_t j = i;
        for (std::size_t k = 0; k < j; ++k) {
            if (sorted[j] < sorted[k]) {
                std::swap(sorted[j],sorted[k]);
            }
        }
        print(sorted);
    }
}


texts: Python: Speeding up vector and matrix operations

texts:
The core of my program are the following lines

import numpy as np
import time

I, J = np.random.randn(20000,800), np.random.randn(10000,800)

d = np.zeros((len(I),1))
for j in range(len(J)):
    t0 = time.time()
    # Compute distance
    matrix_j = np.array([J[j]]).T*np.array([J[j]])
    for i in range(len(I)):
        matrix_i = np.array([I[i]]).T*np.array([I[i]])
        d[i] = np.sum((matrix_i-matrix_j)**2)
    print(time.time()-t0)
    # Do stuff with vector d

I and J are some matrices with data. I basically compare vectors of each matrix where I first extract a vector and than multiply it with its transposed version to get a matrix matrix_i and matrix_j. Afterwards I subtract both matrices from each other and sum all elements. But it takes ages even for such a small data set.

What can I do to speed things a little bit up? Any ideas?


texts: Calculating the terminal width and height

texts:
As part of the bigger problem I am trying to solve smaller problems first and hence below is the code to find the terminal width and height.

Code

'use strict';

class Terminal {
  width() {
    return process.stdout.columns || 80
  }

  height() {
    return process.stdout.rows || 60
  }
}

module.exports = Terminal

How can I make the above code testable? can I use some better abstraction?


texts: Convert string array to string with separator

texts:
I have this little convenience method that takes an String array and returns an String where the values are separated by a provided separator (comma, pipe, etc).

For instance, if given an array with values "abc", "def" and "ghi", and a for separator we passed " | ", the end result would be "abc | def | ghi".

This is the method:

public String getArrayAsString(String[] stringArray, String separator) {
    StringBuilder finalString = new StringBuilder();
    boolean needsSeparator = false;
    for (String s : stringArray) {
        if (needsSeparator) {
            finalString.append(separator);
        }
        finalString.append(s);
        needsSeparator = true;
    }
    return finalString.toString();
}

Notice that the separator must, as its name implies, separate values, and not be appended or prepended artificially to the final String. So, for instance, the following would be incorrect return values: "abc | def | ghi | " or " | abc | def | ghi".

I specifically don't like the needsSeparator flag variable, but without it, the unwanted leading or trailing separators would be added, and then I would need to remove them from the finalString before returning it, which I also don't find to be very elegant.

Is there a more concise (perhaps more elegant) way to achieve this?


texts: Counting the number of digits with a recursion algorithm in c

texts:
I'm learning recursion and I think that I can finally wrap my head around it.

I had to write a program that given an integer would print out its number of digits and I wanted to know if it is correctly implemented and if there's anything I can do to make it better.

Here's my code:

#include<stdio.h>

int countDigits(int n);

int main(void){
  int n,result;
  printf("What is the number?\n");
  scanf("%d", &n);
  result=countDigits(n);
  printf("%d\n", result);
  return 0;
}

int countDigits(int n){
  if(n>=0&&n<10){
    return 1;
  }
  else{
    return 1+countDigits(n/10);
  }
}


texts: QuickCheck properties for function that sorts a list of strings

texts:
I'm reading The Haskell Road to Logic, Math and Programming and for each exercise solution I write some properties to learn QuickCheck. One of the exercises is to write a function that sorts a list of strings (srtStr). I wonder if my properties are right. Also, is there something missing?

propIdempotent ∷ [String] → Bool
propIdempotent xs = srtStr xs == srtStr (srtStr xs)

propLength ∷ [String] → Bool
propLength str = length str == length (srtStr str)

propOrder ∷ [String] → Bool
propOrder xs = process (srtStr xs) True where
    process ∷ [String] → Bool → Bool
    process (x : y : xs) state = process xs (if state then x <= y else False)
    process _            state = state

check ∷ IO ()
check = do
    quickCheck propIdempotent
    quickCheck propLength
    quickCheck propOrder


texts: Extension method splitting string on each capital letter

texts:
I'm creating my own game and for some statistics I need to get the names of specific objects. The problem was that I had them declared like "SmallFireBall" but I wanted them to appear like"Small Fire Ball" because that's something the user is able to see, so I decided to create my own extension method to help me out:

public static string SplitOnCapitalLetters(this string inputString)
{
    List<char> cleanString = inputString.ToList();
    for (int i = 1; i < cleanString.Count; i++)
    {
        if (char.IsUpper(cleanString[i]))
        {
            char[] temp = new char[cleanString.Count - i];
            for (int j = 0; j < temp.Length; j++)
            {
                temp[j] = cleanString[j + i];
            }
            cleanString[i] = ' ';
            cleanString.Add(' ');
            int index = 0;
            for (int j = i + 1; j < cleanString.Count; j++)
            {
                cleanString[j] = temp[index];
                index++;
            }
            i++;
        }
    }
    return new string(cleanString.ToArray());
}

However, I'm not quite confident about it. It seems quite big and maybe a little bit ugly, so please address any performance or code style issues.


texts:
The function receives a string containing a sentence. Its goal is to shorten every word in it to a length of 4 characters until the string is shorter than 38 characters and return.

The 38 characters max length is mandatory and must be reached with the least amount of deletion possible.

Here is what I've done:

# reduces each word to a lenght of 4
def shorten_words(string):
    i = 0
    j = 0
    while(len(string) > 38 and i < len(string)):
         array = list(string)
         if(array[i] != ' ' and array[i] != '-'):
             j += 1
         else:
             j = 0
         if(j > 4):
             array[i] = ''
             i -= 1
         i += 1
         string = ''.join(array)
    return(string)

I feel like the list/join method is inefficient and would like to know how I could improve this function


texts:
This is another solution for this challenge.

Problem statement:

  In this challenge, write a program that takes in three arguments, a
  start temperature (in Celsius), an end temperature (in Celsius) and a
  step size. Print out a table that goes from the start temperature to
  the end temperature, in steps of the step size; you do not actually
  need to print the final end temperature if the step size does not
  exactly match. You should perform input validation: do not accept
  start temperatures less than a lower limit (which your code should
  specify as a constant) or higher than an upper limit (which your code
  should also specify). You should not allow a step size greater than
  the difference in temperatures.

I want to learn more about C++, so if there is some cool C++ feature I could should have used, please comment (or include it in your answer).

#import <iostream>
#import <cmath>

#define COLUMN_SEPARATOR "\t| "
#define MAX_TEMP 500
#define MIN_TEMP -500

inline bool between(double x, double max, double min) {
    return max >= x && min <= x;
}

void getInput(double &lower, double &upper, double &step) {
    double temp1, temp2;
    std::cout << "Please enter consecutively the upper and lower limits, both between " <<  MIN_TEMP << " and " << MAX_TEMP << "." << std::endl;
    std::cin >> temp1;
    std::cin >> temp2;
    while (!between(temp1, MAX_TEMP, MIN_TEMP) || !between(temp2, MAX_TEMP, MIN_TEMP)) {
        std::cout << "At least one of the temperatures is out of bounds. Please reenter:" << std::endl;
        std::cin >> temp1;
        std::cin >> temp2;
    }
    upper = std::max(temp1, temp2);
    lower = std::min(temp1, temp2);
    std::cout << "Please enter a positive stepsize, smaller than the difference between the limits." << std::endl;
    std::cin >> step;
    while (step < 0 || step > upper - lower) {
        std::cout << "The stepsize is out of bounds. Please reenter:" << std::endl;
        std::cin >> step;
    }
}

double toFahrenheit(double celsius) {
    return celsius*(9/5) + 32;
}

void printTable(double start, double end, double step) {
    std::cout << "Celsius" << COLUMN_SEPARATOR << "Fahrenheit" << std::endl;
    std::cout << "=======" << COLUMN_SEPARATOR << "==========" << std::endl;
    for (double i = start; i < end; i += step) {
        std::cout << i << COLUMN_SEPARATOR << toFahrenheit(i) << std::endl;
    }
}

int main() {
    double start, end, step;
    getInput(start, end, step);
    printTable(start, end, step);
    return 0;
}

Sample run:

192:Challenges 11684$ ./a.out Please enter consecutively the upper and lower limits, both between -500 and 500.
3.692
65.937
Please enter a positive stepsize, smaller than the difference between the upper and lower limit.
5.3729
Celsius   | Fahrenheit
=======   | ==========
3.692 | 35.692
9.0649    | 41.0649
14.4378   | 46.4378
19.8107   | 51.8107
25.1836   | 57.1836
30.5565   | 62.5565
35.9294   | 67.9294
41.3023   | 73.3023
46.6752   | 78.6752
52.0481   | 84.0481
57.421    | 89.421
62.7939   | 94.7939


texts: Python list "commander" (modify a list with user commands)

texts:
I made a program that can modify a list using commands that the user enters.

The commands that are supported are (used from actual program):

/add [value1] [value2] [valueN]... - Add a value to the list
/rvalue [value] - Removes a value from the list
/rindex [index] - Removes the value at the specified index from the list
/print - Prints the list
/help - Lists every available command

Here is the code:

#Program to modify lists

value_list = []

def cmd_help():
    print("/add [value1] [value2] [valueN]... - Add a value to the list")
    print("/rvalue [value] - Removes a value from the list")
    print("/rindex [index] - Removes the value at the specified index from the list")
    print("/print - Prints the list")
    print("/help - Lists every available command")

def get_command_params():
    commands = {
        "/add": lambda *value : value_list.extend(list(value)),
        "/rvalue": lambda value : value_list.remove(value),
        "/rindex": lambda value : value_list.pop(int(value)),
        "/print": lambda : print(value_list),
        "/help": cmd_help
    }

    while True:
        input_cmd = input("Enter a command: ")

        #Separate arguments
        command = ""
        current_args_index = -1
        args = []
        last_char = ""

        for char in input_cmd:
            #Update separator
            if char == "/" or char == " ":
                last_char = char

            if last_char == "/":
                command += char
            elif last_char == "append":
                args[current_args_index] += char
            elif last_char == " ":
                args.append("")
                #To append individual characters to same index
                last_char = "append"
                ++current_args_index

        cmd = commands.get(command)
        if cmd == None:
            print("Invalid command!")
            continue

        return cmd, args

def main():
    cmd_help()

    #Wait for command
    while True:
        command, args = get_command_params()

        #Execute command with arguments
        try:
            command(*args)

            #Don't print success if command is print/help
            if args != []:
                print("Success!")
        except IndexError:
            print("Index out of range!")
        except ValueError:
            print("Element not found!")
        except TypeError:
            print("Invalid arguments! Type /help for help")

if __name__ == "__main__":
    main()


texts: SpaceSaving frequent item counter in Python

texts:
In the code below, I implemented the SpaceSaving frequency estimation algorithm described in this paper. Given a parameter eps, the algorithm finds all elements of a data stream of length n that occur more than n/eps times (with high probability). Here's a screenshot from the paper with the pseudocode:

I would appreciate any feedback on my implementation: style, performance, etc.

import math, heapq

class SpaceSavingCounter:
    def __init__(self, eps):
        self.k = math.ceil(1/eps)
        self.n = 0
        self.counts = dict()
        self.queue = []

    def inc(self, x):
        # increment total elements seen
        self.n += 1

        # x is being watched
        if x in self.counts:
            self.counts[x] += 1

        # x is not being watched
        else:
            # make room for x
            if self.n > self.k:
                while True:
                    count, tstamp, key = self.pop()
                    assert self.counts[key] >= count
                    if self.counts[key] == count:
                        del self.counts[key]
                        break
                    else:
                        self.push(self.counts[key], tstamp, key)
            else:
                count = 0

            # watch x
            self.counts[x] = count + 1
            self.push(count, self.n, x)

    def push(self, count, tstamp, key):
        heapq.heappush(
            self.queue,
            (count, tstamp, key)
        )

    def pop(self):
        return heapq.heappop(self.queue)

def test_SpaceSavingCounter():
    seq = [1,5,3,4,2,7,7,1,3,1,3,1,3,1,3]
    counter = SpaceSavingCounter(1 / 1.9)
    for x in seq:
        counter.inc(x)
    assert counter.counts.keys() == {1,3}


texts: Compute Manhattan distance from origin given a set of left-right-step directions

texts:
I am solving the problems for Advent of Code 2016 to learn Rust programming. The prompt for the first problem can be summarized:

I start at position 0,0 on a regular grid. I am given a set of directions to get to a location. I can only travel in "steps" on this grid, and I am only given directions in the form (e.g.):

R5, L2, L1, R1, R3, R3, L3, R3, R4, L2, R4, L4, R4

Where the first character is the direction to turn right or left and the following number is the number of steps to take. I need to compute the Manhattan distance between my starting point and the ending point.

The instructions are saved in a text file called "2016-1.txt".

use std::fs;

struct Pos {
    facing: char,
    x: i32,
    y: i32,
}

fn split_dir(dir_str: &str) -> Vec<&str> {
    dir_str.split(", ").collect()
}

fn update_facing(rel_dir: &char, face_char: &char) -> char {
    if *rel_dir == 'L' {
        match face_char {
            'N' => 'W',
            'S' => 'E',
            'E' => 'N',
            'W' => 'S',
            _ => 'I', // Is there a better way to handle the catch-all?
        }
    } else {
        match face_char {
            'N' => 'E',
            'S' => 'W',
            'E' => 'S',
            'W' => 'N',
            _ => 'I',
        }
    }
}

fn update_x(pos_x: i32, face_char: char, move_num: i32) -> i32 {
    match face_char {
        'E' => pos_x + move_num,
        'W' => pos_x - move_num,
        _   => pos_x
    }
}

fn update_y(pos_y: i32, face_char: char, move_num: &i32) -> i32 {
    match face_char {
        'N' => pos_y + move_num,
        'S' => pos_y - move_num,
        _   => pos_y
    }
}

fn get_manhattan_dist(pos_x: i32, pos_y: i32, origin_x: i32, origin_y: i32) -> i32 {
    (pos_x - origin_x).abs() + (pos_y - origin_y).abs()
}

fn main() {
    let s = fs::read_to_string("2016-1.txt")
        .expect("Failed to read file.");

    let split: Vec<&str> = split_dir(&s);

    let mut pos: Pos = Pos {x: 0, y: 0, facing: 'N'};

    for inst in split {
        // Update direction
        let rel_dir = inst.chars().nth(0).unwrap(); // Get first character of the instruction
        pos.facing = update_facing(&rel_dir, &pos.facing);

        // Update position
        let move_num = &inst[1..].parse::<i32>().unwrap();
        pos.x = update_x(pos.x, pos.facing, *move_num);
        pos.y = update_y(pos.y, pos.facing, &move_num);
    }

    let dist = get_manhattan_dist(pos.x, pos.y, 0, 0);
    println!("{}", dist);
}

I am particularly interested in error handling. Particularly in the update_facing function. This is my first Rust program, so all advice is warranted as well.


texts:
I'm processing about 3.5gb/15minutes, and I was wondering if I could get this down to a better time...

Note that this is for a very specific CSV file, so I am not concerned about generality - only speed of implementation and optimization.

int main(int argc, char *argv[]) {
    std::string filename;
    std::cout << "Please type the file name: " << std::endl;
    std::cin >> filename;

    std::string ticker;
    std::cout << "Please enter the ticker: " << std::endl;
    std::cin >> ticker;

    std::ifstream instream(filename.c_str());
    std::string ask_filename = ticker + "_ASK.NIT";
    std::ofstream askstream(ask_filename.c_str());

    std::string bid_filename = ticker + "_BID.NIT";

    std::ofstream bidstream(bid_filename.c_str());

    std::string line;
    std::getline(instream,line);

    while(std::getline(instream,line))
    {
        std::stringstream lineStream(line);
        std::string cell;
        std::string new_line;
        std::vector<std::string> my_str_vec;
        while(std::getline(lineStream,cell,','))
        {
            my_str_vec.push_back(cell);
            //new_line.append(cell.append(";"));
        }
        // works on date
        std::string my_date = my_str_vec[0];
        std::string::iterator my_iter;
        std::string processed_date = "";
        for(my_iter = my_date.begin(); my_iter != my_date.end(); ++my_iter) {
            if(std::isalnum(*my_iter) || *my_iter == ' ')
                processed_date.append(1,(*my_iter));
        }

        my_str_vec[0] = processed_date;

        std::vector<std::string>::iterator my_vec_iter;
        for(my_vec_iter = my_str_vec.begin() + 1; my_vec_iter != my_str_vec.end(); ++my_vec_iter) {
            std::string my_semicol = ";";
            *my_vec_iter = my_semicol.append(*my_vec_iter);
        }

        askstream << my_str_vec[0] << my_str_vec[1] << my_str_vec[3] << std::endl;
        bidstream << my_str_vec[0] << my_str_vec[2] << my_str_vec[4] << std::endl;
    }

    askstream.close();
    bidstream.close();

    return 0;
}


texts: Returning information about the result of a file processing, without using output parameters

texts:
As part of a C# class CsvConverter that converts various file types to CSV, I am designing a private class CsvConversionResult. My current design choice is to return a null value of CsvConversionResult if processing is successful.

What can I add to or remove from my design to use "best practices"? Returning primitive data types is out of the question since I want to return more than one thing.

public static class CsvConverter
{
    public class CsvConverterError
    {
        public string Message { get; set; }
        public int LineNumber { get; set; }
        public string FileName { get; set; }

        public CsvConverterError(string message, int lineNumber, string fileName)
        {
            Message = message;
            LineNumber = lineNumber;
            FileName = fileName;
        }
    }

    // returns null if successful
    public static CsvConverterError WriteCsvRowsToFile(char delimiter,
                                                 string inputFilePath,
                                                 string outputFilePath,
                                                 string qualifier = "")
    {
        CsvConverterError error = null;

        /* Some code here that sets the value of error accordingly */

        return error;
    }


texts:
I've written this module (using a tutorial on the web I can't find now  to stop unusual requests from clients.  It's working as I've tested it on a local system.

Is the logic fine enough?
Another problem is that it counts requests for non-aspx resources (images, css, ...), but it shouldn't.  How can I filter request for aspx pages ?

This is the module code:

public class AntiDosModule : IHttpModule
{
    const string blockKey = "IsBlocked";
    const string reqsKey = "Requests";

    public void Dispose()
    { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += ValidateRequest;
    }

    private static void ValidateRequest(object sender, EventArgs e)
    {
        // get configs from web.config
        AntiDosModuleSettings setting = AntiDosModuleSettings.GetConfig();

        int blockDuration = setting.IPBlockDuration;

        // time window in which request are counted e.g 1000 request in 1 minute
        int validationTimeWindow = setting.ValidationTimeWindow;

        // max requests count in specified time window e.g 1000 request in 1 minute
        int maxValidRequests = setting.MaxValidRequests;

        string masterKey = setting.MasterKey;

        HttpContextBase context = new HttpContextWrapper(HttpContext.Current);

        CacheManager cacheMgr = new CacheManager(context, masterKey);

        // is client IP blocked
        bool IsBlocked = (bool)cacheMgr.GetItem<Boolean>(blockKey);

        if (IsBlocked)
        {
            context.Response.End();
        }

        // number of requests sent by client till now
        IPReqsHint hint = cacheMgr.GetItem<IPReqsHint>(reqsKey) ?? new IPReqsHint();

        if (hint.HintCount > maxValidRequests)
        {
            // block client IP
            cacheMgr.AddItem(blockKey, true, blockDuration);

            context.Response.End();

        }

        hint.HintCount++;

        if (hint.HintCount == 1)
        {
            cacheMgr.AddItem(reqsKey, hint, validationTimeWindow);
        }

    }

}

internal class IPReqsHint
{

    public int HintCount { get; set; }

    public IPReqsHint()
    {
        HintCount = 0;
    }
}

and this is the CacheManager class:

public class CacheManager
{

    HttpContextBase context;

    string masterKey;

    public CacheManager(HttpContextBase context, string masterKey)
    {
        this.context = context;
        this.masterKey = masterKey;
    }

    public void AddItem(string key, object value, int duration)
    {
        string finalKey = GenerateFinalKey(key);

        context.Cache.Add(
            finalKey,
            value,
            null,
            DateTime.Now.AddSeconds(duration),
            System.Web.Caching.Cache.NoSlidingExpiration,
            System.Web.Caching.CacheItemPriority.Normal,
            null);
    }

    public T GetItem<T>(string key)
    {
        string finalKey = GenerateFinalKey(key);

        var obj = context.Cache[finalKey] ?? default(T);

        return (T)obj;
    }

    string GenerateFinalKey(string key)
    {
        return masterKey + "-" + context.Request.UserHostAddress + "-" + key;
    }
}


texts: How to speed up drawing process of output from .tflite model

texts:
I have piece of code where I draw  output from model pixel by pixel:
fun draw(
        canvas: Canvas) {
        val rotated = sensorOrientation % 180 == 90
        var rotatedW = frameWidth;
        var rotatedH = frameHeight;
        if(rotated) {
            rotatedW = frameHeight
            rotatedH = frameWidth
        }

        val multiplier =
            min(
                canvas.height.toFloat() / rotatedH.toFloat(),
                canvas.width.toFloat() / rotatedW.toFloat()
            )
        val w = (rotatedW * multiplier).toInt()
        val h = (rotatedH * multiplier).toInt()

        results?.let {
            var pos: Int
            val xw = w / 256f
            val xh = h / 256f
            val rectF = RectF()
            for (y in 0 until 256) {
                for (x in 0 until 256) {
                    pos = getIndexOfMax(results!![0][y][x])
                    if (pos > 0) {
                        val vertical = y / 256f * h
                        val horizontal = x / 256f * w
                        rectF.left = horizontal - xw
                        rectF.top = vertical - xh
                        rectF.right = horizontal + xw
                        rectF.bottom = vertical + xh
                        canvas.drawRect(rectF, boxPaint)
                    }

                }
            }
        }
    }

However this works really slow. Nested for is probably one of the main issues here. I don't know how can I speed it up. As you can see both counters are necessary here because I need to get certain field from results. I've heard that Bitmap uasage instead of Canvas would be partial solution because I am able to get certain pixels but I don't really know how to use it right. Method draw() is called here inside MainActivity:
trackingOverlay.addCallback(
            object : OverlayView.DrawCallback {
                override fun drawCallback(canvas: Canvas?) = tracker.draw(canvas!!)
            }
        )

And the trackingOverlay is an instance of OverlayView class which inherits from View:
class OverlayView(ctx: Context, attr: AttributeSet) : View(ctx, attr) {

    private val callbacks: MutableList<DrawCallback> =
        LinkedList()

    fun addCallback(callback: DrawCallback) { callbacks.add(callback) }

    @Synchronized
    override fun draw(canvas: Canvas) {
        for (callback in callbacks) {
            callback.drawCallback(canvas)
        }
    }

    interface DrawCallback {
        fun drawCallback(canvas: Canvas?)
    }
}

I've tried creating Bitmap before draw (to reuse it) and then use canvas.drawBitmap() but it needs transformation Matrix to fill whole screen, otherwise it covers only small chunk of it and even then I haven't noticed any performance increase.
EDIT
That's how getIndexOfMax() looks like:
private fun getIndexOfMax(array: FloatArray): Int {
        if (array.isEmpty()) return -1
        return when {
            array[0] > array[1] -> 0
            else -> 1
        }
    }

Results is 4 dim Array of Float


texts:
I've written the following code for computing the powerset of a list (we consider the list has all distinct elements, although it doesn't really matter).

Can this function be further optimized?

def powerset(A):
    if A == []:
        return [[]]
    a = A[0]
    incomplete_pset = powerset(A[1:])
    rest = []
    for set in incomplete_pset:
        rest.append([a] + set)
    return rest + incomplete_pset


texts: 2vs2 Poker Hand One Pair Winner Algorithm

texts:
I wrote this algorithm to determine the winning hand of two players going head to head with a hand of One Pair.  Note that the hand is sorted once it is given out, and the algorithm has to compare the two hands one pair, if one has a higher one pair such as AA vs 33, there is an obvious winner.  If the hands have matching one pairs, such as 44 & 44, the high card must be compared to determine the winner.

Please take a look at let me know how it looks.  It is my first real algorithm taking into account so many factors.  I am looking more for opinions, not answers.  If you feel it is no good and needs improvement, please tell me so.  It does work 100% as I have ran a lot of tests using different one pair hands of different values.

         // Arrays to hold matching pair and high card
         PlayingCard[] pPairHigh = new PlayingCard[2];
         PlayingCard[] oPairHigh = new PlayingCard[2];
         for(int i = 0; i < POKER_HAND_SIZE - 1 ; i++) {

             if(this.hand[i].compareTo(this.hand[i+1]) == 0) {
                 pPairHigh[0] = this.hand[i];

                 if(i == 3)
                    pPairHigh[1] = this.hand[i - 1];
                 else
                    pPairHigh[1] = this.hand[POKER_HAND_SIZE - 1];
             }

             if(otherHand.hand[i].compareTo(otherHand.hand[i+1]) == 0) {
                 oPairHigh[0] = otherHand.hand[i];

                 if(i == 3)
                    oPairHigh[1] = otherHand.hand[i - 1];
                 else
                    oPairHigh[1] = otherHand.hand[POKER_HAND_SIZE -

         if(pPairHigh[0].compareTo(oPairHigh[0]) == 0){
             if(pPairHigh[1].compareTo(oPairHigh[1]) < 0)
                     return -1;
             else if(pPairHigh[1].compareTo(oPairHigh[1]) > 0)
                 return 1;
             else
                 return 0;
         }

         if(pPairHigh[0].compareTo(oPairHigh[0]) < 0)
             return -1;
         else
             return 1;

     }


texts:
I have this simple cache mechanism for a repeated task in service. It uses static variable to store the information. Please suggest on how is it and if it could be better.

Premise: I need to verify transaction from stores. There can be lots of transactions happening repeatedly from multiple stores. Thus, this simple cache manager for getting the store information. I want it to be simple yet effective and fast.

StoreCacheManager.cs

public class StoreCacheManager
{
    private static List<StoreCacheInformation> _merchantStores = new List<StoreCacheInformation>();
    private DBEntities _db;
    private TimeSpan _cacheTime = new TimeSpan(1, 0, 0);//1 Hour
    public TimeSpan CacheTimeSpan { get { return _cacheTime; } }
    public StoreCacheManager(DBEntities db)
    {
        _db = db;
    }

    public async Task<StoreCacheInformation> Get(int storeId)
    {
        if (_merchantStores.Any())
        {
            var store =
                _merchantStores.FirstOrDefault(i => i.StoreID == storeId);
            if (store != null)
            {
                // Check if Cache time has expired
                if (store.CacheDateTimeUtc.Add(_cacheTime) < DateTime.UtcNow)
                {
                    lock (_merchantStores)
                    {
                        _merchantStores.Remove(store);
                    }
                }
                else
                {
                    return store;
                }
            }
        }
        return await GetAndCache(storeId);
    }

    private async Task<StoreCacheInformation> GetAndCache(int storeId)
    {
        var store = await GetStoreInfo(storeId);
        if (store != null)
        {
            lock (_merchantStores)
            {
                _merchantStores.Add(store);
            }
        }
        return store;
    }
    private async Task<StoreCacheInformation> GetStoreInfo(int storeId)
    {
        var storeInfo = await _db.Stores.Where(i => i.StoreID == storeId).Select(i => new StoreCacheInformation()
        {
            CountryCode = i.CountryObj.CountryCode,
            MerchantID = i.VendorOrgID ?? 0,
            TelephoneCode = i.CountryObj.TelephoneCountryCode,
            StoreID = storeId,
            //todo: deviceId and Token

        }).FirstOrDefaultAsync();
        if (storeInfo != null)
        {
            storeInfo.CacheDateTimeUtc = DateTime.UtcNow;
        }
        return storeInfo;
    }
}

StoreCacheInformation.cs

public class StoreCacheInformation
{
    public int MerchantID { get; set; }
    public int StoreID { get; set; }
    public string TelephoneCode { get; set; }
    public string CountryCode { get; set; }
    public DateTime CacheDateTimeUtc { get; set; }
    public string DeviceId { get; set; }
    public string AuthToken { get; set; }
}


texts:
The task (also found at https://www.youtube.com/watch?v=10WnvBk9sZc):

  Write a function that takes two strings, s1 and s2, and returns the longest common subsequence of s1 and s2.

  "ABAZDC", "BACBAD" → "ABAD"
  "AGGTAB", "GXTXAYB" → "GTAB"

  The longest common subsequence is defined such as all of them appear in the same sequence in both strings, possiblywith other characters in between.

This is the solution I managed to come up with. I utilise the fact that once a full subsequence as been found, any subsequences that start within the boundaries of that subsequence will always be smaller in length, so I skip ahead.

const findFirstSequence = (s1, s2) => {
  let subsequence = ""

  let s1Idx = 0
  let s2Idx = 0

  for (; s1Idx < s1.length; ++s1Idx) {
    const s1Char = s1[s1Idx]
    for (let j = s2Idx; j < s2.length; ++j, ++s2Idx) {
      const s2Char = s2[j]
      if (s1Char === s2Char) {
        subsequence += s1Char
          ++s2Idx
        break
      }
    }
  }
  return subsequence
}

const removeDistinctChars = (s1, s2) => s1.split("").filter(c => s2.includes(c)).join("")
const removeDuplicates = (arr) => Array.from(new Set(arr))

const findAllSubsequences = (s1, s2) => {
  const s1NoDistinct = removeDistinctChars(s1, s2)
  const s2NoDistinct = removeDistinctChars(s2, s1)

  let i = 0

  const sequences = []

  while (i < s1NoDistinct.length) {
    const sequence = findFirstSequence(s1NoDistinct.slice(i), s2NoDistinct)
    i += sequence.length
    sequences.push(sequence)
  }

  return sequences
}

const findLongestSubsequence = (s1, s2) => {
  const a = findAllSubsequences(s1, s2)
  const b = findAllSubsequences(s2, s1)

  console.log('candidates:', [...a, ...b])

  return removeDuplicates([...a, ...b].sort((s1, s2) => s2.length - s1.length).filter((el, idx, arr) => el.length ===
    arr[0].length))
}

const test = (s1, s2) => console.log(findLongestSubsequence(s1, s2))

test("ABAZDC", "BACBAD")
test("AGGTAB", "GXTXAYB")
test("ALSKJDHJASLDH", "HNGFLKSHRADSKLASDJ")
test("aaaa", "aa")


texts: PHP/Apache - Production/staging consts file path

texts:
Is there anything wrong with having a file path as an env variable and using that as-is in a require_once?

<?
$CONSTANTS_FILE = getenv('CONSTANTS_FILE_PATH');
require_once($CONSTANTS_FILE);
echo DB_USER
?>

And here is how it is set in apache:

<VirtualHost *:80>
    #ServerName
    #DocumentRoot
    SetEnv CONSTANTS_FILE_PATH /path/to/file.php
    # Directory
</VirtualHost>

Is there a better way of having variable const files included in the project source code?


texts:
The code it self is pretty self explanatory, however i do not think it is very efficient at all. Is there a better way to do this?

Its basically so i can track spam sites and save the sites into my honeypot db.

<?php
$site = $_GET['url'];
$con=mysqli_connect("localhost","_","","_");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//Gambling
if (strpos($site, "betting") ||strpos($site, "blackjack") ||strpos($site, "casino") ||strpos($site, "craps") ||strpos($site, "football") ||strpos($site, "gamble") ||strpos($site, "gambling") ||strpos($site, "game") ||strpos($site, "gaming") ||strpos($site, "greyhound") ||strpos($site, "highroller") ||strpos($site, "lottery") ||strpos($site, "lotto") ||strpos($site, "odds") ||strpos($site, "poker") ||strpos($site, "racehorse") ||strpos($site, "racing") ||strpos($site, "roulette") ||strpos($site, "royalflush") ||strpos($site, "slotmachine") ||strpos($site, "slots") ||strpos($site, "slotsmachine") ||strpos($site, "sport") ||strpos($site, "wager") ||strpos($site, "paigow") ||strpos($site, "bingo") ||strpos($site, "baccarat"))
{
    //Insert into gambling
    $result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`gambling` (`id`, `url`) VALUES (NULL, '$site');");

}
//Payday
if (strpos($site, "payday") ||strpos($site, "loan") ||strpos($site, "bank") ||strpos($site, "money") ||strpos($site, "wonga") ||strpos($site, "lender") ||strpos($site, "credit") ||strpos($site, "debt") ||strpos($site, "repayment") ||strpos($site, "mortgage"))
{
    //Insert into payday
    $result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`payday` (`id`, `url`) VALUES (NULL, '$site');");
}
//Lawyer
if (strpos($site, "law") ||strpos($site, "solicitor") ||strpos($site, "government") ||strpos($site, "injury") ||strpos($site, "personal") ||strpos($site, "accident") ||strpos($site, "advice") ||strpos($site, "traffic"))
{
    //Insert into lawyer
    $result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`lawyer` (`id`, `url`) VALUES (NULL, '$site');");
}
//Weight Loss
if (strpos($site, "weight") ||strpos($site, "loss") ||strpos($site, "pills") ||strpos($site, "diet") ||strpos($site, "garcinia") ||strpos($site, "cambogia") ||strpos($site, "acai") ||strpos($site, "berry") ||strpos($site, "raspberry") ||strpos($site, "ketone") ||strpos($site, "coffee") ||strpos($site, "tea") ||strpos($site, "health") ||strpos($site, "lose") ||strpos($site, "surgery") ||strpos($site, "fat") ||strpos($site, "dieting") ||strpos($site, "exercise") ||strpos($site, "workout") ||strpos($site, "gym") ||strpos($site, "hypnosis"))
{
    //Insert into weight loss
    $result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`weightloss` (`id`, `url`) VALUES (NULL, '$site');");
}
//Insurance
if (strpos($site, "ppi") ||strpos($site, "insurance") ||strpos($site, "payment") ||strpos($site, "claim") ||strpos($site, "calculator") ||strpos($site, "finance") ||strpos($site, "mis-sold"))
{
    //Insert into insurance
    $result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`insurance` (`id`, `url`) VALUES (NULL, '$site');");
}

mysqli_close($con);
exit();
?>


texts: Calculating a payment price based on a selected phone

texts:
The program shows three phones with prices, and you need to select one of them. The program will then calculate the price based on the payment type you selected.

I'm very new to the world of OOP, and because I'm studying OOP on my own (I actually go to school and we have a computer subject, but I'm taking advance lessons on my own), I have no one to judge my code. I can make programs run, but I'm not sure if I am coding well.

Is there a better way I could have written this simple program? What are the conventions that I did not follow? I did my best based on things I read though, but I'm not sure if I missed things.

package javaPackage;
import java.util.Scanner;
import java.text.DecimalFormat;
public class OopApproach
{
    private String model;
    private double price;
    private double discount;

    public OopApproach(String model,int price)
    {
        this.model=model;
        this.price=price;
    }
    public void setModel( String model )
    {
        this.model = model;
    }
    public void setPrice( double price )
    {
        this.price = price;
    }

    public static void main( String args[] )
    {
        DecimalFormat df = new DecimalFormat("##.00");

        Scanner input=new Scanner(System.in);
        int selection;

        OopApproach iPhone = new OopApproach( "iPhone 6s", 299);
        OopApproach samsung = new OopApproach( "Samsung s6", 199);
        OopApproach lg = new OopApproach( "LG", 99 );

        System.out.println("Press 1:" + iPhone.model+" = " + "$" + df.format(iPhone.price));
        System.out.println("Press 2:" + samsung.model+" = " + "$" +df.format(samsung.price));
        System.out.println("Press 3:" + cherry.model+" = "+ "$" + df.format(lg.price));

        selection=input.nextInt();

        switch(selection)
        {
        case 1:System.out.println( "Your item is " + iPhone.model + " with price of " + "$" + df.format(iPhone.price));
        System.out.println();
        calcPrice(iPhone.model, iPhone.price);
        break;
        case 2:System.out.println( "Your item is " + samsung.model + " with price of " + "$" + df.format(samsung.price));
        System.out.println();
        calcPrice(samsung.model, samsung.price);
        break;
        case 3:System.out.println( "Your item is " + lg.model + " with price of " + "$" + df.format(lg.price));
        System.out.println();
        calcPrice(cherry.model, lg.price);
        break;
        }
    }
        public static void calcPrice(String model,double price)
        {
            Scanner in=new Scanner(System.in);
            DecimalFormat dff=new DecimalFormat("##.00");
            int selec;
            double totalVal;

            System.out.println("Choose payment option");
            System.out.println("1:Cash - 5% discount");
            System.out.println("2:Installment, 3 months - 5% interest");
            System.out.println("3:Installment, 6 months - 10% interest");

            selec=in.nextInt();

            if(selec==1)
            {
                totalVal=price-(price*.05);
                System.out.print("You purchased " + model + " and the total cost is "+ "$" + dff.format(totalVal));
            }
            else if(selec==2)
            {
                totalVal=price+(price*.05);
                System.out.print("You purchased " + model + " and the total cost is "+ "$" + dff.format(totalVal));
            }
            else if(selec==3)
            {
                totalVal=price+(price*.10);
                System.out.print("You purchased " + model + " and the total cost is "+ "$" + dff.format(totalVal));
            }
    }
}

Output:

Press 1:iPhone 6s = $299.00
Press 2:Samsung s6 = $199.00
Press 3:LG = $99.00
1
Your item is iPhone 6s with price of $299.00

Choose payment option
1:Cash - 5% discount
2:Installment, 3 months - 5% interest
3:Installment, 6 months - 10% interest
1
 You purchased iPhone 6s and the total cost is $284.05