texts:
I want to download data for all of my repos from the Github API.

Github paginates their responses and includes a header Link type:"next" when there's another page available. So I know I want to wait for all the pages to be received... but I don't know initially how many pages there are going to be, and I don't know if there's a next page until the one before it comes in.

So far I've got this, and it works:

var allRepos = [];
var repoPageReqs = [$.Deferred()]; // <-- sketchy
function receivedReposPage(data, status, req) {

    //handle error inadequately but whatever for now
    if (status !== "success") { console.log(data, status, req); return; }

    console.log("Received repos from Github:", data);
    for (i in data) {
        allRepos.push(data[i]);
    }
    saveRepos(allRepos);

    var headerLink = req.getResponseHeader("Link");
    var headerLinkNext = parseLinkHeader(headerLink)["next"];
    if (headerLinkNext) {
        console.log("Following 'next' header link, collecting paginated repos.");
        repoPageReqs.push(downloadRepos(headerLinkNext));
    } else {
        repoPageReqs[0].resolve(); // <-- resolve sketchiness
    }
}

function downloadRepos(path) {
    return $.get(path, receivedReposPage);
}

function downloadAllRepos(path) {
    repoPageReqs.push(downloadRepos(path));
    return $.when.apply(null, repoPageReqs);
}

$(function () {
    downloadAllRepos("https://api.github.com/my/repos/path")
      .then(function () {
           console.log("finished downloading all repos");
      })
});

The reason I use the sketchy [$.Deferred()] was because the $.when would resolve before the callback pushed the new $.get promise into the promisey array.

Is there a better way to make/resolve this kind of "unraveling" chain?


texts: Guidance to implement Ordinary least squares more efficiently

texts:
I have implemented a program that carries out ordinary least squares in raw python (but using numpy arrays rather than lists). I would like for my code to be critiqued by the community.
What is a faster/more efficient way to implement ordinary least squares than what I have done in my code snippet below?
The assumption is that there is one feature dimension. (A.T * A is 2 X 2)
My goal is to implement this in C, and then the parallel-izable parts in CUDA C

mat = np.array([
    [1.,1.],
    [1.,2.],
    [1.,3.],
])

arr = np.array([
                [1., 2., 4.]
]).T

def least_squares(mat, arr):
    #matrix for A.T * A
    new_arr = np.array([
                [0.,0.],
                [0.,0.]
    ])
    #Right hand side vector
    new_right = np.array([
            [0., 0.]
    ]).T

    #Solution Vector
    x_hat = np.array([
            [0., 0.]
    ]).T
    #Calculate A.T * A
    for i in range(3):
        new_right[0][0] += mat[i][0] * arr[i]
        new_right[1][0] += mat[i][1] * arr[i]
        for j in range(2):
            new_arr[0][j] += mat[i][0] * mat[i][j]
            new_arr[1][j] += mat[i][1] * mat[i][j]

    #Perform Elimination on A.T * A & right side b
    row_multiple = new_arr[1][0]/new_arr[0][0]
    new_arr[1] -= (row_multiple)*new_arr[0]
    new_right[1,0] -= row_multiple*new_right[0,0]

    #Solve for x-hat
    x_hat[1,0] = new_right[1,0] / new_arr[1,1]
    x_hat[0,0] = (new_right[0,0] - new_arr[0,1]*(new_right[1,0] / new_arr[1,1])) / new_arr[0,0]
    return x_hat


texts:
I'm using the following Bash CGI to upload a file:

#!/bin/bash
echo "Content-Type: text/plain"
echo

if [ "$REQUEST_METHOD" = "POST" ]; then
    TMPOUT=hello
    cat >$TMPOUT

    # Get the line count
    LINES=$(wc -l $TMPOUT | cut -d ' ' -f 1)

    # Remove the first four lines
    tail -$((LINES - 4)) $TMPOUT >$TMPOUT.1

    # Remove the last line
    head -$((LINES - 5)) $TMPOUT.1 >$TMPOUT

    # Copy everything but the new last line to a temporary file
    head -$((LINES - 6)) $TMPOUT >$TMPOUT.1

    # Copy the new last line but remove trailing \r\n
    tail -1 $TMPOUT | tr -d '\r\n' >> $TMPOUT.1
fi

This is for a uClinux/Busybox server. When a file is passed this way, the original $TMPOUT will contain a four line head and one line tail that need to be removed to end up with the same file. The resulting file's hash is identical to the original.

It works but it seems pretty ugly, creating two files and such. I'm by no means a pro in bash, can this be made prettier?

Keep in mind that the target is a little embedded device and has no Perl/Python or anything on it. It needs to be pure bash.


texts: A program to display, update and save a dictionary as .csv

texts:
I'm now looking for feedback on v2.0 of this program instead.

I'd like some feedback about my code. What bad habits do I have? What advice could help me write more Pythonic?

I'm trying to write a console application and want a tool to display, update and save settings in a dictionary.

def file_as_string(file_name):
    with open(file_name, 'r') as opened_file:
        string = opened_file.read().replace('\n', '')
        return string

def csv_as_dict(file_name):
    file_name = file_name + '.csv'
    import csv
    dictionary = {}
    for key, value in csv.reader(open(file_name)):
        dictionary[key] = value
    return dictionary

def print_formatted_dict(dictionary, key_title , value_title):
    print "{:^30} {:^15}".format('%s', '%s') % (key_title, value_title)
    for setting, value in dictionary.items():
        print "{:<30} {:<15}".format(setting, value)

def generic_prompt(prompt):
    value = raw_input(prompt)
    return value

def prompt_for_item(prompt, item):
    prompt = prompt + ' ' + item + ': '
    value = raw_input(prompt)
    return value

def change_dict_value(dictionary, prompt, item):
    value = prompt_for_item(prompt, item)
    dictionary[item] = (value)
    return dictionary

def csv_save_dict(dictionary, file_name):
    file_name = file_name + '.csv'
    import csv
    csv_file = csv.writer(open(file_name, "w"))
    for key, value in dictionary.items():
        csv_file.writerow([key, value])

def change_dict(dictionary):
    specify_question = 'Specify'
    change_question = 'Change settings? '
    setting_question = 'Setting to change: '
    save_question = 'Save settings? '

    change_answer = generic_prompt(change_question)
    while change_answer not in yes_no:
        change_answer = generic_prompt(change_question)
    while change_answer == 'yes':
        change_item = generic_prompt(setting_question)
        while change_item not in dictionary:
            change_item = generic_prompt(setting_question)
        dictionary = change_dict_value(dictionary, specify_question, change_item)
        print_formatted_dict(dictionary, key_title, value_title)
        change_answer = generic_prompt(change_question)
        while change_answer not in yes_no:
            change_answer = generic_prompt(change_question)
        if change_answer == 'no':
            save_answer = generic_prompt(save_question)
            while save_answer not in yes_no:
                save_answer = generic_prompt(save_question)
            if save_answer == 'yes':
                filename_answer = generic_prompt(filename_question)
                csv_save_dict(dictionary, filename_answer)
    return dictionary

def load_dict(dictionary):
    load_answer = generic_prompt(load_question)
    while load_answer not in yes_no:
        load_answer = generic_prompt(load_question)
    if load_answer == 'yes':
        filename_answer = generic_prompt(filename_question)
        dictionary = csv_as_dict(filename_answer)
        print_formatted_dict(dictionary, key_title, value_title)
    if load_answer == 'no':
        pass
    return (dictionary, load_answer)

def load_change_loop(dictionary, load_answer):
    while load_answer == 'yes':
        dictionary = change_dict(dictionary)
        dictionary, load_answer = load_dict(dictionary)
    return dictionary

def main():
    default_dict = csv_as_dict(default_settings)
    print_formatted_dict(default_dict, key_title, value_title)
    dictionary = load_change_loop(default_dict, load_answer)
    return dictionary

#string variables
default_settings = 'default_settings'
load_question = 'Load a dictionary? '
filename_question = 'File name: '
key_title = 'Setting'
value_title = 'Value'
load_answer = 'yes'

#list variables
yes_no = ['yes', 'no']

main()

The console with highlighted user input looks like this:

The program begins by reading a default_settings.csv file, mine looks like this:


texts: Doing #ifdef DEBUG and #define func() right?

texts:
This doesn't seem quite right, but it's the best I could do. Is there a way to do this better? My goal is to use DEBUG when I'm developing by doing a 'cc -DDEBUG' at the prompt.

#ifndef DEBUG
#define ptrValues ptrvaluesRemote
#else
#define ptrValues ptrValuesLocal
#endif

ptrLinks = (struct sLinkDescriptionLayout*) ptrValues();


texts: Handling errors in potentially incomplete responses

texts:
I am using the library geoip2 to get Geolocation of many IP adderesses

"""
input:
        str:   IP
output ordered list:
    [0] str:   City, State, Country
    [1] tuple: (Lat; Log)
    [2] str:   Postal
"""

for i in pd.unique(df_to_print['requesterIp']):
    res = reader.city(i)
    # NOTE: Second snippet is added here
    myDict[i] = [res.city.names['en'] + ", " + res.subdivisions[0].names['en'] + ", " +  res.country.names['en'],(res.location.latitude, res.location.longitude), res.postal.code]

# output:  ['Calgary, Alberta, Canada', (50.9909, -113.9632), 'T2C']

Sometimes the response, which is in JSON, is missing some fields. This causes a exception.
Here is my proposed "fix", the code works as intended, but looks sinful
try:
    city = res.city.names['en']
except:
    city = "-1"

try:
    state = res.subdivisions[0].names['en']
except:
    state = "-1"

try:
    country =  res.country.names['en']
except:
    country =  "-1"

try:
    cord = (res.location.latitude, res.location.longitude)
except:
    cord = (-1, -1)

postal = res.postal.code if res.postal.code is not None else -1

print([city + ", " + state + ", " +  country, cord, postal])
# output: ['-1, -1, China', (34.7725, 113.7266), -1]

What can I do to make my code more professional and efficient?
(this will run for apx. 100K unique IPs, several times a hour; DB is local)


texts:
I am pushing an Excel file to the server and then reading it's contents. XLS and XLSX files need to be read differently, but the DLL that I'm using has the EXACT same function calls for both types. If I use a 'dynamic' type, I can save a lot of lines of code and avoid redundancy. However, I've been told many times before to avoid using dynamic if possible. Is this a good place to use it?

dynamic excelFile; // is this a good use of dynamic?
switch (fileExtension)
{
    case "xls":
        excelFile = new Excel2007();
        break;
    case "xlsx":
        excelFile = new Excel();
        break;
    default:
        results.Message = string.Format("{0} is of an unrecognized format.", uploadFile.FileName);
        return RedirectToAction("ImportWizard");
}

excelFile.OpenDatabase(targetPath, new FieldData());
excelFile.CurrentTable = excelFile.Tables[0];

var excelRecords = excelFile.ReadRecords(100);
excelFile.CloseDatabase();


texts:
I was wondering how I can make this code more pythonic. More professonal-looking and more readable. The code runs perfectly fine.

# Uses Python 3
"""
Finds the closest pair of point from a set of points on a plane
by brute-force (O(n^2)) and divide-and-conquer algorithms (O(nlog(n))).
Input: x,y coordinates (float)
Output: minimum distance (float)& closest pair (complex number)
@ Author: RA
"""

import sys

# Brute force algorithm.

def brute_force(xpoints):  # px will be passed to the function
    n = len(xpoints)
    if n < 2:
        return float('inf'), (None, None)
    else:
        sep = float('inf')  # set the initial minimum to infinity
        pair = ()
        for i in range(n - 1):
            for j in range(i + 1, n):
                if abs(xpoints[i] - xpoints[j]) < sep:
                    sep = abs(xpoints[i] - xpoints[j])
                    pair = (xpoints[i], xpoints[j])

    return sep, pair

# Divide and Conquer

def divide_n_conquer(xpoints, ypoints):
    n = len(xpoints)
    if n <= 3:
        return brute_force(xpoints)

    xmedian = int(n / 2)

    yl, yr = [], []
    for p in ypoints:
        if p.real < xpoints[xmedian].real:
            yl.append(p)
        else:
            yr.append(p)

    (l_sep, l_pair) = divide_n_conquer(xpoints[:xmedian], yl)
    (r_sep, r_pair) = divide_n_conquer(xpoints[xmedian:], yr)

    (sep, pair) = (l_sep, l_pair) if l_sep < r_sep else (r_sep, r_pair)

    sep_strip, pair_strip = split(xpoints, ypoints, sep)

    if sep_strip < sep:
        sep = sep_strip
        pair = pair_strip

    return sep, pair

def split(xpoints, ypoints, sep):
    xdivider = xpoints[int(len(xpoints)/2)].real
    ystrip = [item for item in ypoints if
              abs(item.real - xdivider).real < sep]

    ns = len(ystrip)  # Number of points in the strip
    sep = float('inf')
    pair = ()
    if ns > 1:

        for i in range(ns - 1):
            for j in range(i + 1, min(i + 8, ns)):
                if abs(ystrip[i] - ystrip[j]) < sep:
                    sep, pair = abs(ystrip[i] - ystrip[j]), (ystrip[i], ystrip[j])

    return sep, pair

if __name__ == '__main__':
    _input = sys.stdin.read()
    data = list(map(int, _input.split()))
    n = data[0]
    x = data[1::2]
    y = data[2::2]
    p = [complex(x, y) for x, y in zip(x, y)]
    px = sorted(p, key=lambda p: p.real)  # points sorted by x
    py = sorted(p, key=lambda p: p.imag)  # points sorted by y
    print("{0:.9f}".format(divide_n_conquer(px, py)[0]))


texts:
I'm making a Mario clone in PyGame and I am writing a function that, after releasing the left and right button while Mario is moving horizontally, slows him down until he is at rest. As of right now, the code I am using is functional and works the way it should. Though, I am not sure if there is a way I can write the following code more efficiently:

self.deacc = 0.5 # Always a positive number, never changed anywhere in the code.

if self.horzDir == 'l': # if mario is moving left.
    self.x += self.dx
    self.dx += self.deacc

    # To ensure marios velocity doesnt go below zero.
    if self.dx > (self.deacc * -1):
        self.dx = 0
else:
    self.x += self.dx
    self.dx -= self.deacc

    # Also to ensure marios velocity doesnt go below zero.
    if self.dx < self.deacc:
        self.dx = 0

Everything is working correctly, but I feel like it can be more efficient than this because the if and else statements are very similar, just with slightly different calculations. Any ideas?


texts: C program to create and print a linked list from the command line

texts:
This program will create a linked list, set the values, and print the list by using command line options.

This is my first implementation of a linked list so I'm not sure if I did it correctly. The available options are:

-a to add nodes.

To add several nodes:-a "23 56 1" will add three nodes with the respective values

-p will print the nodes. It has to be used after -a or else it will result in an error message.

I'm not looking for any specific input, style, comments, functions used, anything.

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

struct node{
    int value;
    struct node *next_ptr;
};

struct node *head;

void add_node(int data);
void print_nodes(void);

int main(int argc, char *argv[]){
    int c;
    long node_value;
    char *ptr;
    char *token;
    const char s[2] = " "; /*Split optarg based on this string*/

    while((c = getopt(argc, argv, "pa:")) != EOF){
        switch(c){
        case 'p':
            print_nodes();
            break;
        case 'a':
            token = strtok(optarg, s); /*Split the string*/
            while(token != NULL){
                node_value = strtol(token, &ptr, 10); /*Convert each string to integer*/
                if((*ptr) != 10 && (*ptr) != 0){ /*If it's not a newline or a null then invalid input*/
                    fprintf(stderr, "Invalid number: %c", *ptr);
                    exit(EXIT_FAILURE);
                }
                add_node(node_value);
                token = strtok(NULL, s);
            }
            break;
        default:
            fprintf(stderr, "Unknown option %c, available options are '-p' and 'a'", c);
            break;
        }
    }
    argc -= optind;
    argv += optind;

    return 0;
}

void add_node(int data){
    struct node *temp = head;

    if(temp == NULL){
        head = malloc(sizeof(struct node));
        head->value = data;
        head->next_ptr = NULL;
        return;
    }

    while(temp->next_ptr != NULL){
        temp = temp->next_ptr;
    }

    if((temp->next_ptr = malloc(sizeof(struct node))) == NULL){
        fprintf(stderr, "Out of memory");
        exit(EXIT_FAILURE);
    }

    temp = temp->next_ptr;
    temp->value = data;
    temp->next_ptr = NULL;
}

void print_nodes(void){
    struct node *temp = head;
    if(temp == NULL){
            printf("Linked list is empty\n");
    }
    for(temp = head; temp != NULL; temp = temp->next_ptr){
        printf("%i\n", temp->value);
    }
}

I want to add more options, sort, search, delete and file integration, but I'd like to make sure this is working correctly first.


texts: Rewriting domain only if not on local dev enviroment and forcing www with Mod Rewrite

texts:
I'm trying to write some mod rewrite code to redirect pages on a site to always use www and this has been working fine:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

However, I now want to make sure this doesn't happen on my dev environment, which uses the .local domain extension...

So I changed it to this:

RewriteCond %{HTTP_HOST} !\.local$
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Does that seem correct?

As I understand it, it states: "If it doesn't END with .local AND it doesn't START with www. THEN do the RewriteRule"?


texts:
few days ago i made small PHP Authentication API with all basic functionalities (log in, log out, registration, getting authenticated member) and i got suggestions that i should use prepared statements for better performance and SQL Injection defense, so i made some changes to my script and it looks like this, can anyone confirm if it is good, did i miss something and is there anything else that i can improve here.

<?php
require_once '../dbConnect.php';
session_start();

$object = json_decode(file_get_contents("php://input"), true);

if (isset($object['email']) && isset($object['password'])) {

    $email = $object['email'];
    $password = $object['password'];

    $stmt = $mysqli->prepare("select id, password from members where email = ?");

    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->bind_result($id, $password);
    $stmt->fetch();

    if($id) {
        if (password_verify($object['password'], $password)) {
            $message = array('message' => 'Authentication Successful!');
            $_SESSION["id"] = $id;
            echo json_encode($message);
        } else {
            $message = array('message' => 'Wrong Credentials, Authentication failed!');
            session_destroy();
            http_response_code(400);
            echo json_encode($message);
        }
    } else {
        session_destroy();
        http_response_code(406);
    }

    $mysqli->close();

} else {
    session_destroy();
    http_response_code(400);
}
?>


texts:
This is a program I wrote to print out 100 prime numbers. How can I improve it?

// Calculating primes
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main()
{
    const int MAX(100);      // Number of primes to be identified
    long primes[MAX] = {};
    long trial(5);            // Hold a candidate prime
    int count(0);             // Count primes found
    bool found(false);      // Indicates when a prime is found

    vector <long> nonPrimes; //Vector to hold non prime numbers
    vector <long> disqualify; //Vector to hold prime numbers that disqualify the non prime numbers as prime numbers.

    do
    {
        trial += 2;             // Produce next candidate value
        found = false;      // Reset indicator - assume it is not prime

        for (int i = 0; i < count; i++)   // Try division by existing primes
        {
            found = (trial % primes[i]) == 0; // True if no remainder
            if (found) // No remainder means number is not a prime
                break;
            // Terminate the division loop
        }
        // The above loop will exit either due to a break or after trying all
        // existing primes as a divisor. found was initialized to false. If
        // found is false after exiting the loop, a divisor was not found.
        if (!found)             // We have a new prime: not false = true
            primes[count++] = trial;  // Save candidate in next array position
    } while (count < MAX);

    // Main loop has completed - we have found MAX prime numbers.
    // Display the prime numbers, presenting five numbers on one line.
    cout << "Prime numbers found during the program execution:" << endl;
    for (int i = 0; i < MAX; i++)
    {
        if (i % 5 == 0)      // For a new line on first line of output
            cout << endl;      // and on every fifth line that follows
        cout << setw(10) << primes[i];  // Provide space between numbers
    }

    cout << endl;            // All primes displayed - for a new line

    //system("pause");
return 0;
}


texts: Sample size, P-values (its relationship), and data visualization with plots. ggplot and T test

texts:
We know that P-values (within t-test context as an example..) is highly sensitive to sample size. A larger sample will yield a smaller p-value remaining everything else constant. On the other hand, Cohen´s d effect size remains the same.

I'm inspired in this code here, but I´ve changed some parts to make the difference between means constant, instead of creating a random variable based on a normal distribution.

Although everything is working, I do imagine that some of the experts in this community could improve my syntax.

library(tidyverse)

ctrl_mean <- 8
ctrl_sd <- 1

treated_mean <- 7.9
treated_sd <- 1.2

sample <- numeric() #criar vetor para grupar resultados
nsim <- 1000 #criar variavel
t_result <- numeric()

for (i in 1:nsim) {
  set.seed(123)
  t_result[i] <- (mean(ctrl_mean)-mean(treated_mean))/sqrt((ctrl_sd^2/(i))+(treated_sd^2/(i))) #manual t test
  sample[i] <- i # number of participants
}
ds <- data.frame(
  sample = sample, #assign the sample size
  t_result = round(t_result,3), #get the t test result
  degrees = sample*2-2) #compute the degrees of freedom

ds %>%
  filter(sample>1) %>%
  mutate(P_Value = 2*pt(abs(t_result), df=degrees,lower.tail=FALSE)) %>%
  left_join(ds,.) -> ds

#plot
ggplot(ds, aes(x=sample, y=P_Value)) +
  geom_line() +
  annotate("segment", x = 1, xend=sample, y = 0.05, yend = 0.05, colour = "purple", linetype = "dashed") +
  annotate("segment", x = 1, xend=sample, y = 0.01, yend = 0.01, colour = "red", linetype = "dashed") +
  annotate("text", x = c(1,1), y=c(.035,.001), label = c("p < 0.05", "p < 0.01"))


texts:
Please review this connection pool. I tested it and it works but can we improve it from design or performance perspective?

public class ConnectionPool {

    private static final int MAX_SIZE=10;
    private static final BlockingQueue<Connection> bq;

    static{
        bq= new ArrayBlockingQueue<Connection>(MAX_SIZE);
        for(int i=0;i<MAX_SIZE;i++)
        {
            try {
                bq.add(makeConnection());
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        System.out.println("total size:" + bq.size());
    }

    public static Connection getConnection() throws InterruptedException
    {
        System.out.println("size before getting connection"+ bq.size());
        Connection con=bq.take();
        System.out.println("size after getting connection"+ bq.size());
        return (con);
    }

    public static boolean releaseConnection(Connection con) throws InterruptedException
    {
        System.out.println("size before releasing connection"+ bq.size());
        boolean bool =bq.add(con);
        System.out.println("size after releasing connection"+ bq.size());
        return (bool);
    }

    public static Connection makeConnection() throws SQLException {
        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", "root");
        connectionProps.put("password", "java33");
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        conn = DriverManager.getConnection("jdbc:" + "mysql" + "://"
                + "localhost" + ":" + "3306" + "/test", connectionProps);

        System.out.println("Connected to database");
        return conn;
    }
}


texts: Splitting text into individual characters for animation

texts:
I have code which makes use of jQuery and some additional libraries. But the jQuery part is too overwhelming (and thus it does its job slowly). So I tried to optimize it, but had no luck. Now I'm seeking help from the community.

Here is the code, from the news page in my WP theme:

/*
 CSS Reset
*/
   html,body,div,span,applet,object,iframe,audio,video,h1,h2,h3,h4,h5,h6,h7,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark {
 vertical-align: baseline;
}
#gsap-title-, #gsap-meta- {
    position: relative;
}
#gsap-title- span, #gsap-meta- span  {
 position: relative;
 display:inline-block;
 -webkit-font-smoothing:antialiased;
}
<!DOCTYPE html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">

This is title

To start animation, click Run.

Then click here, or resize the height of this window (simulate 'inview' event).

As you can see, this whole code is too overwhelming. Thus I tried to simplify the jQuery code.

I tried to process  $title and $postmeta with .html() simultaneously, and only then pass them to .on(). Thus :

$([$title, $postmeta]).each(function(){ // ...did work, but incorrectly - all $title and $postmeta were processed, but at the output - in each line containing  some id=gsap-title-, all matching elements gsap-title-1, gsap-title-2... gsap-title-n are displayed (the same as gsap-meta-), ...all of them, in each line ( e.g. merged in an unwanted manner);

Also I had a look at .add(), .concat() and .push() but according to examples, output is similar to .merge() method.

To sum up: current state - lots of code, lots of similar jQuery code, desired state - less jQuery code, with the same functionality.


texts: How to make this algorithm faster. Calculates and searches through large arrays

texts:
Ive got this algoritm thats "complex". The comments in code give examples of how large the various data types could be. My cpu usage is less than 10% when running this and ram usage is good. no leakage or anything.
I have a list of arrays. where each array is x coordinates. We are storing a list of several x coordinate-groups essentially. = "xs" in code
And I have the same thing but for y-values = "ys"
Each array in xs and ys are different sizes. HOWEVER, the size of xs and ys is always the same. So if an array in xs contains 321654 elements then there is a corresponding array in ys with exactly 321654 elements.
The corresponding elements or "paired" xs and ys arrays are always at the same index in their corresponding list. so if xs_array[321654] is in xs[4] then ys_array[321654] is at ys[4].
The following code aims to get mean values. standard deviation and -1std and +1std from mean, as y coordinates from a collection of coordinates. It does this by taking the smallest arrays (the smallest set of x and y coordinates. It then looks at each array in xs and finds the index at which the x-coordinates are in the array. It then goes into ys, finds the corresponding xs array, and gets the y value from the x-coordinate. It goes through this, adds it all up. calculate, mean, std etc etc.
    List<Double[]> xs;  //each array may be be e.g 40000 elements. and the list contains 50 - 100 of those
    List<Double[]> ys; //a list containing arrays with an exact equal size as xs

public void main_algorithm()
{

    int TheSmallestArray = GetSmallestArray(xs); //get the smallest array out of xs and store the size in TheSmallestArray
    for (int i = 0; i < TheSmallestArray; i++)
    {
        double The_X_at_element = The_Smallest_X_in_xs[i]; //store the value at the index i
        //go through each array find the element at which x_values is at. If it doesnt exist, find the closest element.
        List<Double> elements = new List<double>(); //create a new list of doubles
        for (int o = 0; o<xs.Count(); o++) //go through each array in xs
        {
            //go through the array o and find the index at which the number or closest number of the_X_at_element is
            int nearestIndex = Array.IndexOf(xs[o], xs[o].OrderBy(number => Math.Abs(number - The_X_at_element)).First());
            double The_Y_at_index = ys[o][nearestIndex]; //go through ys and get the value at this index
            elements.Add(The_Y_at_index); store the value in elements
        }
        mean_values.Add(elements.Mean()); //get the mean of all the values from ys taken
        standard_diviation_values.Add(elements.PopulationStandardDeviation());//get the mean of all the values from ys taken
        Std_MIN.Add(mean_values[i] - standard_diviation_values[i]); //store the mean - std and add to min
        Std_MAX.Add(mean_values[i] + standard_diviation_values[i]); //store the mean + std and add to max
    }
}

 public int GetSmallestArray(List<double[]> arrays)
{
    int TheSmallestArray = int.MaxValue;
    foreach(double[] ds in arrays)
    {
        if(ds.Length < TheSmallestArray)
        {
            TheSmallestArray = ds.Length; //store the length as TheSmallestArray
            The_Smallest_X_in_xs = ds;//and the entirety of the array ds as TheSmallestArray_xs
        }
    }
    return TheSmallestArray;
}


texts: Return all words which have their reverse present in a string

texts:
Problem Statement:

  Given a string of words return all words which have their reverse present in the string as ( (word1 , reverseword1 ) , (word2 ,reverseword2) )

Example Case:

Input:

  Sachin tendulkar is the best tseb eht nihcaS

Output:

  { ( best ,   tseb )  , ( the  ,  eht) , (Sachin  ,  nihcaS) }

My approach is to use a map and return the words if a match to the reverse of the current word is found in the map.

#include<iostream>
#include<unordered_map>
#include<string>

using namespace std;

int main()
{
unordered_map <string, int> binMap;
string test="Sachin tendulkar is the best tseb eht nihcaS si";
int i=0,j=0;
string temp,rev;
string::iterator it;
cout<<"{";

for(i = 0, it = test.begin() ; it <= test.end(); ++it)
    {

        if(*it==' ' || it==test.end())
        {
            temp=test.substr(j,i-j);
            rev=string(temp.rbegin(), temp.rend());
            if(binMap[rev]==1)
            cout<<"( "<<rev<<","<<temp<<" ), ";
            else
            binMap[temp]=1;
            j=i+1;
        }
        i++;
    }
cout<<"}";
return 0;
}

Is this the most optimal way to solve the problem or am I doing something wrong?


texts:
I wrote a python script that converts English to Entean language from an anime called "The Devil is a part timer". I am sloppy at coding and know that the script can be made better.

In the anime, the language in Ente Isla is called Entean, which is basically most of the consonants in the English alphabet switched around. Vowels and the consonants 'L', 'N', 'Q' keep their original position. ABCDEFGHIJKLMNOPQRSTUVWXYZ is changed to AZYXEWVTISRLPNOMQKJHUGFDCB.
    For example, 'human' is 'tupan', and 'world' becomes 'foklx'.

Here is the code:

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".lower()
switched = "AZYXEWVTISRLPNOMQKJHUGFDCB".lower()

usr_txt = input("Enter Englsih text:")

print(usr_txt)

def get_letter(eng_letter):
    if alphabet.find(letter):
        if eng_letter.isupper():
            alpha_place = alphabet.find(letter.lower())
            return(switched[alpha_place].upper())
        else:
            alpha_place = alphabet.find(letter.lower())
            return(switched[alpha_place])
    else:
        return(eng_letter)

ent_word = ""
ent_output = ""

for word in usr_txt.split(" "):
    ent_word = ""
    for letter in word:
        ent_letter = get_letter(letter)
        ent_word += ent_letter
    ent_output += " " + ent_word

print(ent_output.strip())

If you interested the updated code can be found at https://github.com/Logmytech/English-to-Entean


texts: Class for formatting topics using BBCodes

texts:
I'm developing a program for users from a VBulletin's forum. This forum has a lot of people interested in write good articles but some of them don't know how to use the formatting bar in his favor. Sometimes, the others members don't read this threads/articles because it doesn't have a interesting formatting (crazy world, huh?).
So here's my idea:

Idea

The user don't need to worry about formatting the thread, so he can be focused just on the writing and the content. The formatting part (the boring part) will be generated by the program, the user just need choose colors for titles and text content.

Code

I've created a class named Markup where all models for formatting will be set.

public class Markup {}

Inside this class I created a private enum to define Which BBcodes are accepted by VBulletin, something like:

enum BBcode {
  BOLD("B"),
  ITALIC("I"),
  IMAGE("IMG"),
  UNDERLINE("U"),
  VIDEO("VIDEO");
  /* many others... */

  final String code;
  private BBcode(String code) {
    this.code = code;
  }

  public String code(){
    return this.code;
  }
}

Still inside Markup class I've created a private class named Syntax to define how the BBcode syntax will created., like this:

class Syntax {
  public String in(BBcode bbcode){
    return "[" + bbcode.code() + "]"; // will return "[BOLD]" for example.
  }

  public String inValued(BBcode bbcode, String value){
    return "[" + bbcode.code() + "=" + value + "]"; // will return "[COLOR=#333]" for example.
  }

  public String out(BBcode bbcode){
    return "[/" + bbcode.code() + "]"; // will return "[/BOLD]" for example.
  }
}

So I can handle it like:

public String setContents(BBcode bbcode, String contents){
  return syntax.in(bbcode) + contents + syntax.out(bbcode); // will return "[BOLD]foo[/BOLD]
}

My questions:

The names for class and methods are ok? Other peoples can be part of the project and I want them to know what the class does.
All this stuff are inside the Markup class (because the BBcode and the Syntax will be util just for the Markup). It's a good practice group similar things inside a unique class?


texts: Code Golf Challenge: Calculate Phi (not Pi)

texts:
I'm a newbie to C++ (coming from C#) and I decided to complete this Code Golf challenge for fun (though I definitely wouldn't say it's short). Essentially, the challenge was to calculate the phi(not_pi()) of all the numbers from 1 to 100, and print them out in a loop, where

phi(n) is the number of integers less than or equal to n that are relatively prime to n.
not_pi(n) is the number of composites less than or equal to n.

Here is my code (I'm using Visual C++ 2015):

stdafx.h

#pragma once

#include "targetver.h"

#include <cmath>
#include <cstdio>
#include <tchar.h>

#include <iostream>
#include <stdexcept>

golf.cpp

#include "stdafx.h"

#define __nameof(var) #var

namespace golf
{
    int gcd(int left, int right) noexcept
    {
        if (right == 0)
            return left;
        return gcd(right, left % right);
    }

    bool relatively_prime(int left, int right) noexcept
    {
        return gcd(left, right) == 1;
    }

    int phi(int number)
    {
        if (number < 0)
            throw std::invalid_argument(__nameof(number));
        if (number == 0)
            return 0;
        if (number == 1)
            return 1; // 1 is the only number relatively prime to itself

        int result = 1; // We're always relatively prime to 1
        for (int i = 2; i < number; i++)
        {
            if (relatively_prime(i, number))
                result++;
        }

        return result;
    }

    bool prime(int number)
    {
        if (number < 0)
            throw std::invalid_argument(__nameof(number));

        int bound = static_cast<int>(std::floor(std::sqrt(number)));
        for (int i = 2; i <= bound; i++)
        {
            if (number % i == 0)
                return false;
        }

        return true;
    }

    int not_pi(int number)
    {
        if (number < 0)
            throw std::invalid_argument(__nameof(number));
        if (number <= 3)
            return 0;

        int result = 1;
        for (int i = 6; i <= number; i++)
        {
            if (!prime(i))
                result++;
        }

        return result;
    }

    int main()
    {
        for (int i = 1; i <= 100; i++)
        {
            std::cout << i << " " << phi(not_pi(i)) << std::endl;
        }

        return 0;
    }
}

int main()
{
    // Glue code because I didn't realize main()
    // was supposed to be in the global namespace.
    return golf::main();
}

Any tips on how I could improve my C++ code? Specifically, is there anything I could do to make it more "modern"/C++11-like, or practices I should follow? Are there any sources for undefined behavior/gotchas I didn't see? I'm a beginner so any feedback/critique would be appreciated.


texts: Set value to multiple selector on condition

texts:
I have code and set the value to hidden 0 or 1 on condition. Is there a better way to solve this?

<input type="hidden" name="type_product" value=""   class="type_product"/>
<input type="hidden" name="type_category" value=""  class="type_category" />
<input type="hidden" name="type_modifier" value=""  class="type_modifier"/>
<input type="hidden" name="type_variant" value=""   class="type_variant" />

<script>
   $(function(){
       let dataType = "product"; // category
       if (dataType == "product") {
           $(".type_product").val(1);
           $(".type_category").val(0);
           $(".type_modifier").val(1);
           $(".type_variant").val(0);
}
      if (dataType == "category") {
          $(".type_category").val(1);
          $(".type_product").val(0);
          $(".type_modifier").val(0);
          $(".type_variant").val(1);
      }
   })
 </script>


texts: Adding a node to a Binary Search Tree and printing the path to it

texts:
I wrote BST insertion code with the book. The book uses recursion, but I just want to know how I can do it without recursion.

My code is working, but I don't know if it is correct.

public class BSearchTree {
    BNode root = null;

    public void add(BNode node){
        int depth = 0;

        if(root != null){
            if(node.data == root.data) return;

            BNode p = root;

            while(p != null){
                depth++;

                if(p.data < node.data){
                    if(p.right != null){
                        p = p.right;
                    }else{
                        p.right = node;
                        node.index = depth;
                        break;
                    }
                }else{
                    if(p.left != null){
                        p = p.left;
                    }else{
                        p.left = node;
                        node.index = depth;
                        break;
                    }
                }
            }
        }else{
            root = node;
            node.index = depth;
        }

        inOrder(root, "[ROOT]");
    }

    public void inOrder(BNode node, String direction){
        BNode p = node;
        if(p == null) return;

        inOrder(p.left, "[LEFT]");
        System.out.println(p.index+": "+direction+" "+p.data);
        inOrder(p.right, "[RIGHT]");
    }
}


texts: Improving time complexity for Count the Islands DFS

texts:
For game AI development, I am currently using a slight modification on the DFS "count the islands" problem (specification below) as a solution to the One Hive Rule for the game of Hive. This may not be the ideal solution so I am open to any other ideas if you note DFS is not the best approach. Thank you.

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

My version utilises a 2D map (matrix) which represents a hexagonal board for the game.
The differences are:

My implementation uses hexagons so each cell has 6 neighbours, not 8
Blanks represent 0s and anything else are 1s
My implementation purposely stops if/when it finds more than one island/hive

My question is can the code be improved with regards to time complexity?
from insects import Blank

class HiveGraph:
    def __init__(self, board):
        self.row = board.height
        self.col = board.width
        self.visited = [[False for _ in range(self.col)] for _ in range(self.row)]
        self.graph = board.board

    # A function to check if a given hexagon can be included in DFS
    def is_safe(self, row, col):
        # row number is in range,
        # column number is in range,
        # and hexagon is Blank and not yet visited
        return (0 <= row < self.row and
                0 <= col < self.col and
                not self.visited[row][col] and
                type(self.graph[row][col]) is not Blank)

    # DFS for a 2D matrix. It only considers
    # the 6 neighbours as adjacent pieces
    def dfs(self, row, col):
        print(row, col)
        # These arrays are used to get row and
        # column numbers of 6 neighbours
        # of a given hexagon
        if col % 2 == 1:
            row_nbr = [-1,  0, 0,  1, 1, 1]
            col_nbr = [ 0, -1, 1, -1, 0, 1]
        else:
            row_nbr = [-1, -1, -1,  0, 0, 1]
            col_nbr = [-1,  0,  1, -1, 1, 0]

        # Mark this hexagon as visited
        self.visited[row][col] = True

        # Recur for all connected neighbours
        for k in range(6):
            if self.is_safe(row + row_nbr[k], col + col_nbr[k]):
                self.dfs(row + row_nbr[k], col + col_nbr[k])

    def one_hive(self):
        # Initialize count as 0 and traverse
        # through the all hexagons of given matrix
        count = 0
        for row in range(self.row):
            for col in range(self.col):
                # If a hexagon not Blank and is not visited yet,
                # then new hive found
                if not self.visited[row][col] and type(self.graph[row][col]) is not Blank:
                    # Visit all hexagons in this hive
                    # and increment hive count
                    count += 1
                    if count > 1:
                        return False
                    self.dfs(row, col)
        return True

Refer to this image for row, col matrix values for the layout of hexagons:


texts: Pythonic split list into n random chunks of roughly equal size

texts:
As part of my implementation of cross-validation, I find myself needing to split a list into chunks of roughly equal size.

import random

def chunk(xs, n):
    ys = list(xs)
    random.shuffle(ys)
    ylen = len(ys)
    size = int(ylen / n)
    chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)]
    leftover = ylen - size*n
    edge = size*n
    for i in xrange(leftover):
            chunks[i%n].append(ys[edge+i])
    return chunks

This works as intended

>>> chunk(range(10), 3)
[[4, 1, 2, 7], [5, 3, 6], [9, 8, 0]]

But it seems rather long and boring. Is there a library function that could perform this operation? Are there pythonic improvements that can be made to my code?


texts: Format raw bytes in hex and ascii in manner like Wireshark does in pure C

texts:
This function formats raw buffer output in manner as Wireshark and many others does:

0x00: 68 65 6C 6C 6F 20 77 6F 72 6C 64 02 6B 68 67 61   |hello world.khga|
0x10: 76 73 64 20 0B 20 0A 05 58 61 73 6A 68 6C 61 73   |vsd . ..Xasjhlas|
0x20: 62 64 61 73 20 6A 61 6C 73 6A 64 6E 13 20 20 30   |bdas jalsjdn.  0|
0x30: 31 32 33 34 35 36 37 38 39                        |123456789       |

Please review and assess code quality.
cppshell

#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>

static const char line_placeholder[] = "0x00:                                                   |                |";

size_t format_hex_payload_sizeof_output(const char* payload, size_t payload_len)
{
   size_t number_of_lines = payload_len / 16 + (payload_len%16 > 0);
   size_t sizeof_output = sizeof line_placeholder * number_of_lines;
   return sizeof_output;
}

size_t format_hex_payload(char* output, const char* payload, size_t payload_len)
{
   size_t number_of_lines = payload_len / 16 + (payload_len%16 > 0);
   size_t sizeof_output = sizeof line_placeholder * number_of_lines;
   // char *output = (char*)alloca(sizeof_output);

   char *pout = output;
   const char *p = payload;
   const char *const end = payload + payload_len;
   size_t ascii_offset = strchr(line_placeholder,'|') - line_placeholder + 1;  //could be calculated at compile time

   unsigned char offset = 0;
   for(unsigned l=0; l < number_of_lines; l++, offset+=16)
   {
      char* pline_begin = pout;
      char* pline = pout;
      strcpy(pline,line_placeholder);
      pline += sprintf(pline, "0x%02X: ", offset);
      for(unsigned i=0; i<16 && p < end; ++i, ++p){
         pline += sprintf(pline, "%02X ", *p);
         *(pline_begin+ascii_offset+i) = isprint(*p) ? *p : '.';
      }
      *pline=' ';
      pout += sizeof line_placeholder;  // next line
      pout[-1] = '\n';
   }
   pout[-1] = '\0';
   assert(pout == output + sizeof_output);  // sanity check

   return pout - output;
}

int main()
{
   const char input[] = "hello\x02";
   char outbuf[format_hex_payload_sizeof_output(input, sizeof input -1)];
   format_hex_payload(outbuf, input, sizeof input -1);
   printf("%s\n\n", outbuf);

   {
   const char input[] = "hello world\x02khgavsd \x0B \x0A\x05Xasjhlasbdas jalsjdn\x13xa0";
   char outbuf[format_hex_payload_sizeof_output(input, sizeof input -1)];
   format_hex_payload(outbuf, input, sizeof input -1);
   printf("%s\n\n", outbuf);
   }

   {
   const char input[] = "hello world\x02khgavsd \x0B \x0A\x05Xasjhlasbdas jalsjdn\x13  0123456789";
   char outbuf[format_hex_payload_sizeof_output(input, sizeof input -1)];
   format_hex_payload(outbuf, input, sizeof input -1);
   printf("%s\n\n", outbuf);
   }
}

As an improvement I'd add function that prints to file descriptor and extend current function that has output buffer size limitation, like snprintf().

This question is an improvement of Format raw bytes in hex and ascii in manner like Wireshark does, was created according to @MartinR's suggestion


texts: Get client information with GET request in GO API

texts:
For an API I have defined a "Client" struct which contains all the fields the client has in the database. When a GET request is made with the client ID the whole struct(The struct contains about 60 fields of different types) is returned with all available data. The request can be customized with a querystring "fields" which allow the user to return specific "Client" fields only regardless if they are empty, so omitempty or "-" will not work for my usecase.
GO playground example: https://play.golang.org/p/NTGxGQFz7-Y
type Client struct {
   Firstname   string `json:"firstname"`
   AltAddress  string `json:"alt_address"`
   Lastname    string `json:"lastname"`
}

Example: GET
GET /clients/id/1
Response:
{
  "firstname":   "Michael",
  "alt_address": "",
  "lastname":    "Smith"
}

Example: GET with querystring
Get /clients/id/1?fields=firstname, alt_address
Response:
{
  "firstname":   "Michael",
  "alt_address": ""
}

I have this method(objectToFilteredMap) which converts an interface(struct for example) to a map, removes the fields that are NOT defined in "fieldNames" and outputs it as a json object. But I feel like I am using to many "for" loops. Is there a more efficient way to filter out the unneeded fields? Or any other improvements would be appreciated.
var (
    regex = regexp.MustCompile(`^\w+$`)
)

func inSlice(slice []string, val string) bool {
    for _, item := range slice {
        if item == val {
            return true
        }
    }
    return false
}

func toMap(obj interface{}, fieldNames []string) (map[string]interface{}, error) {
    for k, f := range fieldNames {
        f = strings.TrimSpace(f)
        if !regex.Match([]byte(f)) {
            return nil, fmt.Errorf("Invalid field name: `%s`", f)
        }
        fieldNames[k] = strings.ToLower(f)
    }

    j, err := json.Marshal(obj)
    if err != nil {
        return nil, err
    }

    objMap := map[string]interface{}{}
    err = json.Unmarshal(j, &objMap)
    if err != nil {
        return nil, err
    }

    for k := range objMap {
        if !inSlice(fieldNames, k) {
            delete(objMap, k)
        }
    }

    if len(objMap) == 0 {
        return nil, fmt.Errorf("field(s) not found")
    }

    return objMap, nil
}


texts: Reducing code duplication for my C# math class

texts:
I have a library with a lot of duplicate code to accommodate different collection types, and its starting to get a bit tedious, is there a better way to do this to reduce the amount of duplication going on ? Its only going to get worse the more functions i add...

This is my current library script:

using System.Collections.Generic;
using UnityEngine;

namespace Math {
    public static class Geometry
    {
        public static float Area(List<Vector2> points)
        {
            float a = 0;
            for (int i = 0; i < points.Count; i++)
            {
                var p1 = points[i];
                var p2 = points[(i + 1) % points.Count];

                a += p1.x * p2.y - p2.x * p1.y;
            }

            return a * 0.5f;
        }

        public static float Area(List<Vector3> points)
        {
            float a = 0;
            for (int i = 0; i < points.Count; i++)
            {
                var p1 = points[i];
                var p2 = points[(i + 1) % points.Count];

                a += p1.x * p2.z - p2.x * p1.z;
            }
            return a * 0.5f;
        }

        public static float Area(Vector3[] points)
        {
            float a = 0;
            for (int i = 0; i < points.Length; i++)
            {
                var p1 = points[i];
                var p2 = points[(i + 1) % points.Length];

                a += p1.x * p2.z - p2.x * p1.z;
            }
            return a * 0.5f;
        }

        public static float Area(Vector2[] points)
        {
            float a = 0;
            for (int i = 0; i < points.Length; i++)
            {
                var p1 = points[i];
                var p2 = points[(i + 1) % points.Length];

                a += p1.x * p2.y - p2.x * p1.y;
            }
            return a * 0.5f;
        }

        public static bool IsClockwise(List<Vector3> points)
        {
            float sum = 0;

            for (int i = 0; i < points.Count - 1; i++)
            {
                var point1 = points[i];
                var point2 = points[i + 1];

                sum += (point2.x - point1.x) * (point2.z + point1.z);
            }

            return sum > 0;
        }
        public static bool IsClockwise(Vector3[] points)
        {
            float sum = 0;

            for (int i = 0; i < points.Length - 1; i++)
            {
                var point1 = points[i];
                var point2 = points[i + 1];

                sum += (point2.x - point1.x) * (point2.z + point1.z);
            }

            return sum > 0;
        }
        public static bool IsClockwise(List<Vector2> points)
        {
            float sum = 0;

            for (int i = 0; i < points.Count - 1; i++)
            {
                var point1 = points[i];
                var point2 = points[i + 1];

                sum += (point2.x - point1.x) * (point2.y + point1.y);
            }
            return sum > 0;
        }
        public static bool IsClockwise(Vector2[] points)
        {
            float sum = 0;

            for (int i = 0; i < points.Length - 1; i++)
            {
                var point1 = points[i];
                var point2 = points[i + 1];

                sum += (point2.x - point1.x) * (point2.y + point1.y);
            }

            return sum > 0;
        }
    }
}


texts: how to make pagination more efficient with large arrays and db support

texts:
i have a pagination library in php. i want to know:

how can i make it more efficient when passing large arrays into the constructor
how can i add db support

paginator.php

public function __construct($options = [])
    {
        $this->items = $options['data'];
        $this->limit = $options['limit'] ?? 10;
        $this->currentPage = $options['currentPage'] ?? 1;
        //$this->urlPattern = $options['urlPattern'];
        $this->updateNumPages();
    }

    public function paginate(int $page = 1): PaginatorInterface
    {
        if ($page <= 0 || $this->limit <= 0) {
            throw new \LogicException("Invalid parameters.");
        }
        $offset = ($page - 1) * $this->limit;
        $pagination = new DefaultPaginator();
        $items = new Collection($this->items, $offset, $this->limit);
        if ($this->items instanceof \ArrayObject || is_array($this->items)) {
            $data = new ArrayData();
            $data->fetchItems($items);
        } else {
            throw new \RuntimeException("Data type not supported for pagination.");
        }
        $pagination->setCurrentPageNumber($page);
        $pagination->setNumberOfPages((int) ceil($items->getCount() / $items->getLimit()));
        $pagination->setItems($items->getItems());
        $pagination->setTotal($items->getCount());
        $pagination->setTotalOnCurrentPage(count($items->getItems()));
        $pagination->setTotalPerPage($this->limit);
        return $pagination;
    }

my repository is here https://github.com/shorif2000/pagination

here is where i am slicing the array.

class ArrayData implements DataInterface
{

    public function fetchItems(Collection &$items): void
    {
        if (is_array($items->getCollection())) {
            $items->setItems(array_slice(
                $items->getCollection(),
                $items->getOffset(),
                $items->getLimit()
            ));
            $items->setCount(count($items->getCollection()));
        } elseif ($items->getCollection() instanceof ArrayObject) {

            $collection = $items->getCollection();
            $items->setItems(new ArrayObject(array_slice(
                $collection->getArrayCopy(),
                $items->getOffset(),
                $items->getLimit()
            )));
            $items->setCount($collection->count());
        }
    }
}

UPDATE

I created this class to add support for db or array/ArrayObject

class Pagination
{
    public function __construct($options = [], $mode = 'Default')
    {
        eval('$this = Pagination::factory($options, $mode);');
    }

    public static function &factory($options, $mode)
    {
        $classname = ($mode == 'Default') ? 'Pagination\\Paginator' : 'Pagination\\DbPage' ;
        // If the class exists, return a new instance of it.
        if (class_exists($classname)) {
            $pagination = new $classname($options);
            return $pagination;
        }

        $null = null;
        return $null;
    }
}

UPDATE

with the answer to test i have the following

$pageNumber = 1;
        $itemsPerPage = 10;
        $input = range(0, 100);
        $input = array_slice($input, 0, 10);
        $total = count($input);
        print_r((new PaginatorFactory(new ArrayPageProvider($input)))->createPaginator($pageNumber, $itemsPerPage));


texts:
I created my first plugin in jQuery and just want some inputs on how I can improve the code and features.

Here is the fiddle

    $.fn.fruitZoom = function (options) {

var defaults = {
    ele: "p,span",
};

var settings = $.extend(defaults, options);
$("#fruitZoom :first-child").click(function () {

    fontSize = $(defaults.ele).css("font-size")
    $(defaults.ele).css("font-size", parseInt(fontSize) + 2);
    console.log(fontSize)
});
$("#fruitZoom :last-child").click(function () {
    fontSize = $(defaults.ele).css("font-size")
    $(defaults.ele).css("font-size", parseInt(fontSize) - 2);
    console.log(fontSize)
});
};
})(jQuery);
options = {
    ele: "p,h1",
}
$("#fruitZoom").fruitZoom(options);


texts:
I am a beginner, and so I have decided to program a Roman Numeral to Arabic integer converter. I came up with all of the code on my own.
There are differing opinions about what constitutes 'proper' Roman Numerals. For example, 'IIII' is odd but known to exist in ancient writings, and 'VIIV' is a silly but parsable way to write '8'.
And so my program will treat any valid string as acceptable and attempt to parse it.
It works and I would welcome any comments or considerations, especially with regards to the following:

general best practice,
whether the input verification can be made cleaner,
if there is a nicer way than using a dictionary to match the characters and values,
efficiency of the part which calculates the totals, and
if I should add comments to the code.

import re

bad = 1

while bad == 1:
    roman = input('Enter a Roman Numeral: ')
    test = re.findall('[^IVXLCDM]+', roman)
    lengthtracker = 0
    for item in test:
        length = len(item)
        lengthtracker = lengthtracker + length
        if length != 0:
            print('Roman Numerals may contain only the characters I, V, X, L, C, D, M')
            break
        else:
            continue
    if lengthtracker == 0:
        bad = 0

print('Roman Numeral verified!')

ref = dict()
ref['I'] = 1
ref['V'] = 5
ref['X'] = 10
ref['L'] = 50
ref['C'] = 100
ref['D'] = 500
ref['M'] = 1000

n = len(roman)
m = 0
total = 0
negtotal = 0
tenttotal = 0
while m < n-1:
    if ref[roman[m]] == ref[roman[m+1]]:
        tenttotal = tenttotal + ref[roman[m]]
    elif ref[roman[m]] > ref[roman[m+1]]:
        total = total + tenttotal + ref[roman[m]]
        tenttotal = 0
    else:
        negtotal = negtotal + tenttotal + ref[roman[m]]
        tenttotal = 0
    print(total, negtotal, tenttotal)
    m = m + 1

total = total + tenttotal + ref[roman[m]] - negtotal

print('It equals:', total)


texts:
I wanted to understand the HMAC algorithm. So, I implemented it as a Jupyter Notebook with all intermediate steps being output to console. My objective now is to improve it so it may serve as a reference to anyone trying to implement or understand it.

The Jupyter Notebook on github is easier to read and I would like feedback on the notebook rather than the code below.

Jupiter notebook on GitHub

import hashlib
import hmac

### Define key, message, Block size, hashing algorithm
hash_algo = "sha1"
B = 64
message = b'hello!'
key = b'key'

### hash () for an easy to read code
def hash(M):
    H = hashlib.new(hash_algo)
    H.update(M)
    b_hash = H.digest()
    return b_hash

### XOR Translation table
trans_5C = bytes((x ^ 0x5C) for x in range(256))
trans_36 = bytes((x ^ 0x36) for x in range(256))

### Zero pad key to block length B
K_zpad=key.ljust(B,b'\0')
# Xor with ipad and opad sequence
K_ipad=K_zpad.translate(trans_36)
K_opad=K_zpad.translate(trans_5C)

print("Key XOR ipad(0x363636...):\n"+K_ipad.hex())
print("\n\nKey XOR opad(0x505050...):\n"+K_opad.hex())

### concatinate message
part1=K_ipad+message
print("key XOR ipad || message:\n"+part1.hex())

### hash (key xor ipad || message )
hash1=hash(part1)
print("hash( key XOR ipad || message):\n"+hash1.hex())

### hash (key xor opad || hash ( (key xor ipad)||message ) )
part2 = K_opad + hash1
print("hash (key xor opad || hash ( (key XOR ipad)||message ) ):\n"+part2.hex())
hash_final = hash(part2)
print("\n\nFinal Hash:\n"+hash_final.hex())

# Compare with Python's HMAC Implementation
pyH=hmac.new(key,message,digestmod=hash_algo)
pyH.hexdigest()


texts: AJAX Done Callback to prevent requests from interrupting each other

texts:
I am trying to make sure my client-side code does not send another request before it receives a reply. To the best of my knowledge the code I will post is supposed to do this but I am still getting a -1 for $return.

The AJAX request repeatedly gets the echoed value of a function which is using a batch file to get the size of a file that is being uploaded via FTP. The application using this shifted storage and is now in UNC path and now the AJAX gets nothing in return.

If I run the bat file manually I can get a response, but it might take 1 second or it might take a minute, for some reason there doesn't seem to be a lot in the middle. If I use the PHP script to call it I get $out equal to an empty array and $return equal to -1. My guess is that it's taking so long to process the request the Ajax requests are interrupting each other.

Ajax:

I am using ajaxTime to try and see how long the requests are taking. They are varying from usually around 550-650 response time:

var ajaxTime = new Date().getTime();
getdSize(f, ajaxTime);

function getSize(f, ajaxTime){
        $.ajax({
            url: "php file handling the ajax request",
            type: "POST",
            data: {
                file : encodeURIComponent(f),
                }
            })
        .done(function(data){
            var totalTime = new Date().getTime()-ajaxTime;
            console.log("Ajax Time: " + totalTime);
            console.log("Data: " + data);
        })
        .fail(function(data){
            if ( data.responseCode ){
              console.log( data.responseCode );
            }
            console.log("Ajax failure");
        });
    }

PHP:

    $file = $_POST['file'];
    echo bat_getSize($file);
[this calls bat_getSize function]

function bat_getSize($file){
    exec("getSize \"$file\"",$out, $ret);
    return $out[0];
}

Which calls this batch code:

@echo off
echo %~z1


texts: Passing arguments to a SendMail function referenced by addressOf operator

texts:
I am trying to send daily mail alert to users based on some timer values. For that I've used Addhandler to call the sendmail() function on timer Tick. In this scenario I faced a problem and I am unable to pass arguments to the function through AddressOf.

What I wanted was to use my function, which took these parameters…

 Public Sub SendMail(ByVal UserMailId As String,
                     ByVal UserPassword As String,
                     ByVal HostName As String,
                     ByVal HostPort As String)

by calling it using AddHandler mailTimer.Elapsed, AddressOf userDetails.SendMail(parameters), but that failed with an error:

  'AddressOf' Operand name must be the name of the method without
  parenthesis

After some research, here's my solution for this problem:

Dim userDetails As New Details
' These values are from database that will changed based on some conditions given
' now it is hardcoded for an example
userDetails.HostName = "smtp.gmail.com"
userDetails.HostPort = "587"
userDetails.UserMailId = "mailuser@gmail.com"
userDetails.UserPassword = "mymailPasswo6d"
Dim mailTimer As System.Timers.Timer
mailTimer.Interval = 18000
AddHandler mailTimer.Elapsed, AddressOf userDetails.SendMail
mailTimer.Start()

Where Details is the class which is defined as follows:

Class Details
        Public UserMailId As String
        Public UserPassword As String
        Public HostName As String
        Public HostPort As String
        Public Sub SendMail()
            Try
                Dim smtpServer As New SmtpClient
                Dim eMail As New MailMessage()
                smtpServer.UseDefaultCredentials = False
                smtpServer.Credentials = New Net.NetworkCredential(UserMailId, UserPassword)
                smtpServer.Port = HostPort
                smtpServer.EnableSsl = True
                smtpServer.Host = HostName
                eMail = New MailMessage()
                eMail.From = New MailAddress(UserMailId)
                eMail.To.Add(txtemailTo.Text)
                eMail.Subject = "Test Mail"
                eMail.IsBodyHtml = False
                eMail.Body = txtMessage.Text
                smtpServer.Send(eMail)
                MsgBox("Mail Sent")
            Catch errorT As Exception
                MsgBox(errorT.ToString)
            End Try
        End Sub
    End Class

Now what my question is:

Is the method I was using the correct one? Is there any simple or alternate solution for this?
Can anyone please review the code to improve it? It gives me better results but I think some modification is required.


texts:
Problem:

  Using the recursion approach, find a Fibonacci sum without repetition of computation.

def sum_fibonacci(n):
    """Compute the nth Fibonacci number.

    >>> sum_fibonacci(35)
    9227465
    >>> sum_fibonacci(10)
    55
    >>> sum_fibonacci(0)
    0
    >>> sum_fibonacci(1)
    1
    >>> sum_fibonacci(5)
    5
    """
    """Your code here"""

Solution:

fibcache = {}
def  sum_fibonacci(n):
    """Compute the nth Fibonacci number.

    >>> sum_fibonacci(35)
    9227465
    >>> sum_fibonacci(10)
    55
    >>> sum_fibonacci(0)
    0
    >>> sum_fibonacci(1)
    1
    >>> sum_fibonacci(5)
    5
    """
    if n == 0:
        fibcache[n] = 0
        return fibcache[n]
    elif n == 1:
        fibcache[n] = 1
        return fibcache[n]
    else:
        sum_left = 0
        sum_right = 0
        if n-2 in fibcache.keys():
            sum_left += fibcache[n-2]
        else:
            sum_left += sum_fibonacci(n-2)
            fibcache[n-2] = sum_left
        if n-1 in fibcache.keys():
            sum_right += fibcache[n-1]
        else:
            sum_right += sum_fibonacci(n-1)
            fibcache[n-1] = sum_right
        return sum_left + sum_right

This program uses dictionary data model amidst tree recursion.

Can it be more readable? Can it avoid global cache fibcache update? Because nonlocal is better than global.

Note: I'm currently aware of data models - class 'tuple', class 'list' and class 'dict'.


texts: Subscribe once and reuse the Angular Subscription each second

texts:
I am creating a web application using Angular 8. This application is all about talking to the stock markets server and getting the Live updates every second.
I have one query here. Below is my code:

setInterval(()=> {
this.GETDATA_NSE_EQ_LIVE();},
1000);

 GETDATA_NSE_EQ_LIVE():void{
      this._NSELiveFeedComponent.getData_nse_eq_live(this.stockSymbol)
          .subscribe((nse_eq_live_symbol_data) => this.Nse_Eq_Live_Symbol_data = nse_eq_live_symbol_data,
                     (err) => console.log(err));
    }

As we can see that i am using setInterval() method and i am calling GETDATA_NSE_EQ_LIVE() function in every second.
This means that i am subscribing to getData_nse_eq_live(this.stockSymbol) method every second.
How can i reuse the object once it is subscribed for the first time rather than subscribing it for every second?
Also, is there any better approach than using setInterval() function for getting the stock updates every second?


texts:
I am picking up good Haskell practices!

In this instance, I wanted to pick a file which contains a title in the first line and then every line is a string.

Each string represents a number in base equal to the number of distinct characters that appear on the string, but we do not know what characters correspond to each digit.

We want to find out the difference between the max and min number a string could represent, with the added restriction that a number cannot have leading 0s.

I feel like my code is quite complicated for such a simple task. Can I get any pointers on how to improve it so its more readable and elegant?

import qualified Data.Map as Map
import Data.List
import Data.Maybe

main = do
    contents <- (tail . lines) <$> readFile "submitInput" :: IO [String]
    let input = contents :: [String]
    let result = max_range <$> input
    let decorated_result = ["Case #" ++ show i ++ ": " ++ show s | (i,s) <- zip [1..] result]
    writeFile "output.txt" $ unlines $ decorated_result

-- Computes the difference between the max and min possible decoding
max_range word = max_decoding word - min_decoding word

-- Computes the minimal possible decoding of word
min_decoding :: String -> Integer
min_decoding word =
    let number = fix_decoding $ min_aux word (Map.empty :: Map.Map Char Integer) 0
    in base_conversion (toInteger . length . nub $ number) $ catMaybes number

-- The decodification cannot have leading zeros
fix_decoding :: [Maybe Integer] -> [Maybe Integer]
fix_decoding [] = []
fix_decoding (Just 0:ds) = Just 1 : fix_decoding ds
fix_decoding (Just 1:ds) = Just 0 : fix_decoding ds
fix_decoding (d:ds) = d : fix_decoding ds

min_aux :: [Char] -> Map.Map Char Integer -> Integer -> [Maybe Integer]
min_aux [] _ _ = []
min_aux (c:cs) map next
    | c `Map.member` map    = Map.lookup c map : min_aux cs map next
    | otherwise             = Just next : min_aux cs (Map.insert c next map) (next + 1)

-- Computes the maximal possible decoding of word
max_decoding :: String -> Integer
max_decoding word =
    let number = max_aux word (Map.empty :: Map.Map Char Integer) ((toInteger . length . nub $ word)-1)
    in base_conversion (toInteger . length . nub $ number) $ catMaybes number

max_aux :: [Char] -> Map.Map Char Integer -> Integer -> [Maybe Integer]
max_aux [] _ _ = []
max_aux (c:cs) map next
    | c `Map.member` map    = Map.lookup c map : max_aux cs map next
    | otherwise             = Just next : max_aux cs (Map.insert c next map) (next - 1)

-- Interprets a list of digits as a number in a given base
base_conversion :: Integer -> [Integer] -> Integer
base_conversion base []     = 0
base_conversion base (d:ds) = d * base ^ (length ds) + base_conversion base ds


texts:
I am working on a sample banking system and have the following for deposit functionality, I was wondering if this is idiomatic, and how it can be improved.
I have separated the algebra of the service using a trait but not sure how to enforce that two accounts should not be the same with types

type AccountNumber = String
type Amount = BigDecimal

sealed trait Account {
  val number: AccountNumber
  val balance: Amount
}

case class OpenAccount(number :AccountNumber, balance: Amount) extends Account
case class ClosedAccount(number :AccountNumber, balance: Amount) extends Account

trait BankServices {
  case class Response(from: OpenAccount, to: OpenAccount)
  def deposit(from: OpenAccount, to:OpenAccount, amount: Amount): Option[Response]
  def withdrawal(from: OpenAccount, to:OpenAccount, amount: Amount): Option[Response]

  def closeAccount(account: OpenAccount): ClosedAccount

}

object BankService extends BankServices {

  override def deposit(from: OpenAccount, to: OpenAccount, amount: Amount): Option[Response] = {
    if (from.balance < amount || from.number == to.number) {
      None
    } else {
      val f = OpenAccount(from.number, from.balance - amount)
      val t = OpenAccount(to.number, to.balance + amount)
      Some(Response(f, t))
    }
  }

  override def withdrawal(from: OpenAccount, to: OpenAccount, amount: Amount): Option[Response] = ???

  override def closeAccount(account: OpenAccount): ClosedAccount = ???
}

val c = OpenAccount("125", 80)
val b = OpenAccount("123", 100)

for {
  x  <- BankService.deposit(c, b, 10)
  y  <- BankService.deposit(x.from, x.to, 10)
} yield y


texts: A series of yes-no questions to predict yes-no outcomes

texts:
I have been writing R scripts for about a week. I have been writing code for 20 years. I have a series of yes-no questions that I hope to predict yes-no outcomes so I know the R-squared will be terrible but as long as the variable is significant I am fine.

Since I am creating a number with my yes-no questions the order makes a difference and I have 14 questions which I plan to turn into 8-bit numbers (121,080,960 permutations). This is taking about 88 hours on my desktop. I am looking for anyplace to optimize my code. I have read about Multi core/thread SNOW but that is beyond me right now without some help. I also know I can compile functions but my code is short and only see one place to do so.

Please review my code, any help would be appreciated.

library(data.table)
ffName = "Perms8bit.csv"
# Read table of 1s and 0s
Bin_Matrix <-read.table("LC_FR_F17BIN.csv",header=TRUE,sep=",")

Perm_Best <- 0
holdR  <- 0
s<- Sys.time()
cnt <-0

# Read the file 121,080,960 permutations to test
# Originally read the file in blocks but benchmark testing
rawData <- fread(ffName, sep=",")

   for (cnt in 1:121080960){
        # create a table result x binary number
        Bin_num <- data.table(result = c(Bin_Matrix[,15]),numb = c(2^0* (Bin_Matrix [,as.numeric(rawData[cnt,1])]) + 2^1*(Bin_Matrix [,as.numeric(rawData[cnt,2])]) +
2^2*(Bin_Matrix [,as.numeric(rawData[cnt,3])]) + 2^3*(Bin_Matrix [,as.numeric(rawData[cnt,4])]) +
2^4*(Bin_Matrix [,as.numeric(rawData[cnt,5])]) + 2^5*(Bin_Matrix [,as.numeric(rawData[cnt,6])]) +
2^6*(Bin_Matrix [,as.numeric(rawData[cnt,7])]) + 2^7*(Bin_Matrix [,as.numeric(rawData[cnt,8])])))

    #linear regession
    linearMod <- lm(result ~ numb, data = Bin_num)
    ModSum <- summary(linearMod)
    theR <- ModSum$r.squared

    # Find the top R squared, result is 1s and 0s so R squared will not be high
    if (theR > .0175) {
        holdR = theR
        Perm_Best <- data.table(cnt = cnt,R = holdR,rawData[cnt,])

         #append a file with best fits
         write(toString(Perm_Best,nrows= 1),file = "RSQ.txt", append = TRUE)
      }

   }
print (Sys.time()-s) #benchmark
print(holdR)         # just to let me know its done
print (Perm_Best)

Bin_Matrix is a file with around 2,000 rows, header, and a bunch of 1s and 0s in csv form.  RawData is a  table with 121 million rows with the different permutations (examples:

1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,9
...
14,1,2,3,4,5,6,7
14,1,2,3,4,5,6,8


texts: C functions for fast IO for competitive programming

texts:
In some (perhaps not well-designed) competitive programming problems,
the runtime and score is dependent on how fast your program can
process input. Therefore I've written a small C99 library with optimized
functions for reading from stdin and writing to stdout:

fastio.h:

#ifndef FASTIO_H
#define FASTIO_H

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

#ifdef _WIN32
#define putchar_unlocked putchar
#else
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#endif

// Fast IO routines accessing stdin and stdout. The purpose of them is
// to reduce IO overhead in competitive programming. Therefore, no
// error checking anywhere.

// On Linux and OS X, this is a pointer to stdin's next character. On
// Windows, standard getchar() is used and the pointer
// is NULL.
extern char *
FAST_IO_STDIN;

void
fast_io_init();

// Reading
inline char
fast_io_read_char() {
#ifdef _WIN32
    return getchar();
#else
    return *FAST_IO_STDIN++;
#endif
}

inline unsigned int
fast_io_read_unsigned_int() {
    int val = 0;
#ifdef _WIN32
    while (true) {
        char c = getchar();
        if (c < '0') {
            ungetc(c, stdin);
            break;
        }
        val = val * 10 + c - '0';
    }
#else
    do {
        val = val*10 + *FAST_IO_STDIN++ - '0';
    } while(*FAST_IO_STDIN >= '0');
#endif
    return val;
}

inline int
fast_io_read_int() {
    int val = 0;
    int sgn = 1;

#ifdef _WIN32
    char c = getchar();
    if (c == '-') {
        sgn = -1;
    } else {
        ungetc(c, stdin);
    }
    while (true) {
        char c = getchar();
        if (c < '0') {
            ungetc(c, stdin);
            break;
        }
        val = 10 * val + c - '0';
    }
#else
    if (*FAST_IO_STDIN == '-') {
        sgn = -1;
        FAST_IO_STDIN++;
    }
    do {
        val = val*10 + *FAST_IO_STDIN++ - '0';
    } while(*FAST_IO_STDIN >= '0');
#endif
    return val * sgn;
}

// Writing
inline void
fast_io_write_char(char ch) {
    putchar_unlocked(ch);
}

inline void
fast_io_write_long(long n) {
    if (n < 0) {
        putchar_unlocked('-');
        n *= -1;
    } else if (n == 0) {
        putchar_unlocked('0');
        return;
    }
    long N = n;
    long rev = N;
    int count = 0;
    rev = N;

    while ((rev % 10) == 0) {
        count++; rev /= 10;
    }
    rev = 0;
    while (N != 0) {
        rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;
    }
    while (rev != 0) {
        putchar_unlocked(rev % 10 + '0');
        rev /= 10;
    }
    while (count--) {
        putchar_unlocked('0');
    }
}
#endif

fastio.c

#include "fastio.h"

char *
FAST_IO_STDIN = NULL;

void
fast_io_init() {
#ifdef _WIN32
    // Nothing to do on Windows because we use standard getchar().
#else
    int flags = MAP_SHARED;
#ifdef __linux__
    // Prefills the buffer.
    flags |= MAP_POPULATE;
#endif
    struct stat sb;
    (void)fstat(STDIN_FILENO, &sb);
    FAST_IO_STDIN = (char*)mmap(0, sb.st_size,
                                PROT_READ, flags, STDIN_FILENO, 0);
#endif
}

extern inline char fast_io_read_char();
extern inline unsigned int fast_io_read_unsigned_int();
extern inline int fast_io_read_int();
extern inline void fast_io_write_char(char ch);
extern inline void fast_io_write_long(long n);

I want the library to work on Windows, Linux and OS X, but
performance only matters on Linux because bots for competitive
programming only run on Linux. As the goal is to shave off
milliseconds to win contests, there is absolutely no error
checking.

Does anyone have any ideas how to make it even faster?


texts:
I have a requirement to put a comma between each digit of a number in a Java string.

Example input:

the number is 12345 and the number is 45678

The output should be:

the number is 1,2,3,4,5 and the number is 4,5,6,7,8

I wrote the following and I am not sure if it is optimized. If someone reviews it and help me fine tune it, it will be helpful.

public static void main(String args[]) {
      String str = "the number is 12345 and the number is 45678";
      System.out.println("Original Text:\n" + str);
      System.out.println("Updated Text:\n" + formatNumber(str, ','));
   }

   public static String formatNumber(String text, char separator) {
       Pattern p = Pattern.compile("\\d+");
       Matcher m = p.matcher(text);
       StringBuffer sb = new StringBuffer();
       while(m.find()) {
           String num = m.group();
           num = num.replaceAll(".(?!$)", "$0"+separator);
           m.appendReplacement(sb,num);
       }
       return m.appendTail(sb).toString();
   }

Output:

Original Text:
    the number is 12345 and the number is 45678
    Updated Text:
    the number is 1,2,3,4,5 and the number is 4,5,6,7,8
    Process finished with exit code 0

Though it gave me the output I wanted, I have a feeling that it is not highly optimized when the string size grows larger and larger.


texts: Generic and accurate floating point "equality"

texts:
Like those who have come before me, I foolishly have sought to implement a generic, efficient, idiomatic, and most importantly correct method of comparing floating point numbers for equality. Like those who have come before me, I have most likely failed in at least one of those regards.  I'd appreciate comments on any aspect of the following code

#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <type_traits>

template<bool B, typename T, typename DEFAULT = void>
struct cond
{
    static constexpr bool value = B;
    using default_type = DEFAULT;
    using type = T;
};

template<typename Head, typename... Tail>
struct select
{
    using type =
        typename std::conditional<Head::value,
                                 typename Head::type,
                                 typename select<Tail...>::type>::type;
};

template <typename T>
struct select<T>
{
    using type = T;
};

template <bool B, typename T, typename DEFAULT>
struct select<cond<B, T, DEFAULT>>
{
    using type = typename std::conditional<B, T, DEFAULT>::type;
};

template <typename Head, typename... Tail>
using select_t = typename select<Head, Tail...>::type;

template <typename FloatingPoint>
struct SelectIntegralOfSameSize {
    using type = select_t<
        cond<sizeof(FloatingPoint) == sizeof(int64_t), int64_t>,
        cond<sizeof(FloatingPoint) == sizeof(int32_t), int32_t>,
        cond<sizeof(FloatingPoint) == sizeof(int16_t), int16_t>,
        cond<sizeof(FloatingPoint) == sizeof(int8_t), int8_t>
    >;
    static_assert(!std::is_void<type>::value, "Could not find sane integral type");
};

template <typename FP, typename I = typename SelectIntegralOfSameSize<FP>::type>
union Fp_Int_Union {
    FP fp_;
    I i_;
};

template <typename FP>
bool nearlyEqual(FP left, FP right, FP maxDiff, std::size_t maxUlpsDiff) {
    // handle NaNs and infinities
    if (!std::isfinite(left) || !std::isfinite(right)) {
        return false;
    }

    // ULP comparison breaks for different signs
    if ((left < 0) != (right < 0)) {
        // Handle -0 == +0
        return left == right;
    }

    // ULP comparison fails near zero
    if (std::abs(left - right) <= maxDiff) {
        return true;
    }

    Fp_Int_Union<FP> l, r;
    l.fp_ = left;
    r.fp_ = right;

    return std::abs(l.i_ - r.i_) <= maxUlpsDiff;
}


texts: Using methods and constructors to construct a basic calculator

texts:
I am trying to come up with a simple basic calculator but am supposed to work with the following constructors and methods:

simpleCalc();
simpleCalc(double op1, double op2);
double add();
double add(double op1, double op2);
double mult();
double mult(double op1, double op2);
double exp();
double exp(double op1, double op2);
void show();
void show(int dp);

I have written down some working code and I just want to know if am doing the right thing.

MyClass.java

package basicjavacalculator;

public class MyClass {
public static void main(String[] args) {
// TODO code application logic here
simpleCalc sc = new simpleCalc();
sc.show();

 }

}

simpleCalc.java

package basicjavacalculator;

import java.util.Scanner;

public class simpleCalc {

double add(){
return 0;
}

double mult(){
return 0;
}

double exp(){
return 0;
}

simpleCalc(){

}

void show(){

Scanner userInput = new Scanner(System.in);

System.out.println("=================Welcome to SimpleCalcDemo=================");
System.out.println("\n");

System.out.println("Enter first number: ");
double op1 = userInput.nextInt();

System.out.println("Enter second number: ");
double op2 = userInput.nextInt();

System.out.print("Enter operation to perform (+,x,^):");
String operation= userInput.next();

if(operation.equals("+")){
    System.out.println(add(op1, op2));
}

else if (operation.equals("x")){
    System.out.println(mult(op1, op2));
}

else if (operation.equals("^")){
    System.out.println(exp(op1, op2));
}
else{
System.out.println("The operation is not valid.");

}

}

double add(double op1, double op2){
return op1 + op2;
}

double mult(double op1, double op2){
return op1 * op2;
}

double exp(double op1, double op2){
double result = 1;
while (op2 > 0){
    result = result * op1;
    op2--;
}

return result;
}

}


texts:
I am learning D. I'm trying to implement Haskell's intersperse in D.  I want to use ranges. I feel that the intermediate "interspersed" value is wrong. Additionally, I suspect the concatenation character by character is inefficient. What is a more idiomatic way to implement this function, please?
string translateToSwedish(immutable string english) pure
{
    string interspersed;
    foreach(char c; english)
        interspersed = interspersed ~ c ~ 'f';
    return interspersed;
}

void main()
{
    assert(translateToSwedish("Hello") == "Hfeflflfof");
}

My initial thought was to try std.range.roundRobin with repeat:
string translateToSwedish(immutable string english) pure
{
    import std.range;
    return roundRobin("f".repeat(), english);
}

This however is wrong for at least two reasons:

roundRobin is eager and will evaluate the full range even if another range finishes first. Repeat constructs an infinite range, thus my translateToSwedish function is also infinite.

This code doesn't typecheck:

main.d(6): Error: cannot implicitly convert expression (roundRobin(repeat("f"), english)) of type Result to string


texts:
Type a number \$n\$. Then calculate \$f(n)\$, where

$$ f(n) =
\begin{cases}
n-10 & \text{if}~ n > 100\\[1.5ex]
f(f(n + 11)) & \text{otherwise}
\end{cases}
$$

The output must show all the computations, such as
$$f(99) = f(f(110)) = f(100) = f(f(111)) = f(101) = 91$$

Is there a shorter and better way I can solve this?

#include <iostream>
using namespace std;

int main(){
    int i=0, n, x, k;

cin>>n;

if(n>100) {
cout<<"f("<<n<<")=";
n=n-10;
}
else {
    cout<<"f("<<n<<")=";
while(n<=100){
loop:
x=0;
k=0;
i++;
n+=11;
        while(x<=i){
            x++;
            cout<<"f(";
        }
        cout<<n;
        while(k<=i){
            k++;
            cout<<")";
        }
        cout<<"=";
    if(n>100){

        x=0;
        k=0;
        i=i-1;
        n=n-10;

        while(x<=i){
            x++;
            cout<<"f(";
        }
        cout<<n;
        while(k<=i){
            k++;
            cout<<")";

        }cout<<"=";
    }

        if(n>100){

        x=0;
        k=0;
        i=i-1;
        n=n-10;

        if(i>=0){

        while(x<=i){
            x++;
            cout<<"f(";
        }
        cout<<n;
        while(k<=i){
            k++;
            cout<<")";

        }cout<<"=";

        goto loop;
    }
         break;
    }
    }
    }cout<<n;
 }


texts: Bilinear interpolation using Neon intrinsics

texts:
I'm trying to do a Bilinear interpolation on the ARM Neon. However, I find that my vectorized code is slower than the regular one, on a BeagleBone Black. Any idea why this could happen?

I'm using gprof to debug and compiling with the following flags:

NonNeonFlags: g -Wall -pg -O3 -ffast-math
NeonFlags: $(NonNeonFlags) -D__ARM__ -march=armv7-a -mtune=cortex-a8 -mfloat-abi=hard -mfpu=neon

interp.h

typedef struct InterpValues {
    float32_t ab; //< a,b
    float32_t a1b; //< a+1,b
    float32_t ab1; //< a, b+1
    float32_t a1b1; //< a+1, b+1
} InterpValues;

typedef struct InterpCoords {
    float32_t x1; //< x1
    float32_t x2; //< x2
} InterpCoords;

interp_neon.cpp

void interp_neon(InterpValues* values, InterpCoords* coords, float32_t* r, int n)
{
    const float32_t INIT_ONE[4] = {1.0, 1.0, 1.0, 1.0};

    float32x4x2_t x34;// = vld2q_f32(init_x1_x2);
    float32x4_t aux;
    float32x4_t vResult;
    float32x4_t ONE = vld1q_f32(INIT_ONE);

    for (int i=0;i<n;i+=4)
    {
        float32x4x4_t vValues = vld4q_f32((float32_t*) values);
        float32x4x2_t vCoords = vld2q_f32((float32_t*) coords);

        #define x1 vCoords.val[0]
        #define x2 vCoords.val[1]
        #define x3 x34.val[0]
        #define x4 x34.val[1]
        #define Iab vValues.val[0]
        #define Ia1b vValues.val[1]
        #define Iab1 vValues.val[2]
        #define Ia1b1 vValues.val[3]

        x3 = vmlsq_f32(ONE, x1, ONE);
        x4 = vmlsq_f32(ONE, x2, ONE);

        // Ia,b * x3 * x4
        aux = vmulq_f32(x3, x4);
        vResult = vmulq_f32(Iab, aux);

        // Ia+1,b * x1 * x4
        aux = vmulq_f32(x1, x4);
        vResult = vmlaq_f32(vResult, Ia1b, aux);

        // Ia,b+1 * x2 * x3
        aux = vmulq_f32(x2, x3);
        vResult = vmlaq_f32(vResult, Iab1, aux);

        // Ia+1,b+1 * x1 * x2
        aux = vmulq_f32(x1, x2);
        vResult = vmlaq_f32(vResult, Ia1b1, aux);

        vst1q_f32(r, vResult);

        r += 4;
        values += 4;
        coords += 4;

        #undef x1
        #undef x2
        #undef x3
        #undef x4
        #undef Iab
        #undef Ia1b
        #undef Iab1
        #undef Ia1b1
    }
}

interp.cpp

void interp(InterpValues* values, InterpCoords* coords, float32_t* r, int n)
{
    for (int i=0;i<n;++i)
    {
        float32_t x3 = 1.0 - coords[i].x1;
        float32_t x4 = 1.0 - coords[i].x2;
        r[i] =
            values[i].ab * x3 * x4 +
            values[i].a1b * coords[i].x1 * x4 +
            values[i].ab1 * coords[i].x2 * x3 +
            values[i].a1b1 * coords[i].x1 * coords[i].x2;
    }
}


texts:
Use case:
I want to automatically save data in the storage when a property of an object that implements INotifyPropertyChanged changes. Therefore I subscribe to the PropertyChanged event and call a method that saves the object.

Problem:
It can be that a lot of properties change over a short period of time and that is a problem because the saving method is an I/O operation.

My solution:
Accumulate the save orders over a period of time in a singleton class and perform the saving operations for the last order.

Code:

internal sealed class AccumulatedSaver
{
    private readonly Queue<Tuple<string, object>> _saveOrders = new Queue<Tuple<string, object>>();
    private bool _busy = false;

    internal static AccumulatedSaver Instance { get; } = new AccumulatedSaver();

    internal async Task SaveToAppData<T>(T item, string fileName)
    {
        _saveOrders.Enqueue(new Tuple<string, object>(fileName,item));
        if (_busy)
        {
            return;
        }
        _busy = true;
        await Task.Run(async() => await Task.Delay(500));

        while (_saveOrders.Count > 0)
        {
            Tuple<string, object> saveOrder = _saveOrders.Dequeue();
            if (_saveOrders.All(o => o.Item1 != saveOrder.Item1))
            {
                await SaveHelper.TrySaveToAppData(saveOrder.Item2, saveOrder.Item1);
            }
        }
        _busy = false;
    }
}

Question:
Is that a good idea to do that like that?
What can be made better?


texts:
I'm using the Bogus library to mock up some data for testing.

This is my main method demonstrating how the faking service should be used:

class Program
{
    static void Main(string[] args)
    {
        IFakerService r = new FakerService();

        var dogs = r.Generate<Dog>(10);
        var customers = r.Generate<Customer>(10);
        var cats = r.Generate<Cat>(10);
    }
}

A Dog class looks like:

public class Dog
{
    public string Name { get; set; }
    public bool IsGoodBoy => true;
}

My interface simply defines the only method the service should expose:

public interface IFakerService
{
    IEnumerable<T> Generate<T>(int count) where T : class;
}

And the service itself:

public class FakerService : IFakerService
{
    // Can we do better than <Type, object> ?
    private Dictionary<Type, object> _fakers;

    public FakerService()
    {
        _fakers = InitialiseFakers();
    }

    public IEnumerable<T> Generate<T>(int count) where T : class
    {
        var faker = GetFaker<T>();
        return faker.Generate(count);
    }

    // Types which can be faked are registered here
    private Dictionary<Type, object> InitialiseFakers()
    {
        return new Dictionary<Type, object>()
        {
            {typeof(Dog), new DogFaker().GetFaker()},
            {typeof(Cat), new CatFaker().GetFaker()},
            {typeof(Customer), new CustomerFaker().GetFaker()}
        };
    }

    private Faker<T> GetFaker<T>() where T : class
    {
        if (!_fakers.ContainsKey(typeof(T)))
        {
            throw new ArgumentException($"Type: {typeof(T).FullName} not registered with FakerService");
        }
        var faker = (Faker<T>)_fakers[typeof(T)];
        return faker;
    }
}

The interface for Faker objects:

public interface IFaker<T> where T : class
{
    Faker<T> GetFaker();
}

And one of the implementations:

public class DogFaker : IFaker<Dog>
{
    public Faker<Dog> GetFaker()
    {
        return new Faker<Dog>()
            .RuleFor(dog => dog.Name, f => f.Name.FirstName(Name.Gender.Male))
            .RuleFor(dog => dog.IsGoodBoy, f => f.Random.Bool());
    }
}

Overall I'm quite happy with how it looks - the parts that I was wondering if I could improve on are:

private Dictionary<Type, object> _fakers;

...

return new Dictionary<Type, object>()
{
    {typeof(Dog), new DogFaker().GetFaker()}
}

...

var faker = (Faker<T>)_fakers[typeof(T)];

Any advice is appreciated!


texts: Handle aws lambda function containing multiple axios call

texts:
I have written an aws lambda function in NodeJS which has 2 async axios call.

var stripNS = require('xml2js').processors.stripPrefix;
parseString = require("xml2js").parseString;
const axios = require('axios');
let successflag = true;
let headers = {
'Content-Type': 'text/xml'
}

exports.handler = async (event, context, callback) => {
console.log("start");
let url = event.url;

var firstxmlRQ = '    <?xml version="1.0" encoding="utf-8"?>' +
    '<note importance="high" logged="true">' +
    '    <title>Happy</title>' +
    '    <todo>Work</todo>' +
    '    <todo>Play</todo>' +
    '</note>';

await axios({
    method: 'post',
    url,
    headers,
    data: xmlRQ,
}).then(result => {
    console.log(result)
    parseString(result.data, {
        tagNameProcessors: [stripNS]
    }, function (err, result) {
        //console.log(result)
        try {
            //...other operations
            successflag = true

        } catch (e) {
            successflag;
            callback(null, {
                error: "error"
            });

        }
    });
}).catch(err => {
    console.log(err);
});

if (successflag) {
    let secondxmlRQ = '<<?xml version="1.0" encoding="utf-8"?>' +
        '<note importance="high" logged="true">' +
        '    <email>xyz@gmail.com</title>' +
        '    <todo>Work</todo>' +
        '    <todo>Play</todo>' +
        '</note>';
    await axios({
        method: 'post',
        url,
        headers,
        data: secondxmlRQ,
    }).then(result => {
        console.log(result.data);
    }).catch(err => {
        console.log(err);
    });
}
   callback(null, {
    success: "success"
  });
}

I want to call the second axios only when the first one succeeds. I tried to make it to different functions but then the second function is not getting called properly. Right now I am getting the result but I would like to know an efficient way to handle multiple async axios.


texts: How can this code for applying filters to data by date and size be improved?

texts:
I am going to undergo a code review shortly at work. I feel that my code is too verbose, could log more sensibly, and I feel that my if/else statements are somewhat duplicative/repetitive and can be done better. But I can't seem to be able to put my finger on what I am missing. How would you clean this up such that the code isn't verbose, logs sensible stuff and doesn't look kiddish. I would also like to make it simpler, in case additional filters need to be added in future.

FYI - getDetails method used in the following code, merely contains code for constructing a customer specific "Details" object that contains just 2 things, the name of the customer and a corresponding schedule for invocation.

    /* Filters out invokes that havent reached a size threshold.*/
    private boolean filterBySize(CustomerUnit Customer) {
        CustomerData customerData = new CustomerData(Customer);
        if (customerData.getUsage() > USAGE_THRESHOLD) {
            LOGGER.info("Customer's data usage of " + customerData.getUsage()
                    + "is higher than threshold of " + USAGE_THRESHOLD + " percent for " + Customer.getId());
            return true;
        } else {
            LOGGER.info("Customer's data usage of " + customerData.getUsage()
                    + "is lower than threshold of " + USAGE_THRESHOLD + " percent for " + Customer.getId());
            return false;
        }
    }

    /* Filters out invokes that aren't slated for today.*/
    private boolean filterByDate(CustomerUnit Customer) {
        if (getDetails(Customer).getDOW().equalsIgnoreCase(LocalDate.now().getDayOfWeek().name())) {
            LOGGER.info("Customer : " + getDetails(Customer).getName() + " is invoked to run import today");
            return true;
        } else {
            LOGGER.info("Customer : " + getDetails(Customer).getName() + " isn't invoked to run import today, ");
            return false;
        }
    }

    /* Applies aforesaid filters */
    private void invokeRequestByCustomer(CustomerUnit Customer) throws InterruptedException, UnexpectedDateOrderException {
        if (filterByDate(Customer) && filterBySize(Customer)) {
            invoker.invoke(getDetails(Customer));
            LOGGER.info("Scheduled Customer : " + getDetails(Customer).getName() + " to run import operations at" + getDetails(Customer).getDOW());
        } else {
            LOGGER.info("Customer : " + getDetails(Customer).getName() + " was filtered, no invoke will be executed for it");
        }
    }

As of now, I have thought about using an IfThenElse function, somewhat similar to the following:
IfThenElse example