texts:
Recently I did an exercise to understand Akka FSM. I implemented a Traffic light system with Akka FSM which changes its state every 30 seconds.

My code is like:

LightColour: Enum to encapsulate the traffic light colors.

public enum LightColour {
    RED,
    YELLOW,
    GREEN
}

Light: Class to depict the actual light.

public class Light {

    private LightColour lightColourNow;

    private long lightStartedAt;

    private long numberOfChanges;

    public Light(LightColour lightColourNow) {
        this.lightColourNow = lightColourNow;
        this.lightStartedAt = System.currentTimeMillis();
        this.numberOfChanges = 0;
    }

    public LightColour getLightColourNow() {
        return lightColourNow;
    }

    public long getLightStartedAt() {
        return lightStartedAt;
    }

    public long getNumberOfChanges() {
        return numberOfChanges;
    }

    public long changeLightColor(LightColour lightColourNow) {
        System.out.println(String.format("Changing Light colour from %s to %s. Change Number: %d", this.lightColourNow, lightColourNow, this.numberOfChanges));
        this.lightColourNow = lightColourNow;
        this.numberOfChanges++;
        return numberOfChanges;
    }

    @Override
    public String toString() {
        return "LightTimeout{" +
                "lightColourNow=" + lightColourNow +
                ", lightStartedAt=" + lightStartedAt +
                ", numberOfChanges=" + numberOfChanges +
                '}';
    }
}

LightTimeout: An empty class to denote the event for changing the light.

public class LightTimeout {
}

Finally, the TrafficLight class, which is an FSM to depict the behavior of a Traffic Light, changing colors every 30 seconds.

import akka.actor.AbstractFSM;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

import java.io.IOException;
import java.time.Duration;

public class TrafficLight extends AbstractFSM<LightColour, Light> {

    private final int LIGHT_TIME = 30;

    public static Props props() {
        return Props.create(TrafficLight.class);
    }

    {
        startWith(LightColour.RED, new Light(LightColour.RED));

        when(LightColour.RED, matchEvent(LightTimeout.class, ((timeOut, data) -> {
            data.changeLightColor(LightColour.YELLOW);
            scheduleTimeoutEvent();
            return goTo(LightColour.YELLOW);
        })));

        when(LightColour.YELLOW, matchEvent(LightTimeout.class, (timeOut, data) -> {
            data.changeLightColor(LightColour.GREEN);
            scheduleTimeoutEvent();
            return goTo(LightColour.GREEN);
        }));

        when(LightColour.GREEN, matchEvent(LightTimeout.class, (timeOut, data) -> {
            data.changeLightColor(LightColour.RED);
            scheduleTimeoutEvent();
            return goTo(LightColour.RED);
        }));

        scheduleTimeoutEvent();
        initialize();
    }

    private void scheduleTimeoutEvent() {
        context().system().scheduler().scheduleOnce(Duration.ofSeconds(LIGHT_TIME), getSelf(), new LightTimeout(), context().dispatcher(), getSelf());
    }

    public static void main(String[] args) throws IOException {
        ActorSystem actorSystem = ActorSystem.create("traffic-light-system");
        ActorRef actorRef = actorSystem.actorOf(TrafficLight.props());
        System.out.println("Press any key to exit");
        System.in.read();
        actorSystem.stop(actorRef);
        actorSystem.terminate();
    }
}

I am looking for a review of the solution from Java as well as Akka's perspective. Is my solution ok considering the way I have used Akka FSM or can I improve the solution?


texts:
I have a numpy array called contour of \$N\$ coordinates (x,y) of dimension (N, 2).
For each point in this table, I would like to create a square centered at that point and perform a test on the square formed.
My current code is slow, probably due to the for loop. Can the execution speed be improved?
My code:
def neighbour(point , mask  , n ): # Create the square around this point and count the number of neighbors.
      mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] + int(n/2) + 1]
      return n**2 - np.count_nonzero(mask)

def max_neighbour(contour , mask=maske , n=ne): # Find the point with as many neighbors as possible
    t = np.zeros(len(contour)) # contour is the numpy array of dimension (2,N)
    for i in range(len(contour)):
        t[i] = neighbour(contour[i],mask,n)
    return contour[np.argmax(t)] # t contains the list of neighbors for each contour point.


texts:
I'm working on arrow library for scala

I've come with some new typeclass, which looks like generalized Functor

trait Project[F[_]] extends Functor[F]{
  def project[=>:[_,_], A, B](f: A =>: B)(implicit ar: ArrowChoice[=>:]): F[A] =>: F[B]

  def map[A, B](fa: F[A])(f: A => B): F[B] = project[Function1, A, B](f).apply(fa)
}

where ArrowChoice is subtype of Arrow

example of such typeclass instance could be

implicit def validationProject[E] = new Project[Validation[E, ?]] {
  def project[=>:[_, _], A, B](f: A =>: B)(implicit ar: ArrowChoice[=>:]): Validation[E, A] =>: Validation[E, B] =
    (ar.id[E] +++ f).dimap(_.disjunction, _.validation)
}

However I have some doubt about such definition:

Is name Project is clear enough? Isn't it confusing or dissonating for potential user? Could it be that similar things were already discussed in some blogs or category theory and have some known label?
Is extending Functor a good idea? In following example we have already Functor for Validation[E, ?] defined here. Should I bother they could conflict if user will import too much?


texts: Checking if an array element exists in a JS object

texts:
I have a feature in my application that should allow users to select items in a drop down menu and move them up and down. Once they select and click on the button I have to loop over the array of objects and pull only records that were selected in the drop down menu.

Here is an example of my code:

var selectedColumns = ['first','last','city'];

var data = [
   {
      first: "Mike",
      last: "Ross",
      dob: "05/26/1978",
      city: "Washington DC",
      state: "DC",
      zip: 22904
   },
   {
      first: "John",
      last: "Henderson",
      dob: "11/06/1988",
      city: "Iowa City",
      state: "IA",
      zip: 52401
   },
   {
      first: "Nina",
      last: "Barkley",
      dob: "01/16/1968",
      city: "New York",
      state: "NY",
      zip: 11308
   },
   {
      first: "Jessie",
      last: "Kuch",
      dob: "02/02/1956",
      city: "Des Moines",
      state: "IA",
      zip: 55432
   },
   {
      first: "Jenny",
      last: "Terry",
      dob: "012/28/1988",
      city: "Miami",
      state: "FL",
      zip: 83943
   }
];

In the selected column we only have first, last and city. Then I have to loop over data and pull only selected columns. One way to do that is like this:

for(var key in data){
   for(var i=0; i<selectedColumns.length; i++){
      var columnID = String(columns[i]);
      console.log($.trim(data[key][columnID]));
   }
}

While this solution works just fine, I'm wondering if there is better way to avoid the inner loop and improve efficiency? I use jQuery/JavaScript in my project. If anyone knows a better way to approach this problem please let me know.


texts:
Once again I decided to beat system memcmp function. This time I decided to use a template and to "precompile" all cases from 0 to 31 bytes.

Result is 400% improvement - from about 1:15 min to 0:25 min.

Finally I had rewritten memcmp_fixed_ with naive looking for statement and I noticed that the compiler can optimize it as well.

However I did not tested with random data, so I am not sure what role the cache line and branch predictor plays in the tests.

Here is the code:

#include <cstdint>
#include <cstring>

namespace{

template<size_t SIZE>
int memcmp_fixed_(const unsigned char *s1, const unsigned char *s2){
    for(size_t i = 0; i < SIZE; ++i)
        if (s1[i] != s2[i])
            return s1[i] - s2[i];

    return 0;
}

template<>
int memcmp_fixed_<1>(const unsigned char *s1, const unsigned char *s2){
    return *s1 - *s2;
}

template<size_t SIZE>
int memcmp_fixed_(const void *a1, const void *a2){
    const unsigned char *s1 = (const unsigned char *) a1;
    const unsigned char *s2 = (const unsigned char *) a2;

    return memcmp_fixed_<SIZE>(s1, s2);
}

}

inline int fast_memcmp(const void *a1, const void *a2, size_t const size){
    switch(size){
        case  0: return 0;

        case  1: return memcmp_fixed_< 1>(a1, a2);
        case  2: return memcmp_fixed_< 2>(a1, a2);
        case  3: return memcmp_fixed_< 3>(a1, a2);
        case  4: return memcmp_fixed_< 4>(a1, a2);
        case  5: return memcmp_fixed_< 5>(a1, a2);
        case  6: return memcmp_fixed_< 6>(a1, a2);
        case  7: return memcmp_fixed_< 7>(a1, a2);
        case  8: return memcmp_fixed_< 8>(a1, a2);
        case  9: return memcmp_fixed_< 9>(a1, a2);
        case 10: return memcmp_fixed_<10>(a1, a2);
        case 21: return memcmp_fixed_<21>(a1, a2);
        case 22: return memcmp_fixed_<22>(a1, a2);
        case 23: return memcmp_fixed_<23>(a1, a2);
        case 24: return memcmp_fixed_<24>(a1, a2);
        case 25: return memcmp_fixed_<25>(a1, a2);
        case 26: return memcmp_fixed_<26>(a1, a2);
        case 27: return memcmp_fixed_<27>(a1, a2);
        case 28: return memcmp_fixed_<28>(a1, a2);
        case 29: return memcmp_fixed_<29>(a1, a2);
        case 30: return memcmp_fixed_<30>(a1, a2);
        case 31: return memcmp_fixed_<31>(a1, a2);

        default: return memcmp(a1, a2, size);
    }
}

#include <cstdio>

#include <algorithm>    // min

size_t const MAX = 10000000000;

int main(int argc, char **argv){
    if (argc != 3){
        printf("Usage:\n");
        printf("\t%s [string1] [string2]\n", argv[0]);
        return 1;
    }

    const char *s1 = argv[1];
    const char *s2 = argv[2];

    size_t const size1 = strlen(s1);
    size_t const size2 = strlen(s2);
    size_t const size  = std::min(size1, size2);

    volatile int x = 0;
    for(volatile size_t i = 0; i < MAX; ++i)
        x += fast_memcmp(s1, s2, size);

    printf("%d %d\n", fast_memcmp(s1, s2, size), x );
}

And the baseline is this:

#include <cstdint>
#include <cstring>

#include <cstdio>

#include <algorithm>    // min

size_t const MAX = 10000000000;

int main(int argc, char **argv){
    if (argc != 3){
        printf("Usage:\n");
        printf("\t%s [string1] [string2]\n", argv[0]);
        return 1;
    }

    const char *s1 = argv[1];
    const char *s2 = argv[2];

    size_t const size1 = strlen(s1);
    size_t const size2 = strlen(s2);
    size_t const size  = std::min(size1, size2);

    volatile int x = 0;
    for(volatile size_t i = 0; i < MAX; ++i)
        x += memcmp(s1, s2, size);

    printf("%d %d\n", memcmp(s1, s2, size), x );
}


texts:
Sometimes I need to be able to split data into chunks, and so something like str.split would be helpful. This comes with two downsides:

Input has to be strings
You consume all input when generating the output.

I have a couple of requirements:

It needs to work with any iterable / iterator. Where the items have the != comparator.
I don't want to consume the chunk of data when returning it.
Rather than returning a tuple, I need to return a generator.

And so this left me with two ways to implement the code. A fully lazy version isplit. And one that is semi-lazy where it consumes some of the generator, when moving to the next chunk, without fully consuming it.

And so I created:

from __future__ import generator_stop
import itertools

def _takewhile(predicate, iterator, has_data):
    """
    Return successive entries from an iterable as long as the
    predicate evaluates to true for each entry.

    has_data outputs if the iterator has been consumed in the process.
    """
    for item in iterator:
        if predicate(item):
            yield item
        else:
            break
    else:
        has_data[0] = False

def isplit(iterator, value):
    """Return a lazy generator of items in an iterator, seperating by value."""
    iterator = iter(iterator)
    has_data = [True]
    while has_data[0]:
        yield _takewhile(value.__ne__, iterator, has_data)

def split(iterator, value):
    """Return a semi-lazy generator of items in an iterator, seperating by value."""
    iterator = iter(iterator)
    has_data = [True]
    while True:
        carry = []
        d = _takewhile(value.__ne__, iterator, has_data)
        try:
            first = next(d)
        except StopIteration:
            if not has_data[0]:
                break
            yield iter([])
        else:
            yield itertools.chain([first], d, carry)
            carry.extend(d)

An example of these working are below. There is an edge case with isplit, which is as far as I know inherent from the code being fully lazy. This is shown below too.

print('isplit')
print([list(i) for i in isplit('abc def ghi', ' ')])
print([list(i) for i in isplit(' abc def ghi', ' ')])
s = isplit('abc def ghi', ' ')
print(list(itertools.zip_longest(*itertools.islice(s, 4))))

print('\nsplit')
print([list(i) for i in split('abc def ghi', ' ')])
print([list(i) for i in split(' abc def ghi', ' ')])
s = split('abc def ghi', ' ')
print(list(itertools.zip_longest(*itertools.islice(s, 4))))

Which outputs:

isplit
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
[[], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
[('a', 'b', 'c', None), ('d', 'e', 'f', None), (None, 'g', 'h', None), (None, 'i', None, None)]

split
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
[[], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]


texts:
Can someone please help to rewrite / tidy up this?

// News Article Slideshow
var periodToChangeSlide = 5000;
var pp_slideshow = undefined;
var currentPage = 0;

$('#news-feature-img-wrap li').css('display', 'list-item').slice(1).css('display', 'none');
$('#news-items li:first').addClass('active');

$("#news-feature-wrap #news-items li").click(function () {
    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');

    var index = $(this).parent().index();
    var toShow = $("#news-feature-wrap #news-feature-img-wrap li").eq(index);
    toShow.show();
    toShow.siblings().hide();
    currentPage = index;
    $.stopSlideshow();
});

$.startSlideshow = function () {
    if (typeof pp_slideshow == 'undefined') {
        pp_slideshow = setInterval($.startSlideshow, periodToChangeSlide);
    } else {
        $.changePage();
    }
}

$.stopSlideshow = function () {
    clearInterval(pp_slideshow);
    pp_slideshow = undefined;
}
$.changePage = function () {
    var numSlides = $('#news-feature-wrap #news-feature-img-wrap li').length;
    currentPage = (currentPage + 1) % numSlides;
    var menu = $('#news-feature-wrap #news-items li').eq(currentPage);
    menu.addClass('active');
    menu.siblings().removeClass('active');

    var toShow = $("#news-feature-wrap #news-feature-img-wrap li").eq(currentPage);
    toShow.show();
    toShow.siblings().hide();
}

$.startSlideshow();


texts: Using jquery Callbacks.fire method as a event handler

texts:
So I've got a jquery project where I'm using an external class that has callback style events. Meaning, it has an "onSave" property that takes one function. However, I need to more than one other component to hook into it.

What I've settled on for now, goes like this:

var saveCallbacks = $.Callbacks();
saveCallbacks.fire.callbacks = saveCallbacks;
globalDoodad.onSave = saveCallbacks.fire;

which allows me to do this in my other components:

globalDoodad.onSave.callbacks.add( myMethod );

Is there a better, or at least more standard, way to handle this? It seems to be working ok, just has a bit of a smell to it.


texts: Call html() on two jQuery selector objects

texts:
In my webpage I have two places where I need my JavaScript to write dates. How to do it in one go?

Selectors:

var $today = $('#today');
var $selected = $('#selected');

If I were to do this alternatively the easy way, I'd do:

$('#today, #selected').html(date);

But I kind of need to reuse my #selected jQuery object throughout my code.

The only solution I came up with so far is...

$([$today, $selected]).each(function(idx, obj){obj.html(date);});

Is there a better way?


texts:
I have written REST API for random number generation using Falcon(https://falconframework.org/), just for my learning process.

This is API:

http "localhost:8000/random-number?min=10&max=10"

This is code:

class RandomNumber:
    def on_get(self, req, resp):
        """Handles GET requests"""

        if 'min' not in req.params:
            raise falcon.HTTPMissingParam('min')

        if 'max' not in req.params:
            raise falcon.HTTPMissingParam('max')

        min_n = req.params['min']
        max_n = req.params['max']

        if min_n.isnumeric() == False:
            raise falcon.HTTPInvalidParam('min must be number', min_n)

        if max_n.isnumeric() == False:
            raise falcon.HTTPInvalidParam('max must be number', max_n)

        min_n =int(min_n)
        max_n =int(max_n)

        if min_n > max_n:
            raise falcon.HTTPInvalidParam('min is bigger than max', (min_n, max_n))

        number = random.randint(min_n, max_n)
        result = {'lowerLimit': min_n, 'higherLimit': max_n, 'number': number}
        resp.media = result

api = falcon.API()
api.add_route('/random-number', RandomNumber())

Feedback appreciated.


texts: Rotating contents of a matrix (vector) to the left or right

texts:
Each vector element is a row and each character is a column.
Assume the matrix is square (N*N) and N is < 10.

I have some code to do it but it doesn't look great and would love some feedback on how to make it better. You can use any function of the C++ standard library. The only constraint is it can't be in-place. I'm looking to improve it in style and any optimisations needed.
enum DIRECTION
{
    DIR_RIGHT = 0,
    DIR_LEFT = 1
};

vector<string> rotate(const vector<string>& original, DIRECTION direction)
{
    vector<string> rotated(original);
    for (vector<string>::const_iterator irow = original.begin(); irow != original.end(); ++irow) {
        int new_col = direction == DIR_RIGHT ? (original.size() - 1) - (irow - original.begin())
                                             : (irow - original.begin());
        for (string::const_iterator icol = (*irow).begin(); icol != (*irow).end(); ++icol) {
            int new_row = direction == DIR_RIGHT ? (icol - (*irow).begin())
                                                 : ((*irow).size() - 1) - (icol - (*irow).begin());
            rotated[new_row][new_col] = *icol;
        }
    }
    return rotated;
}

Example input:
"###"
"oho"
"ooo"

Rotating right should output:
"oo#"
"oh#"
"oo#"

P.s. For convenience I've included using namespace std;, the final code uses the namespace explicitly E.g. std::vector.


texts: Dividing a ThreadPool class into component classes to reduce/isolate complexity

texts:
I have a ThreadPool class which has grown to a point where it is becoming difficult to keep all of this unit of work in mind. It is also becoming harder to read. For this reason I would like to break this class into component classes.

First of all here is the class header with comments:

//ThreadPool.h

#ifndef THREADPOOL_H
#define THREADPOOL_H

#define doNothing()

#include <iostream>
#include <chrono>
#include <queue>
#include <vector>
#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>

typedef std::function< void() > voidFunctionType;

class ThreadPool{

 public:
  ThreadPool(unsigned int desiredThreadCount);
  ~ThreadPool();

  //Functions Affecting ThreadPool
  //Function used by threads to submit work to ThreadPool
  void workSubmit(voidFunctionType functionPointer);
  //Function used by threads to take work from ThreadPool
  voidFunctionType takeTask(void);
  //Function which returns the number of work in the queue
  unsigned int workCount(void);
  //Function which
  bool isWorkAvailable(void);

  //Functions Affecting Thread Availability.
  //Increments availableThreads variable which indicates number of threads available
  void incThreadAvailability(void);
  //Decrements availableThreads variable which indicates number of treads available
  void decThreadAvailability(void);
  //Returns availableThreads variable which indicates number of threads available
  unsigned int getThreadAvailability(void);
  //Function returns total number of threads generated
  unsigned int getThreadNum(void);

  //Functions Affecting Threads
  //Checks to see if work is available, if work is not available thread is put to sleep
  //If work is available thread processes work.
  void threadSleepUntillWorkAvail(void);

 private:
  // Number of threads generated
  unsigned int numberOfThreads;

  //Vector of threads
  std::vector<std::thread> workers;

  // Number of threads available to process work
  unsigned int availableThreads;
  // Mutex for the availableThreads variable
  std::mutex threadAvailabilityLock;
  std::unique_lock<std::mutex> threadAvailabilityLockUnique;

  //Workqueue to track work
  std::queue< std::function< void()> > workQueue;
  //WorkSubmissionLock mutex is used to lock submission of work only
  std::mutex workSubmissionLock;
  std::unique_lock<std::mutex> workSubmissionLockUnique;
  std::condition_variable workSubmissionCondition;
  //WorkQueueLock mutex is used to lock all access points to the queue it self
  std::mutex workQueueLock;
  std::unique_lock<std::mutex> workQueueLockUnique;
  std::condition_variable workQueueCondition;

  //Private Member Functions
  //workAccept is used within workSubmit. This function is used to load the workQueue with the
  //Accepted work.
  void workAccept(voidFunctionType functionPointer);

  //Operators
  //Function executed by threads.
  void operator()(void);
};
#endif

I have tried creating a thread component class, however it was highly coupled with the ThreadPool class and the only value it provided was a single routine which was the main routine the threads executed. So I replaced this class with the function method operator within the threadpool class.

Other than the thread class component I am unsure if I can extract out any other single responsibility from this class.

Note:

I am aware of a resource deadlock problem when 3 or more threads are created, I do not want this issue to be the focal point.
I do not think the implementation is relevant to the question, however, it can be viewed here.


texts: Read contents of file with appropriate error handling (Rust)

texts:
I am trying to learn basic Rust. Is this a good way to get the contents of a file? Am I handling errors the best way? Is there any way this could be more performant?

use std::fs::File;
use std::io::Read;

fn main() {
    let path = "bar/foo.txt";

    match read(path) {
        Ok(contents) => println!("{}", contents),
        Err(err) => println!("Unable to read '{}': {}", path, err),
    }
}

fn read(file: &str) -> Result<String, std::io::Error> {
    let mut file = match File::open(file) {
        Ok(mut f) => f,
        Err(err) => return Err(err),
    };

    let mut data = String::new();
    match file.read_to_string(&mut data) {
        Ok(_) => return Ok(data),
        Err(err) => return Err(err),
    }
}


texts:
I'm trying to improve my SQL syntax, take the following for the example

SELECT * FROM `Users:Timesheets`
WHERE
`start` >= '{$monday}'
AND `finish` <= '{$sunday}'
AND `username` = '{$username}'
AND `shift_type` = 'ONCALL'

OR

`start` >= '{$monday}'
AND `finish` IS NULL
AND `username` = '{$username}'
AND `shift_type` = 'ONCALL'

ORDER BY `id` ASC"

There must be a shorter way to achieve this or am I expecting too much?

Any insight to what I may be missing out on?


texts:
I don't want to use the if-statement chain. Can I write the code in a different way? I want to use the smallest amount of if-statements.

#include <stdio.h>
#include <stdlib.h>
main()
{
    int temp;

    printf("type a number: "),
    scanf("%d", &temp);
    printf("\n\n");

    if (temp == 18)
    {
        printf("The temperature is normal, stable conditions. \n");
    }
    else if (temp < 5)
    {
        printf("The temperature is too cold. Massive damage. \n");
    }
    else if (temp > 25)
    {
        printf("The temperature is too hot. Massive damage. \n");
    }

    else
    {
        printf("The temperature is unstable. This condition can make damages. \n");
    }
    system("PAUSE");
}


texts:
I have to reproduce some basic functions in C and one of them is strlcat.

After reading the man and testing the strlcat from <bsd/string.h> library, I wrote the following code which seems to be a working copy of the function:

#include <string.h>

size_t  ft_strlcat(char *dst, const char *src, size_t size)
{
    size_t  lsize;
    size_t  dsize;

    lsize = 0;
    dsize = strlen(dst);
    while (*dst && size > 0 && size--)
    {
        dst++;
        lsize++;
    }
    while (*src && size > 1 && size--)
        *dst++ = *src++;
    if (size == 1)
        *dst = '\0';
    return (dsize + lsize);
}

Is this implementation missing something?


texts: Wait for a "3rd party" element to be appended to the DOM

texts:
Let's say we're writing a user script which interacts with a 3rd party site we don't control. We want to open a menu, so we trigger a click on the button and then wait 10ms before accessing the menu (which is appended to the document after the click), like this:

$button = $('#button');
$button.trigger('click');
setTimeout(function() {
    //access the menu
}, 10);

This works, because it takes less than 10ms for the 3rd party site's handler to appended the menu to the DOM once the button is clicked. But it feels like bad code. Is there a better way to write this?


texts: addClass and removeClass in a switch case

texts:
Since I'm still learning jQuery, I would like to have some feedback on my code:

var showImgage = function()
{
 var selection = $(this).val();

 switch(selection)
 {
  case 'Monica Bellud':
  $('#Belluci').removeClass().addClass('show');
  $('#Andres').removeClass().addClass('hide');
  $('#Seydoux').removeClass().addClass('hide');
  break

  case 'Lea Seydoux':
  $('#Seydoux').removeClass().addClass('show');
  $('#Belluci').removeClass().addClass('hide');
  $('#Andres').removeClass().addClass('hide');
  break

  case 'Ursula Andress':
  $('#Andres').removeClass().addClass('show');
  $('#Belluci').removeClass().addClass('hide');
  $('#Seydoux').removeClass().addClass('hide');
  break

  default:
  selection.removeClass();
 }
}

  Wie van de onderstaande dames is géén Bond Girl in de nieuwe film 'SPECTRE'?
  <input type="radio" value="Monica Bellud" name="girlchoice" id="choicemonica" checked />Monica Bellud
  <input type="radio" value="Lea Seydoux" name="girlchoice" id="choicelea" />Lea Seydoux
  <input type="radio" value="Ursula Andress" name="girlchoice" id="choiceursula" />Ursula Andress

I simply want to change the image (which is in my div of my HTML) for each radiobutton. It works, but it looks like I'm duplicating my code 3 times. How can I make this easier?


texts: Create table that lists worksheet visibility

texts:
Following my previous question Create a table that lists macros in a workbook or worksheet here's my Sub to determine worksheet visibility in a workbook. This arises from updating code that used extremely hard to understand logic and several disparate NamedRanges to subsequently hide/reveal sheets.

Is there a better/optimal to create a string as opposed to what I use: join(Array(param1, param2,...,paramN), DELIMIT)? I only have brief exposure to StringBuilder Class and would like to know how best to do this.

Public Sub ListWorksheetVisibilityInActiveWORKBOOK()
Const DELIMIT As String = "|", COLSPAN As Long = 2
Dim HEADER As String
Dim inputCell As Range
Dim Rw As Long, Col As Long
Dim Ws As Worksheet
Dim ASU As Boolean

Dim TableName As String

    HEADER = join(Array("SheetName", "Visibility"), DELIMIT)
On Error Resume Next 'Error handling to allow for cancelation
    Set inputCell = GetInputCell("Select where you want the table to go")
    If inputCell Is Nothing Then GoTo CleanExit
On Error GoTo 0 'Clear error handling

    TableName = Application.InputBox("Table name", Default:="WorksheetVisibility")
    If TableName = "False" Then
        MsgBox "Table name not entered. No table has been created."
        GoTo CleanExit
    End If

    'Check to avoid overwriting information below
Dim tblVisibility As Range, rngFormulas As Range, rngConstants As Range
    Set tblVisibility = inputCell.Resize(ActiveWorkbook.Worksheets.count + 1, COLSPAN)
On Error Resume Next 'If no cells are found error wont cause issue
    Set rngConstants = tblVisibility.SpecialCells(xlCellTypeConstants)
    Set rngFormulas = tblVisibility.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0 'Clears error handling
    If Not rngConstants Is Nothing Or Not rngFormulas Is Nothing Then
Dim Msg As String
        Msg = "Some cells below will be overwritten. Overwrites cannot be undone..." & vbNewLine & vbNewLine & "Do you wish to proceed?"
        If MsgBox(Msg, vbYesNo + vbCritical, "Your attention please!") = vbNo Then End
    End If

ASU = Application.ScreenUpdating
Application.ScreenUpdating = False

    inputCell.Value2 = HEADER

    Rw = inputCell.row + 1
    Col = inputCell.Column
Dim Value As String
    For Each Ws In ActiveWorkbook.Worksheets
        Value = join(Array(Ws.Name, Ws.Visible), DELIMIT)
        Cells(Rw, Col).Value2 = Value
        Rw = Rw + 1
    Next

    tblVisibility.Columns(1).TextToColumns DataType:=xlDelimited, Other:=True, OtherChar:=DELIMIT

    ActiveSheet.ListObjects.Add(xlSrcRange, tblVisibility, XlListObjectHasHeaders:=XlYesNoGuess.xlYes, Destination:=inputCell).Name = TableName

CleanExit:
Application.ScreenUpdating = ASU
End Sub

Private Function GetInputCell(ByVal Prompt As String) As Range
    On Error GoTo ErrorHandler
    Set GetInputCell = Application.InputBox(Prompt, Type:=8)
    Exit Function
ErrorHandler:
    MsgBox "User Cancelled"
    Set GetInputCell = Nothing
End Function


texts: Strategy design pattern in C++ using unique_ptr

texts:
1. Introduction

This is for my ANN project.

Each building block of ANN, neuron, has activation function which determines how to get the output given the input (see formula in on repo I linked).

I have abstract class Neuron which represents a neuron in ANN. The following points have been taken into account:

Not only activation function is intended to be used but its derivative also
Activation function (and its derivative) returns double and takes double as the only argument
It should be easy and clear how to add and use new defined activation function
Activation function should be initialized at the construction step of Neuron instance

2. Possible solution

2.1. Activation class

Each activation function is represented by an abstract class Activation:

class Activation
{
    public :
        virtual double f( double x ) = 0;
        virtual double fPrime( double x ) = 0;
};

2.2. Concrete activation

Concrete activation is represented by a derived class:

class Identity : public Activation
{
    public :
        double f( double x ) { return x; }
        double fPrime( double x ) { return 1.; }
};

class Sin : public Activation
{
    public :
        double f( double x ) { return sin(x); }
        double fPrime( double x ) { return cos(x); }
};

class Sigmoid : public Activation
{
    public :
        double f( double x ) { return 1. / ( 1. + exp( -x ) ); }
        double fPrime( double x )
        {
            return ( 1. - f(x) ) / f(x);
        }
};

2.3. Activation as a class member

I decided to use std::unique_ptr to store activation function as a member of Neuron class.

class Neuron
{
    private :
        std::unique_ptr<Activation> _act;

    public :
        Neuron( std::unique_ptr<Activation> act ) :
            _act( std::move( act ) )
        { }

        double Act( double x ) { return _act->f( x ); }//get output
        double ActPrime( double x ) { return _act->fPrime( x ); }//get derivative of activation

        //some other functions including pure virtual ones
};

2.4. Adding new activation

In order to add new activation function one "just" should create a class derived from Activation class and overwrite functions f and fPrime.

2.5. Using

Neuron n( std::make_unique<Identity>() );
n.Act( 30. );
n.ActPrime( 30. );

3. Discussion

I am pretty satisfied with this solution but what I am thinking about is is any destructor needed in this case if I use unique_ptr? If so, then what exactly?

Any critic, suggestion, correction, idea, advice etc. would be appreciate.


texts:
I started university this semester. Can you review my code and share your thoughts with me
# 5-November-2020

username = input("Please enter your username: ")
password = input("Please enter your password: ")

username_password = {
    'Mert': "mertt"
}

if username in username_password:
    if username == "Mert" and password == username_password[username]:
        print("Welcome Sir")
    else:
        print("You're not authorized!")
else:
    confirmation = input("Do you want to register? (Y/N): ")
    if confirmation == "Y":
        username = input("Enter your username: ")
        password = input("Enter your password: ")
        password_2 = input("Confirm your password: ")
        if password == password_2:
            username_password[username] = password
        else:
            print("Your password is incorrect!")
    else:
        print("Good bye")
print(username_password)

If you have any improvement suggestion please tell me.


texts: Check if a binary tree is a subtree of another tree

texts:
I am doing a refresher on algorithms.
I tried to solve the problem of determining if you have 2 trees (T1 and T2), one is a subtree of the other.

I came up with the following:

public boolean isSubtree(Node n1, Node n2){

   if(n2 == null) //Empty Subtree is accepted
      return true;

   if(n1 == null)
      return false;

   //If roots are equal, check subtrees
   if(n1.data == n2.data){
       return isSubTree(n1.left, n2.left) && isSubTree(n1.right, n2.right);
   }
   else{//No match found for this root. Check subtrees
       return isSubTree(n1.left, n2) || isSubTree(n1.right, n2);
   }

}

I think it is correct.
Just to clarify n1 is the root of the tree and n2 the root of the subtree we search for.
I was wondering if someone could review it please? Besides correctness the following trouble me:

How would I calculate its complexity?
Also by Googling I found code for this which was similar to mine but not exactly the same.
For example the code fragments I found had if(n1 == null) return false; while I also check if the n2 is not null.
Mu rationale is that an empty tree and an empty subtree should return true.
But either my logic is wrong or the code posts I found on the internet usually ignore this case.

Any input is highly appreciated


texts: Searching for a specific object in an ArrayList

texts:
Is this an efficient way to search for a specific object in an ArrayList?

Product is the superclasS. Mobo, CPU, RAM, GPU... are the subclasses.
ArrayList(called stock) stores Product objects. I consider that they key i am searching is found when class and the attribute "model"(you can see the getter of the attribute in my code) are matching.

public static boolean checkAvailability(ArrayList<Product> stock, Product product) {
    boolean found = false;
    for(Product p: stock) {
        if(p instanceof Mobo && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof CPU && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof GPU && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof RAM && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof Monitor && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof Keyboard && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof Mouse && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
        if(p instanceof Printer && (product.getModel() == p.getModel())) {
            found = true;
            break;
        };
    };
    return found;
}


texts:
Instead of having to use something like char buf[100500] and hope that no possible user input could be longer than 100500 bytes, I decided to make the following function:

char* input (FILE* in, size_t size)
{
    char * input_str = NULL;
    int c;
    size_t len = 0;

    /*initial allocation*/
    input_str = malloc(size);
    if (!input_str) return NULL;

    while ((c = fgetc(in)) != EOF && c != '\n')
    {
        input_str[len++] = c;

        /*allocate more room if needed*/
        if (len == size)
        {
            input_str = realloc(input_str, size += 16);
            if (!input_str) return NULL;
        }
    }

    input_str[len++] = 0;

    return realloc(input_str, len);
}

My questions about this code:

Is leaving it up to the calling function to free memory a bad idea?
Is there a way to increase performance for this (memory pool, etc)? I don't like making so many syscalls...
In general, is there a better way to go about this?


texts:
I'm trying to create some easily accessible database of different skills. General idea is that every skill should do something different and be able to act on different things (ex. one skill which icreases weapon attack by 'x' [it acts on weapon] and other one which icreases chances to drop item by 'z'% [it acts on monster]).

I see it that way:

There is static database of skills accessible from everywhere
Skills have effects(methods with different return types, different parameters and calculations)
To use skill we add it's effect in particular calculations;

Example: If we want to increase drop chance of monster by 'z'% then, in place where we calculate that drop chance (in this case in Monster class), lets say (Monster.DropChance = 0.5f) we add skill effect : after skill implementation (Monster.DropChance = 0.5f + SkillDatabase.IncreaseDropChance.Effect (this))

I came up with a code like this:

public static class SkillData   // Static class acting as database for keeping skills in one place
{
    // Names of skills
    public enum Name
    {
        IncreaseDropChance = 1,
        IncreaseWeaponAtk = 2
    }

    // T - return type of skill effect, U - type of object on which effect works
    public class Skill<T, U>
    {
        public int Level { get; set; }
        public float ExperienceCost { get; set; }
        public Name SName;

        // Delegate for creating unique effects for each skill
        public delegate T EffectDel (U onWhat);
        public EffectDel Effect;

        public Skill (Name name)
        {
            SName = name;
        }
    }

    // Custom dictionary for generic skill
    public class SkillDictionary
    {
        private Dictionary<Name, object> _dict = new Dictionary<Name, object>();

        public void Add<T, U>(Name key, Skill<T, U> skill)
        {
            _dict.Add(key, skill);
        }

        public Skill<T, U> GetValue<T, U>(Name key)
        {
            return _dict[key] as Skill<T,U>;
        }
    }

    // Static for easy access
    public static SkillDictionary DB = new SkillDictionary ();

    static SkillData ()
    {
        // Here I want to create skills one after another and add them to DB
        // This is example skill creation
        Skill <float, Player> IncrWpnAtk = new Skill<float, Player> (SName.IncreaseWeaponAtk);
        IncrWpnAtk.Level = 5;
        // Let's say we want to increase weapon attack by 100% * skillLvl
        IncrWpnAtk.Effect = (player) => { float additionalAtk = player.Eq.Weapon.Atk * IncrWpnAtk.Level;
                                          return additionalAtk; };
        DB.Add <float, Player> (Name.IncreaseWeaponAtk, IncrWpnAtk);
    }
}

Now in weapon attack calculation we add SkillData.DB.GetValue<float, Player> (IncreaseWeaponAtk).Effect (player) .
Yeah... It's terrible. Load of text for such a tiny effect. It's my second time using delegates and third time creating generic classes, I just don't know any other solution for creating same class with different methods.

How would you solve it guys? Do you know any way to maintain organized, easily accessible database of skills? Or maby this approach is generaly wrong?


texts:
This is a simple flashcard app. With flags to control the sides of the flashcards and the number of flashcards in the session.

All the flashcards without any input at the prompt, are deleted from the map. And ones with an input, remain. The idea is that, the user marks the flashcard that they want to revise in case they had forgotten it, later in the session.

The outer loop, loops until the length of the map is >= 1

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "log"
    "math/rand"
    "os"
    "os/exec"
    "runtime"
    "time"

    "github.com/fatih/color"
)

var (
    flagNoColor = flag.Bool("no-color", false, "disable color output")
    csvPath = flag.String("src", "src.csv", "source")
    side = flag.Int("s", -1, "side")
    num = flag.Int("n", -1, "number")
)

var clear map[string]func()

func init() {
    clear = make(map[string]func())
        clear["linux"] = func() {
        cmd := exec.Command("clear")
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
    clear["windows"] = func() {
        cmd := exec.Command("cmd", "/c", "cls")
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
}

func CallClear() {
    value, ok := clear[runtime.GOOS]
    if ok {
        value()
    } else {
        panic("Panic!")
    }
}

func random(min int, max int) int {
    return rand.Intn((max-min) + 1) + min
}

func main() {

    flag.Parse()

    file, err := os.Open(*csvPath)
    if err != nil {
        log.Println(err)
        return
    }
    defer file.Close()

    csvReader := csv.NewReader(file)

    csvData, err := csvReader.ReadAll()
    if err != nil {
        log.Println(err)
        return
    }

    qaRaw := make(map[string]string, len(csvData))
    for _, data := range csvData {
        qaRaw[data[0]] = data[1]
    }

    qaPair := make(map[string]string)

    if *num != -1 {
        i := 1
        for one, two := range qaRaw {
            if i <= *num {
                qaPair[one] = two
            }
            i++
        }
    } else {
        for one, two := range qaRaw {
            qaPair[one] = two
        }
    }

    done := make(chan bool)

    go func() {
        if *flagNoColor {
            color.NoColor = true
        }
        white := color.New(color.FgWhite)
        boldWhite := white.Add(color.Bold)

        qNum := 0

        for len(qaPair) >= 1 {
            for one, two := range qaPair {
                rand.Seed(time.Now().UnixNano())
                randomNum := random(1, 2)
                if *side != -1 {
                    randomNum = *side
                }
                var userInput string
                CallClear()
                boldWhite.Printf("\n #\t%d / %d\n", qNum+1, qNum+len(qaPair))
                qNum++
                if randomNum == 1 {
                    boldWhite.Printf("\n Q\t%s", one)
                    fmt.Scanln(&userInput)
                    boldWhite.Printf("\n A\t%s", two)
                    fmt.Scanln(&userInput)
                    if len(userInput) == 0 {
                        delete(qaPair, one)
                    }
                } else if randomNum == 2 {
                    boldWhite.Printf("\n Q\t%s", two)
                    fmt.Scanln(&userInput)
                    boldWhite.Printf("\n A\t%s", one)
                    fmt.Scanln(&userInput)
                    if len(userInput) == 0 {
                        delete(qaPair, one)
                    }
                }
                CallClear()
            }
        }
        done <- true
    }()

    select {
        case <-done:
            fmt.Println("blah blah blah")
    }

}

Flashcards example data (.csv file)

"hola","hi"
"sí","yes"
"¿qué pasa?","what's up?"
"¡vamos!","let's go!"
"¡salud!","cheers!; bless you!"
"no","no"
"por favor","please"
"lo siento","I'm sorry"
"buenos días","good morning"
"buenas noches","good night"
"gracias","thank you"
"vale","okay"
"hasta luego","see you later"
"adiós","goodbye"
"cómo","how (questions)"


texts:
I have implemented a Bubble Sort. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.

def bubble_sort(nums):

    for i in range(len(nums)-1):
        for j in range(0,len(nums)-1-i,1):
            if nums[j] > nums[j+1]:
                swap(nums, j, j+1)

    return nums

def swap(nums, i, j):
    temp = nums[i]
    nums[i] = nums[j]
    nums[j] = temp

if __name__ == "__main__":

   a = [0,0,0,-1,-0,1,2,3,2,1]
   print(bubble_sort(a))


texts:
This is part of Invoice. If I have 20 items of it I need to copy nth row (because end user set format only on few cells in nth row) so to keep it formated I need to copy entire row and paste it special.

For j = 1 To clItems.Count - 1
    For i = 1 To nNumberOfRowsPerItem
        xlSheet.Rows(nLastItemRow).Insert()
        xlSheet.Rows(nFirstItemRow + i).Copy()
        xlSheet.Rows(nFirstItemRow + (j * nNumberOfRowsPerItem) + i).PasteSpecial()
    Next i
Next j

But the main problem is when I have two user formated rows and need to insert / paste special them 20 times. It works super slow. Any way to speed up this code?


texts: All-Python implementation of n-dimensional convolution

texts:
To better understand how discrete finite convolution works (read educational purposes) I wrote an all-python implementation of the convolution function. The idea was for it to give the same output as numpy.convolve, including the mode options. I generalized the code so that it functions for n-dimensional convolutions rather than just for 1-dimensional convolutions. This means it more closely matches the behavior of scipy.signal.convolve.

def py_nd_convolve(s, k, mode='full'):
    # All python implementation of n-dimensional scipy.signal.convolve for educational purposes

    # First ensure that one of the arrays fits inside of the other and by convention call this one
    # the kernel "k" and call the larger array the signal "s".
    if all(np.less_equal(k.shape, s.shape)):
        pass
    elif all(np.greater(k.shape, s.shape)):
        s, k = k.astype(float), s.astype(float)
    else:
        raise ValueError(f'Arrays have mismatched shapes: {k.shape} and {s.shape}')

    dim_list = np.arange(s.ndim)
    n_s = np.array(s.shape, dtype=int)
    n_k = np.array(k.shape, dtype=int)
    n_full = n_s + n_k - 1
    out = np.zeros(n_full, dtype=float)
    zero_arr = np.zeros(s.ndim, dtype=int)
    for ind, val in np.ndenumerate(out):
        ind_arr = np.array(ind)  # convert index tuple to numpy array so it can be used for arithmetic

        # i_min and i_max specify the allowed range which indices can take on in each dimension
        # to perform the convolution summation. The values for these are non-trivial near the
        # boundaries of the output array.
        i_min = np.maximum(zero_arr, ind_arr - n_k + 1)
        i_max = np.minimum(ind_arr, n_s - 1)

        # create a d-dimensional tuple of slices to slice both the kernel and signal to perform the convolution.
        s_slicer = tuple([slice(i_min[d], i_max[d] + 1) for d in dim_list])
        k_slicer = tuple([slice(ind[d]-i_max[d], ind[d]-i_min[d]+1) for d in dim_list])

        # element-wise product and summation of subset of signal and reversed kernel
        out[tuple(ind)] = np.multiply(s[s_slicer], np.flip(k[k_slicer])).sum()

    # This section of code clips the output data as per user specification to manage boundary effects
    n_min = np.zeros_like(n_full)
    n_max = n_full
    if mode == 'full':  # take all possible output points, maximal boundary effects
        pass
    elif mode == 'valid':  # eliminate any part of the output which is effect by boundary effects
        n_min = n_k-1
        n_max = n_s
    elif mode == 'same':  # clip the output so that it has the same shape as s
        n_min = (n_k-1)/2
        n_max = n_s + (n_k-1)/2
    slicer = [slice(int(n_min[d]), int(n_max[d])) for d in dim_list]  # d-dimensional slice tuple for clipping
    return out[tuple(slicer)]

Since this code was for educational purposes I did not desire it to run fast, I namely desired for it to be very readable. As written the code is very very slow. While scipy.signal.convolve can convolve a (200, 200) array with a (50, 50) array in a few milliseconds this code takes a few seconds.

I am not interested in making this code as fast as possible because I know that for that I could simply use the built in functions. I also know that I could possibly perform this operation faster by using an fft approach.

Question

Rather, I am curious if there are any glaring performance issues with the code that can be easily modified so that I can maintain a similar level of readability and logical flow but a higher level of performance.

For example, am I making an egregious numpy mistakes such as copying arrays unnecessarily or misusing memory in a very bad way?

I've noticed that I could flip the k array outside of the loop but it doesn't look like this will save much time.
It looks like a big chunk of time is spent on defining s_slicer and k_slicer.


texts: Running shell script as root via external binary

texts:
I'm not an experienced Linux user and I wanted an easy way to run shell scripts as root from a PHP script, I came up with this:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>

int main(int argc, char *argv[])
{
    if (access(argv[1], F_OK) != -1)
    {
        struct stat filestat;

        if (stat(argv[1], &filestat) == 0)
        {
            if ((filestat.st_uid == 0) && (filestat.st_gid == 0) && (filestat.st_mode & S_IXUSR) && (!(filestat.st_mode & S_IWOTH)))
            {
                char* match = strrchr(argv[1], '.');

                if ((match != NULL) && (strcasecmp(match, ".sh") == 0))
                {
                    if (setuid(0) != -1)
                    {
                        execl("/usr/bin/sudo", "/usr/bin/sudo", argv[1], (char*) NULL);
                        return 0;
                    }
                }
            }
        }
    }

    return 1;
}

Any potential security issues with this? If so how can I improve it?

Example Usage:

Lets say I have a script located at:

/some/path/script.sh

With the following in it:

#!/bin/bash
echo $USER

Now lets say I compile the above C code to a binary and place it at:

/some/path/run-as

and do:

chown root:root /some/path/run-as
chmod 6755 /some/path/run-as

Now I run this PHP script owned by www-data (via browser / local apache web server):

<?php
    echo exec('/some/path/run-as /some/path/script.sh');
?>

I expect the script to output 'root' when ran.


texts: Finding the submatrix with the maximum sum

texts:
Given an arbitrary \$N \times N\$ matrix, find the maximum sum submatrix. This particular approach uses the Kadane's algorithm. What could be improved both in terms of algorithm and code style?

def read_matrix_from_input():
    return [[int(s) for s in input().split(" ")] for row in range(int(input()))]

def max_subarray_sum(array):
    max_sum = current_sum = array[0]
    for number in array[1:]:
        current_sum = max(current_sum + number, number)
        max_sum = max(max_sum, current_sum)

    return max_sum

def max_submatrix_sum(row_major_matrix):
    column_major_matrix = list(map(list, zip(*row_major_matrix)))
    num_columns = len(column_major_matrix)
    num_rows = len(column_major_matrix[0])
    max_sum = column_major_matrix[0][0]

    for left_offset in range(num_columns):

        partial_sums = [0] * num_rows
        for right_column in column_major_matrix[left_offset:]:
            partial_sums = [partial_sums[row] + number for row, number in enumerate(right_column)]
            max_sum = max(max_sum, max_subarray_sum(partial_sums))

    return max_sum

if __name__ == "__main__":
    print(max_submatrix_sum(read_matrix_from_input()))


texts: "Edit distance" UVA programming challenge

texts:
I'm trying to solve a programming challenge for fun. The programming challenge is here and my solution for the same can be found here.

It currently causes an exceeded time limit.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

int a[25001];

bool is_edit_distance_one(string one, string two) {
  if ( one.size() == two.size() ) {
    bool found_diff = false;
    for ( int i = 0 ; i < one.size(); i++ ) {
      if ( found_diff && one[i] != two[i] ) return false;
      else if ( one[i] != two[i] ) found_diff = true;
    }
    return true;
  }

  else if ( (one.size() - two.size()) == 1 && one.find(two) != string::npos )
    return true;
  else if ( (two.size() - one.size()) == 1 && two.find(one) != string::npos )
    return true;

  return false;
}

map<string, bool> generate(string one) {
  map<string, bool> edits;
  string all_chars = "abcdefghijklmnopqrstuvwxyz";

  // Generate all strings by adding another letter
  for ( int i = 0; i <= one.size(); i++ ) {
    for ( int j = 0; j < all_chars.size(); j++ ) {
      // split the string at i
      string temp = one.substr(0, i);
      temp += all_chars[j];
      temp += one.substr(i, one.size()-i);
      edits[temp] = true;
    }
  }

  // Generate all strings by deleting a letter
  for ( int i = 0; i < one.size(); i++ ) {
    string temp = one.substr(0, i);
    temp += one.substr(i+1, one.size()-i);
    edits[temp] = true;
  }

  // Generate all strings by changing a letter
  for ( int i = 0; i < one.size(); i++ ) {
    for ( int j = 0; j < all_chars.size(); j++ ) {
      string temp = one.substr(0, i);
      temp += all_chars[j];
      temp += one.substr(i+1, one.size()-i);
      edits[temp] = true;
    }
  }
  return edits;
}

int main() {
  string s;
  int i = 0;
  int l;
  vector<string> all;
  while ( cin >> s ) {
    a[i] = 0;
    all.push_back(s);

    l = all.size();
    for ( int i = 0; i < l-1; i++ ) {
      map<string, bool> edits = generate(all[l-1]);
      if ( edits[all[i]] ) {
        a[l-1] = max(a[i]+1, a[l-1]);
      }
    }
  }
  sort(a, a+l);
  cout << a[l-1] + 1 << endl;
}

Instead of calculating the edit distance between strings (using is_edit_distance_one), I'm generating a map with all possible edit strings of a string and checking if previous strings are present in it (using the function "generate").

Are there any implementation level mistakes that I'm making that's slowing it down?
Any particular data structure I should/should not be using?
Any other algorithm I could use to speed things up?


texts: Making adjustments based on biblatex style

texts:
The styles which are provided by the biblatex package can be categorised into a few different families, e.g. numeric (numeric, numeric-comp and numeric-verb) or authoryear (authoryear, authoryear-comp, authoryear-ibid and authoryear-icomp). I'm currently working on a mechanism for beamer to apply some adjustments based on which of these style families is used. For example for numeric styles I would like the numbers to be shown in the bibliography or for authoryear styles I would like to prevent the icon from going into the margin.

My current version of the code tests for each style individually, e.g. three if-cases for the numeric styles and another four if-cases for the authoryear styles. This feels overly complicate, so I would like to hear what you think about this approach. Can it be improved?

\documentclass{beamer}

\usepackage[
%   style=numeric,
%   style=numeric-comp,
%   style=numeric-verb,
%   style=authoryear,
    style=authoryear-comp,
%   style=authoryear-ibid,
%   style=authoryear-icomp,
]{biblatex}

\addbibresource{biblatex-examples.bib}% included in full tex distributions or from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib

\makeatletter
\newcommand{\fixnumericstyles}{%
    \setbeamertemplate{bibliography item}{\insertbiblabel}
}

\newcommand{\fixauthoryearstyles}{%
    \newlength{\beamer@bibiconwidth}
    \settowidth\beamer@bibiconwidth{\usebeamertemplate*{bibliography item}}
    \setlength{\labelwidth}{-\beamer@bibiconwidth}
    \addtolength{\labelwidth}{2\labelsep}
    \addtolength{\bibhang}{\labelsep}
}

% Numeric styles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\beamer@namenumeric{numeric}
\ifx\blx@bbxfile\beamer@namenumeric
    \fixnumericstyles
\fi
%
\def\beamer@namenumericcomp{numeric-comp}
\ifx\blx@bbxfile\beamer@namenumericcomp
    \fixnumericstyles
\fi
%
\def\beamer@namenumericverb{numeric-verb}
\ifx\blx@bbxfile\beamer@namenumericverb
    \fixnumericstyles
\fi
%
% author year styles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\beamer@nameauthoryear{authoryear}
\ifx\blx@bbxfile\beamer@nameauthoryear
    \fixauthoryearstyles
\fi
\def\beamer@nameauthoryear{authoryear-comp}
\ifx\blx@bbxfile\beamer@nameauthoryear
    \fixauthoryearstyles
\fi
\def\beamer@nameauthoryear{authoryear-ibid}
\ifx\blx@bbxfile\beamer@nameauthoryear
    \fixauthoryearstyles
\fi
\def\beamer@nameauthoryear{authoryear-icomp}
\ifx\blx@bbxfile\beamer@nameauthoryear
    \fixauthoryearstyles
\fi
\makeatother
\begin{document}

\begin{frame}
\cite{sigfridsson}
\printbibliography
\end{frame}

\end{document}

(a variant of the above code incorporated into beamer can be found in this fork: https://github.com/samcarter/beamer/tree/PrivateCollectionBugFixes)


texts: Calling a function from a dynamically loaded DLL (version 2)

texts:
Please, have a look at the previous (bad) implementation and the review here.

After reading the suggested article at HowTo: Export C++ classes from a DLL, I have decided to use a plain C function approach. However, I want to use C++ code inside the DLL later. Anyway, the exported one will be a plain C function with the const char * argument.

In my earlier attempt, I tried to pass reference to the vector<string> argument, which is not possible or at least safe. The vector of strings was the result of parsing the line from a text file. Now, I am passing the line itself, and the parsing is done inside the DLL. The code of the caller and the type of the called function look like this:

typedef __declspec(dllimport) int (__cdecl *CONVERTPROC)(const char *);

int call_convert_from_dll(const std::string & dllname, const char * line)
{
    HINSTANCE hinstLib;
    CONVERTPROC convert;
    BOOL fRunTimeLinkSuccess = FALSE;

    // Get a handle to the DLL module.
    hinstLib = LoadLibrary(dllname.c_str());

    // If the handle is valid, try to get the function address.
    if (hinstLib != nullptr)
    {
        convert = (CONVERTPROC)GetProcAddress(hinstLib, "convert");

        // If the function address is valid, call the function.
        if (convert != nullptr)
        {
            fRunTimeLinkSuccess = TRUE;
            (convert)(line);
        }
        else {
            DWORD err = GetLastError();
            if (err == ERROR_PROC_NOT_FOUND)
                cerr << "procedure convert() was not found" << endl;
            else
                cerr << "runtime link failed: " << err << endl;
        }
        // Free the DLL module.
        FreeLibrary(hinstLib);
    }

    // If unable to call the DLL function, use an alternative.
    if (!fRunTimeLinkSuccess) {
        cerr << "Failed when using '" << dllname << "' library." << endl;
        return 1;
    }

    return 0;
}

The name of the called function (from the DLL) is passed as a string. Because of that, the extern "C" must be used to avoid identifier mangling.

The mentioned article also says that no exception should cross the boundary of the DLL module (if it is not the special case when both parts are written in C++ and compiled by the same version of the compiler). Because of that, the try/catch wraps the body of the called function. Any exception is transformed to the error code equal to 1:

extern "C" {          // we need to export the C interface

__declspec(dllexport) int __cdecl convert(const char * line)
{
    int err = 0;
    try {
        cout << "my.dll: '" << line << "'" << endl;
        vector<string> vs;
        StringTok(vs, line, " \t\n");
        err = xmain(vs);
    }
    catch (...) {
        return 1;
    }
    return err;
}

} // extern "C"

Can you see any other flaw in the code?


texts: Is this a 100% safe from SQL Injection and will work correctly for any input?

texts:
$a=$_GET["a"];
$b=$_GET["b"];
$a=str_replace("%", "\%", $a);
$b=str_replace("%", "\%", $b);
$sql="SELECT * FROM table ";
$sql.="WHERE ColA LIKE :txtA AND ColB LIKE :txtB";
$query = $db->prepare($sql);
$query->bindValue(':txtA', '%'.$a.'%', PDO::PARAM_STR);
$query->bindValue(':txtB', '%'.$b.'%', PDO::PARAM_STR);
$query->execute();

I want to give user ability to search anything. Should I filter more characters? Will it be 100% safe and work as it should do for searching pieces of text in database?

Edit:
ColA and ColB are strings, just text (phrase and tags in search engine)


texts:
Given a sorted linked list, delete all duplicates such that each element appears only once.

  For example:

  Given 1->1->2, return 1->2.
  Given 1->1->2->3->3, return 1->2->3.

The following is my code:

struct ListNode {
    int data;
    ListNode *next;
    ListNode(int x) : data(x), next(NULL) {}
};

ListNode *getNextElement(ListNode *head){
    while ((head != NULL) && (head->next != NULL)
          && (head->data == head->next->data)){
        head = head->next;
    }

    return head->next;
}

ListNode *deleteDuplicates(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    ListNode *cur = head;
    ListNode *next = NULL;
    while (cur != NULL){
        next = getNextElement(cur);
        cur->next = next;
        cur = next;
    }
    return head;
}


texts: A Tiny Text File Read/Write class Implementation in C#

texts:
I am trying to implement a tiny text file read / write class FileIO in order to make the operations of reading / writing pure text files easily. The usage is like:
FileIO.Instance.FileWrite("TextFile1.txt", "This is a test1.");
FileIO.Instance.FileWrite("TextFile2.txt", "This is a test2.");
Console.WriteLine(FileIO.Instance.ReadTxTFile("TextFile1.txt", System.Text.Encoding.Default));
Console.WriteLine(FileIO.Instance.ReadTxTFile("TextFile2.txt", System.Text.Encoding.Default));

The experimental implementation
The experimental implementation of FileIO class is as below.
class FileIO
{
    public readonly static FileIO Instance = new FileIO();

    public void FileWrite(string filename, string inputString)
    {
        FileStream file_stream = new FileStream(filename, FileMode.Append);
        byte[] Input_data = System.Text.Encoding.Default.GetBytes(inputString);
        file_stream.Write(Input_data, 0, Input_data.Length);
        file_stream.Flush();
        file_stream.Close();
    }

    public void FileWrite(string filename, string inputString, FileMode fileMode)
    {
        FileStream file_stream = new FileStream(filename, fileMode);
        byte[] Input_data = System.Text.Encoding.Default.GetBytes(inputString);
        file_stream.Write(Input_data, 0, Input_data.Length);
        file_stream.Flush();
        file_stream.Close();
    }

    public void FileWrite(string filename, string inputString, FileMode fileMode, Encoding encoding)
    {
        FileStream file_stream = new FileStream(filename, fileMode);
        byte[] Input_data = encoding.GetBytes(inputString);
        file_stream.Write(Input_data, 0, Input_data.Length);
        file_stream.Flush();
        file_stream.Close();
    }

    public string ReadTxTFile(string filename, Encoding encoding)
    {
        System.IO.StreamReader textreader;
        string inputString;
        inputString = "";
        try
        {
            textreader = new System.IO.StreamReader(filename, encoding);
        }
        catch (Exception)
        {
            return "";
            throw;
        }
        inputString = textreader.ReadToEnd();
        textreader.Close();
        return inputString;
    }
}

If there is any possible improvement about:

Performance: including data reading/writing speed things

The naming and readability

Potential drawbacks of the implemented methods

, please let me know.


texts: Finding difference between adjacent integers in an array - recursive Implementation

texts:
I'm trying to do a recursive implementation of the problem mentioned below.

The code works, and takes care of a corner case with only 1 element in array (in which case I should return 0 - (element[]). Could there be improvements to this solution (like say not having to pass 4 arguments or anything like similar).

Also, I don't like that count variable because its used only for 1 purpose (finding that corner case of only 1 element in original array). How can I bypass that?

(This is not a homework problem; I'm trying to learn recursion.)

  Examples

  input Array: {1, 2, 3, 4, 5} Difference output: {1, 1, 1, 1}

  input Array: {2} Difference output: {-2}

  input Array: {2, 5, 1} Difference output: {3, -4}

void differenceSequence(int array[], int n, int count, int resultArray[]) {

if (n == 0 && count == 0) {
    /* Only 1 element in array */
    resultArray[n] = -1 * array[n];
    return;
}
if(n == 0) {
    /* second base case where size will be 0, and array recursion should end */
    return;
}
resultArray[n-1] = array[n] - array[n-1];
differenceSequence(array, n-1, ++count, resultArray);
}

int main() {

int *array = (int*) malloc (sizeof(int) * ARRAY_SIZE);
int *resultArray= (int*) malloc (sizeof(int) * ARRAY_SIZE-1);
int i = 0, size = ARRAY_SIZE;

// array = (int[ARRAY_SIZE]){5, 4, 3, -1, 0};
array = (int[ARRAY_SIZE]){1};

differenceSequence(array, ARRAY_SIZE-1, 0, resultArray);

/* Print Arrays */
printf("Original Array \n");
for (i = 0; i < size; i++) {
    printf("%d \t", array[i]);
}
printf("\n");

/* Check for result array where there is only 1 element in original
 * array
 */
if(ARRAY_SIZE == 1) {
    size = ARRAY_SIZE;
} else {
    size = ARRAY_SIZE - 1;
}

printf("Difference Array \n");
for (i = 0; i < size; i++) {
    printf("%d \t", resultArray[i]);
}
printf("\n");

return 0;
}


texts: Calculate hourly, weekly and annual wage

texts:
Currently my solution for calculating wages based on average weekly hours and any other wages field is very long and elaborate. I think it can be concised and make more readable but when I try to do it it creates some nasty bugs as it is based on field changed. Any elegant refactoring suggestion would be much appreciated!

/**
 * Executed on change of Hourly Wage.
 * Calculates monthly and annual wage based on average weekly hours and hourly wage.
 *
 * @param {object} executionContext : provided by dynamics
 * @returns {boolean} : returns true if calculation is done
 */
function onChangeHourlyWage(executionContext) {
    const formContext = executionContext.getFormContext();

    const {
        AVERAGE_WEEKLY_HOURS,
        HOURLY_WAGE,
        MONTHLY_WAGE,
        ANNUAL_WAGE
    } = EMPLOYMENT_HISTORY_FIELDS;

    const averageWeeklyHours = formContext
        .getAttribute(AVERAGE_WEEKLY_HOURS)
        .getValue();

    const hourlyWage = formContext
        .getAttribute(HOURLY_WAGE)
        .getValue();

    if (!averageWeeklyHours || !hourlyWage) return false;

    annualWage = hourlyWage * averageWeeklyHours * WEEKS_IN_A_YEAR;
    monthlyWage = annualWage / 12;

    formContext.getAttribute(ANNUAL_WAGE).setValue(annualWage);
    formContext.getAttribute(MONTHLY_WAGE).setValue(monthlyWage);

    return true;
}

/**
 * Executed on change of Monthly Wage.
 * Calculates hourly and annual wage based on average weekly hours and monthly wage.
 *
 * @param {object} executionContext : provided by dynamics
 * @returns {boolean} : returns true if calculation is done
 */
function onChangeMonthlyWage(executionContext) {
    const formContext = executionContext.getFormContext();

    const {
        AVERAGE_WEEKLY_HOURS,
        HOURLY_WAGE,
        MONTHLY_WAGE,
        ANNUAL_WAGE
    } = EMPLOYMENT_HISTORY_FIELDS;

    const averageWeeklyHours = formContext
        .getAttribute(AVERAGE_WEEKLY_HOURS)
        .getValue();

    const monthlyWage = formContext
        .getAttribute(MONTHLY_WAGE)
        .getValue();

    if (!averageWeeklyHours || !monthlyWage) return false;

    annualWage = monthlyWage * 12;
    hourlyWage = annualWage / (WEEKS_IN_A_YEAR * averageWeeklyHours);

    formContext.getAttribute(ANNUAL_WAGE).setValue(annualWage);
    formContext.getAttribute(HOURLY_WAGE).setValue(hourlyWage);

    return true;
}

/**
 * Executed on change of Annual Wage.
 * Calculates hourly and monthly wage based on average weekly hours and annual wage.
 *
 * @param {object} executionContext : provided by dynamics
 * @returns {boolean} : returns true if calculation is done
 */
function onChangeAnnualWage(executionContext) {
    const formContext = executionContext.getFormContext();

    const {
        AVERAGE_WEEKLY_HOURS,
        HOURLY_WAGE,
        MONTHLY_WAGE,
        ANNUAL_WAGE
    } = EMPLOYMENT_HISTORY_FIELDS;

    const averageWeeklyHours = formContext
        .getAttribute(AVERAGE_WEEKLY_HOURS)
        .getValue();

    const annualWage = formContext
        .getAttribute(ANNUAL_WAGE)
        .getValue();

    if (!averageWeeklyHours || !annualWage) return false;

    hourlyWage = annualWage / (WEEKS_IN_A_YEAR * averageWeeklyHours);
    monthlyWage = annualWage / 12;

    formContext.getAttribute(HOURLY_WAGE).setValue(hourlyWage);
    formContext.getAttribute(MONTHLY_WAGE).setValue(monthlyWage);

    return true;
}

/**
 * Executed on change of AverageWeeklyHours.
 * Calculates hourly, monthly and annual wage if any three of a mentioned
 * field and average weekly hours is filled.
 *
 * @param {object} executionContext : dynamics 365 execution context
 */
function onChangeAverageWeeklyHours(executionContext) {
    if (onChangeHourlyWage(executionContext)) return;
    if (onChangeMonthlyWage(executionContext)) return;
    onChangeAnnualWage(executionContext);
}


texts: Adding, subtracting, and multiplying a vector by a scalar

texts:
Exercise 2.46.

  A two-dimensional
  vector v running from the origin to a
  point can be represented as a pair
  consisting of an x-coordinate and a
  y-coordinate. Implement a data
  abstraction for vectors by giving a
  constructor make-vect and
  corresponding selectors xcor-vect and
  ycor-vect. In terms of your selectors
  and constructor, implement procedures
  add-vect, sub-vect, and scale-vect
  that perform the operations vector
  addition, vector subtraction, and
  multiplying a vector by a scalar:

  $$ (r_1, y_1) + (r_2, y_2) = (r_1 + r_2, y_1 + y_2) \\ (r_1, y_1) - (r_2, y_2) = (r_1 - r_2, y_1 - y_2) \\ s \cdot (r, y) = (sr, sy) $$

I wrote the following:

(define (make-vect xcor ycor) (cons xcor ycor))
(define xcor-vect car)
(define ycor-vect cdr)

(define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2))
                                    (+ (ycor-vect v1) (ycor-vect v2))))
(define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2))
                                    (- (ycor-vect v1) (ycor-vect v2))))
(define (scale-vect v1 s) (make-vect (* (xcor-vect v1) s)
                                     (* (ycor-vect v1) s)))

Can it be improved?


texts:
I have this messy helper method:

def gesture(klass, item, text, desc)
  element_class = klass.to_s + " gesture"
  content_tag :li do
    if klass == :sell
      link_to new_reply_path(item_id: item.id), title: desc, data: {qtip: desc}, class: element_class do
        content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
      end
    elsif klass == :alternative
      link_to new_reply_path(item_id: item.id, alternative: true), title: desc, data: {qtip: desc}, class: element_class do
        content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
      end
    elsif klass == :join
      link_to new_item_affiliation_path(item), title: desc, data: {qtip: desc}, class: element_class do
        content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
      end
    end
  end
end

As you can see, it has a lot of repetition, any idea on how I can refactor it?


texts:
This question is about swapping bytes of an uint64_t value, or in other words, about converting between endianness of an integer value:
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>

uint64_t& swapBytes1(uint64_t& num) {
    using std::swap;

    union {
        uint8_t bytes[8];
        uint64_t num;
    } transformer;

    transformer.num = num;

    swap(transformer.bytes[0], transformer.bytes[7]);
    swap(transformer.bytes[1], transformer.bytes[6]);
    swap(transformer.bytes[2], transformer.bytes[5]);
    swap(transformer.bytes[3], transformer.bytes[4]);

    return num = transformer.num;
}

uint64_t& swapBytes2(uint64_t& num) {
    using std::swap;

    union {
        struct {
            uint8_t b0;
            uint8_t b1;
            uint8_t b2;
            uint8_t b3;
            uint8_t b4;
            uint8_t b5;
            uint8_t b6;
            uint8_t b7;
        } bytes;

        uint64_t num;
    } transformer;

    transformer.num = num;

    swap(transformer.bytes.b0, transformer.bytes.b7);
    swap(transformer.bytes.b1, transformer.bytes.b6);
    swap(transformer.bytes.b2, transformer.bytes.b5);
    swap(transformer.bytes.b3, transformer.bytes.b4);

    return num = transformer.num;
}

void main() {
    uint64_t num = 0x0123456789abcdef;
    std::cout << std::hex << num << "\n";
    std::cout << swapBytes1(num) << "\n";
    swapBytes2(num);
    std::cout << num << "\n";
}

Critique request
As I am not a professional C++ developer, I would like to receive any comment/answer that could improve my C++ coding habits.


texts: Finding out the prime factors of a number

texts:
This finds the prime factors of a number given in a variable. Is it efficient or in need of improvement?

public class PrimeFactorFinder {
    public static void main(String args[]){
        long n = 18;
        long md = 2;
        while(n!=java.lang.Math.sqrt(n)){

            if(n%md==0){
                System.out.print(" "+md);
                n /= md;
            } else {
                md++;
            }
        }
    }
}


texts: Oracle query to split 1 row into two where conditions are applicable

texts:
The scenario question:

"I'm having difficulties with splitting a single row into two individual ones."

My test schema is:

CREATE TABLE T
    (id int,
     old varchar2(24),
     new varchar2(24))
;

where old and new are strings that need to be split, an example row:

  INTO T (id, old, new)
     VALUES (14, 'L-D / T-E', 'L-E / T-E')
  INTO T (id, old, new)
     VALUES (14, 'L-D / T-E', 'L-D / T-D')
  INTO T (id, old, new)
     VALUES (12, 'L-D / T-E', 'L-E / T-D')

In this example 'L' has changed in row 1, 'T' has changed in row 2 and both have changed in row 3.

The table is:

ID    OLD         NEW
14    L-D / T-E   L-E / T-E
14    L-D / T-E   L-D / T-D
12    L-D / T-E   L-E / T-D

I'm trying to split these so that the resulting table will have individual rows for each significant change such that the result will look like:

ID  OLD     NEW
1   L-D     L-E  //for existing row 1
2   T-E     T-D  //for existing row 2
//then two rows for existing row 3
3   L-D     L-E
4   T-E     T-D

Once these rows have been inserted, I'd then like to delete the existing rows.

My solution looks like:

    drop table t;
CREATE TABLE T
    (id int,
   key int,
  old varchar2(24),
  new varchar2(24))
;
INSERT ALL
      INTO T (id, key, old, new)
         VALUES (12, 638, 'L-D / T-E', 'L-E / T-E')
      INTO T (id, key, old, new)
         VALUES (13, 638, 'L-D / T-E', 'L-D / T-D')
      INTO T (id, key ,old, new)
         VALUES (14, 638, 'L-D / T-E', 'L-E / T-D')
SELECT * FROM dual;
SELECT * FROM T;
--insert into t (id, old, new) values (1,'dasdsad', 'asdasd');

BEGIN
  INSERT INTO t (id, key, old, new)
      WITH DATA AS
      (SELECT id, old, new
      FROM t
      WHERE
      --1 change in t
      ((SUBSTR(OLD,3,1) = SUBSTR(NEW, 3,1)
        AND SUBSTR(OLD, 9) <> SUBSTR(NEW, 9)
        )) )--end select,
    SELECT id, 646, substr(old, 7, 9) old,
               substr(new, 7, 9) new

    FROM DATA
      CONNECT BY  level = 1;

    INSERT INTO t (id, key, old, new)
      WITH DATA AS
      (SELECT id,OLD, new
      FROM t
      WHERE
      --1 change in t
      ((SUBSTR(OLD,3,1) <> SUBSTR(NEW, 3,1)
        AND SUBSTR(OLD, 9) = SUBSTR(NEW, 9)
        )) )--end select,
    SELECT id, 645, substr(old, 1, 3) old,
               substr(new, 1, 3) new

    FROM DATA
      CONNECT BY  level = 1;

    INSERT INTO t (id,key,old, new)
      WITH DATA AS
      (SELECT id,OLD, new
      FROM t
      WHERE
      --BOLLOX, need two keys, one for each row.
      ((SUBSTR(OLD,3,1) <> SUBSTR(NEW, 3,1)
        AND SUBSTR(OLD, 9) <> SUBSTR(NEW, 9)
        )) )--end select,
    SELECT id,
          (644+level), --will result in 645 and 646 --needs testing
          trim(regexp_substr(OLD, '[^/]+', 1, LEVEL)) OLD,
          trim(regexp_substr(NEW, '[^/]+', 1, LEVEL)) NEW
    FROM DATA
      CONNECT BY (LEVEL <= regexp_count(new, '/')+1);

      delete from t where key = 638;
END;
 /

It's not very elegant, so any advice, critique and suggestions are welcome.


texts: Shell script to create a boilerplate proyect

texts:
This is actually my first shell script and just by looking at it I know this can look better. I use Elixir and Phoenix for most of my projects and I started using Zurb Foundation 6, changing from Bootstrap to Foundation is kinda tiresome sometimes so I decided to make a script to automate this process.

This is the script

#!/bin/sh

JAVI_PATH="$HOME/.javi"

name=${1}
path=${2}
rest=${@:3}

### Funcs
get_files() {
  cd ${name}/assets

  echo "Installing extra dependencies"
  npm install --save jquery sass-brunch foundation-sites normalize-scss

  echo "Getting files to replace"

  get_brunch
  get_scss

  cd ../..

  echo "Got and replaced files on 'assets' folder"

  # Replaces content from 'app.html.eex' file
  get_apphtml
}

get_brunch() {
  rm -rf brunch-config.js && \
  wget https://raw.githubusercontent.com/aguxez/javi/master/brunch-config.js
}

get_scss() {
  cd css && \
  rm -rf app.css phoenix.css && \
  wget https://raw.githubusercontent.com/aguxez/javi/master/app.scss
}

get_apphtml() {
  cd lib/${name}_web/templates/layout && \
  rm -rf app.html.eex && \
  wget https://raw.githubusercontent.com/aguxez/javi/master/app.html.eex

  # Here we replace the title with the 'name' variable
  uppercased_name=`sed -e "s/\b\(.\)/\u\1/g" <<< "${name}"`
  eval sed -i -e 's/CHANGE_TITLE/${uppercased_name}/g' app.html.eex
}

## If installing
INSTALL=0
if [ "$1" = "install" ] ; then
  INSTALL=1
fi

if [ "$INSTALL" = 1 ] ; then
  if [ ! -d "$JAVI_PATH" ] ; then
    mkdir $JAVI_PATH && \
    curl -sSL https://raw.githubusercontent.com/aguxez/javi/master/javi > $JAVI_PATH/javi && \
    chmod +x $JAVI_PATH/javi

    echo "Javi has been configured"
  fi
elif [ -z "${name}" ]; then
  echo "Please give a name to your project"
elif [[ -d ${path} ]]; then
  echo "Creating project in ${path}"
  cd ${path}
  mix phx.new ${name} ${rest}
  # Runs function
  get_files
else
  mix phx.new ${name} ${rest}
  # Function
  get_files
fi

Maybe I could think of a better way of handling arguments here

if [ "$INSTALL" = 1 ] ; then
  if [ ! -d "$JAVI_PATH" ] ; then
    mkdir $JAVI_PATH && \
    curl -sSL https://raw.githubusercontent.com/aguxez/javi/master/javi > $JAVI_PATH/javi && \
      chmod +x $JAVI_PATH/javi

    echo "Javi has been configured"
  fi
elif [ -z "${name}" ]; then
  echo "Please give a name to your project"
elif [[ -d ${path} ]]; then
  echo "Creating project in ${path}"
  cd ${path}
  mix phx.new ${name} ${rest}
  # Runs function
  get_files
else
  mix phx.new ${name} ${rest}
  # Function
  get_files
fi

But I'm not sure what I can change or HOW can I change it.


texts: Detect objects that the mouse is close to

texts:
Here is a little widget that I've made. I'm looking to refactor the way that I'm doing hit detection. Currently, every square on the screen finds the distance between itself and the cursor.

Because there are quite a few of these squares, and that they are all being rendered 60 times per second. It's quite inefficient.

The squares are all stored in a 2D array where squares2d represents rows, and squares2d[0 -> squares2d.length - 1] represents columns. Because the spacing between the squares is a constant 25px, I'm thinking that there is a better way that I can find what the mouse is close to. Maybe something like spatial partitioning?

It performs pretty well, anyways. But for the sake of writing good code, I'm looking for advice.

class Square {
    constructor(x, y, size, xpos, ypos) {
      this.x = x;
      this.y = y;
      this.size = size;
      this.sr = 0;
      this.color = '#222222';
      this.forward = true;
      this.xpos = xpos;
      this.ypos = ypos;
      this.maxSize = 15;
    }

    getDistance() {
      const xMid = this.x + this.size / 2;
      const yMid = this.y + this.size / 2;

      return Math.sqrt( (( mouseX - xMid ) ** 2) +
                        (( mouseY - yMid ) ** 2) );
    }

    draw () {
      ctx.fillStyle = this.color;
      const dist = this.getDistance();

      if (dist / 2 < this.maxSize - 5 && mousein) {
        this.size = dist / 2;
        this.sr = 5; // initial energy to start waves
      } else {
        /* irrelivant */
      }
      ctx.fillRect(this.x - this.size / 2, this.y - this.size / 2, this.size, this.size);
    }
  }

  function draw() {
    stats.begin();
    ctx.fillStyle = '#fb933b';
    ctx.fillRect(0, 0, w, h);

    if (update) { // resizing and resetting
      /* also irrelivant */
    }

    for (let i = 0; i < squares2d.length; i++) {
      for (let j = 0; j < squares2d[i].length; j++) {
        squares2d[i][j].findShrinkRate();
        squares2d[i][j].draw(); // here's the kicker
      }
    }
    stats.end();
  }

  // this sets the framerate (60fps);
  thread = setInterval(draw, 1000 / 60);


texts: Command Pattern with Undo , returning response in Invoker and Command class or Callback?

texts:
I have used command pattern with undo support. The terms associated with Command Pattern are as follows

Client → Invoker → Command instance execute() → Receiver

so the client will need to know whether the operation was successfully so that it can decide whether to undo.

In my example, Receiver talks to the Volt DB using some APIs, so there are predefined response classes with result code and result message.

It would be bad if I sent those all the way to the client.

Having Invoker and Command to return boolean indicating success or failure feels better. I have seen an example where they use callbacks. Is this something only for asynchronous operations or I can also use it here? Which would be better?

Snippets of the code are below; full code is available on GitHub.

Invoker class

package com.spakai.undoredo;

import java.util.Stack;

public class Invoker {

    private final Stack<Command> undoStack;
    private final Stack<Command> redoStack;

    public Invoker() {
        undoStack = new Stack<>();
        redoStack = new Stack<>();
    }

    public void execute(Command cmd) {
        undoStack.push(cmd);
        redoStack.clear();
        cmd.execute();
    }

    public void undo() {
        if (!undoStack.isEmpty()) {
            Command cmd = undoStack.pop();
            cmd.undo();
            redoStack.push(cmd);
        }
    }

    public void redo() {
        Command cmd = redoStack.pop();
        cmd.execute();
        undoStack.push(cmd);

    }
}

Receiver interface

package com.spakai.undoredo;

public interface Receiver {
    public CreateGroupResponse createGroup(int groupId, int subscriptionId);
    public DeleteGroupResponse deleteGroup(int groupId);
    //many more
}

Command interface

package com.spakai.undoredo;

public interface Command {
    public void execute();
    public void undo();
    public void redo();
}

Sample Command instance

package com.spakai.undoredo;

public class CreateGroupAndSubscription implements Command {

    // which states do i need to store in order to execute and undo
    private int groupId;
    private int subscriptionId;

    // this is the Volt handle apis that talks to VoltDB
    private Receiver receiver;

    public CreateGroupAndSubscription(int groupId, int subscriptionId, Receiver receiver) {
        this.groupId = groupId;
        this.subscriptionId = subscriptionId;
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        CreateGroupResponse response = receiver.createGroup(groupId,subscriptionId);
    }

    @Override
    public void undo() {
        DeleteGroupResponse response = receiver.deleteGroup(groupId);
    }

    @Override
    public void redo() {
        execute();
    }
}

Any other suggestions on the whole code are most welcomed.


texts: Method that reserves a reservable entity and charges the user

texts:
This method works for what I need it to do, but I just don't think it's extremely readable, and could be abstracted into different methods. I have a feeling I'm going against some best practices. Please let me know your suggestions:

  def reserve
  return render json: { error: "This entity is not available to reserve" }, status: :forbidden if @reservable.status != Reservable::STATUS[:available]
  Reservable.transaction do
    @reservable.status = Reservable::STATUS[:reserved]
    @reservable.current_use = Use.create(
      user_id: @user.id,
      reservable_id: @reservable.id,
      start_location: @reservable.location,
      start_time: DateTime.now,
      status: Use::STATUS[:progress])
    # Check payment
    payment_type = params[:payment_type]
    if payment_type === Transaction::METHODS[:subscription]
      # put subscription logic here
    else
      return render json: { error: @user.errors }, status: :payment_required, location: new_payment_path unless @user.validates_has_payment_and_good_standing
      if payment_type === Transaction::METHODS[:prepay]
        @reservable.current_ride.trans = Transaction.charge_user_for_use(@user, @reservable.current_use, payment_type)
      else # :per_minute
        # put pay_per_minute logic here
      end
    end
    @reservable.save!
  rescue ActiveRecord::RecordInvalid => exception
    render :json => { :error => exception.messages }, status: :unprocessable_entity
    raise ActiveRecord::Rollback #force a rollback
  end
end


texts: Naïve optimization by stepping until the error falls below a threshold

texts:
As an exercise, I wanted to rewrite this toy Python code in Haskell:

def f(x):
    return abs(42-x)**2

def improve(x):
    newX = x + 0.1
    return newX, f(newX)

def optimize(f, goal):
    x = 0
    err = f(x)
    while not err < goal:
        x, err = improve(x)
    return x, err

print(optimize(f, 0.5))

Ideone

My solution works but is quite ugly:

f :: (Num a) => a -> a
f x = abs(42-x)^2

improve :: (Fractional a) => (a -> b) -> a -> (a, b)
improve f x =
    let newX = x+0.1
    in (newX, f newX)

step :: (Fractional a, Ord b) => (a -> b) -> b -> a -> (a, b)
step f goal x =
    let
        newX = x+0.1
        err = f newX
    in
        if err < goal then (newX, err) else step f goal newX

optimize :: (Fractional a, Ord b) => (a -> b) -> b -> (a, b)
optimize f goal = step f goal 0

main :: IO ()
main = print $ optimize f 0.5

Ideone

I am trying to find a solution without explicit recursion using a fold or something, but did not have an idea yet on how to do it. Can anybody help me out?


texts:
data = ['HTTP/1.1 200 OK', 'CACHE-CONTROL: max-age=1810', 'DATE: Wed, 14 May 2014 12:15:19 GMT', 'EXT:', 'LOCATION: http://192.168.94.57:9000/DeviceDescription.xml', 'SERVER: Windows NT/5.0, UPnP/1.0, pvConnect UPnP SDK/1.0', 'ST: uuid:7076436f-6e65-1063-8074-78542e239ff5', 'USN: uuid:7076436f-6e65-1063-8074-78542e239ff5', 'Content-Length: 0', '', '']

From the above list, I have to extract the .xml link.

My code:

for element in data:
    if 'LOCATION' in element:
        xmllink = element.split(': ').[1]

It's taking too much time.  How can I make this faster?

Actually I am doing SSDP discovery for finding devices in a network.  After sending the M-SEARCH command, devices send a datagram packet which I have taken in a data variable.  From this I have to extract the file link of that device for processing it.

When I use indexing to extract, it was done quickly.


texts:
I was solving this problem at Pramp and I have trouble figuring out the algorithm for this problem. I'll paste the problem description and how I kind of solved it. It's the correct solution.  It is similar to the edit distance algorithm and I used the same approach.  I just wanted to see what are other ways to solve this problem.

  The deletion distance of two strings is the minimum number of characters you need to delete in the two strings in order to get the same string. For instance, the deletion distance between "heat" and "hit" is 3:

  By deleting 'e' and 'a' in "heat", and 'i' in "hit", we get the string "ht" in both cases.
  We cannot get the same string from both strings by deleting 2 letters or fewer.
  Given the strings str1 and str2, write an efficient function deletionDistance that returns the deletion distance between them. Explain how your function works, and analyze its time and space complexities.

  Examples:
  input:  str1 = "dog", str2 = "frog"
  output: 3
  input:  str1 = "some", str2 = "some"
  output: 0
  input:  str1 = "some", str2 = "thing"
  output: 9
  input:  str1 = "", str2 = ""
  output: 0

What I want to do in this solution, is to use dynamic programming in order to build a function that calculates opt(str1Len, str2Len). Notice the following:
I use dynamic programming methods to calculate opt(str1Len, str2Len), i.e. the deletion distance for the two strings, by calculating opt(i,j) for all 0 ≤ i ≤ str1Len, 0 ≤ j ≤ str2Len, and saving previous values

  def deletion_distance(s1, s2):
    m = [[0 for j in range(len(s2) +1)] for i in range(len(s1)+1)]
    for i in range(len(s1)+1):
      for j in range(len(s2)+1):
        if i == 0:
          m[i][j] = j
        elif j == 0:
          m[i][j] = i
        elif s1[i-1] == s2[j-1]:
          m[i][j] = m[i-1][j-1]
        else:
          m[i][j] = 1 + min(m[i-1][j], m[i][j-1])
    return m[len(s1)][len(s2)]


texts:
-ish because I removed the input functionality from the compiler. And, the compiler does not support nested loops

I've been recently reading up on compilers and how they work. Although this doesn't use most of the things I've learned about (the lexical and parser things), I thought it would be fun to try create a brainf*ck compiler, rather than an interpreter.

bfc.c

#include <stdio.h>

static int i;
static char *code; // these two as static so get_amt_to_change can easily interact

int get_amt_to_change(char c); // so the compiler doesn't write (ie) add di, 1 ten times

int main(int argc, char **argv) {
    code = argv[1];
    puts("xor di, di\n"
         "setup_loop:\n"
         "mov byte [tape + di], 0\n"
         "add di, 1\n"
         "cmp di, 101\n"
         "jne setup_loop\n"
         "xor di, di"); // sets up the tape with all 0's
    int loop_count = 0; // to keep track of asm subroutines for [ and ]
    for(i = 0; code[i] != '\0'; i++) {
        switch(code[i]) {
            case '+':
                printf("add byte [tape + di], %d\n", get_amt_to_change('+'));
                break;
            case '-':
                printf("sub byte [tape + di], %d\n", get_amt_to_change('-'));
                break;
            case '>':
                printf("add di, %d\n", get_amt_to_change('>'));
                break;
            case '<':
                printf("sub di, %d\n", get_amt_to_change('<'));
                break;
            case '.':
                puts("mov ah, 0Eh\n"
                     "mov al, byte [tape +di]\n"
                     "int 10h");
                break;
            case '[':
                printf("cmp byte [tape + di], 0\n"
                       "je end_loop%d\n"
                       "start_loop%d:\n", loop_count, loop_count);
                break;
            case ']':
                printf("cmp byte [tape + di], 0\n"
                       "jne start_loop%d\n"
                       "end_loop%d:\n", loop_count, loop_count);
                loop_count++; // to not repeat subroutine names
                break;
        }
    }
    puts("jmp $\nsection .bss\ntape resb 100"); // a 100 byte tape
    return 0;
}

int get_amt_to_change(char c) {
    int amt;
    for(amt = 0; code[i] == c; amt++, i++);
    i--; // if it wasn't == c, then go back one character and find out what it was equal to in the next call
    return amt;
}

The above code reads Brainf*ck code passed via command line argument and produces an assembly code, which could then be passed into the NASM assembler.

Examples

Purpose: nothing. brainf*ck doesn't have a purpose logs 'd' to output

Brainf*ck

Note: the backslashes are there so the terminal doesn't read the < and > symbols as it normally would.

\>++++++++++[\<++++++++++\>-]\<.

Assembly

xor di, di
setup_loop:
mov byte [tape + di], 0
add di, 1
cmp di, 101
jne setup_loop
xor di, di
add di, 1
add byte [tape + di], 10
cmp byte [tape + di], 0
je end_loop0
start_loop0:
sub di, 1
add byte [tape + di], 10
add di, 1
sub byte [tape + di], 1
cmp byte [tape + di], 0
jne start_loop0
end_loop0:
sub di, 1
mov ah, 0Eh
mov al, byte [tape +di]
int 10h
jmp $
section .bss
tape resb 100

Purpose: to show the generated assembly code for each of the symbols

Brainf*ck

++--\>\>\<\<.,[]

Assembly

xor di, di
setup_loop:
mov byte [tape + di], 0
add di, 1
cmp di, 101
jne setup_loop
xor di, di
add byte [tape + di], 2
sub byte [tape + di], 2
add di, 2
sub di, 2
mov ah, 0Eh
mov al, byte [tape +di]
int 10h
cmp byte [tape + di], 0
je end_loop0
start_loop0:
cmp byte [tape + di], 0
jne start_loop0
end_loop0:
jmp $
section .bss
tape resb 100

Questions

My C code only has one subroutine. Are there any other logical ones to add?
I did a lot of optimizing on the assembly code output. Could it be further optimized?
My main problem with compilers I've written in the past is that I've over-complicated things. Is that an issue with this (C) code?


texts: Test that all Python keywords are mentioned in a dictionary's values

texts:
I have a dict of categories of Python keywords, with lists of keywords as the values:

Keywords_33=[('File_2', ['with', 'as']),
             ('Module_2', ['from', 'import']),
             ('Constant_3', {'bool': ['False', 'True'],
                             'none': ['None']}),
             ('Operator_4', {'boolean_operation': {'or', 'and', 'not'},
                             'comparison': {'is'}}),
             ('Container_operation_2', ['in', 'del']),
             ('Klass_1', ['class']),
             ('Function_7',['lambda', 'def', 'pass',
                            'global', 'nonlocal',
                            'return', 'yield']),
             ('Repetition_4', ['while', 'for', 'continue', 'break']),
             ('Condition_3', ['if', 'elif', 'else']),
             ('Debug_2', ['assert', 'raise']),
             ('Exception_3', ['try', 'except', 'finally'])]

I want to ensure that every keyword is in a category.  This code does that:

from keyword import kwlist
s = str(Keywords_33)
intersection_with_kwlist = [keyword for keyword in kwlist if keyword not in s]
print(intersection_with_kwlist)

Expected (and actual) output:

[]

This indicates that no keywords are missing from Keywords_33.

Can I make this code more elegant?


texts: Identifying local peaks among some 2D points

texts:
The following MATLAB code takes in multiple peak coordinates and heights and eliminates lesser peaks that are within a certain distance threshold of the highest peak of the vicinity. Is there a better way to implement this code? Does a more efficient algorithm exist?
Code
function [ the_peaks,idx_list ] = max_peaks( peak_list, vicinity_threshold )
%MAX_PEAKS(peak_list, vicinity_threshold) returns the highest peaks within
%the vicinity specified by the vicinity_threshold.
%
%   peak_list is an array with rows defined by [x,y, amplitude]
%
%   vicinity_threshold is the distance within which all lesser peaks are
%   killed.
[sorted_peaks,orig_idx]=sortrows(peak_list,3,'desc');
the_peaks=zeros(size(sorted_peaks));     % Preallocate
idx_list=zeros(length(sorted_peaks),1);
peak_idx=1;
while(~isempty(sorted_peaks))
    the_peaks(peak_idx,:)=sorted_peaks(1,:);     %The greatest peak.
    idx_list(peak_idx)=orig_idx(1);
    peak_idx=peak_idx+1;
    D=pdist2(sorted_peaks(1:end,1:2),sorted_peaks(1,1:2));     %Distance to other peaks
    np=D<vicinity_threshold;     % Peaks in the vicinity
    sorted_peaks(np,:)=[];     % Kill peaks in the vicinity
    orig_idx(np)=[];
end
idx_list(~any(the_peaks,2),:)=[];     % clear preallocated extras
the_peaks(~any(the_peaks,2),:)=[];
end

example
test_peaks=[1,1,0.5; 5,5,0.9; 5,1,0.6; 300,300,0.2; 303,303,0.7; 1,100,0.9; 1,104,0.95; 1,250,.7; 1,200,.75];
mP=max_peaks(test_peaks,10)
scatter (test_peaks(:,1),test_peaks(:,2),'o');
hold on
scatter (mP(:,1),mP(:,2),'*');