texts: Refactoring the Go HTTP API code/flow/structure

texts:
This app loads application specific global configs and starts http server so that it is ready to serve API requests.

While structuring and coding, I've followed some "best" practises either from the official docs, widely followed resources and some others. Given that the app below works, I have a feeling that it could be improved hence reason I am asking questions below. My aim is to make it more of a Go-like app than my own invention with bad practises. Just a side note, I've cut things sorter to keep the post short but if you want to see full picture this is the GitHub page.

Is the way I am bootstraping the app correct? The main.go prepares things and passes to api.go who starts the server so main.go is responsible for bootstraping things and api.go starts things.
The config.go has global vars but I am not directly accessing them in where they are needed. Instead, I am injecting them to functions that depend on them. Am I currently over engineering it or is it ok?
Shall I create/bootstrap http.handler with New() in main.go and inject into app.go as I do for the config? Or is it fine to keep it as is just because both server.go and handler.go files are under same directory?

.
├── bin
│   └── api
├── cmd
│   └── api
│       └── main.go
└── internal
    ├── app
    │   └── api.go
    ├── config
    │   └── config.go
    ├── controller
    │   └── index
    └── http
        ├── handler.go
        └── server.go

cmd/api/main.go

# This is also boots logger but removed to keep it short for now
package main

import (
    "github.com/myself/api/internal/app"
    "github.com/myself/api/internal/config"
)

func main() {
    config.Load()

    app.Run(config.Srv.Address)
}

internal/config/config.go

# This has more stuff in it
package config

import "sync"

var (
    App application
    Srv server
    o sync.Once
)

type application struct {
    Env string
}

type server struct {
    Address string
}

func Load() {
    o.Do(func() {
        App = application{Env:"dev"}
        Srv = server{Address:"0.0.0.0:8080"}
    })
}

internal/app/api.go

# This is as simple as this
package app

import "github.com/myself/api/internal/http"

func Run(addr string) {
    http.Start(addr)
}

internal/http/server.go

# This actually handles signals and shutdown
package http

import (
    "log"
    "net/http"
)

func Start(addr string) {
    if err := http.ListenAndServe(addr, handler()); err != nil {
        log.Fatalf("couldn't start http server")
    }
}

internal/http/handler.go

# This has little bit stuff in it
package http

import (
    "github.com/myself/api/internal/controller/index"
    "github.com/julienschmidt/httprouter"
)

func handler() *httprouter.Router {
    rtr := httprouter.New()
    rtr.GET("/", index.Index)

    return rtr
}

internal/controller/index/index.go

package index

import (
    "github.com/julienschmidt/httprouter"
    "net/http"
)

func Index(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
}


texts: Insert and attach tag to the post in same time

texts:
I created a form with title, body and tag input and there are 3 tables: posts, tags and post_tag.

Now I use this function to add new tags and attach them to the post

postcontroller.php

 public function store(Request $request)
    {
        $input = $request->all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=>$tag]);
        $tagid = $tagdone->id; //insert tag to tags table

        $posts = Posts::create($input); //insert posts table
        $postid = $posts->id;

        Posts::find($postid)->tags()->attach($tagid); //attach tag to the post
    }

There are actually 3 actions at the same time. But I think there are better ways than this one, so I'd like some feedback on what I've written.


texts: Breaking a 32-bit value into bytes for an ArrayList

texts:
I am very new to Java and its collections and I'm trying to figure out "best" way to populate an ArrayList<Byte> in Java.  In particular, I'm trying to take a 32 bit number, divide it into bytes, and put it into big-endian order into the list.  I'm not particularly interested in hyper-optimizing in this case; I'd rather the code be clean and readable.

I've got a couple issues that are obvious to me, but the biggest one is that I hate the fact that I am initializing the list with bogus values before I update them.  But my choices seem to be that, or adding the elements in ascending order, which seems to make the code to extract the bytes significantly more complex.

Am I missing a better solution?

public void Add32BitValue(int value) {
    // Adding 4 elements first to the list, so that
    // I can modify them so they'll be in big endian
    // order.
    // (The code to directly add them in big endian
    // order seems much more complex.)
    for (int i=0; i<4; i++) {
        list.add((byte)0);
    }

    // Now that the elements are in the arraylist, they
    // can be set.
    for (int i = 3; i >= 0; i--) {
        list.set(list.size() + i - 4, (byte)value);
        value = value >> 8;
    }
}


texts: Setting manager class for reading and managing Settings.ini file of my program

texts:
Setting manager class for reading and managing Settings.ini file
I have started a project creating Software Installer application for auto download and auto install software, similar how Ninite works. I have created SettingsManager.java class for reading and managing Settings.ini file of the program so the rest of the program can use it. This is just a draft of the class an it is not complete, but it is functional. I would like your opinions on the overall design and implementation of this kind of class.
The SettingsManager.java class
package com.zoran_jankov.software_installer.app;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.ini4j.Ini;

public class SettingsManager
{
    private static SettingsManager instance;

    private static final String SETTINGS_FILE_PATH = "D:/Programing/Java/Software Installer/src/main/resources/Settings.ini";

    private Map<Software, String> localRepositories = new HashMap<Software, String>();
    private Map<Software, String> networkRepositories = new HashMap<Software, String>();
    private Map<Software, String> onlineRepositories = new HashMap<Software, String>();
    private Map<Software, String> arguments = new HashMap<Software, String>();

    private SettingsManager()
    {
        loadSettings();
    }

    public static SettingsManager getInstance()
    {
        if(instance == null)
        {
            instance = new SettingsManager();
        }
        return instance;
    }

    public void loadSettings()
    {
        Ini settings = null;

        try
        {
            settings = new Ini(new File(SETTINGS_FILE_PATH));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        localRepositories = getInstallerSettings(settings, "Local Repositories");

        networkRepositories = getInstallerSettings(settings, "Network Repositories");

        onlineRepositories = getInstallerSettings(settings, "Online Repositories");

        arguments = getInstallerSettings(settings, "Arguments");

    }

    private Map<Software, String> getInstallerSettings(Ini setttings, String sectionName)
    {
        Map<Software, String> list = new HashMap<Software, String>();

        for (Software installer : Software.values())
        {
            list.put(installer, setttings.get(sectionName, installer.name()));
        }

        return list;
    }

    public String getLocalRepository(Software software)
    {
        return localRepositories.get(software);
    }

    public String getNetworkRepository(Software software)
    {
        return networkRepositories.get(software);
    }

    public String getOnlineRepository(Software software)
    {
        return onlineRepositories.get(software);
    }

    public String getArguments(Software software)
    {
        return arguments.get(software);
    }
}

The Software.java enum
package com.zoran_jankov.software_installer.app;
public enum Software
{
    AIMP,
    CCleaner,
    DWGSee,
    Firefox,
    FoxitReader,
    ImgBurn,
    Java,
    LibreOffice,
    Notepad,
    Office365,
    OpenOffice,
    RocketChat,
    Skype,
    SpacePlanning,
    Speccy,
    Thunderbird,
    UltraVNC,
    VLC,
    ZabbixAgent,
    Zip;
}

The Settings.ini file
So you can better understand what is happening in the code.


texts:
I want to know if there is any other better way to write this algorithm. What other data structures could be used to make it more simple and effective?

public class BubbleSort {

        public static void bubbleSort(int array[]) {
            int n = array.length;
            int k;
            for (int m = n; m >= 0; m--) {
                for (int i = 0; i < n - 1; i++) {
                    k = i + 1;
                    if (array[i] > array[k]) {
                        swapNumbers(i, k, array);
                    }
                }
                printNumbers(array);
            }
        }

        private static void swapNumbers(int i, int j, int[] array) {

            int temp;
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }

        private static void printNumbers(int[] input) {

            for (int i = 0; i < input.length; i++) {
                System.out.print(input[i] + ", ");
            }
            System.out.println("\n");
        }

        public static void main(String[] args) {
            int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
            bubbleSort(input);

        }
    }

Output:

    2, 4, 6, 9, 12, 23, 0, 1, 34,
    2, 4, 6, 9, 12, 0, 1, 23, 34,
    2, 4, 6, 9, 0, 1, 12, 23, 34,
    2, 4, 6, 0, 1, 9, 12, 23, 34,
    2, 4, 0, 1, 6, 9, 12, 23, 34,
    2, 0, 1, 4, 6, 9, 12, 23, 34,
    0, 1, 2, 4, 6, 9, 12, 23, 34,
    0, 1, 2, 4, 6, 9, 12, 23, 34,
    0, 1, 2, 4, 6, 9, 12, 23, 34,
    0, 1, 2, 4, 6, 9, 12, 23, 34


texts:
Please review my implementation of the Minesweeper game Kata. Any and all feedback will be much appreciated. I would love to hear your feedback on readability, simplicity, performance, and any code smells. I even welcome nitpicking. Overall I want to know is the code clean (I know there is always room for improvement).

The rules of the application can be found here: Minesweeper. I have modified it a bit I'm not reading from a file.

public class MineSweeper {
    public char[][] getSweptMatrix(char[][] matrix) {
        if(matrix == null) throw new IllegalArgumentException();
        buildSweepMatrix(matrix);
        return matrix;
    }

    private void buildSweepMatrix(char[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                int count = checkAdjacentsForBombs(matrix, i, j);
                if (matrix[i][j] != '*') matrix[i][j] = (char) (count + '0');
            }
        }
    }

    private int checkAdjacentsForBombs(char[][] matrix, int i, int j) {
        int count = 0;
        count += checkNorthForBomb(matrix, i, j);
        count += checkNorthEastForBomb(matrix, i, j);
        count += checkEastForBomb(matrix, i, j);
        count += checkSouthEastForBomb(matrix, i, j);
        count += checkSouthForBomb(matrix, i, j);
        count += checkSouthWestForBomb(matrix, i, j);
        count += checkWestForBomb(matrix, i, j);
        count += checkNorthWestForBomb(matrix, i, j);
        return count;
    }

    private int checkNorthForBomb(char[][] matrix, int i, int j) {
        return i - 1 >= 0 && matrix[i - 1][j] == '*' ? 1 : 0;
    }

    private int checkNorthEastForBomb(char[][] matrix, int i, int j) {
        return j + 1 < matrix[0].length && i - 1 >= 0 && matrix[i - 1][j + 1] == '*' ? 1 : 0;
    }

    private int checkEastForBomb(char[][] matrix, int i, int j) {
        return j + 1 < matrix[0].length && matrix[i][j + 1] == '*' ? 1 : 0;
    }

    private int checkSouthEastForBomb(char[][] matrix, int i, int j) {
        return j + 1 < matrix[0].length && i + 1 < matrix.length && matrix[i + 1][j + 1] == '*' ? 1 : 0;
    }

    private int checkSouthForBomb(char[][] matrix, int i, int j) {
        return i + 1 < matrix.length && matrix[i + 1][j] == '*' ? 1 : 0;
    }

    private int checkSouthWestForBomb(char[][] matrix, int i, int j) {
        return j - 1 >= 0 && i + 1 < matrix.length && matrix[i + 1][j - 1] == '*' ? 1 : 0;
    }

    private int checkWestForBomb(char[][] matrix, int i, int j) {
        return j - 1 >= 0 && matrix[i][j - 1] == '*' ? 1 : 0;
    }

    private int checkNorthWestForBomb(char[][] matrix, int i, int j) {
        return j - 1 >= 0 && i - 1 >= 0 && matrix[i - 1][j - 1] == '*' ? 1 : 0;
    }


texts: Non-sequential template class container C++

texts:
I'm pretty new to templates, and admittedly I'm not particularly good at C++, but I've written a little container that does not move allocated objects once they are created, so you can use weak pointers to access elements, and be aware of their existence. I'm sure that much of it can\should be improved, but I lack the experience to know what exactly. Thoughts and critique are welcome.

#include <memory>
#include <vector>
#include <iostream>

class NSC_OOR_ERR : public std::exception
{
    virtual const char* what() const throw()
    {
         return "NSContainer access out of range";
    }
};

class NSC_BA_ERR : public std::exception
{
    virtual const char* what() const throw()
    {
        return "NSContainer out of memory";
    }
};

template<typename A_Type>
class CNSContainer
{
    NSC_OOR_ERR NSC_OOR_m;
    NSC_BA_ERR NSC_BA_m;
    std::vector<std::shared_ptr<A_Type>> pointers_m;
public:
    size_t size()
    {
        return pointers_m.size();
    }

    template <class... Args>
    std::weak_ptr<A_Type> push(Args&&... args)
    {
        try {
            std::shared_ptr<A_Type> ptr(new A_Type(std::forward<Args>(args)...));
        }
        catch (std::bad_alloc& ba) {
            throw NSC_BA_m;
        }
        pointers_m.emplace_back(ptr);
        return ptr;
    }

    void remove(const size_t& key)
    {
        pointers_m.erase(pointers_m.begin() + key);
    }

    std::weak_ptr<A_Type> operator[](const size_t& key)
    {
        try {
            return pointers_m[key];
        }
        catch (const std::out_of_range& oor) {
            throw NSC_OOR_m;
        }
    }
};

int Test()
{
    CNSContainer<int> container;

    //push into container
    container.push(1);
    container.push(2);
    container.push(3);
    container.push(4);

    //get size
    size_t container_size = container.size();

    //iterate
    for (size_t i = 0; i < container_size; ++i)
    {
        std::weak_ptr<int> wptr = container[i];

        if (!wptr.expired())
        {
            auto sptr = wptr.lock();
            int value = *sptr;
            std::cout << "Value is " << value;
        }
    }

    /*take element pointer to do something with it later.
    Maybe in another thread*/
    std::weak_ptr<int> wptr = container[0];

    /*the pointer now points to nothing*/
    container.remove(0);

    /*but we know that, because it's expired*/
    if (!wptr.expired())
    {
        //do stuff
    }

    return 0;
}


texts:
In need for testing if a string is a number which could be a double or integer, I wrote a simple skeleton, which parses a string like this:

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

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

char* to_convert = argv[1];
char* p = NULL;
errno = 0;
long val = strtol(argv[1], &p, 0);

if (errno != 0)
return 1;// conversion failed (EINVAL, ERANGE)

if (to_convert == p){
// conversion to int failed (no characters consumed)
double val2 = strtod(p, &p);
if (*p){
printf("Not a number!\n");
return 1;
}
printf("Double %lf\n" , val2);
return 0;
}

if (*p != 0){
// conversion to int failed (trailing data)
double val2 = strtod(argv[1], &p);
if (*p){
printf("Not a number!\n");
return 1;
}
printf("Double %lf\n" , val2);
return 0;
}

printf("Int %ld\n" , val);
return 0;
}

/*
$ ./a.out 123
Int 123
$ ./a.out -123
Int -123
$ ./a.out 31.1
Double 31.100000
$ ./a.out -231
Int -231
$ ./a.out NaN
Double nan
$ ./a.out -Nan
Double nan
$ ./a.out -INF
Double -inf
$ ./a.out INF
Double inf
$ ./a.out 12.3
Double 12.300000
$ ./a.out -12,3  # Although some european localels (like German, would consider this a number)
Not a number!
$ ./a.out -12.3
Double -12.300000
$ ./a.out foo
Not a number!
*/

I would like to know if this could be done better, without iterating on all the characters like here.

Is there any case I didn't think of which breaks this code?
or causes undefined behaviour (except numbers larger than long on my architechture)?

Another thing is the problem with decimal seperator. How do you convert a number where the decimal separator is comma instead of a point like in the German language? This would be a nice to have, but not a must.

For example, my code says 12,3 is not a number, for a German person this would be a number (12.3 for English speakers).


texts: The solution for the exercise 1-22 from the book "The C programming language" K&R2

texts:
Exercise 1-22. Write a program to "fold" long input lines into two or
more shorter lines after the last non-blank character that occurs
before the n-th column of input. Make sure your program does something
intelligent with very long lines, and if there are no blanks or tabs
before the specified column.

The key idea is that I process whitespace character by character while processing a sequence of non-blank characters block by block, i.e. I read a block then decide whether to print it in the current line or next line.
#include <stdio.h>

#define LINE_MAX_SIZE 21        /* The maximum number of columns allowed in a single line */
#define IN_NON_BLANK_SEQ 1      /* Indicate that a sequence of non-blank character are being processed */
#define TAP_STOP_DIST 5

#define NON_BLANK(ch)   (ch != '\t' && ch != '\n' && ch != ' ')

int get_next_tap_pos(int current_column) {
    // columns numbered 0, 1, 2... there is a tap stop at 0, 5, 10, 15, 20
    return current_column / TAP_STOP_DIST * TAP_STOP_DIST + TAP_STOP_DIST;
}

int main(void)
{
    char block[LINE_MAX_SIZE+1];
    int column_pos = 0;                 /* Indicate the current column in the output where the next character will be printed*/
    int index_non_blank = 0;            /* Indicate the number of the non-blank char in the next non-blank char sequence */
    int state = !IN_NON_BLANK_SEQ;      /* Indicate whether a non-blank character is being processed */

    int ch;
    while ( (ch = getchar()) != EOF) {
        if (NON_BLANK(ch)) {

            state = IN_NON_BLANK_SEQ;
            if (index_non_blank == LINE_MAX_SIZE) {
                // There is a word bigger than the size of the line
                block[LINE_MAX_SIZE] = '\0';
                // Should I print it in the current line or in the next line ?
                // Our word is as big as our line. so if current line is not empty, we can't print it here
                if (column_pos != 0)
                    putchar('\n');
                printf("%s\n", block);
                column_pos = 0;
                index_non_blank = 0;
                block[index_non_blank] = ch;
            }
            else {
                block[index_non_blank] = ch;
                ++index_non_blank;
            }
        }
        else {
            // Is there a non-blank sequence that just finished ?
            if (state == IN_NON_BLANK_SEQ) {
                // Should the current word be printed in the current line or next line ?
                block[index_non_blank] = '\0';
                int expected_column_num = column_pos + index_non_blank;
                if (expected_column_num <= LINE_MAX_SIZE) {
                    printf("%s", block);
                    column_pos = expected_column_num;
                }
                else {
                    putchar('\n');
                    printf("%s", block);
                    column_pos = index_non_blank;
                }

                state = !IN_NON_BLANK_SEQ;
                index_non_blank = 0;
            }
            // now print the whitespace character and update column position
            if (ch == '\n') {
                putchar(ch);
                column_pos = 0;
            }
            else if (ch == ' ' && column_pos < LINE_MAX_SIZE) {
                putchar(ch);
                ++column_pos;
            }
            else if (ch == '\t' && column_pos < LINE_MAX_SIZE) {
                putchar(ch);
                column_pos = get_next_tap_pos(column_pos);
            }
            else {
                putchar('\n');
                column_pos = 0;
            }
        }
    }
}

Github link


texts: Is there a better way to make sure a variable is initialized when using blocks?

texts:
I have a method to provide an NSManagedObjectContext using UIManagedDocument. I need to ensure that the context did initialize before I return, so I added an infinite while loop at the end of the method. But I think that was very stupid and is not acceptable.

- (NSManagedObjectContext *)context {
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"Test"];
    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];

    if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
        [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            if (success) {
                self.managedObjectContext = document.managedObjectContext;
            }
            else {
                NSLog(@"[%@ %@] FATAL Error CANNOT create DB", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
                exit(1);
            }
        }];
    }
    else if (document.documentState == UIDocumentStateClosed) {
        [document openWithCompletionHandler:^(BOOL success) {
            if (success) {
                self.managedObjectContext = document.managedObjectContext;
            }
            else {
                NSLog(@"[%@ %@] FATAL Error CANNOT open DB", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
                exit(1);
            }
        }];
    }
    else {
        self.managedObjectContext = document.managedObjectContext;
    }

    while (!self.managedObjectContext) {
        // Is there any way better?
        NSDate *futureTime = [NSDate dateWithTimeIntervalSinceNow:1];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:futureTime];
    }

    return self.managedObjectContext;
}

Any suggestion will be appreciated.


texts: Prime number calculator using Sieve of Eratosthenes

texts:
I've been writing this prime number calculator, and I've gotten it pretty quick in comparison to most I've seen knocking about. This one uses the Sieve of Eratosthenes approach, and I've optimised the code as much as possible with my knowledge. A more experienced mind might be able to make it better.

Machine: 2.4GHz Quad-Core i7 w/ 8GB RAM @ 1600MHz

Compiler: clang++ main.cpp -O3

Benchmarks:

Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100

Calculated 25 prime numbers up to 100 in 2 clocks (0.000002 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000

Calculated 168 prime numbers up to 1000 in 4 clocks (0.000004 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 10000

Calculated 1229 prime numbers up to 10000 in 18 clocks (0.000018 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100000

Calculated 9592 prime numbers up to 100000 in 237 clocks (0.000237 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000000

Calculated 78498 prime numbers up to 1000000 in 3232 clocks (0.003232 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 10000000

Calculated 664579 prime numbers up to 10000000 in 51620 clocks (0.051620 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100000000

Calculated 5761455 prime numbers up to 100000000 in 918373 clocks (0.918373 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000000000

Calculated 50847534 prime numbers up to 1000000000 in 10978897 clocks (10.978897 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 4000000000

Calculated 189961812 prime numbers up to 4000000000 in 53709395 clocks (53.709396 seconds).
Caelans-MacBook-Pro:Primer3 Caelan$

Source:

#include <iostream> // cout
#include <cmath> // sqrt
#include <ctime> // clock/CLOCKS_PER_SEC
#include <cstdlib> // malloc/free

using namespace std;

int main(int argc, const char * argv[]) {
    if(argc == 1) {
        cout << "Please enter a number." << "\n";
        return 1;
    }
    long n = atol(argv[1]);
    long i;
    long j;
    long k;
    long c;
    long sr;
    bool * a = (bool*)malloc((size_t)n * sizeof(bool));

    for(i = 2; i < n; i++) {
        a[i] = true;
    }

    clock_t t = clock();

    sr = sqrt(n);
    for(i = 2; i <= sr; i++) {
        if(a[i]) {
            for(k = 0, j = 0; j <= n; j = (i * i) + (k * i), k++) {
                a[j] = false;
            }
        }
    }

    t = clock() - t;

    c = 0;
    for(i = 2; i < n; i++) {
        if(a[i]) {
            //cout << i << " ";
            c++;
        }
    }

    cout << fixed << "\nCalculated " << c << " prime numbers up to " << n << " in " << t << " clocks (" << ((float)t) / CLOCKS_PER_SEC << " seconds).\n";

    free(a);

    return 0;
}


texts:
I am building an API server in golang with mongodb. My main.go file looks something like this:

func main() {
    r := mux.NewRouter()

    question := r.PathPrefix("/question").Subrouter()
    question.HandleFunc("", handler.PostQuestion).Methods("POST")
    question.HandleFunc("/{id}", handler.UpdateQuestion).Methods("PUT")
    question.HandleFunc("/{id}", handler.DeleteQuestion).Methods("DELETE")
    question.HandleFunc("/{id}", handler.GetQuestion).Methods("GET")
    r.HandleFunc("/questions", handler.GetAllQuestions).Methods("GET")

    if err := http.ListenAndServe(":8080", r); err != nil {
        log.Fatalf("could not listen on port 8080 %v", err)
    }
}

Every handler has some logic which changes data in MongoDB. Regardless of what I am doing with the question collection, this is common in all the handlers.

client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := client.Connect(ctx)
if err != nil {
    panic(err)
}

defer client.Disconnect(ctx)
collection := client.Database("myapp").Collection("questions")

These functions are in handler/handler.go.

As you can see, I am using the official Mongo driver. What is the best kind of refactor which can be done?


texts: Learning OOP PHP, simple MySQL connection class.

texts:
I have posted an earlier version of this and here is the improved version from the feedback I recieved. Some of the feedback I received was;

Don't chain method (tried my best to limit this)
Do not use print() or die() and an error response (still a little lost, but I did attempt to use a redirect to a custom error page)

I tried my best to rewrite the code, I am still very new to this so go easy. I did read up on OOP methodology and read about Interfacing and Implementation, so I tried to incorporate that in my class.

I would love to see some different ideas on how to make this the most efficient as possible. I am sure it needs a ton of changing, but that is why I am here to help me learn and grow. I am a visual learner so if possible actual code would be awesome, but any response would be greatly appreciated.

<?php
class Mysql
{
        private $user;
        private $pass;
        private $data;
        private $host;

        public function __construct($user,$pass,$data,$host)
        {
                $this->user = $user;
                $this->pass = $pass;
                $this->data = $data;
                $this->host = $host;
                $this->process();
        }

        /* INTERFACE */
        private function process()
        {
                if($this->verifyNullFields()==true)
                {
                        if($this->verifyDatabaseConnection()==true)
                        {
                                if($this->verifyDatabaseExist()==true)
                                {
                                        print('ALL PASSED'); //for debugging
                                }
                                else
                                {
                                        print('redirect to custom error page will go here');
                                }
                        }

                        else
                        {
                                  print('redirect to custom error page will go here');
                        }

                }
                else
                {
                        print('redirect to custom error page will go here');
                }
        }

        /* IMPLEMENTATIONS */
        private function verifyNullFields()
        {
                if($this->user != NULL)
                {
                        if($this->data != NULL)
                        {
                                if($this->host != NULL)
                                {
                                        return true;
                                }
                                else
                                {
                                        return false;
                                }

                        }
                        else
                        {
                                return false;
                        }
                }
                else
                {
                        return false;
                }
        }
        private function verifyDatabaseConnection()
        {
                $link = @mysql_connect($this->host,$this->user,$this->pass);
                if(!$link)
                {
                        return false ;
                }
                else
                {
                        return true;
                }
        }
        private function verifyDatabaseExist()
        {
                $db = @mysql_select_db($this->data);
                if(!$db)
                {
                        return false;
                }
                else
                {
                        return true;
                }
        }
}
?>
<?php
$m = new Mysql("root","","magic","localhost");
?>


texts: Convert a type u16 number to a matrix (Vec> or array) of 4 x 4

texts:
I am a Rust newbie and I am not familiar with all the iterator options. This is what I have so far. How can I make this better or at least avoid collecting twice into a Vec?

let num: u16 = 0b0010001000100010; // input number
let bin = format!("{:016b}", num);

let parsed = bin
    .split("")
    .filter_map(|s| s.parse().ok())
    .collect::<Vec<u8>>();

let mat = parsed.chunks(4).collect::<Vec<_>>();

println!("{:?}", mat);

// outputs [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]


texts: Is it correct to use delegates as properties?

texts:
I need to create a class with two properties:

LogOutput
ExceptionOutput

These properties (of type Action) send a message or a exception depending on the target function. This target function is set via properties.
Currently, I have the following code:

public class Output
{
    private Action<string> logOutput;
    private Action<Exception, string> exceptionOutput;

    public Action<string> LogOutput
    { set { this.logOutput = value; } get { return this.logOutput; } }
    public Action<Exception, string> ExceptionOutput
    { set { this.exceptionOutput = value; } get { return this.exceptionOutput; } }

    public Output() : this(null, null) { }

    public Output(Action<string> logAction, Action<Exception, string> exceptionAction)
    {
        this.logOutput = logAction;
        this.exceptionOutput = exceptionAction;
    }

    public void WriteLogMessage(string format, params object[] args)
    {
        if (this.logOutput != null)
        logOutput(string.Format(format, args));
    }

    public void WriteExceptionMessage(Exception ex, string format, params object[] args)
    {
        if (this.exceptionOutput != null)
        exceptionOutput(ex, string.Format(format, args));
    }
}

And this is my form code:

private void MainForm_Load(object sender, EventArgs e)
{
    Output myOutput = new Output();

    myOutput.ExceptionOutput = this.WriteExceptionMessageToTextBox;
    myOutput.LogOutput = this.WriteLogMessageToTextBox;

    myOutput.WriteLogMessage("this is my log message to text box");
    myOutput.WriteExceptionMessage(new Exception("this is my exception"),
        "this is my exception message to text box");
}

private void WriteLogMessageToTextBox(string message)
{
    if (this.txtBox.IsDisposed)
    return;

    if (this.InvokeRequired)
    {
        BeginInvoke(new MethodInvoker(delegate() { WriteLogMessageToTextBox(message); }));
    }
    else
    {
        this.txtBox.AppendText(message + Environment.NewLine);
    }
}

private void WriteExceptionMessageToTextBox(Exception ex, string message)
{
    if (this.txtBox.IsDisposed)
    return;

    if (this.InvokeRequired)
    {
        BeginInvoke(new MethodInvoker(
            delegate() { WriteExceptionMessageToTextBox(ex, message); }));
    }
    else
    {
        string msg = "";
        msg += string.Format("Program:{0}", message);
        msg += string.Format("Message{0}", ex.Message);
        msg += string.Format("StackTrace:{0}", ex.StackTrace);
        msg += string.Format("Source:{0}", ex.Source);
        this.txtBox.AppendText(msg + Environment.NewLine);
    }
}

The thing is I don't know if this is correct (although it's working). If it's not correct, how can I change it? How can I implement it with events?


texts: Tiny MVC - Handling validation / sanitization in a model

texts:
I'm fairly new to MVC concepts and PHP input validation.

I'm open to all input, but I'm largely wanting to know if the following:

Follows the MVC pattern correctly - if not, how can I change it to better follow that?
Has any huge apparent security flaws with the validation procedure - if so, what are they and do you have any suggestions for how I can address it?

The assumptions are that this form will be available to a pre-defined set of persons within my company on our intranet. It connects to a MySQL database through PDO and utilizes only parameterized queries when working with variables. The actual code checks many more fields and does it for Bid, Campus, Contact, and Company (all exist as seperate models and tables).

Bid_Controller.php

class Bid_Controller extends Controller{

    public function index(){
        //load default view that contains the initial form, form action targets the Bid_Controller->process method through routing
    }

    public function process(){
        $this->load->model('Bid_Model', 'bid');

        if($this->bid->validateBid()){
            // try to save the bid
            // show errors on fail, success message on success
        }else{
            // load default view, pre-populate fields, show form errors
        }
    }
}

Bid_Model.php

class Bid_Model extends Model{
    public $bid_date_open; // assume a POST of '9/17/2013' for this
    public $bid_location; // assume a POST of 'Texas' for this
    public $bid_company; // assume a POST of 'Walmart' for this
    public $probability; // assume a POST of '50' for this

    private $errors;

    public function validateBid(){

        $requiredFields = array(
            // format of 'field_name', FILTER_TYPE, FILTER_OPTIONS, 'Error Message.'
            array('bid_company', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH, "You must enter a company."),
            array('bid_location', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH, "You must enter a location.")
        );

        foreach ($requiredFields as $i => $data) {
            $sanitizedInput = filter_var($_POST[$data[0]], $data[1], $data[2]);

            if (empty($sanitizedInput)) {
                $this->$data[0] = null;
                array_push($this->errors, $data[3]);
            } else {
                $this->$data[0] = $sanitizedInput;
            }
        }

        $notRequiredFields = array(
            // format of 'field_name', FILTER_TYPE, FILTER_OPTIONS, 'default value'
            array('bid_date_open', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH, null),
            array('bid_probability', FILTER_SANITIZE_INT, null, null)
        );

        foreach ($notRequiredFields as $i => $data) {
            $sanitizedInput = filter_var($_POST[$data[0]], $data[1], $data[2]);

            if (empty($sanitizedInput)) {
                $this->$data[0] = $data[3];
            } else {
                $this->$data[0] = $sanitizedInput;
            }
        }
    }

    public function fetchErrors(){
        // if isset this->errors, return this->errors
    }

    public function saveBid(){
        // use the public variables above as parameters in PDO insert query
    }
}


texts: WordPress plugin to reveal coupons after several visits to a page

texts:
My file tree is here.

It does not look good. I would appreciate any tips you have on improving code organization. My React mindset of breaking folders by component didn't carry over well into php/wordpress. I'm thinking for my next project I'll follow convention to put all classes in /classes

As is most of the project is in /adminSettingsArea. The React app is in the subfolder /src but what I really would like feedback on is how to organize all the PHP and dependent code.

Here is my entryPoint.php:

<?php

namespace DelayedCoupons;

////// Plugin Declaration (read by WP Core) //////

/**
 * Plugin Name: Delayed Coupons
 * Description: Show coupons after a visitor visits a specific page a certain number of times
 * */

/** Basic Project Setup
 * Env variables, constant definitions, class autoloads
 */
require_once ('bootstrap.php');

////// On Plugin Activation //////

require_once ('adminSettingsArea/DataBase.php');

/** Creates DB tables on plugin activation
 */
use \DataBase;
$database = new DataBase();

register_activation_hook(__FILE__, [$database, 'initializeTables']);
register_activation_hook(__FILE__, [$database, 'initializeDummyTable']);

////// Page Builder Functions & Matching Hooks //////

// Admin Page
require_once ('adminSettingsArea/index.php');

/** Handles all aspects of triggers and coupon display
 * Cookie setting. Trigger checks. Coupon retrieval and rendering
 */
require_once (ADMIN_SETTINGS_PATH . '/Visitors.php');
use admin\controllers\Visitors;
$visitors = new Visitors();
add_action('init', [$visitors, 'logVisitsAndControlCouponDisplay']);

/** Rest Api Extensions
 * Endpoints for adding coupons, deleting, and loading coupon data.
 */
require_once ('adminSettingsArea/ApiController.php');
use \admin\controllers\ApiController;

function hookAllRestControllers() {
  $apiController = new ApiController();
  $apiController->registerDummyRoute();
  $apiController->registerLoadCouponRoute();
  $apiController->registerDeleteSingleCouponRoute();
}
add_action('rest_api_init', '\DelayedCoupons\hookAllRestControllers');


texts: Finding the maximum value in a binary tree

texts:
I have to find the maximum value in a binary tree. This is how I did it iteratively:

int maxValue(Node* node)
{
    if (node == nullptr)
        throw "BT is empty";

    int max = node->data;
    for (Node* left = node; left != nullptr; left = left->left)
    {
        if (left->data > max)
            max = left->data;
    }

    for (Node* right = node; right != nullptr; right = right->right)
    {
        if (right->data > max)
            max = right->data;
    }

    return max;
}

I don't know if this is the best way to do it. How can this be improved? Is there a recursive solution?


texts: Sorting Each Entry (code review + optimization)

texts:
I have a requirement where there are 3 selection criteria user selects countries from a map displayed as lets say in 3 categories , i am maintaining 3 arraylist for the same.Each time he selects a country i have to display list of country names displayed in Alphabetical order in a bottom bar with font color distinguishing each category .I have written a code which will add all the values of arraylist in a different arraylist and sort it and then based on category it will create font for each and display them in the bottom so each time user  selects a country this method is called.Please review and let me know if i can improve the performance.Below is  the code

Lets say issuingOffice,selectedCountries and deSelectedCountries are arraylist declared in global scope and have values.

function updateBottomBar(){
    var initalContent="Countires: ";
    require(["dojox/collections/ArrayList"],function(arrayList){
    var bottomBar = new arrayList();
    var it = issuingOffice.getIterator();
    while (!it.atEnd()) {
        var country = it.get();
        bottomBar.add(country);
    }
    var scit = selectedCountries.getIterator();
    while (!scit.atEnd()) {
        var country = scit.get();
        bottomBar.add(country);
    }
    var descit = deSelectedCountries.getIterator();
    while (!descit.atEnd()) {
        var country = descit.get();
        bottomBar.add(country);
    }
    bottomBar.sort();
    var bbit = bottomBar.getIterator();
    while (!bbit.atEnd()) {
        var country = bbit.get();
        if(selectedCountries.contains(country)){
            initalContent!=""+country+"";
        }else if(selectedCountries.contains(country)){
            initalContent!=""+country+"";
        } else{
            initalContent!=""+country+"";
        }
    }
    initalContent+="";
    dojo.byId("displayCountryName")=initalContent;
    });
}


texts: Average histogram combining multiple files and vector of vectors (in c++)

texts:
I run a program of simulation N times (I use each time a different random numbers to initialize it). The results of the program are stored in 2N directories: every run produces two approximations. The directories contain the same files and have the following structure:

def-risultati-i, i = 1, ... , N
exc-risultati-i, i = 1, ... , N

Where def and exc are test names of the approximations. In each one of the directories there are histograms files (file-a.dat, file-b.dat, ...)

bin_left bin_right weight error

Where each bin is identified by the values of beginning and end.
I've written a program that takes a file from every directory and produces the average of the corresponding histogram. So for instance I take the file risultati.dat from

def-risultati-1,
def-risultati-2, ... , def-risultati-N,

The code works fine but I'd like to improve the structure of the function that does all the job. There are some redundant passages (e.g. I store the values of the bins for the files taken from every directory, even though they are the same for every run of the program) and my c++ skills are rusty. I'm not sure about those nested for loops on a vector of vectors...
Here it is a "demo" of the program:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <cmath>

void merge(int N, std::string appr, std::string title) {
  double a;
  std::string fin_dir = appr + "-totale";
  std::string init_dir = appr + "-risultati-";
  std::string num, dir;
  std::ifstream ri;
  std::ofstream out(fin_dir+title);
  std::vector<std::vector<double>> v_ri;

  for(int j=1; j<=N; j++){
    num = std::to_string(j);
    dir = init_dir+num+title;
    ri.open(dir);
    std::vector<double> v;

    while(ri >> a){
      v.push_back(a);
    }

    v_ri.push_back(v);
    ri.close();
  }

  a=0;
  std::vector<double> weight;
  for(int k=2; k<v_ri[0].size(); k=k+4){
    for(int j=0; j<v_ri.size(); j++){
      a = a+v_ri[j][k]/double(N);
    }
    weight.push_back(a);
    a=0;
  }

  a=0;
  std::vector<double> err;
  for(int k=3; k<v_ri[0].size(); k=k+4){
    for(int j=0; j<v_ri.size(); j++){
      a = a+pow(v_ri[j][k], 2)/double(N);
    }
    a = sqrt(a);
    err.push_back(a);
    a=0;
  }

  int cont = 0;
  for(int i=0; i<v_ri[0].size(); i=i+4){
    out << std::scientific << v_ri[0][i] << " " << v_ri[0][i+1] << " ";
    out << std::scientific << weight[cont] << " " << err[cont] << std::endl;
    cont++;
  }
}

int main(){
  //merge(numeber_of_directories, "exc"/"def", title)
  //title: /namefile.dat

  int N=3;

  merge(N, "exc", "/ris.dat");
  merge(N, "def", "/ris.dat");

  return 0;
}


texts: Guess the computer's number using functions

texts:
I am looking to improve the Python Number Guessing Game program:

How is the overall structure of the code?
Have I used functions to the best of their ability?
Can the code be simplified? If yes, please feel free to show how.
The replay_game() function especially seems un-pythonic and overkill.

# Guess My Number Game
# MacOSX (Latest), Python 3.4.3, 27/08/2017
# Guess The Computers number between 1-100

from random import randint
from time import sleep

def gen_number():
    random_number = randint(0, 101)
    return random_number

def intro():
    print("Welcome to, Guess My Number!")
    print("Simply guess the number between 1-100 that the Computer is 'thinking' of!")
    print()

def ask_number(question, random_number):
    response = None
    while response != random_number:
        try:
            response = int(input(question))
            if response > random_number:
                print("Lower... ")
            elif response < random_number:
                print("Higher... ")
            else:
                correct = response
                congrat_winner(correct, random_number)
        except ValueError:
                print("Invalid. Enter a number between 1-100 ")
    return response

def human_guess():
    print("Ok Human! Let's begin... ")
    sleep(1)
    random_number = gen_number() # Named the variable random_number, the same as the variable in gen_number(). Is this good practise?
    guess = ask_number("Guess the number: ", random_number)

def congrat_winner(correct, random_number):
    if correct == random_number:
        print()
        print("Calculating results...")
        sleep(1)
        print()
        print("WELL DONE!")
        print("The answer was indeed,", str(correct) + "!")

def replay_game():
    replay_question = None
    while replay_question != 'y' or 'n':
        replay_question = input("Would you like to play again (y/n)? ").lower()
        if replay_question == 'y':
            print()
            print("Rebuilding game... ")
            main()
        elif replay_question == 'n':
            print("Goodbye!")
            exit()
        else:
            print("please enter either 'y' or 'n'... ")

def main():
    intro()
    human_guess()
    replay_game()

main()


texts:
I'm just getting started with frontend development. I tried to make a pretty barebones cookie consent notice. I still don't fully understand flexbox and positioning, so the code is messy.
HTML:
    <button id="shownotice">Click to ask</button>

Are you fine with cookies?

        <button class="consent_button" id="yes">Yes</button>
        <button class="consent_button" id="no">No</button>

CSS:
#shownotice {
    background-color: cyan;
    border:0;
    padding: 5px;
}

[hidden] { display: none !important; }

.consent_notice {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    background-color: red;
    bottom:0px;
    left: 0px;
    right: 0px;
    overflow: auto;
}

#buttons {
    display: flex;
    margin-right: 10px;
    flex-direction: column;
    padding: 5px;
}

.consent_button {
    margin: 5px;
    background-color: gray;
    border: 0;
    padding: 3px;
}

JS:
show_button = document.querySelector("#shownotice");
consent_elem = document.getElementById("consent_elem");

show_button.onclick = (e) => {
    consent_elem.hidden = consent_elem.hidden ? false : true;
}


texts: x64 Assembly - checking for largest prime factor

texts:
Using x64 assembly, I solved the Largest Prime Factor problem on Project Euler.

The problem is as follows:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

The answer is 6857.

I think I have a top notch algorithm to do the job (speed wise), which doesn't actually check if a number is prime. The algorithm just reduces the number they gave you instead.

p3 proc

    mov rbx, 600851475143          ; The original number
    mov rcx, 1                     ; The starting position of the counter
    mov rdx, 0                     ; Just to clear garbage data

    mainloop:

        mov rax, rbx           ; rbx hold the number, and saves it, because the number in rax will change, and a backup needs to be stored

        inc rcx                ; Increment counter
        noinc:                 ; This is where the loop starts at each iteration that the previous division operation had no remainder
        mov rbx, rax           ; At this instruction, we know that rax has been reduced, and save it into rbx

        cmp rax, rcx           ; These two lines check if the counter rcx reached its maximum value, and if so, the program quits and returns the result in rax
            je done
        mov rdx, 0             ; makes sure there is no junk data in rdx

        div rcx                ; Perform division to check for a remainder
        cmp rdx, 0
            jz noinc           ; If there is no remainder: Reduce the value and dont increment next iteration
            jnz mainloop       ; If there is a remainder, jump back to the top of the loop, increment the value, and try the division again.

    done:                      ; Exit
        ret
p3 endp

I am a beginner in assembly, and this is one of my first x64 assembly programs. Are there any standard conventions that I am not following, or general things that could have been done better? Any advice? Is there a simpler way to do what I did?

Please be brutal and detailed in your response.


texts: Powershell zip subfolders recursively, conditionally

texts:
This is a progression of the script I posted here: Zip the contents of subfolders, conditionally

It does this:

Determines all subfolders recursively
Checks each subfolder for files older than 31 days which aren't .zip
If such files found, creates a new folder within, labelled with the date
Moves the files to the new folder
Creates a zipped copy of the new folder
Deletes the new folder and its contents

There's error-handling and logging built-in

#Run under Powershell v1 or v2

#Pass the target log folder as a parameter: '-LogFolder Path\to\logfolder'
param(
    [parameter(Mandatory=$true)]
    [ValidateScript({
        if (Test-Path $_ -PathType Container) {$true}
        else {Throw "Folder $_ not found"}})]
    [String]
    $LogFolder
)

#Get working directory, for outputting log file
$WorkingDirectory = (pwd).path

#Print datestamp to the log file
Get-date >> "$WorkingDirectory\OutputLog.txt"
"Log directory: $LogFolder" >> "$WorkingDirectory\OutputLog.txt"

#Record total size of the target log folder before compression
$Logsize = Get-ChildItem -recurse $LogFolder | Measure-Object -property length -sum
$MBsize = "{0:N2}" -f ($Logsize.sum / 1MB) + " MB"
"Initial Log folder size: $MBsize" >> "$WorkingDirectory\OutputLog.txt"

#Verify that the Zip.dll is present
$testzip = Test-Path .\ICSharpCode.SharpZipLib.dll

#If the Zip.dll is found, bind it to a variable and load it, otherwise exit
#In other words, if the script cannot load the Zip module, it will do nothing
if ($testzip -eq $True){
$ZipModule = Get-ChildItem .\ICSharpCode.SharpZipLib.dll | Select -ExpandProperty FullName
[void][System.Reflection.Assembly]::LoadFrom($ZipModule)
}
Else{
"Zip dll not found or couldn't be loaded.
Check file is present and unblocked.
Exiting" >> "$WorkingDirectory\OutputLog.txt"
Exit
}

#Get all subfolders
$subfolders = Get-ChildItem $LogFolder -Recurse |
Where-Object { $_.PSIsContainer -and $_.fullname -notmatch "\\jsonTemplates\\verifier\\?" }

ForEach ($s in $subfolders) {

    $path = $s  #$s variable contains each folder
    $path
    Set-Location $path.FullName

    $fullpath = $path.FullName

    #Get all items older than 31 days, exclude zip files and folders
    $items = Get-ChildItem -Exclude *.zip |
    Where-Object {$_.LastWriteTime -lt (Get-date).AddDays(-31)
    -and -not $_.psIsContainer}

    #Verify that there are such items in this directory, catch errors
    if ( $(Try { Test-Path $items }
    Catch { "Cannot find items in $fullpath.
    Sub-folders will be processed afterwards.
    ERROR: $_" >>  "$WorkingDirectory\OutputLog.txt"  }) ) {

        $date = Get-Date -Format 'yyyy-MM-dd_HH-mm'
        $newpath = "$path-$date"
        $newpath
        $newfld = New-Item -ItemType Directory -name $newpath

        $src = $newfld.FullName

        #move items to newly-created folder
        Move-Item $items -destination $src

        $dest = "$src.zip"
        "Compressing $src to $dest"  >>  "$WorkingDirectory\OutputLog.txt"

        #the following block zips the folder
        try{
            $zip = New-Object ICSharpCode.SharpZipLib.Zip.FastZip
            $zip.CreateZip($dest, $src, $true, ".*")
            Remove-Item $src -force -recurse
        }
        catch {
            "Folder could not be compressed. Removal of $src ABORTED.
            ERROR: $_" >> "$WorkingDirectory/OutputLog.txt"
        }
    }

}

#Record total size of the target log folder after compression
$Logsize = Get-ChildItem -recurse $LogFolder | Measure-Object -property length -sum
$MBsize = "{0:N2}" -f ($Logsize.sum / 1MB) + " MB"
"Final Log folder size: $MBsize" >> "$WorkingDirectory\OutputLog.txt"

Set-Location $LogFolder


texts: Creating a fast Android dictionary (word counts)

texts:
This is a follow-up of my question here:

I am currently working on an application for various statistics. One task is to analyse a good amount of sentences for their word counts.

The specifications are:

sentences are read from SQLiteDatabase (up to 20k with an average of about 15 words)
transformation: split by whitespaces (to get the words of the sentences)
transformation: toLowerCase (to minimize variations of words)
transformation: replace [^a-zA-Z] (for the same reason as above)
get word + count for the first x (not sure yet, maybe 10-15) most common words
preserve a flag if the messages was sent/received

What I'm looking for:

improvements to make the code run faster
alternative approaches for this task
(general hints to improve the task)

Current version with the suggested improvements made

//fields

private static final CharMatcher pat_rep = CharMatcher.inRange('A', 'Z').or(CharMatcher.inRange('a', 'z'))
        .precomputed();
private static final Pattern pat_split = Pattern.compile("\\s");
private HashMultiset<String> sent = HashMultiset.create();
private HashMultiset<String> rcvd = HashMultiset.create();
private Cursor c1;
private Cursor c2;

//start

    c1 = db.rawQuery("select lower(DATA) as SENTENCE, SENT from MESSAGELIST", null);
    while (c1.moveToNext()) {
        String[] words = pat_split.split(c1.getString(c1.getColumnIndex("SENTENCE")));
        int from_me = c1.getInt(c1.getColumnIndex("key_from_me"));
        for (String in : words) {
            in = pat_rep.retainFrom(in);
            if (!in.equals("")) {
                if (from_me == 1) {
                    sent.add(in);
                } else {
                    rcvd.add(in);
                }
            }
        }
    }

    db.execSQL("create temp table if not exists WORDS (WORD varchar, SENT integer, CNT integer)");
    SQLiteStatement ins = db.compileStatement("insert into WORDS values (?, ?, ?)");
    db.beginTransaction();

    Iterator<Entry<String>> i = sent.entrySet().iterator();
    Entry<String> e = null;
    while (i.hasNext()) {
        e = i.next();
        ins.bindString(1, e.getElement());
        ins.bindLong(2, 1);
        ins.bindLong(3, e.getCount());
        ins.executeInsert();
    }
    i = rcvd.entrySet().iterator();
    while (i.hasNext()) {
        e = i.next();
        ins.bindString(1, e.getElement());
        ins.bindLong(2, 0);
        ins.bindLong(3, e.getCount());
        ins.executeInsert();
    }
    db.setTransactionSuccessful();
    db.endTransaction();

    c1 = db.rawQuery("select WORD, CNT from WORDS where SENT=0 group by WORD order by CNT desc limit 10", null);
    c2 = db.rawQuery("select WORD, CNT from WORDS where SENT=1 group by WORD order by CNT desc limit 10", null);


texts: Is there any downside to define a function that use one dictionary as an argument instead of several (+10) arguments?

texts:
I tried to refactoring someone else's code and I found that there is alot of this pattern

def train(a, b, c, d, e, f, g, h, i, j, k): #Real code has longer name and around 10-20 arguments
    x = Dostuff()
    y = DoMoreStuff(b,c,d,e,f,g,h,x)
    z = DoMoreMoreStuff(a,b,d,e,g,h,j,y)

def DoMoreStuff(b,c,d,e,f,g,h):
    DoPrettyStuff(b,c,d,e,f,g,h) # The actually depth of function call is around 3-4 calls

I though that it would it be better to collect all of that a,b,c,d into one dictionary. I got this idea when I was reading about rail rack's middleware.

env = {"a":1, "b", 2.......}
def train(env):
    x = Dostuff()
    y = DoMoreStuff(env.update({"x":x}))
    z = DoMoreMoreStuff(env.update({"y":y}))

def DoMoreStuff(env)
    DoPrettyStuff(env)

But I am not sure if there is any downside about this approach ? If it does help, every function here has a side-effect.

EDIT: For more clarification. I think most of my problem are about the propagation of variables. The call pattern has very deep and wide hierarchy. Any further suggestion about this one ?

def main(a,b,c,d,e,f,g,h,i,j,k,l,m....z):
    Do(...)
    #maybe other function()

def Do(a,b,c,d,e,f,g,h,i,j,k,l):
    Do1(d,e,f,g,h,i,j,k,l)

def Do1(d,e,f,g,h,i,j,k,l)
    Do2(f,g,h,i,j,k,l)

def Do2(f,g,h,i,j,k,l)
    Do3(f,g,h,i)
    Do4(j,k,l)

EDIT 2:  Well, my intention is that I want the code more easier to read and followed. Performance in python code does not matter much since the program spend most of the time on SVM and machine learning stuff. If anyone interest and don't mind a very dirty code that I still working on it. Here is the real code https://github.com/yumyai/TEES/tree/30b3aeaab011e30dcdc3c1151062697861ddcae1

The code start with train.py (training model), classify.py (classify using model). In this case I'll use train.py as an example.
https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/train.py: line 136 where it start to call everything under it and pass a gigantic arguments to. These arguments are pass down to https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/Detectors/EventDetector.py: line 49. And then EventDetector pass these argument to it members (line 24-28).

Some argument is reused throughout the code, for example, def train(.......exampleStyles). exampleStyles is passed around to several member that is called by train.


texts:
The "Save Humanity" problem on Hackerrank asks us to:

  ... find all substrings in the patient DNA that either exactly matches the virus DNA, or has at most one mismatch.

  For example: "aa" and "aa" are matching, "ab" and "aa" are matching, while "ab" and "ba" are not.

  Input Format

  The first line contains the number of test cases T. T test cases follow.
  Each case contains two strings P(Patient DNA) and V(Virus DNA) separated by space.

  Output Format

  Output T lines, one corresponding to each test case. For each test case, output a space delimited list of starting indices (0 indexed) of substrings of P which are matching with V according to the condition mentioned above. The indices have to be in an increasing order. If there is no matching output No Match!.

In a nutshell, it requires me to compare two strings and find the beginning index value for all occurrences of the second substring in the first. The catch is that upto one mismatch in the substring is allowed.

I've coded the following solution which seems to work well for the first 3 testcases. The problem is it timed-out after the 3rd test case. I can't seem to optimize it any further than what I've already done unless my logic is somehow overly complicated or I'm not using enough in-built methods to quicken things up.

inp = inp.split('\n')
del inp[0]
for h in inp:
    P,sep,V = str(h).partition(' ')
    upperlimit = len(P) - len(V) + 1
    if P == V:
            print("0")
            continue
    else:
        matches=0
        for i in range(0,upperlimit):
            Psub = P[i:i+len(V)]
            if Psub == V:  # Check if they match exactly
                print(str(i) + " ", end='')
                matches += 1
                continue   # Just proceed with the next iteration of loop if they match
            mismatches = 0
            for j in range(0,len(V)): # If we hit this code then, we're about to see how many characters mismatch in the substring
                if Psub[j] != V[j]:
                    mismatches += 1
                if mismatches>=2: # No point checking the substrings alphabet by alphabet any further, more than 1 mismatch present here.
                    break
            if mismatches<2:
                print(str(i)+" ",end='')
                matches += 1
        if matches==0:      # This is possible ONLY if none of the above conditions were ever met.
            print("No Match!",end='')
    print()

Can someone please tell me why code is slow? Also, let me know if you want me to comment more of my code so it's easier to understand. The link to the problem description should be quite useful in understanding the problem.


texts:
Of course the recursive version is trivial:

hanoi n = solve n 1 2 3

solve 0 _ _ _ = []
solve n from help to = (solve (n-1) from to help) ++ [(from,to)] ++ (solve (n-1) help from to)

However my iterative version looks terrible with a lot of code repetition:

hanoi n = map rep $ solve [1..n] [] [] where
          rep (x,y) | odd n = ([1,3,2] !! (x-1), [1,3,2] !! (y-1))
                    | otherwise = (x,y)

solve from help to = head $ mapMaybe ready $ iterate step (from,help,to,[]) where
   step (1:xs,ys,zs,sol) = let (xs',zs',sol') = try xs zs 1 3 ((1,2):sol)
                           in (xs',1:ys,zs',sol')
   step (xs,1:ys,zs,sol) = let (xs',ys',sol') = try xs ys 1 2 ((2,3):sol)
                           in (xs',ys',1:zs,sol')
   step (xs,ys,1:zs,sol) = let (ys',zs',sol') = try ys zs 2 3 ((3,1):sol)
                           in (1:xs,ys',zs',sol')
   try [] [] _ _ sol = ([],[], sol)
   try (x:xs) [] a b sol = (xs,[x], (a,b):sol)
   try [] (y:ys) a b sol = ([y],ys, (b,a):sol)
   try (x:xs) (y:ys) a b sol | x < y = (xs,x:y:ys, (a,b):sol)
                             | y < x = (y:x:xs,ys, (b,a):sol)
   ready ([],[],_,sol) = Just $ reverse sol
   ready ([],_,[],sol) = Just $ reverse sol
   ready _ = Nothing

Any ideas? More general, how to deal with situations like this where you have a lot of different cases and args?

[Clarification]

With "iterative solution" I mean the algorithm described here: http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution


texts:
I want to find the corresponding hash in an array from a string that contains a criterion defined in a hash of the array.

I do something like that :

types = [
 {key: 'type_1', criteria: ['type_1a', 'type_1b']},
 {key: 'type_2', criteria: ['type_2a', 'type_2b']},
 ...
]

def find_type(str)
  types.each do |type|
    type[:criteria].each do |criterion|
      return type if str =~ /#{criterion}/i
    end
  end
  nil
end

I'm sure it could be more ruby but don't find how...


texts:
This is a homework question, and I have written the code but wasn't sure if I had picked the right data structure for this job and minimised time complexity. Can anyone give me some feedback, anything about space complexity or potential bugs that can occur is appreciated as well.
Problem Description

MagicTheGathering
Aim: deal with a series of command (SUMMON, KILL, HEAL). Each SUMMON
command will create a monster and each monster has a initial HP value.
Each KILL command will kill the monster with the lowest HP. And each
HEAL command applies to every monster in your list.
Input: N, the number of commands. Followed by N lines of commands.
Output: Each KILL command requires you to print the HP of the monster
that was killed. At the end of the series of commands, print the HP of
the remaining. monsters.
Input example:
8
SUMMON 30
SUMMON 20
SUMMON 50
HEAL 5
KILL
SUMMON 7
KILL
HEAL 10

Output example:
25
7
45 65

Attempt
import java.util.*;
import java.util.stream.*;

class  Yugioh {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        PriorityQueue<Integer> queue = new PriorityQueue(Comparator.naturalOrder());
        for (int i =0;i<count;i++) {
            String cmd = sc.next();
            if (cmd.equals("SUMMON")) {
                int health = sc.nextInt();
                queue.add(health);
            } else if (cmd.equals("HEAL")) {
                int health = sc.nextInt();
                PriorityQueue<Integer> newQueue = new PriorityQueue<>(Comparator.naturalOrder());
                List<Integer> data = queue.stream().map(x -> x + health).collect(Collectors.toList());
                newQueue.addAll(data);
                queue = newQueue;
            } else if (cmd.equals("KILL")) {
                System.out.println(queue.poll());
            }
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}


texts:
I use NLog everywhere and I really don't like writing the inserts everytime. You need to write the same variable three times: two for the insert and one for the parameter for example:

<target xsi:type="Database" name="Log" dbProvider="System.Data.SqlClient" connectionString="...">
    <commandText>
        INSERT
        INTO [dbo].[Log]([Foo], [Bar], ...)
        VALUES(@FOO, @BAR, ...)
    </commandText>
    <parameter name="@FOO" layout="..." />
    <parameter name="@BAR" layout="..." />
    ...
</target>

It's very error-prone (I always make a mistake somewhere by forgetting one or two of them) and hard to maintain.

I just want to add the parameters and create the INSERT automatically because it's nothing unusual and can be automated so I came up with this idea:

The commandText must not be empty for database targets and I also need to somehow specify the table name. So initially I put the table name there.

<target xsi:type="Database" name="TestLog" commandText="[dbo].[TestLog]" dbProvider="System.Data.SqlClient" connectionString="Data Source=(local);Initial Catalog=TestDb;Integrated Security=True;Connect Timeout=30">
    <parameter name="@Timestamp" layout="${longdate:universalTime=true}" />
    <parameter name="@LogLevel" layout="${level:uppercase=true}" />
    <parameter name="@Logger" layout="${logger}" />
    <parameter name="@Message" layout="${message}" />
    <parameter name="@Exception" layout="${onexception:${exceptionLayout}}" />
</target>

In this case the INSERT would be:

INSERT INTO [dbo].[TestLog](Timestamp, LogLevel, Logger, Message, Exception)
VALUES(@Timestamp, @LogLevel, @Logger, @Message, @Exception)

Next I use a set of extensions to update the commandText. Fortunatelly the CommandText property has a public setter.

static class NLogExtensions
{
    public static void UpdateCommandText(this NLog.Config.LoggingConfiguration config)
    {
        var tableNameMatcher = new Regex(@"^(\[(?<schemaName>.+?)\].)?\[(?<tableName>.+?)\]$");

        var autoCommandTextDatabaseTargets =
            config.AllTargets
                .OfType<DatabaseTarget>()
                .Where(x => tableNameMatcher.IsMatch(x.CommandText()))
                .Select(x => x);

        foreach (var databaseTarget in autoCommandTextDatabaseTargets)
        {
            databaseTarget.CommandText = databaseTarget.CreateCommandText();
        }
    }

    public static string CommandText(this DatabaseTarget databaseTarget)
    {
        return ((NLog.Layouts.SimpleLayout)databaseTarget.CommandText).OriginalText;
    }

    public static string CreateCommandText(this DatabaseTarget databaseTarget)
    {
        const string insertQueryTemplate = "INSERT INTO {0}({1}) VALUES({2})";

        return string.Format(
                insertQueryTemplate,
                databaseTarget.CommandText(),
                string.Join(", ", databaseTarget.Parameters.Select(x => x.Name.TrimStart('@'))),
                string.Join(", ", databaseTarget.Parameters.Select(x => x.Name)));
    }
}

Then I use it like this:

    var config = NLog.LogManager.Configuration;
    config.UpdateCommandText();

    var logger = NLog.LogManager.GetLogger("Program");
    logger.Debug("Hallo NLog!");

I cannot use C# 6


texts:
I am thinking about how to split my website into smaller reusable apps.  I've finally figured out something and need your opinion.

My main problem was that each app uses Profile model.  This is of course a snippet of my work with the most important parts.

# App Userdata
class BaseProfile(models.Model):
    city = models.CharField(max_length=100, null=True, blank=True)
    user = models.OneToOneField(User)

class Photo(models.Model):
    profile = models.ForeignKey(BaseProfile)
    url = models.URLField()

# App Social Connect
class SocialConnectProfile(models.Model):
    pass

class SocialConnect(models.Model):
    profile = models.ForeignKey(SocialConnectProfile)

# App Forum
class ForumProfile(models.Model):
    pass

class Question(models.Model):
    profile = models.ForeignKey(ForumProfile)

class Answer(models.Model):
    profile = models.ForeignKey(ForumProfile)
    question = models.ForeignKey(ForumProfile)

# App Base
class Profile(BaseProfile, SocialConnectProfile, ForumProfile):
    pass

What I am worrying about is that there are 5 tables with a one-to-one relationship.
What do you think?  Are there any better options?

Yes, the code has been pretty much simplified. Each app has many models indeed. (BaseProfile has 8, SocialConnect only 1, Forum 18)

My target is to extract them as Python-Django components in future, but I haven't done it before.

I want to project them in this way now to save time in future with new applications or extending existing one, but I am not sure  if it's the best approach.


texts: Number of occurrences of strings in array

texts:
This is a Hackerrank problem (https://www.hackerrank.com/challenges/sparse-arrays/problem).
We're given an array of strings and an array of queries, and have to return an array of the number of occurrences of each query in the array of strings.
For example: s = ['ab', 'abc', 'aba', 'ab']. q = ['ab', atr', 'abc]. We need to return [2, 0, 1].
The constraints are 1 <= n <= 1000, 1 <= q <= 1000, where n and q are the number of strings and queries respectively, and 1 <= |strings[i]|, |queries[i]| <= 20.
Here is my code:
def matchingStrings(strings, queries):
    results = []
    dic = {q:0 for q in queries}
    for s in strings:
        if s in dic: dic[s] += 1
    for q in queries:
        if q in dic: results.append(dic[q])
    return results

Is there anything I can optimize? Speed, memory usage? Anything else?


texts:
I've written the following C# code to insert rows (that a user enters from a web application) into a SQL database.  How does this code look?  Is there a better, more efficient way to accomplish the task?

public void UpdateDeviceStatus(string[] deviceId, byte[] status, string userId, string[] remarks, DateTime dateTurnin)
{
        if (deviceId.Length != status.Length || status.Length != remarks.Length)
            throw new ArgumentOutOfRangeException("Invalid arguments passed to UpdateDeviceStatus: deviceId, status, and remarks must contain the same number of entries.");
        if (deviceId.Length == 0)
            throw new ArgumentOutOfRangeException("UpdateDeviceStatus expects to update status for at least one deviceId, but an empty array was passed in.");

        // Build the SQL statement
        StringBuilder sbSql = new StringBuilder();
        sbSql.Append(@"INSERT INTO AT_Event_History(deviceId,parentCode,statusCode,remarks,userId,whenEntered) VALUES");
        for (int i = 0; i < deviceId.Length; i++)
        {
            string values = string.Format("({0},0,{1},{2},{3},{4}),",
                new string[] { "@deviceId" + i.ToString(), "@statusCode" + i.ToString(), "@remarks" + i.ToString(), "@userId", "@whenEntered" });
            sbSql.Append(values);
        }
        string sql = sbSql.ToString();
        sql = sql.TrimEnd(','); // remove the trailing comma ','

        Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("AssetTrackConnection");

        DbCommand command = db.GetSqlStringCommand(sql);
        command.CommandType = CommandType.Text;
        command.CommandText = sql;

        // Add in parameters
        db.AddInParameter(command, "@userId", DbType.AnsiString, userId);
        db.AddInParameter(command, "@whenEntered", DbType.Date, dateTurnin);
        for (int j = 0; j < deviceId.Length; j++)
        {
            db.AddInParameter(command, "@deviceId" + j.ToString(), DbType.Guid, new Guid(deviceId[j]));
            db.AddInParameter(command, "@statusCode" + j.ToString(), DbType.Byte, status[j]);
            db.AddInParameter(command, "@remarks" + j.ToString(), DbType.AnsiString, remarks[j]);
        }

        // Execute the statement.
        db.ExecuteNonQuery(command);
}

As you can see, I am looping to add db parameters to hold the value for each row.  I think that there may be a better way to do this.


texts: MVC Layout - Which way to add listeners is better?

texts:
So I'm doing a basic MVC layout for a pretty basic game that I am making. The game requires the user to move up/down/left/right via buttons on the GUI. Since I'm using an MVC layout and my buttons are in a different class than the ActionListeners, I was wondering what the best way to add the action listeners are?

Method 1:

View Class ActionListener method:

public void addMovementListeners(ActionListener u, ActionListener d, ActionListener l, ActionListener r){
    moveUp.addActionListener(u);
    moveDown.addActionListener(d);
    moveLeft.addActionListener(l);
    moveRight.addActionListener(r);
}

Control Class add ActionListener method:

private void addListeners(){
    viewGUI.addMovementListeners(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buttonPressed = 1;
        }
    },
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buttonPressed = 2;
        }
    },
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buttonPressed = 3;
        }
    },
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buttonPressed = 4;
        }
    });
}

Method 2:

View Class ActionListener method:

public void addMovementListeners(ActionListener a){
    moveUp.addActionListener(a);
    moveDown.addActionListener(a);
    moveLeft.addActionListener(a);
    moveRight.addActionListener(a);
}

public JButton[] getButtons(){
    JButton[] temp = new JButton[4];
    temp[0] = moveUp;
    temp[1] = moveDown;
    temp[2] = moveLeft;
    temp[3] = moveRight;

    return temp;
}

Control Class add ActionListener method:

JButton[] movementButtons;

private void addListeners(){
    movementButtons = viewGUI.getButtons();
    viewGUI.addMovementListeners(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == movementButtons[0]){
                buttonPressed = 1;
            }else if(e.getSource() == movementButtons[1]){
                buttonPressed = 2;
            }else if(e.getSource() == movementButtons[2]){
                buttonPressed = 3;
            }else if(e.getSource() == movementButtons[3]){
                buttonPressed = 4;
            }
        }
    });
}

Which method is better? Is there another method that is even better than these two? Let me know! Trying to get this MVC thing down :). (Any other suggestions welcome as well)!


texts: Simple dispatcher for an embedded system

texts:
This code is something that I have used for about 3-4 simple embedded systems projects.

The idea is something like this:

This is non-OS based implementation, everything is done in an outer infinite loop. No dynamic memory involved or advised.
It's an interrupt-driven system, polling for peripherals is not used anywhere.
Peripherals like Timer, UART, I2C, etc loads a particular value based on the event, in a Queue-like variable.
Non-trivial tasks like blinking an LED is done in a common Idle task.
Dispatcher loads the function handlers based on the event added in the queue.
(UPDATE) All read/write activities on CPU registers are managed in the respective Interrupt Service Routine. Adding the event in queue is possibly the last thing the code does in the ISR.

Enum for possible events:

typedef enum {

    TASK_EMPTY = 0,
    TASK_INITIALIZE = 1,
    TASK_IDLE,
    TASK_SOMETHING_1,
    TASK_SOMETHING_2,
    TASK_SOMETHING_3,
    TASK_SOMETHING_4,
    TASK_SOMETHING_N,

    MAX_TASKS,
    TASK_INVALID = -1,

} eTasks_t ;

A constant array which contains the event mapped to the handler:

const stTask_t GlobalTasksList[MAX_TASKS] =
{
    { TASK_EMPTY,              Placeholder             },
    { TASK_INITIALIZE,         SystemInitialization    },
    { TASK_IDLE,               Idle                    },
    { TASK_SOMETHING_1,        Handler_1               },
    { TASK_SOMETHING_2,        Handler_2               },
    { TASK_SOMETHING_3,        Handler_3               },
    { TASK_SOMETHING_4,        Handler_4               },
    { TASK_SOMETHING_N,        Handler_N               },
};

I talked about a Queue:

eTasks_t Queue[MAX_TASKS];
eTasks_t qTasksToAdd[MAX_TASKS * 2];

There is a structure which binds an event and it's handler together:

typedef struct stTask {

    eTasks_t TaskID;
    bool (*handler) (void);   // Would return true for success, and false for failure

} stTask_t;

stTask_t Task;

A Dispatcher function will take care of queued events:

void Dispatcher(void)
{
    while(1)
    {
        // Assign the task handler
        Task.handler = GlobalTasksList[Task.TaskID].handler;

        //Invoke handler
        if(FAILURE == Task.handler())
        {
            //Something went wrong with handler, Error!
            // Error handling

        }

        //Does the task needs a retry, or is a recurring task?
        // Reload if yes, else discard and load the next
        if(bTaskRetry == FALSE)
        {
            Queue_DiscardTask0();
        }

        //Assign the 0th task from Queue
        Task.TaskID = Queue[0];
    }
}

Let's look at an example of adding the event in the Queue from an ISR:

#pragma vector=PORT2_VECTOR
__interrupt void PORT2_Interrupt(void)
{
    // Clear interrupt
    CLR_BIT(P2IFG, 2);  //P2IFG is a CPU register which indicates the Port pin that has generated an interrupt.
    // Check if the queue is overflowing
    if(qIndexTasksToAdd < MAX_TASKS-1)
    {
        // Add event
        qTasksToAdd[qIndexTasksToAdd++] = TASK_SOMETHING_1;
    }
}

As of now, this strategy works fine without any questionable latency.
I have used the same skeleton for systems that could have as many as 20 events lined-up, and it works as per requirement to say the least.

Another advantage of this implementation that I felt is in regards with the efficiency this has when I am debugging an issue. Everything is routed through the handler/dispatcher, so I precisely know where to have a debug point/print setup.

The concern that I have with this implementation is the fixed memory footprint is has. For example, this won't be memory efficient for a LED blinking project.

Any thoughts where I could improve on this?


texts:
I have this problem to solve:

Given an integer \$z\$ and an array \$a\$ of distinct integers sorted in ascending order, find two numbers, \$x\$ and \$y\$, belonging to the array such that \$x + y = z\$. All this has to be done with \$O(n)\$ time performance in the worst case and \$O(1)\$ space.

I tried to jot down a trivial solution:
public static boolean find(int[] a, int z) {
    for (int i = 0; i < a.length; i++) {
        for (int j = i + 1; j < a.length; j++) {
            if (a[i] + a[j] == z)
                return true;
        }
    }
    return false;
}

However, it is clearly O(n^2) and I cannot find a better algorithm.
Can you help me?


texts: Implementation of Linux cp in modern C++

texts:
This is my simple implementation of the Unix cp command.  It is a C++ program but makes use of some of the lower level C library I/O functions.

Any suggestions for style or performance improvements would be appreciated.

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char* argv[]) {
    // cmd : cp file1 file2

    if ( argv[1] == nullptr || argv[2] == nullptr ){
        std::cout << "missing arguments: moderncp file1 file2 ";
        return 0;
    }
    const std::string input{argv[1]};
    const std::string output{argv[2]};

    // create a vector with 1024 byte allocated
    std::vector<char> buf(1024);
    // input file descriptor
    int infd = open(input.c_str(),O_RDONLY);
    // output file descriptor
    int outfd = open(output.c_str(),O_WRONLY|O_CREAT|O_EXCL,0664);

    while(true){
        auto count = read(infd,buf.data(),buf.size());
        if (count == 0) break;

        auto num_written = 0;
        auto num_to_write = count;
        while(num_written < num_to_write){
            num_written += write(outfd,buf.data()+num_written,count-num_written);

        }
    }
    close(infd);
    close(outfd);

    std::cout << input << '\t' << output ;
}


texts:
I was wondering if I have any hidden bugs or traps in my code I wrote for an exercise.

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<algorithm>
using namespace std;

# define MAX 1000

int binSearch(int *arr, int arrSize, int num)
{
    int leftPos = 0, rightPos = arrSize - 1;

    while(mid != leftPos)
    {
        int mid = (rightPos + leftPos)/2;
        if(arr[mid] == num)
            return mid;
        else if(arr[mid] > num)
            rightPos = mid;
        else
            leftPos = mid;
    }

    return -1;
}

int main(){

    /*testing program */
    int arr[MAX];
    for(int i = 0; i < MAX; i++)
        arr[i]=rand()%100;

    sort(arr, arr+MAX);

    cout<<binSearch(arr, MAX, 4);

}


texts: Angular Models as Property or Injectable?

texts:
I have an application that looks like such:

var app = angular.module('app', []);

app.Person = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

app.controller = function('myController', function($scope) {

    $scope.pageData = [];
    $scope.pageData.firstName = ['John'];
    $scope.pageData.lastName = ['Smith'];

    $scope.pageData.people = [];

    // just a demo. The point of this is just to show the controller creating Person objects
    // assume that first name and last name will always be the same length;
    for (var i = 0; i < firstName.length; i++) {
        $scope.pageData.people.push(new Person($scope.pageData.firstName[i], $scope.pageData.lastName[i]);
    }
});

Is there a better way of structuring Person? Should it be in a factory or service?


texts: Python converter: number-to-English - Project Euler 17

texts:
So I wrote this function to convert a given number to its interpretation in the English language as part of the Project Euler exercises.  It works fine, but I sense that it's rather sloppy and inelegant, especially for Python where many things can be done quickly in a couple of lines.  Any feedback on how to make this code more beautiful/Pythonic is appreciated!

NUMBER_WORDS = {
    1 : "one",
    2 : "two",
    3 : "three",
    4 : "four",
    5 : "five",
    6 : "six",
    7 : "seven",
    8 : "eight",
    9 : "nine",
    10 : "ten",
    11 : "eleven",
    12 : "twelve",
    13 : "thirteen",
    14 : "fourteen",
    15 : "fifteen",
    16 : "sixteen",
    17 : "seventeen",
    18 : "eighteen",
    19 : "nineteen",
    20 : "twenty",
    30 : "thirty",
    40 : "forty",
    50 : "fifty",
    60 : "sixty",
    70 : "seventy",
    80 : "eighty",
    90 : "ninety"
}

def convert_number_to_words(num):
    #Works up to 99,999
    num = str(num)
    analyze = 0
    postfix = remainder = None
    string = ""
    if len(num) > 4:
        analyze = int(num[0:2])
        remainder = num[2:]
        postfix = " thousand "
    elif len(num) > 3:
        analyze = int(num[0:1])
        remainder = num[1:]
        postfix = " thousand "
    elif len(num) > 2:
        analyze = int(num[0:1])
        remainder = num[1:]
        postfix = " hundred "
        if int(remainder) > 0:
            postfix += "and "
    elif int(num) in NUMBER_WORDS:
        analyze = int(num)
    else:
        analyze = int(num[0:1] + "0")
        remainder = num[1:]
        postfix = "-"
    string = NUMBER_WORDS[analyze]
    if postfix is not None:
        string += postfix
    if remainder is not None and int(remainder) > 0:
        return string + convert_number_to_words(remainder)
    else:
        return string


texts: Asp.Net Custom Server Control: PostBack handling

texts:
I wrote a custom server control. The data in it can be manipulated on the client and the changes will be written into the hidden field. The data represents a property of the control and should be retrieved on a postback. I achieved this by using the value changed event to set the property and all its dependencies.
Is this a good a way to do this? Or can this code be improved?

public class Control : CompositeControl {

  private bool mProperty;
  private HiddenField hiddenField;

  public virtual bool Property {
    get {
      return mProperty;
    }
    set {
      mProperty = value;
      if (contentPanel != null) contentPanel.Visible = value;
      if (hiddenField != null && hiddenField.Value != value.ToString().ToLower()) hiddenField.Value = value.ToString().ToLower();
    }
  }
  protected override void CreateChildControls() {
    Controls.Clear();
    CreateControlHierarchy();
    ClearChildViewState();
  }
  protected virtual void CreateControlHierarchy() {
    CreateHiddenField();
    CreateContent();
  }

  protected virtual void CreateHiddenField() {
    hiddenField = new HiddenField();
    hiddenField.ID = "hiddenField";
    hiddenField.Value = Property.ToString().ToLower();
    hiddenField.ValueChanged += hiddenField_ValueChanged;
    Controls.Add(hiddenField);
  }
  protected virtual void CreateContent() {
    contentPanel = new Panel();
    contentPanel.ID = "content";
    contentPanel.Vsiible = Property;
    Controls.Add(contentPanel);
  }
  void hiddenField_ValueChanged(object sender, EventArgs e) {
    Property = Convert.ToBoolean(hiddenField.Value);
  }
  protected override void OnInit(EventArgs e) {
    EnsureChildControls();
    base.OnInit(e);
  }
}


texts: Returning information about searches performed by a user

texts:
I have this simple piece of code from my django project. I feel that it isn't very well written.

Maybe it possible to write this simple function in a better way? Maybe could you give me any advices how to improve this code? I'm trying to learn how to write good quality code.

Or maybe this code is good enough?

import datetime
from accounts.models import UserProfile

def get_search_data(request):
    if request.user.is_authenticated():
        user_email = request.user.email
        user_profile = UserProfile.objects.get(user=request.user)
        user_phone = user_profile.phone_number
    else:
        user_email = ''
        user_phone = ''
    search_date = datetime.datetime.now()
    rent_starts = datetime.datetime.strptime(request.GET.get('date_start'), '%Y-%m-%d')
    rent_ends = datetime.datetime.strptime(request.GET.get('date_end'), '%Y-%m-%d')

    rent_duration = rent_ends - rent_starts
    days_till_rent_start = rent_starts - search_date

    search_date = search_date.strftime('%Y-%m-%d')
    rent_duration = rent_duration.days
    days_till_rent_start = days_till_rent_start.days

    data = {'user_email': user_email, 'user_phone': user_phone,
        'search_date': search_date, 'rent_duration': rent_duration,
        'days_till_rent_start': days_till_rent_start}

    return {'search_data': data}

I use this function to return information about searches user make on page. Function returns data in readable format for user. I give this info to javascript function. This information is used for remarketing.


texts: Relaying stdin data from one thread to another

texts:
I'd like to know if this piece of code is thread-safe. I'm learning something about threads, queues and synchronization, and I'd like to make sure this is correct, before moving forward to next step.

The code is very simple. It just runs two threads (producer and consumer). Producer reads data from stdin (until "0" is entered) and pushes into a queue.
Consumer, just prints queue contents each 10 secs.

The way I tried to make it thread-safe:

using an atomic boolean variable, running,  in the consumer loop
push to and pop from queue using mutex variable, m_queueMutex.

I cannot use c++11 standard. That's why I used boost library.

The code compiles and works as expected using GCC. To compile:
g++ -g -o queues queues.cpp  -lboost_thread -lboost_system -lboost_chrono

Any other advice will be very welcome.

Code:

#include <iostream>
#include <queue>
#include <string>
#include <boost/thread.hpp>
#include <boost/thread/scoped_thread.hpp>
#include <boost/chrono.hpp>
#include <boost/atomic.hpp>

std::queue<std::string> myqueue;
boost::atomic<bool> running;
boost::mutex m_queueMutex;

void push(std::string& val) {

    boost::mutex::scoped_lock lock(m_queueMutex);
    myqueue.push(val);
}

std::string pop() {
    std::string val = "";

    boost::mutex::scoped_lock lock(m_queueMutex);

    if (!myqueue.empty()){
        val = myqueue.front();
        myqueue.pop();
    }

    return val;
}

void wait(int seconds) {
  boost::this_thread::sleep_for(boost::chrono::seconds(seconds));
}

void consume () {
    while (running || !myqueue.empty()) {
        if (!myqueue.empty()) {
            std::string dt = pop();

            wait(10);
            std::cout << "[CONS] -- Got: " << dt << std::endl;
        }
        wait (1);
    }

    std::cout << "[CONS] -- Quiting.. " << std::endl;
}

void produce() {
    std::string data;

    do {
        std::cout << "# ";
        std::cin >> data;
        if (data != "0") {
            push(data);
            std::cout << "[PROD] -- Add: " << data << std::endl;
        }
    } while (data != "0");

    std::cout << "[PROD] -- Quiting.. " << std::endl;

    running = false;
}

int main() {
    std::cout << "Started... " << std::endl;

    running = true;

    boost::thread producer = boost::thread(produce);
    boost::thread consumer = boost::thread(consume);
    //boost::scoped_thread<> producer((boost::thread(produce)));
    //boost::scoped_thread<> consumer((boost::thread(consume)));

    producer.join();
    consumer.join();

    std::cout << "Ended... " << std::endl;
}


texts: A sleep primitive for CUDA device-side code

texts:
I've so far been spared the need to waste any cycles on the GPU, but it seems like this might change. After getting some information I was missing about the semantics of CUDA's clock64() function, I've written the following bit of code for use in kernels (or other device-side functions):

// Shouldn't this be typedef'ed in the CUDA headers somewhere?
using clock_value_t = long long;

namespace detail {

__device__ void sleep(
    clock_value_t            num_cycles,
    volatile clock_value_t*  buffer_to_avoid_optimization)
{
    clock_value_t start = clock64();
    clock_value_t now;
    while (true) {
        now = clock64();
        // (Note the assumption of no wrap-around)
        clock_value_t cycles_elapsed = now - start;
        if (cycles_elapsed >= num_cycles) { break; }
    }
    // The memory write here should (hopefully) prevents the compiler
    // from optimizing the entire loop away
    *buffer_to_avoid_optimization = now - start;
}

} // namespace detail

/**
 * Have the executing warp busy-sleep until at least a certain
 * number of SM clock cycles have passed.
 *
 * @note The exact number of cycles busy-slept will depend on how soon the
 * warp will be scheduled to execute again after the last time it
 * iterates the elapsed-cycles check.
 *
 * @param num_cycles The minimum number of cycles to busy-sleep
 */
__device__ void sleep(clock_value_t num_cycles)
{
    static volatile clock_value_t buffer;
    detail::sleep(num_cycles, &buffer);
}

Other than general observations which are welcome, I have a few questions:

Is this approach reasonable, or should I be doing something very different?
Is there a better way of avoiding the while(true) loop from being optimized away?
Do I even need the volatile modifier on buffer_to_avoid_optimization?
Could I use a reference instead of a pointer?
Should I give it a different name?


texts: Retrieving my public IP address with the javascript Fetch API (no jquery, no json)

texts:
Note for future reference and google searches
The list of urls for IP retrieving will very likely need continuous adjustments in the future.
// Few services that should return the IP as plain text,
// properly configured to accept CORS
const IP_URLs = [
  'https://api.ipify.org/',
  'https://ipecho.net/plain',
  'https://api.kwelo.com/v1/network/ip-address/my',
  'https://myexternalip.com/raw',
];

Original question
This code is for retrieving the public IP address. I wanted something that can automatically switch between a few services in case the some of them are down. Since I do not use jquery in my project, I preferred the Fetch API aiming at keeping the code as light as possible. I was not able to find anything similar in the web, so here we go!
I am mostly concerned about correctness, but since I consider myself a beginner in JS, also readability, style, indentation are all very relevant. Should I have used async/await?
// Few services that should return the IP as plain text, properly configured to accept CORS
const IP_URLs = [
  'https://api.ipify.org/',
  'https://ipecho.net/plain',
  'https://api.kwelo.com/v1/network/ip-address/my',
  'https://myexternalip.com/raw',
];

// Log my public IP in the console
get_ip(IP_URLs, console.log);

// Trampoline that deep copies the urls array to later allow for pop() and recursion
function get_ip(urls, callback) {
  get_ip_impl(urls.slice(), callback);
}

function get_ip_impl(urls, callback) {
  if (urls.length > 0) {
    let url = urls.pop();
    let init = {
      method: 'GET', // *GET, POST, PUT, DELETE, etc.
      mode: 'cors', // no-cors, *cors, same-origin
      cache: 'no-store', // *default, no-cache, reload, force-cache, only-if-cached
      credentials: 'same-origin', // include, *same-origin, omit
      headers: {
        'Content-Type': 'application/text'
      },
      redirect: 'follow', // manual, *follow, error
      referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    };
    fetch( url, init).then(
      response => {
        response.text().then(
          txt   => { if (isValidIP(txt)) {
                       callback(txt);
                     } else {
                       console.log("Invalid IP: "+url+" --> "+txt);
                       get_ip_impl(urls, callback);
                     }
                   },
          notxt => { console.log("text(): "+url+" --> "+notxt);
                     get_ip_impl(urls, callback);
                   }
        )
      },
      reason => { console.log("Fetch: "+url+" --> "+reason);
                  get_ip_impl(urls, callback); }
    );
  } else {
    callback("No more URLs");
  }
}

function isValidIP(txt) {
  return /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(txt);
}


texts: Sort characters in a Python string by frequency

texts:
I wrote a solution to the leetcode problem Sort characters by frequency and the solution passes 34/35 test cases. On the last test case, there is a "time limit exceeded" error with an input string of 100000+ "a" and "b" characters. How can the following code be optimized to handle an input of that size?

 def frequencySort(s):
        """
        :type s: str
        :rtype: str
        """
        freq = {}
        for i in s:
            if i in freq:
                freq[i] +=1
            else:
                freq[i] = 1
        output = ""
        newDict =  sorted(freq.items(), key=lambda kv: kv[1],reverse = True)
        for k,v in newDict:
            for i in range(v):
                output += k
        return output


texts:
So I came across this question on SO and I felt like it would be a cool thing to try and write a parser for since I always wanted to try it. So I present to you:
My first time writing a parser.
It converts strings like this:
"a,s,[c,f],[f,t], [[a,c],[d3,32]]"

into list objects
['a', 's', ['c', 'f'], ['f', 't'], [['a', 'c'], ['d3', '32']]]

Here is my code for now
def parseToList(string, cont=0):
  result = list()
  temp = ''
  i = cont
  while i < len(string):
    if string[i] == ',':
      if len(temp) and temp != ' ':
        result.append(temp)
      temp = ''
    elif string[i] == '[':
      res = parseToList(string, i+1)
      i = res[1]
      result.append(res[0])
    elif string[i] == ']':
      if len(temp) and temp != ' ':
        result.append(temp)
      return (result,i)
    else:
      temp += string[i]
    i += 1
  if len(temp) and temp != ' ':
    result.append(temp)
  return (result, i)

def listParse(string):
  return parseToList(string)[0]

s = 'a,s,[c,f],[f,t], [[a,c],[d3,32]]'

print(s)
print(listParse(s))

Is there anything I am doing wrong? Something I should change?