texts: Merge the two sorted array of numbers into single array

texts:
I have written a code were I pass two sorted array of numbers from command line, and out is one array with numbers sorted.

the code is as follows,

(function(){
    'use strict';

    var getCommandLineVariables = getCommandLineVariables;

    var mainFunction = mainFunction;

    mainFunction();

    function mainFunction(){
        var array = getCommandLineVariables();
        var firstArray = array[0],
            secondArray = array[1],
            mergedArray = [], i = 0, j = 0;

        for(i = 0; i < firstArray.length; i++){
            for(j = j; j < secondArray.length; j++){

                if(firstArray[i] < secondArray[j]){ // if number from first array is less than number of second array
                    mergedArray.push(firstArray[i]);
                    break;
                }else{ // if number of second array is less than number of first array
                    mergedArray.push(secondArray[j]);
                }

            } // end of for

            /*
                The below condition executes when
                length of first array is greater than second array
            */
            if(j >= secondArray.length){
                mergedArray.push(firstArray[i]);
            }
        } // end of for

        /*
            If length of second array is greater than
            first array
        */
        for(j = j; j < secondArray.length;j++){
            mergedArray.push(secondArray[j])
        }

        console.log(mergedArray);
    } // mainFunction

    /*
        Capture the numbers passed as commandline arguments
    */
    function getCommandLineVariables(){
        var arg_array = process.argv.slice(2),
            someArray = [];

        if(arg_array.length !== 2){
            throw "Pass two comma seperated numbers";
        }

        for(var i = 0; i < arg_array.length; i++){

            someArray.push((function(someString){
                var someArray = someString.split(",");

                someArray = someArray.map(function(str){
                    return parseInt(str);
                });

                return someArray;
            })(arg_array[i]));

        } // end of for

        return someArray;
    } // end of getCommandLineVariables
})();

The output of the above code is as follows,

E:\DataStructuresAndAlgorithms\array>node mergeSortedArray01.js 1,3,100 2,4,5,7,10
[ 1, 2, 3, 4, 5, 7, 10, 100 ]

E:\DataStructuresAndAlgorithms\array>

One more output

E:\DataStructuresAndAlgorithms\array>node mergeSortedArray01.js 3,27,100 2,4,5,7,10
[ 2, 3, 4, 5, 7, 10, 27, 100 ]

E:\DataStructuresAndAlgorithms\array>

Can you please review my code a check is there any room for improvement,
Can the above problem be solved in other ways.


texts: Finding the number which satisfies specific conditions

texts:
I saw this question somewhere:

There is an 8-digit number. The first digit from left to right determines how many zeroes are in the number. The second digit tells you how many 1s are in the number, the third digit tells you how many 2s are in the number and so on, until the 8th digit, which tells you how many 7s are in the number. Find the number.

I wrote a piece of code in Python to find out the digit. Apart from the conditions mentioned above, I have a few additional checks like 'sum of digits should be 8' and 'no 8 or 9 should be present in the number'. This is just brute force since I take every number and check for conditions. I was curious to know if there is any better way of solving the problem.

def returnStat(number, digit, count):
    number = str(number)
    digit = str(digit)
    print "Analysing for ",digit," to see if it appears ",count, " times in ",number,"."
    actCnt = number.count(digit)
    count = str(count)
    actCnt = str(actCnt)
    if (actCnt == count):
        return 1
    else:
        return 0
def validateNum(number):
    numList = str(number)
    if '8' in numList:
        print "Skipping ",number, " since it has 8 in it"
        return (-1)
    elif '9' in numList:
        print "Skipping ",number, " since it has 9 in it"
        return (-1)
    elif (sum(int(digit) for digit in numList) != 8):
        print "Skipping ",number, " since its sum is not equal to 8"
        return (-1)
    index = 0
    flag = 0
    for num in numList:
        if (returnStat(number,index,num)) :
            index = index+1
            continue
        else:
            flag = 1
            break
    if (flag == 1):
        return (-1)
    else:
        return number

for num in range(0,80000000):
    number = '{number:0{width}d}'.format(width=8,number=num)
    desiredNum = "-1"
    desiredNum = validateNum(number)
    if (desiredNum == -1):
        print number," does not satisfy all "
        continue
    else:
        print "The number that satisfies all contition is ",number
        break


texts: Send Data from DynamoDB to Lambda (C#) and to Azure Queue

texts:
I am a beginner and trying to send data from AWS DynamoDB to Azure Queues. Note that this code will be invoked 10,000 and alot more. Can you guys review it once.

using System;
using System.IO;
using System.Text;

using Newtonsoft.Json;

using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;
using Amazon.DynamoDBv2.Model;
using Microsoft.Azure.ServiceBus;
using System.Threading.Tasks;

    // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
    [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace Lambda
{
    public class Function
    {
        private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();

        public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
        {
            context.Logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records...");

            foreach (var record in dynamoEvent.Records)
            {
                context.Logger.LogLine($"Event ID: {record.EventID}");
                context.Logger.LogLine($"Event Name: {record.EventName}");

                string streamRecordJson = SerializeStreamRecord(record.Dynamodb);
                await Send(streamRecordJson);
                context.Logger.LogLine($"DynamoDB Record:");
                context.Logger.LogLine(streamRecordJson );
            }

            context.Logger.LogLine("Stream processing complete.");
        }

        private static async Task Send(string stream)
        {
            const string connectionString = "QUEUE END POINT";
            string queueName = "QUEUE NAME";
            ServiceBusConnectionStringBuilder svc = new ServiceBusConnectionStringBuilder(connectionString);
            ServiceBusConnection svc1 = new ServiceBusConnection(svc);
            var client = new QueueClient(svc1, queueName, ReceiveMode.PeekLock, RetryPolicy.Default);
            var message = new Message(Encoding.UTF8.GetBytes(stream));
            await client.SendAsync(message);
        }

        private string SerializeStreamRecord(StreamRecord streamRecord)
        {
            using (var writer = new StringWriter())
            {
                _jsonSerializer.Serialize(writer, streamRecord);
                return writer.ToString();
            }
        }
    }
}


texts: Checking if a date comes after another in Java

texts:
I need to test if a date is posterior to another in java, I just need to be sure that my approach is a good one

public class Date {
    private int day;
    private int month;
    private int year;

    public Date(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public int getDay() {
        return day;
    }

    public int getMonth() {
        return month;
    }

    public int getYear() {
        return year;
    }

    public boolean posterieurTo(Date dateToCompare){
        if (year > dateToCompare.getYear())
            return true;
        else if (month > dateToCompare.getMonth())
            return true;
        else if (day > dateToCompare.getDay())
            return true;
        else
            return false;
    }

}


texts:
I have two time intervals i1 and i2, each defined by two values, begin and end (epoch time). I need to write a function returning a boolean value indicating whether the intervals overlap.

According to my understanding, an overlap can occur in four following cases:

while the last case (where the i2 is fully included within i1 is already covered by first two cases so can be dismissed.

The remaining three cases lead me to the following logic:

private static boolean isThereOverlap(Interval t1, Interval t2) {

        return t1.begin.isAfter(t2.begin) && t1.begin.isBefore(t2.end) ||
                t1.end.isAfter(t2.begin) && t1.end.isBefore(t2.end) ||
                t1.begin.isBefore(t2.begin) && t1.end.isAfter(t2.end);
}

where:

t1 and t2 represent i1 and i2 accordingly.

I wonder whether there's a more concise way to identify the overlap or a
way to simplify the code?

EDIT1:

Including the Interval class which is utilizing java.time:

import java.time.Instant;

private class Interval {
        private Instant begin;
        private Instant end;

        private Interval(long begin, long end) {
            this.begin = Instant.ofEpochMilli(begin);
            this.end = Instant.ofEpochMilli(end);
        }
    }


texts:
Let's take the following example. Even if the number of parameters is acceptable, I find that the code block is too long.

Are these validations at the right place? Is there a better approach in such cases?

public function __construct(
    array $config,
    EntityManager $em,
    EventDispatcherInterface $dispatcher
) {
    $this->em = $em;
    $this->dispatcher = $dispatcher;
    if (isset($config['endPoint'])) {
        $this->endpoint = $config['endPoint'];
    } else {
        throw new ConfigurationException();
    }
    if (isset($config['partnerLogin']) && isset($config['partnerPass'])) {
        $this->partnerLogin = $config['partnerLogin'];
        $this->partnerPass = $config['partnerPass'];
    } else {
        throw new MissingCredentialsException();
    }
    if (isset($config['account_id'])) {
        $this->ids['account_id'] = $config['account_id'];
    } else {
        throw new MissingCredentialsException();
    }
    if (isset($config['user_id'])) {
        $this->ids['account_id'] = $config['account_id'];
    } else {
        throw new MissingCredentialsException();
    }
    $this->apiClient = $this->createApiClient();
}


texts: Calculating Luhn-algorithm checksum digit

texts:
Today I decided to learn some basic Haskell, and for starters I made a program for calculating the checksum of a Swedish personal identification number. It uses the Luhn-algorithm, aka. IBM MOD-10.

Explanation of this code can be found on Swedish Wikipedia and English Wikipedia

Here's a description of how the algorithm works:

Given a string of 9 digits, abcdefghi compute:

array = [a*2, b, c*2, d, e*2, f, g*2, h, i*2]

Then you computer the sum of the digits in this array, so for example if a*2 is 16, then that part counts as 1 + 6.

Then the result is how much more you have to add to make it evenly divisible by 10. For example, if sum == 54 then the result is 6 as 60 - 54 = 6.

import Data.Char

sumOfChars :: String -> Int
sumOfChars "" = 0
sumOfChars str = digitToInt(str !! 0) + sumOfChars(tail str)

twoMult :: Char -> String
twoMult c = show (digitToInt(c) * 2)

identificationSum :: String -> Int
identificationSum "" = 0
identificationSum str = if length str `mod` 2 == 1 then sumOfChars(twoMult(str !! 0)) + identificationSum(tail str)
  else digitToInt(str !! 0) + identificationSum(tail str)

remainingToTens :: Int -> Int
remainingToTens x = ceiling(fromIntegral x / 10) * 10 - x

determineLastDigit :: String -> Int
determineLastDigit str = remainingToTens(identificationSum(str))

To test the code:

determineLastDigit("811228987")

Prints:

4

As this is the first time ever I managed to make something in Haskell, any comments are welcome. Even though it is the first time though, feel free to rip my code apart as much as you would like and suggest any advanced things, I am always eager to learn.


texts: Bugs - Program that Creates a Directory in C

texts:
I have the following code that creates a directory in C. I tested it multiple times, reviewed it a few times and it looks fine at the moment.

What I really wanna know is what bugs does it have and how can I fix them ? (comparing it with the mkdir command from linux)

#include "ourhdr.h"
#include <sys/stat.h>
#include <limits.h>
#include <dirent.h>

int main(int argc, char **argv)
{

    if(argc != 2)
    {
        printf("./i78 /locatie/nume_director sau ./i78 nume_director\n");
        return 1;
    }

    char buff[PATH_MAX];
    strcpy(buff,argv[1]);

    if (mkdir(buff,S_IRWXU|S_IRWXG|S_IRWXO)<0)
    {
    printf("%s: cannot create directory '%s': File exists\n",argv[0],buff);
    }
    else

    printf("\n Creare director [%s]\n",buff);

}


texts:
I have some classes with properties, wich could only have numeric values in a given range (e.g. 0 to 8). This should be validated and wrong values prevented with an exception. The given behavior may be implemented without duplicating the given code.
There are some ValidatorAttributes in C# but I can't get them to running. They don't seem to prevent the assignment with wrong values in a normal class.
My current solution is to copy paste this snippet for every attribute. But copy paste is not perfect:
private short _index;
public short Index
{
    get => this._index;
    private set
    {
        const short min = 0;
        const short max = 8;
        if (value < min || max < value)
        {
            throw new ArgumentOutOfRangeException("The passed value is not between " + min + "  and " + max + " (values included)");
        }
        this._index = value;
    }
}


texts: `ls` indicates when directory is empty/full of dotfiles

texts:
I want ls to print a message when run on an empty or full of dotfiles directory. Instead of:

$ ls empty_dir/ dotfiles/
$

I want:

$ ls empty_dir/ dotfiles/
empty_dir is empty

dotfiles contains only hidden files
$

If dir contains only dotfiles, and if the ls command is able to show them, the following should appear:

$ ls dotfiles/
dotfiles contains only hidden files
$ ls dotfiles/ -A
.hidden_dir

I searched a solution for that behavior, but can't found anything, so end up to implement it myself, using zsh:

# Wrapper around ls function, printing dedicated messages
#  if directory is empty/full of hidden files.
#  Parse parameters in order to call verbosels_onefile correctly.
function verbosels() {
    # extract options and filepaths
    ls_options=""
    ls_filepaths=""
    for parameter in "$@"
    do
        #echo "PARAM: $parameter"
        # it's an option if it's start with a dash
        if [[ "$parameter" =~ ^-.* ]]; then
            #echo "OPTION"
            ls_options="$ls_options $parameter"
        else  # it's a path: call ls on it
            #echo "FILEPATH"
            # get escaped version of given filename
            filepath=$(print -r -- "${(q)parameter}")
            #echo "filepath: $filepath"
            ls_filepaths="$ls_filepaths $filepath"
        fi
    done
    # remove options surrounding spaces
    ls_options=$(echo "$ls_options" | tr -d "[:space:]")
    isnotfirst=  # set to true after the first iteration
    # call verbosels_onefile for each filepath
    for filepath in ${(z)ls_filepaths}
    do
        # print space only between ls calls
        if [ "$isnotfirst" ]; then
            echo ""  # line jump
        else
            isnotfirst=1
        fi
        #echo "CMD: |verbosels_onefile $filepath $ls_options|"
        verbosels_onefile $filepath $ls_options
    done
}

# Perform an ls call on only one directory/file, that must be in first parameter.
# The other parameters remain untouched.
# The ls call take into account any aliases on ls.
# This function is called by the higher level verbosels function.
function verbosels_onefile() {
    if [ "$1" ]; then
        1="$1"
    else
        1="."
    fi
    if [ -d "$1" ]; then
        # contains files (hidden included)
        if [ -n "$(command ls -A "$1")" ]; then
            if [ -n "$(command ls "$1")" ]; then
                ls "$@"
            else
                # the directory is not empty, and contains only hidden files:
                # print message only if the ls command returns nothing
                # NOTE: run the ls command twice. Could be costly.
                if [ -n "$(ls "$@")" ]; then
                    ls "$@"
                else
                    echo "$1 contains only hidden files" 1>&2
                fi
            fi
        else
            echo "$1 is empty" 1>&2
        fi
    elif [ -e "$1" ]; then
        ls "$@"
    else
        echo "$1 doesn't exists" 1>&2
    fi
}

Remarks:

seems over-complicated
non-perfect handling of some ls options, notably -l in case of only-dotfiles directory (print total 0)
if a directory contains only dot files, the ls command is runned twice. Could be costly if the directory contains a lot of dot files.

The following is not valid, because ls formatting (colors, columns,…) are not kept:

ls_result=$(ls "$@")
if [ "$ls_result" ]; then
    echo "$ls_result"
else
    echo "$1 contains only hidden files" 1>&2
fi

I'm using zsh, because it provides some easier treatment. A solution involving only generalist bash could be better because of the portability.
I'm looking for any readability/efficiency improvement, eventually for modules/programs that already do the job.


texts:
THIS IS JUST FOR LEARNING PURPOSES. I WON'T BE USING THIS TO HACK ANYONE

Here is a small algorithm I made to crack a passwork. This is just the background of a more complex code I'm going to make.

To be honest, this code is TERRIBLY written, so I need help on making it more efficient and flexible. It is limited to 5-characters password and not easy to expand.

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

std::string checkCharacters = {
    '%',
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    '1','2','3','4','5','6','7','8','9','0'
};

std::string search(std::string password) {
    for (int a = 0; a < checkCharacters.size(); a++)
        for (int b = 0; b < checkCharacters.size(); b++)
            for (int c = 0; c < checkCharacters.size(); c++)
                for (int d = 0; d < checkCharacters.size(); d++)
                    for (int e = 0; e < checkCharacters.size(); e++)
                    {
                        std::string checkString = "";
                        checkString += checkCharacters[a];
                        checkString += checkCharacters[b];
                        checkString += checkCharacters[c];
                        checkString += checkCharacters[d];
                        checkString += checkCharacters[e];

                        checkString.erase(std::remove(checkString.begin(), checkString.end(), '%'), checkString.end());

                        if (checkString == password)
                            return checkString;
                    }

    return "TARGET_PASSWORD_NOT_FOUND";
}

int main() {
    while (1) {
        std::string password;
        std::cout << "Enter password : ";
        std::cin >> password;
        std::cout << "Your password is : " << password << std::endl;
        std::string attempt = search(password);
        std::cout << attempt << std::endl << std::endl;
    }
}


texts:
I was hoping if anyone could tell me if I'm doing this correctly, I know there are other questions like this but everyone codes different and I just feel that I'm not doing this right. I'm trying to make a modular OOP site so all the files will be called through the one index file which will then route the user to the correct page. All the code below works correctly (I have tested it) but I was curious about a few things.

Is this the correct way of using OOP and classes (mainly the DB
connection)?
Why (if it is correct) when I use Netbeans PHP that it doesn't pick
up the functions? See images below.

db.php (DB connection file)

$host = "localhost";
$username = "root";
$password = "";
$database = "als";

$errors = new errors();

try {
    $db = new PDO("mysql:host=$host;dbname=$database", $username, $password);
} catch(PDOException $ex) {
    trigger_error($ex->getMessage());
    $errors->addLog($ex->getPrevious(), true);
    exit;
}

User.php (class)

class user {
    private $db = null;

    public function __construct() {
        global $db;
        $this->db = $db;
    }

    public function deleteUser($ID) {
        if(isset($ID) && !empty($ID) && is_int($ID) == TRUE) {
            $deleteUser = $this->db->prepare("DELETE FROM `users` WHERE userid=?");
            $deleteUser->bindParam(1, $ID, PDO::PARAM_INT);
            $deleteUser->execute();
        } else {
            return FALSE;
        }
    }
}

index.php (main file)

include 'config/autoloader.php';
include 'config/db.php';

$user = new user();

$user->deleteUser(1);


texts: Building a summary string from a flags enum

texts:
I'm trying to replicate the attributes text that appears in File Explorer, for files and directories.

I can't just use the enum names, as the summary text uses a single character for each set flag, and that character isn't always the first character of the enum member. I'm also not using the reserved FileAttribute.Device attribute. So, I'm using a string.join operation to concatenate the flag characters.

    public string AttributeSummary
    {
        get
        {
            FileAttributes fatt = (FileAttributes)_attribs;

            return string.Join(string.Empty,
                (fatt.HasFlag(FileAttributes.ReadOnly) ?          "R" : string.Empty),
                (fatt.HasFlag(FileAttributes.Hidden) ?            "H" : string.Empty),
                (fatt.HasFlag(FileAttributes.System) ?            "S" : string.Empty),
                (fatt.HasFlag(FileAttributes.Directory) ?         "D" : string.Empty),
                (fatt.HasFlag(FileAttributes.Archive) ?           "A" : string.Empty),
                (fatt.HasFlag(FileAttributes.Normal) ?            "N" : string.Empty),
                (fatt.HasFlag(FileAttributes.Temporary) ?         "T" : string.Empty),
                (fatt.HasFlag(FileAttributes.SparseFile) ?        "P" : string.Empty),
                (fatt.HasFlag(FileAttributes.ReparsePoint) ?      "L" : string.Empty),
                (fatt.HasFlag(FileAttributes.Compressed) ?        "C" : string.Empty),
                (fatt.HasFlag(FileAttributes.Offline) ?           "O" : string.Empty),
                (fatt.HasFlag(FileAttributes.NotContentIndexed) ? "I" : string.Empty),
                (fatt.HasFlag(FileAttributes.Encrypted) ?         "E" : string.Empty),
                (fatt.HasFlag(FileAttributes.IntegrityStream) ?   "V" : string.Empty),
                (fatt.HasFlag(FileAttributes.NoScrubData) ?       "X" : string.Empty));
        }
    }

Am I going about this in the most efficient way?


texts: This function for populating the attributes of a class, using a DB model and REST API

texts:
Recently, I've been trying to transform my code to be more OO and adhere to SOLID principles. I also have been trying to get into the habit of making my code more testable and have been trying to implement a TDD mindset. Here is a snippet of my code from my class ChargebackReport:

/**
 * Populates the properties of this class (ChargebackReport) using CamsModel
 * which is a database model responsible for executing queries and returning
 * the required information. GeoIPUtils is a class used to populate the
 * loginIpInformation attribute by making a GET request to an API.
 */
public function generateReport() {
    $this->transactions = $this->camsModel->getLastIntTransactionsByUser($this->userId, 20);
    $this->loginHistory = $this->camsModel->getLastIntLoginsByUser($this->userId, 100000);
    $this->chargebacks = $this->camsModel->getChargebacksByUser($this->userId);
    $this->chargebackTotal = $this->camsModel->getChargebackValueByUser($this->userId);

    $geoUtils = new GeoIPUtils();
    $loginIps = $this->camsModel->getLoginIpsFromLoginHistory($this->loginHistory);
    $this->loginIpInformation = $geoUtils->getIPAddressInfo($loginIps);

    $resultsToMap = [
        "userId" => $this->camsModel->getIDUrl($this->userId),
        "user"   => $this->camsModel->getUserById($this->userId),
        "cc"     => $this->camsModel->getCCInfoByUser($this->userId, $this->chargebacks)
    ];

    foreach($resultsToMap as $result) { $this->mapResultsToProperties($result); }
}

The responsibility of this function is to populate the various properties of this class. Some properties can be directly populated from the query. Other queries return arrays of information, which needs to be parsed through and assigned via the mapResultsToProperties() method, which maps variable keys to their respective property within the class.

Now, it's apparent that this function has a lot of stuff going on, but its overall goal is to just populate the fields in the class using the CamsModel and another class called GeoIPUtils which returns information on a given IP. The function is not responsible for querying and making GET request to an API, so I delegated those responsibilities to other classes.

Am I applying the SOLID principles properly in this example?

And for my second question, how would I go about making this class unit testable? The function as is doesn't return anything, nor are any exceptions thrown which could potentially halt the execution of it. It seems like it wouldn't be beneficial to have the function return true and just making an assert akin to the following:

$this->assertTrue($chargebackReport->generateReport());

I don't know how beneficial it would be to mock every single method in the CamsModel class (I call 8 different functions from CamsModel), have it return random input, and just checking if it assigned properly.


texts:
This function started very clean but I had to add requirements:

Added a Stopwatch to only update the caller periodically. I guess that responsibility could be handled elsewhere but I'm undecided about whether or not it should be.
Added a Stopwatch to only check a computationally expensive operation periodically.
Give the user the option to cancel the whole thing.

Additionally, I'd like for the enclosing class to be static so that calls to it look like this:

var encoded = Codec.Encode(myImage, myMessage, myCheckCancelMethod);
var decoded = Codec.Decode(myImage, myCheckCancelMethod);

There is a corresponding Encode method here that should match as closely as possible. The code works (UWP and Android so far, you have to use a .png right now).

What I see as being the problem is this function is supposed to just call out to other functions but there is so much coordination going on that the coordination function has gotten complicated and you can't really take anything out.

public static async Task<byte[]> Decode(Bitmap carrierImage, byte[] eofMarker, Func<double, bool> checkCancel)
{
    var shuffleSeed = FisherYates.GetSeed(eofMarker);

    bool foundEof = false;
    bool userCancelled = false;

    List<bool> messageBuilder = new List<bool>();
    byte[] decodedMessage = null;

    var userUpdateStopwatch = new Stopwatch();
    var eofStopwatch = new Stopwatch();
    userUpdateStopwatch.Start();
    eofStopwatch.Start();

    await Task.Run(() => // move away from the calling thread while working
    {
        IterateBitmap(carrierImage, shuffleSeed, (x, y) => {
            var pixelBitsAsBools = DecodePixel(carrierImage, x, y);
            messageBuilder.AddRange(pixelBitsAsBools);

            if(eofStopwatch.ElapsedTicks > EOF_CHECK_RATE)
            {
                eofStopwatch.Reset();
                foundEof = MessageBuilderHasEof(messageBuilder, eofMarker);
            }

            var percentComplete = (double)messageBuilder.Count / carrierImage.BitCapacity;
            userCancelled = CheckCancelAndUpdate(userUpdateStopwatch, percentComplete, checkCancel);

            return userCancelled || foundEof;
        });

        foundEof = MessageBuilderHasEof(messageBuilder, eofMarker); // check for eof again in case the IterateBitmap loop completed since the last time we checked.
        if (foundEof)
        {
            decodedMessage = GetMessageWithoutEof(messageBuilder, eofMarker);
        }
    });

    return userCancelled || !foundEof ? null : decodedMessage;
}


texts:
Yesterday, I introduced a bug into our codebase by calling #titleize on a string that could possibly come in as nil:

def route
  medication.route_name.titleize
end

This threw an error on production and a coworker fixed this by adding try:

def route
  medication.route_name.try(:titleize)
end

I'm not totally happy with this solution, after being really influenced by Avdi's article on #try, and I've been trying to come up with something I like better. Here are two possibilities.

Firstly, in Avdi's talk "Confident Code", he talks about asking for the data type you need: if you need a string, ask for a string. So I thought about this:

def route
  medication.route_name.to_s.titleize
end

This way, nil will be converted to empty string, and #titleize will be called, which will not error. The obvious issue with this is that you're calling #to_s on something which is only ever an instance of String or NilClass.

The only other approach I could think of was this:

def route
  medication.route_name.present? medication.route_name.titleize : ''
end

The issue here is the if/else parading around as prettier code through the use of a ternary operator, and the repetition of medication.route_name. This could be minified by delegating route_name to medication, or some other work around. But there's still the if/else conditional. And that's more code.

The bigger question here is how to handle nil values. This method is a pretty typical example of how this comes up. How would you handle it?


texts:
class ChristmasTree
{
    private static void byHand()
    {
        System.out.println( "Chritsmas tree, yey." );
        System.out.println( "     *" );
        System.out.println( "    ***" );
        System.out.println( "   *****" );
        System.out.println( "  *******" );
        System.out.println( " ********" );
        System.out.println( "**********" );
        System.out.println( "    |" );
        System.out.println( "    _" );
    }

    private static void withLoops()
    {
        int rows = 6;
        StringBuilder sb = new StringBuilder();
        for( int row = 0; row < rows; ++row )
        {
            for( int spaces = rows - row; spaces > 0; --spaces )
            {
                sb.append( " " );
            }

            for( int stars = 0; stars < 2 * row + 1; ++stars )
            {
                sb.append( "*" );
            }
            sb.append( "\n" );

        }

        for( int spaces = 0; spaces < rows; ++spaces )
        {
            sb.append( " " );
        }
        sb.append( "|" );
        sb.append( "\n" );
        for( int spaces = 0; spaces < rows; ++spaces )
        {
            sb.append( " " );
        }
        sb.append( "_" );
        System.out.println( sb.toString() );
    }

    private static String spaces( int num )
    {
        StringBuilder sb = new StringBuilder();
        for( int spaces = 0; spaces < num; ++spaces )
        {
            sb.append( " " );
        }
        return sb.toString();
    }

    private static String properly( int rows )
    {
        StringBuilder sb = new StringBuilder();
        for( int row = 0; row < rows; ++row )
        {
            for( int spaces = rows - row; spaces > 0; --spaces )
            {
                sb.append( " " );
            }

            for( int stars = 0; stars < 2 * row + 1; ++stars )
            {
                sb.append( "*" );
            }
            sb.append( "\n" );

        }
        sb.append( spaces( rows ) );
        sb.append( "|" );
        sb.append( "\n" );
        sb.append( spaces( rows ) );
        sb.append( "_" );

        return sb.toString();
    }

    public static void main(String[] args)
    {
        byHand();

        withLoops();

        // What if the tree needs to be 100 lines high?
        // We arrive at the concept of `scalability`.
         System.out.println( properly( 16 ) );
    }
}

Topics I have considered but decided against:

pass the tree height on the command line via java.util.Scanner;
make a copy of spaces() called stars()
explain the purpose of the class at the very beginning a la python docstring
split the methods so the don't exceed 20 LOC

Also there's this.


texts: InputStream Wrapper that closes the stream once reading is done

texts:
I faced some issues in a project with spring and hibernate where the stream given to Blob is not closed.

Blob blob = Hibernate.getLobCreator(currentSession).createBlob(inputStream, size);

I can't use things like try with resources since the stream is only read after the transaction commits. One of my friends suggested a hacky way to do this. Basically, his idea was to close the stream once the reading is complete.

import java.io.IOException;
import java.io.InputStream;

public class InputStreamWrapper extends InputStream {

    private InputStream inputStream;

    public InputStreamWrapper(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public int read() throws IOException {
        int val = this.inputStream.read();
        if (val != -1) {
            return val;
        } else {
            this.inputStream.close();
            return -1;
        }
    }
}

I've done a simple test and it works. I understand that there can be a performance issue with the if check. However, I think there are other caveats in this as well. Can someone shed some light on those?

Blob blob = Hibernate.getLobCreator(currentSession).createBlob(new InputStreamWrapper(inputStream), size);


texts: HackerRank Sherlock and Squares: count perfect squares in an interval

texts:
I've exceeded the time limit on Sherlock and Squares on hackerrank.com.
Problem
Given the number of test cases and a range (inclusive), find the number of numbers within that range that are perfect squares.
Sample Input

2   (number of test cases)
3 9 (first test case)
17 24 (second test case)

Sample Output

2 (in range [3,9], there are two perfect square numbers)
0 (in range [17, 24], there are no perfect square numbers)

My code in C++
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

int main()
{
  unsigned test_cases, low_range, high_range, count = 0;
  vector<unsigned> sherlock_squares;
  cin >> test_cases;
  while(test_cases != 0)
  {
    cin >> low_range >> high_range;
    for(unsigned i = low_range; i <= high_range; ++i)
    {
      if(sqrt(i) == floor(sqrt(i)))
        count += 1;
    }
    sherlock_squares.push_back(count);
    count = 0;
    --test_cases;
  }
  for(unsigned i = 0; i < sherlock_squares.size() - 1; ++i)
    cout << sherlock_squares.at(i) << endl;
  cout << sherlock_squares.at(sherlock_squares.size() - 1);
  return 0;
}

I'd appreciate it if an explanation is provided in your response, since I'm new to programming and Stack Exchange.


texts:
I need to run several identical threads. All threads must wait to do their job, until all threads are running (alive).
I use wait/notify to synchronize: when a thread is created it waits until it gets a notify to continue.

It works, but not sure it's the best way. Is it efficient?
I read from Java 5, is it better to use concurrency package. Is it true?

public class MainTest {

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

        TestTH[] ths = new TestTH[5];

        System.out.println("== Start == ");

        for (int i = 0; i < ths.length; i++) {
            ths[i] = new TestTH("Name_" + i, new Object()); //<- Creates runnable class and lock object that will be used to synchronize
            ths[i].start(); //<- Creates and starts thread
        }

        Thread.sleep(100L); // <- All threads are running

        for (int i = ths.length -1 ; i >= 0; i--) {
            Object lock  = ths[i].getLock();
            synchronized (lock) {
                lock.notify();  //<- Thread i, can continue;
            }
            ths[i].getThread().join(); // Wait until thread i, finishes
        }

        System.out.println("== End == ");
    }

}

class TestTH implements Runnable {
    private String name;
    private Object lock;
    private Thread t;

    public TestTH(String name_, Object lock_) {
        this.name = name_;
        this.lock = lock_;
        System.out.println("Create thread " + this.name);
    }

    public Object getLock() {
        return this.lock;
    }

    public Thread getThread () {
        return t;
    }

    public void start() {
        if (t == null) {
            t = new Thread(this, name);
            t.start();
        }
    }

    @Override
    public void run() {
        System.out.println("Init thread  " + this.name);

        synchronized (lock) {
            try {
                lock.wait(); // <- Once started, it waits current until notify.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // doStuff(); // <- do stuff when lock is released

        System.out.println("End thread " + this.name);
    }

}

Any advice, will be very welcome.


texts: Speed up lights-out variant solver in pure Python

texts:
I'm doing some challenges to learn new and interesting concepts, this one is about a Lights out variant, instead of toggling only the adjacent tiles, it toggles the whole row and col.

It must be solved in pure python, so no numpy or other libraries that might help are allowed here.

I adapted the algorithm of this excellent ressource. Using a n2*n2 toggle matrix and a flattened puzzle P we can use a linear algebra to calculate T*x = P mod 2, where x is the matrix of buttons we need to push to solve the puzzle.

Since 1 < n < 16, this algorithm may need to solve matrices up to 225x225, which takes ~420ms on my machine. The exact time constraints aren't given, but I get a timeout error after submitting.

I pasted a running example here, this generates a random 15x15 puzzle and prints out a few timings and the solution to that particular puzzle.

The method performGaussianElimination(toggle, puzzle) takes by far the longest and seems to be the only bottleneck, but I don't see a place where I could use memoization or other shortcuts to save time. I've looked for other pure python linear algebra solvers, but there are only a few (numpy is so much easier) and don't seem to be a lot different.

def performGaussianElimination(toggle, puzzle):
    nextFreeRow = 0
    n = len(puzzle)
    for col in xrange(n):
        pivotRow = findPivot(toggle, nextFreeRow, col)
        if pivotRow is None:
            continue

        swap(toggle, nextFreeRow, pivotRow)
        swap(puzzle, nextFreeRow, pivotRow)

        for row in xrange(pivotRow + 1, n):
            if toggle[row][col]:
                for i in xrange(len(toggle[row])):
                    toggle[row][i] ^= toggle[nextFreeRow][i]
                puzzle[row] ^= puzzle[nextFreeRow]

        nextFreeRow += 1

    return toggle, puzzle

Can I speed this up? Might this traditionally fast algorithm not be the fastest for this variant?


texts: Implementation of an Stack without Linked Lists in C

texts:
I'm a beginning C programmer. As an exercise, I have attempted to implement a stack of strings in C. This is my first real exercise working with pointers. I looked at some other similar posts on here, and read through the comments. It seems that most individuals have chosen to do this by using linked lists, whereas I've just created an ArrayStack.

Maybe it would have been better to go the linked list route. Nonetheless, this is how I did it. I'm hoping there's not any glaring errors, but I'm sure there will be.

Also, question: I have a variable for the number of slots available in the array, which is used to determine when more memory needs to be allocated. But it would seem to me that I can use sizeof on the array, and sizeof on a single pointer in the array, and use division to get the number of slots, thus eliminating a variable. Would this be a better approach?

stack.h

#include <stdlib.h>

typedef struct stringstack {
    int count;
    int slots;
    char** stack;
} stringstack;

void * makestack(void);
void push(struct stringstack* ptr, char stringtext[]);
char * pop(struct stringstack* ptr);
char * peek(struct stringstack* ptr);
int isempty(struct stringstack* ptr);
void destroy(struct stringstack* ptr);

stack.c

#include "stack.h"

/* Function creates a new stringstack object and returns a pointer to it */
void * makestack(void) {
    stringstack *ptr = (stringstack *) malloc(sizeof(stringstack));
    ptr->count = 0;
    ptr->slots = 1;
    ptr->stack = (char **) malloc(sizeof(char*));
    return ptr;
}

/* Pushes a string onto the top of a stack */
void push(struct stringstack* ptr, char stringtext[]) {
    ptr->count++;
    if (ptr->count == ptr->slots) /* Allocate more space if necessary */
        ptr->stack = (char **) realloc(ptr->stack, sizeof(char *)*((ptr->slots*=2)+1));
    char *stringptr = (char *) malloc(sizeof(stringtext));
    stringptr = stringtext;
    *(ptr->stack + ptr->count) = stringptr;
}

/* Removes the top item from the stack, returning a pointer to it */
char * pop(struct stringstack* ptr) {
    if (ptr->count>0)
        return *(ptr->stack + ptr->count--);
    return NULL;
}

/* Returns a pointer to top item from stack but does not pop it */
char * peek(struct stringstack* ptr) {
    if (ptr->count>0)
        return *(ptr->stack + ptr->count);
    return NULL;
}

/* Returns whether a stringstack contains at least one string */
int isempty(struct stringstack* ptr) {
    return (ptr->count == 0);
}

/* Frees a stringtack from memory */
void destroy(struct stringstack* ptr) {
    size_t n;
    for (n = 0; n <= ptr->count; n++ )
        free(ptr->stack+n);
    free(ptr->stack);
    free(ptr);
}


texts: Subtract multiple columns in PANDAS DataFrame by a series (single column)

texts:
Background

I have tons of very large pandas DataFrames that need to be normalized with the following operation; log2(data) - mean(log2(data))

Example Data

The example DataFrame my_df looks like this;

     iovrrx    nfinsu    mvdfjc    idjges    fubmrg    lvuhfv
0  0.987654  0.206104  0.802920  0.011157  0.860618  0.575871
1  0.706397  0.860083  0.939230  0.436194  0.557081  0.706964
2  0.043139  0.729435  0.597488  0.700998  0.974193  0.917758
3  0.316080  0.461547  0.844540  0.510143  0.908475  0.877330
4  0.828839  0.177670  0.610833  0.328238  0.327697  0.689756

Question

I have tried to perform the normalization operation noted above many different ways however the following code snippet is the only one that I have gotten to work;

log_div_ave = my_df.apply(np.log2).values.T - my_df.apply(np.log2).mean(axis=1).values

log_div_ave = pd.DataFrame(log_div_ave.T,columns=my_df.columns)

print(log_div_ave)

   iovrrx    nfinsu    mvdfjc    idjges    fubmrg    lvuhfv
0  1.667378 -0.593258  1.368628 -4.800610  1.468744  0.889117
1  0.056992  0.340988  0.467991 -0.638518 -0.285601  0.058149
2 -3.467018  0.612699  0.324830  0.555330  1.030127  0.944032
3 -0.941776 -0.395590  0.476099 -0.251165  0.581380  0.531053
4  0.933714 -1.288174  0.493400 -0.402633 -0.405015  0.668708

As you can see I'm converting the DataFrame to a numpy array and transposing it just so I can subtract by the mean of the data. I then have to transpose the resulting array then reconstitute it as a DataFrame. Is there a simpler way to do all of this?


texts: Longest Palindrome Substring: Where is the dynamic programming?

texts:
In this LeetCode problem, Longest Palindromic Substring, it is listed under Dynamic Programming for Google interview preparation. My understanding of dynamic programming is roughly "recursion + memoization + guessing." In the Python solution to this answer below it is not clear to me where the dynamic programming is if it exists at all. This is Approach 4 under solutions (translated from Java to Python). Approach 3 references dynamic programming but no solution is given.

Is there any dynamic programming going on here? Or is this just a solution to solve the problem in O(1) space, where the dynamic programming solution requires O(n^2) space?

This algorithm technically has a time complexity of O(n^2) right? Is this the best we could reasonably be expected to do in an interview?

class Solution:
    def longestPalindrome(self, s):
        res = ""
        for i in range(len(s)):
            # odd case, like "aba"
            tmp = self.helper(s, i, i)
            if len(tmp) > len(res):
                res = tmp
            # even case, like "abba"
            tmp = self.helper(s, i, i+1)
            if len(tmp) > len(res):
                res = tmp
        return res

    # get the longest palindrome, l, r are the middle indexes
    # from inner to outer
    def helper(self, s, l, r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1; r += 1
        return s[l+1:r]


texts: Fast implementation to output nested dict to JSON

texts:
Each line of the JSON has a structure looks as the following

|- Sentence
|   |-- WordPosition:
|   |--   |-- Candidate
|   |--   |--   |-- index:
|   |--   |--   |-- retrievals

Example of a line in JSON output (parameter num_retrieval=2)

Current implementation

def output_conll_retrievals_to_json(output_file, conll_mcs,conll_sentences, num_retrieval):

    num_sentence = len(conll_sentences)

    with open(output_file, 'w') as f:
        for i in range(num_sentence):
            num_position = len(conll_sentences[i])
            level2 = dict()
            level1 = dict()
            for j in range(num_position):
                level0 = dict()
                for mc in conll_mcs[i][j]:
                    mc_str = ' '.join(mc.mention_string)
                    level0[mc_str] = dict()
                    level0[mc_str]['index'] = mc.mention
                    level0[mc_str]['retrievals'] = self.get_one_mc_retrievals(mc, num_retrieval)
                level1[conll_sentences[i][j]] = level0
            level2[' '.join(conll_sentences[i])] = level1
            json.dump(level2, f)
            f.write('\n')

Note that self.get_one_mc_retrievals is implemented in parallel, accessing a memory map and performs a hierarchical search. Executing the snippet of code, status showing that CPUs are under-used (like 10-20% for each core as writing is serial programming) and the whole JSON output takes 8 days (approximately 3000 sentences with num_retrievals of 100) to generate. Would it be possible to boost the speed (i.e., Cython, parallel or something else)?

** Edited **

This just comes off my head, would it be possible to utilize multiprocessing to speed up JSON writing? Right now, my code is kind of serially doing a process that retrieves a dict from reading conll_mcs[i] and writes a line to the JSON file. If I could simultaneously perform many of such a process, speed will very likely improve, however I am still trying to find how to put such an idea into practice. Any help would be greatly appreciated.


texts: Neatly printing integers interspersed with spaces

texts:
The next iteration is here.

I have this small method for printing long integers neatly. For example:

neatify(123L)    = "123"
neatify(1234L)   = "1 234"
neatify(12345L)  = "12 345"
.
.
.

The code:

import java.util.Scanner;

public class Main {

    public static String neatify(final long number,
                                 final int groupLength) {
        final String str = Long.toString(number);

        if (groupLength < 1) {
            return str;
        }

        final char[] charArray = str.toCharArray();
        final StringBuilder sb = new StringBuilder();

        for (int i = 0; i < charArray.length; ++i) {
            if (i != 0 && (charArray.length - i) % groupLength == 0) {
                sb.append(' ');
            }

            sb.append(charArray[i]);
        }

        return sb.toString();
    }

    public static String neatify(final long number) {
        return neatify(number, 3);
    }

    public static void main(final String... args) {
        final Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLong()) {
            System.out.println(neatify(scanner.nextLong()));
        }
    }
}


texts: Performance testing functions for wrapping an index

texts:
After asking this question, I decided to write a test and determine the fastest way to wrap an index (where my maxSize is always a power of 2).

There are 3 functions that I'm comparing:

// plain wrap
public static int WrapIndex(int index, int endIndex, int maxSize)
{
    return (endIndex + index) > maxSize ? (endIndex + index) - maxSize : endIndex + index;
}

// wrap using mod
public static int WrapIndexMod(int index, int endIndex, int maxSize)
{
    return (endIndex + index) % maxSize;
}

// wrap my masking out the top bits
public static int WrapIndexMask(int index, int endIndex, int maxSize)
{
    return (endIndex + index) & (maxSize - 1);
}

Here is my test:

public static void WrapTest(int numRuns = 10000)
{
    int index = 256;
    int endIndex = 0;
    int maxSize = 4096;

    long wrapPlain = 0;
    long wrapMod = 0;
    long wrapMask = 0;

    Stopwatch sw = new Stopwatch();

    for (int i = 0; i < numRuns; i++)
    {

        // plain
        sw.Start();
        for (int j = 0; j < numRuns; j++)
        {
            WrapIndex(index, endIndex, maxSize);
        }
        sw.Stop();
        wrapPlain += sw.ElapsedTicks;
        sw.Reset();

        // mod
        sw.Start();
        for (int j = 0; j < numRuns; j++)
        {
            WrapIndexMod(index, endIndex, maxSize);
        }
        sw.Stop();
        wrapMod += sw.ElapsedTicks;
        sw.Reset();

        // mask
        sw.Start();
        for (int j = 0; j < numRuns; j++)
        {
            WrapIndexMask(index, endIndex, maxSize);
        }
        sw.Stop();
        wrapMask += sw.ElapsedTicks;
        sw.Reset();

        // change indexes
        endIndex++;
        endIndex = endIndex % maxSize;

        index++;
        index = index % maxSize;
    }
    Console.WriteLine(String.Format("Plain: {0} Mod: {1} Mask: {2}", wrapPlain / numRuns, wrapMod / numRuns, wrapMask / numRuns));
}

I ran the test and I'm consistently getting the following results (in ticks):

Plain: 25 Mod: 16 Mask: 16 (maxSize = 512)
Plain: 25 Mod: 17 Mask: 17 (maxSize = 1024)
Plain: 25 Mod: 17 Mask: 17 (maxSize = 4096)

I was expecting that the mask will be faster than all of them, but it seems to be as fast as using the modulo operator. I've also tried increasing the numRuns, but the results are consistent.

Is my test valid? Is there a better way to test the performance?


texts: Enter year, date, and month in any order, I'll organize it

texts:
I would like some advice on how I could make it less repetitive and use more functions and classes.

#include <iostream>
#include <string>

using namespace std;

class date
{
public:
    date() = default;
    date(istream &is) { is >> year >> month >> day; }

    bool organizeInfo();
    bool organize();
    ostream &outputInfo(std::ostream &os) { os << year << " " << month << " " << day; return os; }

private:

    bool checkValid();
    bool checkSwitch(unsigned &item1, unsigned &item2, unsigned &item3);
    void switchItems(unsigned &item1, unsigned &item2) { unsigned tempItem1 = item1; item1 = item2; item2 = tempItem1; }

    unsigned year = 0;
    unsigned month = 0;
    unsigned day = 0;
};

inline bool date::checkValid()
{
    if (month <= 12 && day <= 31)
        return 1;
    return 0;
}

inline bool date::checkSwitch(unsigned &item1, unsigned &item2, unsigned &item3)
{
    switchItems(item1, item2);
    if (checkValid())
        return 1;
    else
    {
        switchItems(item1, item2);
        switchItems(item2, item3);
        if (checkValid())
            return 1;
        else
        {
            switchItems(item2, item3);
            switchItems(item1, item3);
            if (checkValid())
                return 1;
            else
            {
                return 0;
            }
        }
    }
}

inline bool date::organize()
{
    if (checkValid())
        return 1;
    else
    {
        if (checkSwitch(day, month, year))
            return 1;
        else if (checkSwitch(year, month, day))
            return 1;
        else if (checkSwitch(day, year, month))
            return 1;
        return 0;
    }
}

bool date::organizeInfo()
{
    if (checkValid())
        return 1;
    else
    {
        if (organize())
            return 1;
        else
            return 0;
    }
    return 0;
}

int main()
{
    cout << "Enter year, month, date and ill try and organize it" << endl;
    date dawg(cin);
    if(dawg.organizeInfo())
        dawg.outputInfo(cout) << endl;
    return 0;
}


texts: Ruby - Summing groups of odd and even integers in an array until no groups remain

texts:
The problem my code solves is listed below. I know my code can be improved, it takes a while to run when bigger arrays are entered as input.

"Problem - Given an array of integers, sum consecutive even numbers and consecutive odd numbers. Repeat the process while it can be done and return the length of the final array."

def sum_groups(arr)

  z = arr.size
  x = []
  i = 0

  until i == z
    arr = arr.chunk{|x| x.even?}.map{|x, y| y}.map{|x| x.inject(&:+)}
    x << arr
    i += 1
  end

  x[-1].size

end

An example input -

For arr = [2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9]

The result should be 6.

[2, 1, 10, 5, 30, 15] - Value of numbers in final array.

The length of final array is 6

Any review and help would be appreciated to make this code more efficient.


texts:
Here is AlarmService for setting up notifications on my phone. Currently, the code works and is functional. However, I noticed my code looks different than a few examples I found online. Should I be using Notification Compact builder instead?

Also, any advice on how to make it better/cleaner would be great.

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class AlarmService extends Service
{

    private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent arg0)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate()
    {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @SuppressWarnings("static-access")
    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);

        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(),ScoreCollectionPager.class);

        Notification notification = new Notification(R.drawable.clock,"Score Collection!", System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(this.getApplicationContext(), "Score Collection!", "Please enter scores at this time!", pendingNotificationIntent);

        //Default notification alerts to vibrate and make a notification sound
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;

        mManager.notify(0, notification);
    }

    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}


texts:
I am calling a C library via P/Invoke. That library needs to be called in sucession with an increasing unsigned int, and returns a pointer. That pointer is then mapped to a managed type, until it returns a NULL pointer.

In C, the idiomatic way to write it, is probably for(i=0;;i++), but what is the most idiomatic way to write it in C#?

Currently it is using a do {} while loop, as in my opinion, this is the clearest way to show that this loop will repeat until newPort is null.

static IEnumerable<Port> GetPorts ()
{
    List<Port> ports = new List<Port>();
    uint i = 0;
    Port newPort;
    do {
        // This calls an C library, and maps the returned pointer
        // to the Port class
        newPort = GetPortData (i);
        if (newPort != null){
            ports.Add (newPort);
        }
        i++;
    } while(newPort != null);
    return ports;
}

On the other hand, the variables i and newPort are only used inside the loop, so using for would be another solution, but it does not clearly show the breaking condition.

    for (uint i = 0; ; i++) {
        Port newPort = GetPortData (i);
        if (newPort == null) {
            break;
        }
        ports.Add (newPort);
    }

Which version should I use?


texts:
I am trying to create an invert index structure in C++. An invert index, in this case, refers to image retrieval system, where each invert index refers to a numbers of "Patch ID". (simply called "ID" in the code) These IDs are basically for describing many kind of pixel gradient patches from all images in the database.

The invert index is a map container and will be very sparse and each index of the invert index will contain a sub-map. A sub-map will have an "Image ID" and frequency counting integer. For example, if we have 2 images with "Image ID" 10 and 20, and both of these images have "Patch ID" 999, appear once in "Image ID" 10 and appear twice in "Image ID" 20, we will have the following:

  invertID[999] == sub-map with <10,1> and <20,2>

I've written the code below for this, but somehow I am not quite satisfied.

One instance, I have to put back the sub-map into the invert ID's index as you can see below.

Another thing is I am not quite sure whether I am using the correct type of container for the correct job or not. I have about 5000 images (so that's 5000 "Image ID") and I see that "Patch ID" could vary from 1 to numbers as high as 40 billion.

In this case, performance-wise and design-wise, should I be using map or should I go for some other container? Suggestions are welcome.

Note: this will be run in a server that doesn't have a C++11 compiler.

unsigned long long int ID, index = 0;
map<unsigned long long int, map<int, int>> invertID;

...
...

//for the sake of convenient, two for loops below are shown as pseudocode.
for each image{ //loop with imageID, incrementing variable imageID in each iteration

//for each gradient patches in the image
for each gradient patch of this image{ //loop with index, incrementing variable index in each iteration.

    //processID encapsulates the procedure to generate an ID for each interesting point in the image. We basically read values in the respective file and do some calculation.
    ID = processID(index);

    //if this ID exists in InvertID,
    map<unsigned long long int, map<int,int>>::iterator mainMapIt = invertID.find(ID);
    if (mainMapIt != invertID.end()){

        //if this ImageID key exists in InvertID sub-map,
        map<int,int> M = mainMapIt->second;
        map<int,int>::iterator subMapIt = M.find(imageID);
        if (subMapIt != M.end()){
            //the index already exists, so increment the number (frequency) of this ImageID key
            ++M[imageID];
        }
        else{
            //the index does not exist, so add ImageID key with value 1 into the InvertID
            M[imageID] = 1;
        }

        //get this sub-Map back to the invert ID's index.
        invertID[ID] = M;
    }
    else{
        //the ID does not exist in the InvertId, yet, so
        //create the first empty map with the key as image ID with value 1 and put it into the invertID.
        map<int,int> M;
        M[imageID] = 1;
        invertID[ID] = M;
    }
}
}


texts:
This is my homework.  Kindly help me check it?
The instructions are:

Implement an infix expression to postfix expression converter. You are to implement the infix to postfix algorithm presented in the lecture. You are to use only the stack that was provided in the lab lecture. The use of the stack of JDK or any other stack is not allowed. The supported operators are +, -, *, / and ^. Grouping operator are ( and ).
Input: Infix expresseion where each token (operand and operator) are space-separated (console-based). Explore the StringTokenizer class for tokenizing (separating the infix expression into tokesn) the input. The book of Deitel and Deitel has examples on how to use StringTokenizer.
Output: Postfix expression (console-based). The tokens (operand and operator) are also space-separated in the output. "

The code I wrote is:
import java.util.*;

public class PostfixConverter {
private String infixExpression;

public PostfixConverter(String infixExpression) {
this.infixExpression = infixExpression;
}

private String convertInfixExpression() {
StringTokenizer tokens = new StringTokenizer(infixExpression);
Stack operatorStack = new ArrayStack();
String converted = "";

while(tokens.hasMoreTokens()) {
    String token = tokens.nextToken();
    if(token.equals("(")) {
        operatorStack.push(new String(token));
    }
    else if(token.equals(")")) {
        while(operatorStack.top().equals("(") != true) {
                converted = converted + " " + operatorStack.pop();
            }
        if(operatorStack.top().equals("(")) {
            operatorStack.pop();
        }
    }
    else if (isOperator(token)){
        if(operatorStack.isEmpty() == true) {
            operatorStack.push(new String(token));
        }
        else {
            if(ICP(token) < ISP((String) operatorStack.top())) {
                converted = converted + " " + operatorStack.pop();
                operatorStack.push(token);
            }
            else {
                operatorStack.push(new String(token));
            }
        }
    }
    else {
        converted = converted + " " + new String(token);
    }
}
while(operatorStack.isEmpty() != true) {
    converted = converted + " " + operatorStack.pop();
    }

return converted;
}

public int ISP(String token) {
int precedence = 0;
if(token.equals("+")|| token.equals("-")) {
    precedence = 2;
}
else if(token.equals("*") || token.equals("/")) {
    precedence = 4;
}
else if(token.equals("^")) {
    precedence = 5;
}
else if(token.equals("(")) {
    precedence = 0;
}
return precedence;
}

public int ICP(String token) {
int precedence = 0;
if(token.equals("+")|| token.equals("-")) {
    precedence = 1;
}
else if(token.equals("*") || token.equals("/")) {
    precedence = 3;
}
else if(token.equals("^")) {
    precedence = 6;
}
return precedence;
}

private boolean isOperator(String token) {
return (token.equals("+") ||
        token.equals("-") ||
        token.equals("*") ||
        token.equals("/") ||
        token.equals("^") );
}

public static void main(String[] args) {
System.out.println("Input the infix expression "
        + "(operands, operators are separated by spaces):");
Scanner input = new Scanner(System.in);
String infixExpression = input.nextLine();
PostfixConverter converter = new PostfixConverter(infixExpression);
System.out.println("The converted expression is " +
        converter.convertInfixExpression());
}

}


texts: The Rust Programming Language Pig Latin Exercise

texts:
This is my implementation of the Pig Latin recommended exercise in The Rust Programming Language book. I am using the unicode segmentation crate to split the string into words while also keeping the delimiters. Any pointers on making this code more idiomatic or run more optimal?
use unicode_segmentation::UnicodeSegmentation;

#[allow(overlapping_patterns)]
fn translate_word(s: &str) -> String {
  let mut it = s.chars();
  let first = it.next().unwrap();
  match first.to_ascii_lowercase() {
    'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", s),
    'a'..='z' => format!("{}-{}ay", it.collect::<String>(), first),
    _ => s.to_string(),
  }
}

pub fn translate(s: &str) -> String {
  s.split_word_bounds()
    .map(translate_word)
    .collect::<Vec<_>>()
    .join("")
}

The code is inside a module named pig_latin.


texts:
I'm learning Go at this moment and it is my first program in Go, so I will be thankfull for any suggestion, remarks and observations.

package main

import (
    "fmt"
)

const ascii = "abcdefghijklmnopqrstuvwxyz"
var goodness_values = []float32 { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 }

func zip(s1 string, s2 string) map[string]string {
    result := make(map[string] string)

    for i, v := range s1 {
        result[string(v)] = string(s2[i])
    }

    return result
}

func crypt(s string, table map[string]string) string {
    result := ""

    for _, v := range s {
        result += table[string(v)]
    }

    return result
}

func encode(message string, key int) string {
    shifted_ascii := ascii[key:] + ascii[:key]
    trans_table := zip(ascii, shifted_ascii)

    return crypt(message, trans_table)
}

func decode(secret string, key int) string {
    shifted_ascii := ascii[key:] + ascii[:key]
    trans_table := zip(shifted_ascii, ascii)

    return crypt(secret, trans_table)
}

func goodness(version string, letter_goodness map[string] float32) float32 {
    var result float32 = 0.0

    for _, v := range version {
        result += letter_goodness[string(v)]
    }

    return result
}

func crack(secret string) string {
    var best_score float32  = 0.0
    result := ""
    letter_goodness := make(map[string] float32)

    for i, v := range ascii {
        letter_goodness[string(v)] = goodness_values[i]
    }

    for i := 0; i <= 26; i++ {
        version := decode(secret, i);
        score := goodness(version, letter_goodness);

        if(score > best_score) {
            best_score = score
            result = version
        }
    }

    return result
}

func main() {
    fmt.Printf("%s\n", encode("hello", 10))
    fmt.Printf("%s\n", decode("rovvy", 10))
    fmt.Printf("%s\n", crack("pybrscpexnkwoxdkvmyxdbsledsyxcdydronopsxsdsyxkxnnocsqxypzbyqbkwwsxqvkxqekqoc"))
}


texts:
I have a lottery simulator on my website that simulates you playing the lottery every week until your death and tells you how much you would have won or lost. It can take a custom number of balls and rewards scheme, as I made it after Camelot changed the rules for the UK national lottery to give people an idea of how the change could affect their winnings.

Here is the code that actually simulates the lottery, once given values for prizes, number of balls and cost of play:

// Setting up some variables normally given values by POST
$numbers = range(1,49);
$choices = array(8,15,28,36,40,47);
$ZeroWin = 0;
$OneWin = 0;
$TwoWin = 0;
$ThreeWin = 10;
$FourWin = 100;
$FiveWin = 1000;
$BonusWin = 50000;
$Jackpot = 1000000;
$plays = 2000;
$cost = 1;

//No wins yet
$ZeroWinCount = 0; $OneWinCount = 0; $TwoWinCount = 0; $ThreeWinCount = 0;
$FourWinCount = 0; $FiveWinCount = 0;$BonusWinCount = 0;$JackpotCount = 0;

//Lottery simulating
for ($p = 1; $p<=$plays; $p++) {
    $hits = 0;
    shuffle($numbers); //Spinning the wheel
    $BonusHit = False;
    $balls = array_slice($numbers, 0, 7); //Choosing balls
    for ($a = 0; $a<=5; $a++) {
        for ($b = 0; $b<=5; $b++) {
            if ($choices["$a"] == $balls["$b"]) {
                $hits++;    } } }
    switch ($hits) {
        case 0:
            $ZeroWinCount++;
            break;
        case 1:
            $OneWinCount++;
            break;
        case 2:
            $TwoWinCount++;
            break;
        case 3:
            $ThreeWinCount++;
            break;
        case 4:
            $FourWinCount++;
            break;
        case 5:
            for ($q = 0; $q<=5; $q++) {
                if ($choices["$q"] == $balls['6']) {
                    $BonusHit=True;
                    break;
                }
            }
            if ($BonusHit) {
                $BonusWinCount++;
            } else {
                $FiveWinCount++;
            }
            break;
        case 6:
        $JackpotCount++;
    }
}
//Calculate winnings
$winnings = (($ZeroWinCount * $ZeroWin) + ($OneWinCount * $OneWin) +
            ($TwoWinCount * $TwoWin) + ($ThreeWinCount *$ThreeWin) +
            ($FourWinCount * $FourWin) + ($FiveWinCount * $FiveWin) +
            ($BonusWinCount * $BonusWin) + ($JackpotCount * $Jackpot));

$losings = $plays * $cost;
$net = $losings - $winnings;

Seven balls are chosen because in the UK we have one bonus ball, and the balls of the player are either chosen by the visitor of the site or through lucky dip.

How efficient is this code? It isn't very complicated, but as the loop can be carried out thousands of times, and has loops within it, small things can make a big difference. If you see an improvement, or an outright mistake, please let me know.


texts:
Here i have javascript code where is 'animals' object and 'people' array of objects. User selects the data from select box and accordingly table fills with selected data(which is array of objects) and when user wants to reset everything to the state before selected data, user just clicks 'backtozero' button.
the code is a little complicated to understand for beginners specially two 'for loops'(i know foreach but maybe someting else ?) and also information which is inside of 'addEventListeners function' any suggestion for making whole thing easier to read for beginners ? feel free to make changes :

let animals
let animalCols = ['Animal', 'Animal 2']
let peopleCols = ['Person', 'Person 2']

function myFunction() {
  paivitys(animals, animalCols)
}

function paivitys(dataa, arvvoja) {
  console.log(dataa);
  //----
  if (dataa.hasOwnProperty("animal")) {
    document.getElementById("1name").innerHTML = dataa.animal;
  } else {
    document.getElementById("1name").innerHTML = dataa.person;
  }
  //----
  if (dataa.hasOwnProperty("animal2")) {
    document.getElementById("2name").innerHTML = dataa.animal2;
  } else {
    document.getElementById("2name").innerHTML = dataa.person2;

  }

  document.getElementById("1name1").innerHTML = arvvoja[0];
  document.getElementById("2name1").innerHTML = arvvoja[1];

  //-----
  document.getElementById("id").innerHTML = dataa.id;
}

function paivitaselekt(araytassa, arvvoja) {

var i, j;
for (i = 0; i < araytassa.length; i++) {
    var ssellecct = document.getElementById("Select");
    var oppttion = document.createElement("option");
    for (j = 0; j < arvvoja.length; j++) {
       oppttion.textContent += araytassa[i][arvvoja[j]] + " ";
    }
    ssellecct.appendChild(oppttion);
}
}

animals = {
  "animal": "tiger",
  "animal2": "lion",
  "id": "54321",
  "dole": {
    "Key": "fhd699f"
  }
}

paivitys(animals, animalCols);
let infoarray;

people = [{
    "person": "kaka",
    "person2": "julle",
    "id": "9874",
  },
  {
    "person": "Ronaldo",
    "person2": "jussi",
    "id": "65555",
  }
]
infoarray = people;
paivitaselekt(infoarray, ["person", "id"]);

document.getElementById("Select").addEventListener("change", function(event) {
  const chosenid = event.target.value.split(" ")[1];
  const choseninfo = infoarray.filter((dataa) => dataa.id === chosenid)[0];
  paivitys(choseninfo, peopleCols);
});
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    />
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
      integrity="sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
      crossorigin="anonymous"
    />

        Animal
        Animal
        id

  <select id="Select" ></select>
  <button onclick="myFunction()">backtozero</button>


texts:
As the question reads, I am building a database with 3 tables. Now these tables are going to be used to store names.

Table 1 will store First Names
Table 2 will store Last Names
Table 3 will be a one to one table linking the First names to the Last names

Now all this data will be coming from a text file in the format of:

  Firstname MI Lastname

I estimate that their will be over 100 million records. I also don't want to do a insert for every name it will be an update record on duplicate Key. So what is the most optimal way to enter this into my database. By the way it is a Innodb so the whole table gets locked so I can't do multiple insert updates at a time

Now this whole process will be done via C# using mysql connection and I have:

sqlRequest += "START TRANSACTION ;" +
    "UPDATE firstName SET LastUpdated = CURRENT_TIMESTAMP WHERE first= '" + countSplit[0] +"' ;" +
    "INSERT INTO firstName(first, LastUpdated) SELECT '" + countSplit[0] + "' AS first, CURRENT_TIMESTAMP AS LastUpdated FROM dual WHERE NOT EXISTS ( SELECT * FROM firstName d WHERE d.first= '" + countSplit[0] + "') ;" +
    "COMMIT ;";
sqlRequest += "START TRANSACTION ;" +
    "UPDATE lastName SET LastUpdated = CURRENT_TIMESTAMP WHERE last = '" + countSplit[2] + "' ;" +
    "INSERT INTO lastName (last, LastUpdated) SELECT '" + countSplit[2] + "' AS last, CURRENT_TIMESTAMP AS LastUpdated FROM dual WHERE NOT EXISTS ( SELECT * FROM lastName d WHERE d.last = '" + countSplit[2] + "') ;" +
    "COMMIT ;";
sqlRequest += "START TRANSACTION ;" +
    "INSERT INTO first_to_last " +
    "(firstid,lastid,LastUpdated) VALUES "+
    "((SELECT firstid FROM firstName WHERE first='" + countSplit[0] + "')," +
    "(SELECT lastid FROM lastName WHERE last='" + countSplit[2] + "' )," +
    "CURRENT_TIMESTAMP)"+
    "ON DUPLICATE KEY UPDATE LastUpdated = CURRENT_TIMESTAMP;"+
    "COMMIT ;";

So do you think that this is the best way? Or do you think there is something better?


texts: ReactiveX observable that uses another observable

texts:
I am trying to write an Angular service that will wrap the regular Http service and automatically make authentication calls if Bearer token is not available or invalid.

Here's an illustration of a regular GET call made via the service:

this.httpWithAutomagicAuth
    .get("http://localhost:5001/books")
    .map(res => res.json())
    .subscribe(
        data => {
            self.data = data;
        }
    );

And here's my very sloppy implementation for such service. Obviously, I'm not using the right ReactiveX idioms in the code.

As you can easily notice I am trying to build an observable (Observable.create) that is using another observable returned by this.login(). I am sure there is a better way of chaining/nesting observable for this scenario.

Please, suggest improvements that will make code:

terse
easy to read and understand

@Injectable()
export class HttpWebApiAuthService {

constructor(private http: Http) { }

// ...

public get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    // TODO this code is for test purpose only (basically, it required to enforce the jwtToken retrieval branch execution)
    // this.clearJwtToken();

    if (!this.getJwtToken()) {
        return Observable.create(
            (result: Observer<Response>) => {
                this.login()
                    .map(res => res.json())
                    .subscribe(
                        data => {
                            this.saveJwtToken(data.id_token);

                            this.executeGet(url, options)
                                .subscribe(authenticationResult => {
                                    result.next(authenticationResult);
                                });
                        },
                        error => { console.error("Authentication error", error); },
                        () => { console.info("Authentication complete"); }
                    );
                },
                error => { console.error("OBSERVABLE error: ", error); },
                () => { console.info("OBSERVABLE complete");
            }
        );
    } else {
        return this.executeGet(url, options);
    }
}

private login() : Observable<Response> {
    const authBody =
        {
            "client_id": "...",
            "username": "...",
            "password": "...",
            // ...
        };
    const headers = new Headers();
    headers.append("Content-Type", "application/json");

    return this.http.post("https://AUTH_URL", JSON.stringify(authBody), { headers: headers });
}

// ...

}


texts: Selecting the most recent record for each product

texts:
I have the following structure of a table:

|  id  |  profile_id  |  sku  |  vendor  | price |  importRun  |
|  1   |     39       |  123  |  myVen   |  2.0  |      1      |
|  2   |     39       |  456  |  myVen   |  2.0  |      1      |
|  3   |     39       |  123  |  myVen   |  3.0  |      2      |

Related: StackOverflow question

(I'm not sure If I'm supposed to nearly copy/paste the question. If so, drop me a note pls and I'll update the question).

What I want (short summary)

Get a List of all articles in my DB. If sku's are redundant, I just want the newest entry (or the highest importRun associated). I already got that going thanks to SO, but the query takes way too much time to execute (waiting for like 10 mins already, still no output).

This is the query I'm using.

SELECT DISTINCT t1.*
FROM import_data t1
INNER JOIN import_profiles imp
ON t1.profile_id = imp.id
INNER JOIN (
    SELECT sku, MAX(importRun) AS importRun
    FROM import_data
    GROUP BY sku
) t2
ON t1.sku = t2.sku
WHERE imp.creditornr = 73329
AND t1.vendor = 'fortinet'
AND t1.importRun = t2.importRun

The has ~ 50.000 entries and is expanding on a weekly base, so I assume, every week the query will take longer to execute.

Any idea on how to improve that?

Here is the explain


texts:
Given an array and a value, find all the triplets in the array whose sum is equal to the given value. For example, if the given array is {12, 3, 4, 1, 6, 9} and the given sum is 24, then this is one triplet (12, 3 and 9) which contributes to the total sum of 24.
Solution for given example:
6, 9, 9
6, 6, 12
3, 9, 12
Conditions:

The ordering of the numbers in the solution does not matter.

Duplicate triplet is not allowed.

A number is not allowed to be used multiple times.

A similar question was asked here, though it was HashMap-based.
Github
public class ThreeSumUsingBinarySearch {

     static class Triplet {
        final List<Integer> triplets;

        public Triplet(int x, int y, int z) {
            triplets = Arrays.asList(x, y, z);
            Collections.sort(triplets);
        }

        @Override
        public String toString() {
            return String.format("(%d,%d,%d)", triplets.get(0), triplets.get(1), triplets.get(2));
        }

        @Override
        public int hashCode() {
            return triplets.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof Triplet) {

                Triplet other = (Triplet) o;
                return other.triplets.equals(this.triplets);
            }

            return false;
        }
    }

    public static Set<Triplet> findTriplets(int array[], int targetSum) {

        int[] numbers = Arrays.copyOf(array, array.length);
        Set<Triplet> triplets = new HashSet<>();

        Arrays.sort(numbers);

        for (int i = 0; i < array.length; i++) {
            int complement = targetSum - numbers[i];

            for (int low = i + 1, high = numbers.length - 1; low < high; ) {
                int total = numbers[low] + numbers[high];

                if (total < complement) {
                    low++;
                } else if (total > complement) {
                    high--;
                } else {
                    // found the match
                    triplets.add(new Triplet(numbers[i], numbers[low], numbers[high]));
                    low++;
                    high--;
                }
            }
        }

        return triplets;
    }
}


texts: Matrix class with overloaded `operator[]`

texts:
I have implemented a Matrix class that allocates memory using unique_ptr. How to make it more diverse and optimized in terms of memory usage and efficiency?

//
// Created by Mayukh Sarkar on 26/12/19.
//

#ifndef DP2_MATRIX_H
#define DP2_MATRIX_H

#include <cstdio>
#include <memory>
#include <algorithm>

template <typename T>
class Matrix {
private:
    size_t row{};
    size_t col{};
    std::unique_ptr<T[]> data;
public:
    explicit Matrix(size_t row, size_t col, T def) {
        // Create a matrix of row X col and initialize
        // each element of the matrix with def
        this->row = row;
        this->col = col;
        this->data = std::make_unique<T[]>(this->row * this->col);
        std::fill_n(data.get(), row*col, def);
    }

    // Overload the [] operator for the 2d array like access
    T* operator[](int r) {
        if (r >= row) {
            throw std::out_of_range("Can not access out of bound element!");
        }
        return &this->data[r*col];
    }

    // Overload the << operator for console logging
    friend std::ostream& operator<< (std::ostream& os, Matrix &mObj) {
        auto shape = mObj.shape();
        for(int i=0; i< shape.first; i++) {
            for(int j=0; j<shape.second; j++) {
                os << mObj[i][j] << " ";
            }
            os << "\n";
        }
        return os;
    }

    // Set all the values of the Matrix
    void setValues(T value) {
        std::fill_n(data.get(), row*col, value);
    }

    // Get row and col values
    std::pair<size_t, size_t> shape() const {
        return std::make_pair(this->row, this->col);
    }
};

#endif //DP2_MATRIX_H

I want to specifically optimize the []operator overloading because I feel it is not good to handle pointers directly. Any suggestions?


texts:
This is my first PHPUnit test with mocks, for a Symfony 3 project. Can anyone give me some advice about this code?

class CourierManager extends BaseManager
{
    /**
     * @param Courier $courier
     */
    public function create (Courier $courier) : void
    {
        $this->em->persist($courier);
        $this->em->flush();
    }

    /**
     * @param Courier $courier
     */
    public function update (Courier $courier) : void
    {
        $this->em->flush();
    }

    /**
     * @param $phone
     * @return null|Courier
     */
    public function findByPhone (string $phone) : ?Courier
    {
        return $this->repository->findOneByPhone($phone);
    }
}

BaseManager __construct method:

    public function __construct (EntityManager $entityManager,  $repositoryClass, Container $container)
    {
        $this->em = $entityManager;
        $this->repository = $entityManager->getRepository($repositoryClass);
        $this->container = $container;
        $this->entity = Order::class;
    }

And CourierManagerTest:

class CourierManagerTest extends \PHPUnit_Framework_TestCase
    {
        /**
         * @var EntityManager
         */
        private $em;

        /**
         * @var Container
         */
        private $container;

        /**
         * @var EntityRepository
         */
        private $repository;

        /**
         * @var CourierManager
         */
        private $manager;

        private static $courierClass = Courier::class;

        public function setUp () : void
        {
            $this->em = $this->getMockBuilder(EntityManager::class)->disableOriginalConstructor()->getMock();
            $this->em->expects($this->any())->method('persist')
                ->with($this->isInstanceOf(static::$courierClass))
            ;

            $this->repository = $this->getMockBuilder(EntityRepository::class)->disableOriginalConstructor()->getMock();

            $this->em->expects($this->any())->method('flush');
            $this->em->expects($this->any())->method('getRepository')->with($this->equalTo('AppBundle:Courier'))->will($this->returnValue($this->repository));

            $this->container = $this->getMockBuilder(Container::class)->getMock();
            $this->manager = new CourierManager($this->em, 'AppBundle:Courier', $this->container);
        }

        public function testCreate () : void
        {
            $this->manager->create($this->getCourier());
        }

        public function testFindByPhone () : void
        {
            $this->manager->findByPhone('1234567890');
        }

        private function getCourier () : Courier
        {
            return new static::$courierClass();
        }
    }


texts: Improving speed of word search algorithm

texts:
I've been working on this word search algorithm and had some issues about its speed. It kinda looks like it takes a little too much time.

If anyone could offer suggestions on making this better and improving my skills, that would be great.

    #include <iostream>
    #include <string>
    #include <fstream>

    using namespace std;

    bool Check(string Letter, string Matrix)
    {
        return (Letter == Matrix) ? true : false;

    }

    int main()
    {
        int Height = 0, Widht = 0, Numb = 0, Longer = 0, Look = 0, Look1 = 0, Look2 = 0, Look3 = 0, Poz = 0, Poz1 = 0;

        int Loop = 0, Loop1 = 0, Loop2 = 0, Loop3 = 0, Loop4 = 0, Loop5 = 0, Loop6 = 0;

        bool Found, Found1, Found2, Found3;

        ifstream Data("Files/Info.txt");

        Data >> Widht >> Height;

        string Matrix[Height][Widht];

        while(Loop < Height)
        {
            Loop1 = 0;

            while(Loop1 < Widht)
            {
                Data >> Matrix[Loop][Loop1];

                Loop1++;
            }

            Loop++;
        }

        Data >> Numb;

        string Words[Numb];

        while(Loop2 < Numb)
        {
            Data >> Words[Loop2];

            Loop2++;
        }

        Data.close();

        while(Loop3 < Numb)
        {
            Longer = Words[Loop3].size();
            Loop4 = 0;
            Loop6 = 0;

            cout << Words[Loop3] << endl;

            while(Loop4 < Height) // Looks horizantaly
            {
                Loop5 = 0;
                Look = 0;
                Look1 = 0;

                while(Loop5 < Widht - Longer + 1)
                {
                    Found = Check(Words[Loop3].substr(Look, 1), Matrix[Loop4][Loop5]);

                    if(Found)
                    {
                        Loop6 = 1;
                        Look = Loop5;
                        Poz = Loop4;
                        Poz1 = Loop5;

                        while(Loop6 < Longer)
                        {
                            Look++;

                            Found1 = Check(Words[Loop3].substr(Loop6, 1), Matrix[Loop4][Look]);

                            if(Found1)
                            {
                                Loop6++;
                            }
                            else
                            {
                                Loop5 += Loop6;
                                Loop6 = Longer + 1;
                            }
                        }
                    }

                    if(Loop6 == Longer)
                    {
                        cout << "Word " << Words[Loop3] << " was found at: " << Poz << " collumn " << Poz1 + 1 << " symbol. Horizontaly from right to left" << endl;
                        Loop5 = Widht;
                        Loop4 = Height;
                        Loop3++;
                    }

                    Loop5++;
                }

                Loop4++;
            }

            Loop3++;
        }

        return 0;
    }

The infos file looks like this:

10 10
a s d f g h j k l o
e t a k t r e e a d
t e d a w e f g d a
r e s a g a f a q w
d c s q a z x v n b
q w e t a s f w p s
w a r y i w t o o a
s b b d s s w q o k
w e r a d g d a p a
q w r c b a x l s k
3
tree
poop
test

Of course, I will later add other directions in which words might be written.


texts: Rotate image 90 degree clockwise recursively

texts:
Previous question:

Rotate image 90 degree clockwise

In this code I have used tail recursive, which is bad. Time complexity is still \$O(N^2)\$, which is worse-case. The only good part is memory complexity.

How can I improve the recursive part of this code?

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

template<typename T>
using matrix = std::vector<std::vector<T>>;

// for debug info
static size_t numTotalSwaps = 0;

template<typename T>
matrix<T> rotateImage(matrix<T>&& image, size_t row = 0, size_t column = 0)
{
    if (row == image.size())
    {
        std::cout << "\nNumber of total swaps: " << numTotalSwaps << '\n';
        return image;
    }

    if ( ++column == image.size() )
    {
        std::reverse(image[row].begin(), image[row].end());
        ++row;
        column = 0;
    }

    if (row != column && row < column)
    {
        ++numTotalSwaps;
        std::swap(image[row][column], image[column][row]);
    }

    return rotateImage(std::move(image), row, column);
}

int main()
{
    const size_t SIZE = 7;

    matrix<int> image(SIZE, std::vector<int>(SIZE));

    std::cout << "******* original image ******\n";

    int value = 0;

    for (auto&& i : image)
    {
        for (auto&& j : i)
        {
            std::cout << std::setfill(' ') << std::setw(3) << (j = value++) << ' ';
        }

        std::cout << '\n';
    }

    std::cout << "******* rotated image ******\n";

    for (const auto& i : rotateImage(std::move(image)))
    {
        for (const auto& j : i)
        {
            std::cout << std::setfill(' ') << std::setw(3) << j << ' ';
        }

        std::cout << '\n';
    }
}


texts: A simple bubble sort implementation in Java

texts:
I've written a Bubble Sort algorithm in Java and I want a review on these:

Performance improvements.
Code conventions.
Algorithm design improvements.
Cleaner approaches.

I would highly appreciate if you can review based on the points above, and I would prefer if you can add more points on top if it if you find necessary.

Here's the code:

package com.hassanalthaf.sortingalgorithms;

public class BubbleSort {

    private int temporary;

    public int[] sort(int[] numbers) {
        for (int mainIterations = 0; mainIterations < numbers.length; mainIterations++) {
            int comparisonsCount = (numbers.length - mainIterations) - 1;

            for (int comparisons = 1; comparisons < comparisonsCount; comparisons++) {
                if (numbers[comparisons] > numbers[comparisons + 1]) {
                    this.temporary = numbers[comparisons];
                    numbers[comparisons] = numbers[comparisons + 1];
                    numbers[comparisons + 1] = this.temporary;
                }
            }
        }

        return numbers;
    }

}

Here's my main class calling the BubbleSort sort method:

package com.hassanalthaf.sortingalgorithms;

public class Main {

    public static void main(String[] args) {
        int[] numbers = {1, 20, 51, 12, 43, 2, 20};

        BubbleSort bubbleSort = new BubbleSort();

        numbers = bubbleSort.sort(numbers);

        for (int iterations = 0; iterations < numbers.length; iterations++) {
            System.out.println(numbers[iterations]);
        }
    }

}

This produces an output:

1
2
12
20
20
43
51


texts: Backing up two tables using SQL transactions

texts:
I'm using a transaction statement in SQL Server 2012 for the first time.

I want to insert Table1's data in Table1_Backup before I delete everything from Table1.  Same process for Table2. Should I name my transactions?  Does this transaction code even look right?

DECLARE @err int
BEGIN TRANSACTION Table1
insert into [Table1_BU]
select * from [Table1] order by ID
SET @err = @@ERROR

IF @err = 0
BEGIN
delete from Table1
END

IF @err = 0
COMMIT TRANSACTION Table1
ELSE ROLLBACK TRANSACTION Table1

SET @err = 0
BEGIN TRANSACTION Table2
insert into [Table2_BU]
select * from Table2 order by ID
SET @err = @@ERROR

IF @err = 0
BEGIN
delete from Table2
END

IF @err = 0
COMMIT TRANSACTION Table2
ELSE ROLLBACK TRANSACTION Table2


texts: Making the save and cancel buttons editable

texts:
The following code makes a div tag editable and handles the save and cancel buttons. But there is a lot of duplication. How could I remove the duplication on this?

var originalTexts = {};
$("div.edit-panel").find("span").click(function() {
    var panel = $(this).closest('div.simple-panel');
    var text  = panel.find(".info");
    var id = $(this).parent().attr("id");
    panel.find(".edit-panel").addClass('editable');
    text.addClass("content-editable").prop('contenteditable', 'true');
    originalTexts[id] = text.text();
})

$("div.edit-panel").find(".cancel-editable").click(function() {
    var panel = $(this).closest('div.simple-panel');
    var text  = panel.find(".info");
    var id    = $(this).parent().attr("id");
    text.text(originalTexts[id]);
    panel.find(".edit-panel").removeClass('editable');
    text.removeClass("content-editable").prop('contenteditable', 'false');
})

$("div.edit-panel").find(".save-editable").click(function() {
    var panel = $(this).closest('div.simple-panel');
    var text  = panel.find(".info");
    var currentText = text.text();
    text.text(currentText);
    panel.find(".edit-panel").removeClass('editable');
    text.removeClass("content-editable").prop('contenteditable', 'false');
})


texts: Large number stored as vector, increase performance

texts:
I made a code to initialize char vectors with random numbers representing very large numbers with more than 20.000 digits. The additions and multiplications are correct but my code is too slow (1 minute). I know that I can change char by 64 int to make operations with 19 numbers at a time, instead of 1 digit at a time, but I don't know how to do that without changing my current output that is correct.

Thanks for your help

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

unsigned int seed;

int newrandom() {
  seed = (214013*seed+2531011);
  return (seed>>13);
}

void LongNumInit( char *L, unsigned N )
{
  for ( int i=0; i< N; i++ )
  {
    L[i] = newrandom() % 10;
  }
}

void PrintNumber( char *L, unsigned N, char *Name )
{
  printf("%s:", Name);
  for ( int i=N; i>0; i-- )
  {
    printf("%d", L[i-1]);
  }
  printf("\n");
}

void ValueSet( char *L, unsigned N, char digit )
{
  for ( int i=0; i< N; i++ )
  {
    L[i] = digit;
  }
}

void CPNumber( char *Vin, char *Vout, unsigned N )
{
  for ( int i=0; i< N; i++ )
  {
    Vout[i] = Vin[i];
  }
}

char Add( char *Vin1, char *Vin2, char *Vout, unsigned N )
{
  char CARRY = 0;
  for ( int i=0; i< N; i++ )
  {
    char R = Vin1[i] + Vin2[i] + CARRY;
    if ( R <= 9 )
    {
      Vout[i] = R; CARRY = 0;
    }
    else
    {
      Vout[i] = R-10; CARRY = 1;
    }
  }
  return CARRY;
}

char DigitAddition( char *V, char digit, unsigned N )
{
  int i=0;
  char R = V[0] + digit;
  if (R < 10)
  {
    V[0] = R; return 0;
  }

  V[0] = R-10;
  char CARRY = 1;
  i = 1;
  while ( CARRY && i < N )
  {
    if ( V[i] < 9 )
    {
      V[i] = V[i] + 1; CARRY = 0;
    }
    else
    {
      V[i] = 0; i++;
    }
  }
  return CARRY;
}

char AddInHorizontal( char *Vin, char *Vout, unsigned N )
{
  char CARRY = 0;
  ValueSet ( Vout, N, 0 );
  for ( int i=0; i< N; i++ )
  {
    DigitAddition ( Vout, Vin[i], N );
  }
  return 0;
}

char MultiplyConst( char *V, unsigned N, char digit )
{
  char CARRY = 0;
  for ( int i=0; i< N; i++ )
  {
    char R = V[i] * digit + CARRY;
    CARRY = R / 10;
    R = R - CARRY*10;
    V[i] = R;
  }
  return CARRY; // may be from 0 to 9
}

void Mult( char *Vin1, char *Vin2, char *VoutH, char *VoutL,  unsigned N )
{

  unsigned char *TEMP= (unsigned char*) malloc( 2*N*sizeof(unsigned char) );
  unsigned char *RES = (unsigned char*) malloc( 2*N*sizeof(unsigned char) );

  ValueSet  ( RES, 2*N, 0 );    // Set RES to 0

  for ( int i=0; i<N; i++ )
  {
    ValueSet  ( TEMP, 2*N, 0 );
    CPNumber ( Vin1, TEMP+i, N );
    MultiplyConst( TEMP, 2*N, Vin2[i] );
    Add ( TEMP, RES, RES, 2*N ); // TEMP + RES -> RES
  }

  CPNumber ( RES,   VoutL, N );
  CPNumber ( RES+N, VoutH, N );
}

int main (int argc, char **argv)
{
  int i, sum1, sum2, sum3, N=20000;

  seed = 12345;

  if (argc>1) { N    = atoi(argv[1]); }
  if (argc>2) { Rep  = atoi(argv[2]); }

  unsigned char *V1= (unsigned char*) malloc( N*sizeof(unsigned char) );
  unsigned char *V2= (unsigned char*) malloc( N*sizeof(unsigned char) );
  unsigned char *V3= (unsigned char*) malloc( N*sizeof(unsigned char) );
  unsigned char *V4= (unsigned char*) malloc( N*sizeof(unsigned char) );

  LongNumInit ( V1, N );
  LongNumInit ( V2, N );
  LongNumInit ( V3, N );

  Add ( V1, V2, V4, N );
  Mult ( V3, V4, V2, V1, N );
  AddInHorizontal ( V1, V2, N );
  DigitAddition ( V3, V2[0], N );

  PrintNumber( V1, 32, "V1" );
  PrintNumber( V2, 32, "V2" );
  PrintNumber( V3, 32, "V3" );
  PrintNumber( V4, 32, "V4" );

  free(V1);
  free(V2);
  free(V3);
  free(V4);
  return 0;
}

```


texts:
I need to take a month (defined as a start and end date) and return a set of date ranges for each week in that month.  A week is defined as Sunday through Saturday.  A good way to visualize it is if you double click on your Windows date in the start bar:

The month of October 2011 has 6 weeks:

  10/1-10/1

  10/2-10/8

  10/9-10/15

  10/16-10/22

  10/23-10/29

  10/30-10/31

I can describe each week as a struct:

   struct Range
   {
      public DateTime Start;
      public DateTime End;

      public Range(DateTime start, DateTime end)
      {
         Start = start;
         End = end;
      }
   }

I need to write a function that takes a month and returns an array of ranges within it.  Here's my first attempt, which appears to work and addresses the obvious edge cases:

public static IEnumerable<Range> GetRange(DateTime start, DateTime end)
{
   DateTime curStart = start;
   DateTime curPtr = start;
   do
   {
      if (curPtr.DayOfWeek == DayOfWeek.Saturday)
      {
         yield return new Range(curStart, curPtr);
         curStart = curPtr.AddDays(1);
      }

      curPtr = curPtr.AddDays(1);
   } while (curPtr <= end);

   if(curStart <= end)
      yield return new Range(curStart, end);
}

I would like to know if there's a cleaner or more obvious approach to do the same.  I'm not overly concerned about performance, but I'd like to improve code readability and make the algorithm a bit more concise.  Perhaps there's a very creative solution involving a single LINQ expression or something.