texts:
I think the following is thread safe. Am I right? How would you improve this code? Are there new APIs or methods I can use?

Data:

public class Data {
  private int value;
  public Data(int value) {
    this.value = value;
  }

  public synchronized int getValue(int mTrhead) {
    System.out.println("MyTrhead " + mTrhead + " gets value " + value);
    return value;
  }

  public synchronized void setValue(int value, int mTrhead) {
    System.out.println("MyTrhead " + mTrhead + " sets value " + value);
    this.value = value;
  }
}

MyTrhead:

public class MyTrhead extends Thread {
  private Data mData;
  private int id;

  public MyTrhead(Data mData, int id) {
    this.mData= mData;
    this.id = id;
  }

  @Override
  public synchronized void run() {
    try {
      for (int a = 1; a <= 10; a++)
      {
        mData.setValue(mData.getValue(id) + 1, id);
      }
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}


texts:
I have created a registration form using jQuery. I am validating username and password using an AJAX request. The "submit" button is originally disabled and is only enabled when all three fields of username, email and password are filled and validated.

How and what can I improve in this code?

$(document).ready(function() {
    var usernameFlag = 1, emailFlag = 1, passwordFlag = 1;

    //event handler on input for username
    document.getElementById("reg_username").addEventListener("input", function() {
        var username = $("#reg_username").val();
        if(username !== null && username !== "") {
            usernameCheck(username).done(usernameCallback);
        }
        else {
            usernameFlag = 1;
            $("#tick_username").hide();
            $("#cross_username").hide();
            enableButton();
        }
    });

    //event handler on input for email
    document.getElementById("reg_email").addEventListener("input", function () {
        var email = $("#reg_email").val();
        if(email !== null && email !== "") {
            emailCheck(email).done(emailCallback);
        }
        else {
            emailFlag = 1;
            $("#tick_email").hide();
            $("#cross_email").hide();
            enableButton();
        }
    });

    //event handler on input for password
    document.getElementById("reg_password").addEventListener("input", function () {
        var password = $("#reg_password").val();
        if (password !== null && password !== "") {
            passwordFlag = 0;
            enableButton();
        }
        else {
            passwordFlag = 1;
            enableButton();
        }
    });

    function usernameCallback(response) {
        var usernameResponse = parseInt(response);
        usernameFlag = usernameResponse;
        if(usernameResponse === 1) {
            $("#tick_username").hide();
            $("#cross_username").fadeIn();
        }
        else {
            $("#cross_username").hide();
            $("#tick_username").fadeIn();
        }
        enableButton();
    }

    function emailCallback(response) {
        var emailResponse = parseInt(response);
        emailFlag = emailResponse;
        if(emailResponse === 1) {
            $("#tick_email").hide();
            $("#cross_email").fadeIn();
        }
        else {
            $("#cross_email").hide();
            $("#tick_email").fadeIn();
        }
        enableButton();
    }

    //ajax call to validate username
    function usernameCheck (username) {
        return $.ajax({
            type: "POST",
            url: "check_availability.php",
            data: "username="+username
        });
    }

    //ajax call to validate email
    function emailCheck (email) {
        return $.ajax({
            type: "POST",
            url: "check_availability.php",
            data: "email="+email
        });
    }

    //function to enable submit button
    function enableButton () {
        if (usernameFlag === 0 && emailFlag === 0 && passwordFlag === 0) {
            $("#register_btn").prop("disabled", false);
        }
        else {
            $("#register_btn").prop("disabled", true);
        }
    }

});

I am using three extra variables to keep track of the fields. The flags are updated if the user changes a value. After every change in input field, enableButton() checks the flags and enables the button if all of them have a value of 0.


texts:
This is an implementation of C++17 std::allocator under the name my_std::allocator, with deprecated stuff omitted for simplicity.

// A implementation of C++17 std::allocator
// with deprecated members omitted

#include <cstddef>
#include <new>
#include <type_traits>

namespace my_std {

  template <typename T>
  class allocator {
  public:
    using value_type = T;
    using propagate_on_container_move_assignment = std::true_type;
    using is_always_equal = std::true_type;

    allocator() noexcept = default;
    allocator(const allocator&) noexcept = default;
    ~allocator() = default;

    template <class U>
    allocator(const allocator<U>&) noexcept
    {
    }

    T* allocate(std::size_t n)
    {
      if constexpr (alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
        return static_cast<T*>(
          ::operator new(n * sizeof(T), static_cast<std::align_val_t>(alignof(T)))
        );
      else
        return static_cast<T*>(
          ::operator new(n * sizeof(T))
        );
    }

    void deallocate(T* p, std::size_t n)
    {
      if constexpr (alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
        return ::operator delete(p, n * sizeof(T),
                                 static_cast<std::align_val_t>(alignof(T)));
      else
        return ::operator delete(p, n * sizeof(T));
    }
  };

  template <class T, class U>
  bool operator==(const allocator<T>&, const allocator<U>&) noexcept
  {
    return true;
  }

  template <class T, class U>
  bool operator!=(const allocator<T>&, const allocator<U>&) noexcept
  {
    return false;
  }

}

I have tested it like this:

int main()
{
  std::set<std::string, std::less<std::string>,
       my_std::allocator<std::string>> words;

  for (std::string w; std::cin >> w;)
    words.insert(std::move(w));

  for (const auto& w : words)
    std::cout << w << "\n";
}

And currently no bug is discovered.


texts: Is there a way to optimize this aggregate postgreSQL statement by using CASE?

texts:
I have a working SQL statement which shows the following:

Player
Champion
Role
Total Kill/Death Ratio
Total Kill+Assist/Death Ratio
Total Win %
Difference between Ratio from one month ago
Difference between KA Ratio from one month ago
Difference between win % from one month ago

However, I don't think it's quite as optimized as it could be:

with CTERatio as (

select tt.playerid, tt.champid, tt.roleid,
    sum(tt.words) as kills,
    sum(tt.words2) as deaths,
    sum(tt.words3) as assists,
    sum(tt.words)/sum(tt.words2) as ratio,
    (sum(tt.words)+sum(tt.words3))/sum(tt.words2) as kdar,
    avg(tt.complete) as win
from schema.records tt
group by tt.playerid, tt.champid, tt.roleid
having count(*) > 2
order by ratio desc

),

hist as (

select tt.playerid, tt.champid, tt.roleid,
    sum(tt.words) as kills,
    sum(tt.words2) as deaths,
    sum(tt.words3) as assists,
    sum(tt.words)/sum(tt.words2) as ratio,
    (sum(tt.words)+sum(tt.words3))/sum(tt.words2) as kdar,
    avg(tt.complete) as win
from schema.records tt
where tt.sys_time < date_trunc('day', NOW() - interval '1 month')
group by tt.playerid, tt.champid, tt.roleid
having count(*) > 2
order by ratio desc

)
select c.playerid as player, c.champid as champion, c.roleid as rolee,
    round(c.ratio, 2) as ratio, round(c.kdar, 2) as kdar, round(c.win, 2) as win,
    round(c.ratio - h.ratio, 2) as ratiochange,
    round(c.kdar - h.kdar, 2) as kdarchange,
    round(c.win - h.win, 2) as winchange
from CTERatio c, hist h
where c.playerid = h.playerid
and c.champid = h.champid
and c.roleid = h.roleid
order by c.ratio desc

Is it possible I can incorporate using CASE instead of WITH? Such as:

avg(c.kills) - avg
(
case when tt.sys_time <  date_trunc('day', NOW() - interval '1 month')
then h.words
end
)


texts: Saving model's data in the model vs an external data manager class

texts:
I have a bunch of models (using activejdbc) Person, Company, Health, .... etc (I have 8 models). I'm showing an example of just one model Person

In the first approach I have a data manager that handles all my insertions to my various models, for example for Person I have

public class Person extends Model {
    static {
        validatePresenceOf(“name”, “birthdate”);
    }
}

and in the Data Manager I do the insertion

public class DataManager {
    private DBManager dbManager;
    public void insertData(Data data) throws Exception {
        try {
            dbManager.openActiveJDBCBaseConnection();
            insertPerson(data)
        } catch (Exception e) {
            // stuff
        } finally {
            dbManager.closeActiveJDBCBaseConnection();
        }
    }
   public void insertPerson(Data data) {
       Person person = new Person();
       person.set(“name”, data.name);
       person.set(“birthdata”, data.birthdata);
       person.set(“country”, data.country();
       person.saveit();
}

Versus doing the actual insertion from the person model itself using a static method and then calling it from the data manager

public class Person extends Model {
    static {
        validatePresenceOf(“name”, “birthdate”);
    }
    public static void insertPerson(PersonData data) {
        Person person = new Person();
        person.set(“name”, data.name);
        person.set(“birthdata”, data.birthdata);
        person.set(“country”, data.country();
        person.saveit();
    }

}

public class DataManager {
    private DBManager dbManager;
    public void insertPerson(PersonData data) throws Exception {
        try {
        dbManager.openActiveJDBCBaseConnection();
            Person.insertPerson(data);
        } catch (Exception e) {
            // stuff
        } finally {
            dbManager.closeActiveJDBCBaseConnection();
        }
    }
}

Which is better?


texts: Throttling promise execution (API requests, etc)

texts:
I was working on a client for a remote api and realized that I needed to throttle requests at a maximum rate of 4 Hertz (4 requests per second). I wrote a simple typescript class to do it and wanted to solicit code review. It basically should accept a () => Promise<R> and return a Promise<R> that resolves once executed by the queue.

My prototype solution is here, and I'd just like to solicit feedback for it. Original code here.

/**
 * Request throttle has an add() method which takes a () => Promise<string>
 * and queues the promise to be executed in order.
 * add() returns a promise that resolves with the original promise result.
 */
class RequestThrottle {
  stack = [];
  spacing = 1000;

  add: (req: () => Promise<string>) => Promise<string> = req => {
    let executor;
    const requestPromise: Promise<string> = new Promise((resolve, _reject) => {
      let localExecutor = () => {
        resolve(req());
      };
      executor = localExecutor;
    });

    this.stack.push(executor);
    return requestPromise;
  };

  pullAndExecute = () => {
    const op: () => Promise<string> = this.stack.shift();
    // if (op) console.log("throttle found:", op);
    if (op) op();
  };

  interval = setInterval(this.pullAndExecute, this.spacing);

  stop = () => clearInterval(this.interval);
}

const throttle = new RequestThrottle();

/**
 * Promise tester - to add a bit of extra async operations
 * (eg a network request to an api)
 * */
const addChild: (c: number | string) => Promise<string> = count => {
  const list = document.getElementById("list");
  const node = document.createElement("LI");
  node.innerHTML = count.toString();
  list.appendChild(node);
  const promise: Promise<string> = new Promise(resolve =>
    setTimeout(() => {
      log(`added "${count}"`);
    }, 500)
  );
  return promise;
};

const log = (s: string) => {
  const list = document.getElementById("log");
  const node = document.createElement("pre");
  node.innerHTML = s;
  list.appendChild(node);
};

addChild("Starting a List").then(console.log);

const enqueue: (i: number | string) => () => Promise<string> = i => {
  console.log("enqueueing " + i);
  return () => {
    return addChild(i);
  };
};

for (var i in [1, 2, 3, 4, 5, 6]) {
  throttle.add(enqueue(i)).then(console.log);
}


texts: Searching the Array Index & Element Equality

texts:
I was asked this question from online coding interview and I have provided my solution that passes all of the test cases. I wanted to see if someone can review my code.

Array Index & Element Equality
Given a sorted array arr of distinct integers, write a function
indexEqualsValueSearch that returns the lowest index i for which
arr[i] == i. Return -1 if there is no such index. Analyze the time and
space complexities of your solution and explain its correctness.
Examples:
input: arr = [-8,0,2,5] output: 2 # since arr[2] == 2
input: arr = [-1,0,3,6] output: -1 # since no index in arr satisfies
arr[i] == i.
[input] array.integer arr [output]: interger

I think you can find this question through this link.
My implementation uses binary search, which gives me \$O(\log(N))\$ time complexity, and space complexity is \$O(1)\$ in my solution.
def index_equals_value_search(arr):
    left = 0
    right = len(arr) - 1

    ind = 0
    last = -1
    while left < right:
        ind = (left + right) // 2
        if arr[ind] - ind < 0:
            left = ind + 1
        elif arr[ind] == ind:
            right = ind - 1
            last = ind
        else:
            right = ind - 1
    if arr[left] == left:
        return left
    return last

Test cases:

Passed 6 Test cases:
Test Cases #1
Input: [0],Expected: 0,Actual: 0
Test Case #2
Input: [0,3],Expected: 0,Actual: 0
Test Case #3
Input: [-8,0,1,3,5],Expected: 3,Actual: 3
Test Case #4
Input: [-5,0,2,3,10,29],Expected: 2,Actual: 2
Test Case #5
Input: [-5,0,3,4,10,18,27],Expected: -1,Actual: -1
Test Case #6
Input: [-6,-5,-4,-1,1,3,5,7],Expected: 7,Actual: 7


texts: Zip the contents of subfolders, conditionally

texts:
I've written a script in Powershell for zipping files into new folders.

This script performs the following steps:

Check whether each subfolder contains non-zip files which are older than 31 days
If so, create a new folder within, labelled with the date
Move the old files to the newly-created folder
Create a zipped copy of said folder
Delete the unzipped source folder

If I could get some feedback, that'd be great!

$initpath = get-location #determine initial location, in order to return later
foreach($path in get-childitem -recurse) { #get all subfolders
if ($path.Attributes -eq "Directory") {
    set-location $path.FullName
    $date = "$((Get-Date).ToString('yyyy-MM-dd_hh-mm'))"
    $newpath = [io.path]::combine("$path$date","")

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

    #verify that there are such items in this directory
    if ( $(Try { Test-Path $items } Catch { $false }) ) {
        $newfld = New-Item -ItemType Directory -name $newpath

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

        #the following block zips the folder
        $src = $newfld.FullName
        $dest = "$src.zip"
        [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
        [System.IO.Compression.ZipFile]::CreateFromDirectory($src, $dest)

        Remove-Item $src -force -recurse #remove the unzipped source folder
    }
    Else {
    Continue #continue to the next folder if there are no relevant files present
    }

    }
}
set-location $initpath #return to the initial location


texts: Calculating the Average Minimum Length of Random Numbers From 0 - 1 that Adds up to Greater Than 1

texts:
My Computer Science teacher gave us a task to calculate the average after one billion trials.

His exact assignment was this:

  Consider generating a sequence of random numbers on the interval [0, 1) perhaps using Math.random() in a loop and adding them together.  How many numbers would you expect to generate in such a sequence before the sum exceeds 1.0 ? (i.e. probability)

  Write a program that simulates these trials a billion times and calculates the average length of the sequences.
  This is a neat exercise in nested loops.

  Examples:

  0.449   0.814

  length of sequence: 2

  0.167 0.138 0.028 0.934

  length of sequence: 4

  0.640 0.258 0.417

  length of sequence: 3

  0.911 0.212

  length of sequence: 2

  Average of the four lengths is 11/4 ≈ 2.75

  What is the average of one billion random sequences?

My code was this:

import random

def genSequence():
  storenums = 0
  numTrials = 1000000000
  for x in range(0,numTrials):
    numberOfAttempts = 0
    getToOne = 0
    while (getToOne < 1): #keeps on generating random numbers and adding it to getToOne until it reaches 1 or is over 1
      getToOne += random.random()
      numberOfAttempts += 1
    storenums = storenums + numberOfAttempts
    #print (x)
    #print(storenums)
  calculateAverage(storenums,numTrials)

def calculateAverage(num,den):
  average = num/den
  print(average)

genSequence()

*Note: I am using repl.it to run my code so there is no main.

The problem with my code is that it can't reach 1 billion trials and stops working at around 227,035. I'm pretty sure this is a memory issue but I don't know how to fix this. What can I do so that it actually completes the billion trials and preferably not in an egregiously long amount of time.

EDIT: My teacher the result should be e, but that isn't the point as I just need to write the code. Getting e just means I did it right.


texts: Passing argument to a constructor and using it only in some class methods

texts:
I've created some controller for handling clicked links statistics. Does this class meet Single Responsibility Principle?

class StatisticsController
{
    protected $statisticsQuery;

    public function __construct(StatisticsQuery $statisticsQuery)
    {
        $this->statisticsQuery = $statisticsQuery;
    }

    public function recordClickedLink(array $request)
    {
        (...)
        if ($this->canRecordClick()) {
            // record clicked link
        }
        (...)
    }

    public function getStatistics(array $request)
    {
        (...)
        $someRequestParam = $request['id'];
        $statistics = $this->statisticsQuery->get($someRequestParam);
        (...)
    }

    protected function canRecordClick()
    {
        // returns true of false
    }
}

If has two public methods. The first is responsible for saving clicked link to a database by delegating it to a model class. The second public method is responsible for getting statistics and it is the only method which use $statisticsQuery object passed to a class' constructor. Is it OK that recordClickedLink method doesn't need constructor's argument?

I wonder also if it is OK that my class contain canRecordClick method with logic for checking if link click can be saved during particular request.

If this class doesn't meet SRP, how can I refactor it?


texts: Parse and sort domain names and their prices

texts:
I set out to write a small Python script to tell me cheapest domains. I manually scraped for data from iwantmyname.com into a plain text file as follows:

.COM
Commercial
$14.90
The most registered domain extension on the planet.
.CO 48% off!
Colombia
$19.90
then $39.00/year
It's .com without the m.
.APP
Generic
$29.00
Your app needs a new home
.NET
Network
$17.10
Think garage startups, beards before they were cool, and hobbyist tinkering.

This file has about 2050 lines.

First I wrote a script to get the domains and prices by reading lines that start with a . for domain and a $ for the associated price.

from operator import itemgetter

domain_prices_raw = []

with open(r'domain_prices.txt') as f:
    domain_prices_raw = f.readlines()

domain_prices_raw = [x.strip() for x in domain_prices_raw]

domains = []
prices = []

for line in domain_prices_raw:
    if line.startswith('.'):
        domains.append(line.split(' ')[0])
    if line.startswith('$'):
        prices.append(float(line.replace('$', '')))

sorted_domain_prices = sorted(
    list(zip(domains, prices)), key=itemgetter(1))

with open('sorted_domain_prices.txt', 'w') as f:
    for domain, price in sorted_domain_prices:
        f.write("{0}\t{1}\n".format(domain, price))

A bit later I realized that some domains have a low price only for the first year and subsequently have higher price per year. So I updated the script to read the lines that start with then.

Example from the file:

.CO 48% off!
Colombia
$19.90
then $39.00/year

Updated script is as follows:

from operator import itemgetter

domain_prices_raw = []

with open(r'domain_prices.txt') as f:
    domain_prices_raw = f.readlines()

domain_prices_raw = [x.strip() for x in domain_prices_raw]

domains = []
prices = []
prices_after_first_year = []

for line in domain_prices_raw:
    if line.startswith('.'):
        domains.append(line.split(' ')[0])
    if line.startswith('$'):
        prices.append(float(line.replace('$', '')))

    prices_after_first_year.append(float(line.split(' ')[1].split(
        '/')[0].replace('$', '')) if line.startswith('then') else 0)

sorted_domain_prices = sorted(
    list(zip(domains, prices, prices_after_first_year)), key=itemgetter(1))

with open('sorted_domain_prices.txt', 'w') as f:
    for domain, price, after in sorted_domain_prices:
        f.write("{0}\t{1}\t{2}\n".format(domain, price, after))

The script ran quickly enough and I was happy that I could get a working solution, if only for a few minutes.

I know I used zip to associate adjacent items and that took care of most of the logic that I would have had to write if I weren't aware the existence of something like zip from the knowledge of other programming languages.

Could the script be improved other ways to be more pythonic, more performance oriented and if nothing else, just a more expressive and or OO way to solve the problem?

Bonus question: Could a CS degree have guided me to arrive at a proper solution?


texts: Turn multiple key presses into single GameAction

texts:
The InputHandler class for my game detects key presses, turns each one into a GameAction, and raises an event:

public class InputHandler
{
    public delegate void ActionListener(GameActions gameAction);

    public event ActionListener ActionRequested;

    private void ProcessKeyboard(KeyboardState keyboardState)
    {
        var pressedKeys = keyboardState.PressedKeys();

        foreach (var inputAction in pressedKeys.Select(GetInputAction))
        {
            ActionRequested(inputAction.Down);
        }

        var releasedKeys = keyboardState.ReleasedKeys(prevPressedKeys);

        foreach (var inputAction in releasedKeys.Select(GetInputAction))
        {
            ActionRequested(inputAction.Up);
        }

        prevPressedKeys = pressedKeys;
    }
}

Only one GameAction can be requested at a time. This means that if you press the key bound to GameActions.MoveUp and the key bound to GameActions.MoveLeft at the same time, two separate events are raised and it looks like your character is moving diagonally.

Now, I need to detect this as a single GameAction, e.g. GameActions.MoveUpLeft. There has to be a better way to do it than what I've come up with.

private void ProcessKeyboard(KeyboardState keyboardState)
{
    var pressedKeys = keyboardState.PressedKeys();

    var inputActions = pressedKeys.Select(GetInputAction).ToList();
    var downActions = inputActions.Select(ia => ia.Down);

    if (downActions.Contains(GameActions.MoveUp) && downActions.Contains(GameActions.MoveLeft))
    {
        ActionRequested(GameActions.MoveUpLeft);
    }
    else if (downActions.Contains(GameActions.MoveUp) && downActions.Contains(GameActions.MoveRight))
    {
        ActionRequested(GameActions.MoveUpRight);
    }
    else if ...
}

I'm sure you can see how this can get quickly out of hand. How can I make it better?


texts:
I have this code for Merge Sort. I want to improve this code. I have learned Here

that we should use Iterartor so that we can use any container. How to use iterator in this code.

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

template<class T>
void merge(std::vector<T>& v, int p, int q, int r)
{
int size1 = q-p+1;
int size2 = r-q;
std::vector<T> L(size1);
std::vector<T> R(size2);

for(int i = 0; i < size1; i++)
{
    L[i] = v[p+i];
}
for(int j = 0; j < size2; j++)
{
    R[j]=v[q+j+1];
}

int i=0,j=0;
int k;
for(k = p; k <= r && i < size1 && j < size2; k++)
{
    if(L[i] <= R[j])
    {
        v[k] = L[i];
        i++;
    }
    else
    {
        v[k] = R[j];
        j++;
    }
}
for(i = i; i < size1; ++i)
{
    v[k] = L[i];
    k++;
}

for(j = j; j < size2; j++)
    {
        v[k] = R[j];
        k++;
    }
}

template<class T>
void merge_sort(std::vector<T>& v, int p, int r){
if(p < r)
{
    int q = (p+r)/2;
    merge_sort(v, p, q);
    merge_sort(v, q+1, r);
    merge(v, p, q, r);
}
}

int main()
{
std::vector<int>vec;
vec.push_back(13);
vec.push_back(5);
vec.push_back(7);
vec.push_back(7);
vec.push_back(4);
vec.push_back(2);
vec.push_back(10);
int sz = vec.size();
std::cout << "Entered array : ";
for(int n = 0; n < sz; n++){
    std::cout << vec[n] <<" ";
}
std::cout << "\n";
std::cout << "Sorted array : ";
merge_sort(vec, 0, sz-1);
for(int n = 0; n < sz; n++){
    std::cout << vec[n] << " ";
}
std::cout << "\n";

std::vector<char> c;
c.push_back('d');
c.push_back('y');
c.push_back('h');
c.push_back('l');
c.push_back('e');
c.push_back('a');
int sz1 = c.size();
std::cout << "Entered array : ";
for(int n = 0; n < sz1; n++){
    std::cout << c[n] <<" ";
}
std::cout << "\n";
std::cout << "Sorted array : ";
merge_sort(c, 0, sz1-1);
for(int n = 0; n < sz1; n++){
    std::cout << c[n] << " ";
}
std::cout << "\n";

std::vector<std::string> str;
str.push_back("car");
str.push_back("dog");
str.push_back("apple");
str.push_back("ball");
str.push_back("tree");
int sz2 = str.size();

std::cout << "Entered array : ";
for(int n = 0; n < sz2; n++){
    std::cout << str[n] <<" ";
}
std::cout << "\n";
std::cout << "Sorted array : ";
merge_sort(str, 0, sz2-1);
for(int n = 0; n < sz2; n++){
    std::cout << str[n] << " ";
}
std::cout << "\n";

    return 0;
}


texts: Traversing from left or from right - Leetcode 140: Word Break II

texts:
I have watched Professor Sheep's Leetcode 140: Word Break II

YouTube video here

CPP code here

My own Python translation code is below. I am thinking that the code can be optimized by traversing from right to left in this case as the code only start working with the last word. I have submitted both implementation to leetcode and traversing from left executed with 40ms and traversing from right executed with 36ms.

I believe that left and right are not the same. Just like in functional programming where foldLeft generally (no language optimization or special cases) have advantage over foldRight. In this case, I believe that approaching from Right has advantage over Left.

Please help me validate my thinking or prove me wrong convincingly.

From Left (like Professor Sheep)

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        dic = set(wordDict)
        memo = {}

        def internal(sc):
            if not sc:
                return []
            if sc in memo:
                return memo[sc]
            res = []
            if sc in dic:
                res.append(sc)

            for pos in range(1, len(sc)):
                right = sc[pos:]
                if right not in dic:
                    continue
                left = sc[:pos]
                lfls = internal(left)
                for lf in lfls:
                    res.append(lf + " " + right)
            memo[sc] = res
            return res
        return internal(s)

From Right

    def wordBreak(self, s: str, wordDict):
        dic = set(wordDict)
        memo = {}

        def internal(sc):
            if not sc:
                return []
            if sc in memo:
                return memo[sc]
            res = []
            if sc in dic:
                res.append(sc)

            for pos in range(len(sc), -1, -1):
                right = sc[pos:]
                if right not in dic:
                    continue
                left = sc[:pos]
                lfls = internal(left)
                for lf in lfls:
                    res.append(lf + " " + right)
            memo[sc] = res
            return res
        return internal(s)
```


texts: Find the Hardy–Ramanujan number using R5RS scheme

texts:
I remember once going to see [Srinivasa Ramanujan] when he was ill at Putney. I had ridden in taxi cab number 1729 and remarked that the number seemed to me rather a dull one, and that I hoped it was not an unfavorable omen. "No," he replied, "it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two different ways." [G. H. Hardy as told in "1729 (number)"]

In "Math Wrath" Joseph Tartakovsky says about this feat:

  So what? Give me two minutes and my calculator watch, and I'll do the same without exerting any little gray cells.

I don't know how Mr. Tartakovsky would accomplish that proof on a calculator watch, but the following is my scheme function that enumerates numbers starting at 1 and stops when it finds a number that is expressable in two seperate ways by summing the cubes of two positive numbers. And it indeeds returns 1729.

There are two areas where I would appreciate suggestions for improvement. One area is, being new to scheme, style and idiom. The other area is around the calculations. Sisc does not return exact numbers for roots, even when they could be.

For example (expt 27 1/3) yields 2.9999999999999996. But I do get exact results when cubing an exact number, (expt 3 3) yields 27. My solution was to get the exact floor of a cube root and then test against the cube of the floor and the cube of the floor plus one, counting as a match if either match. This solution seems messy and hard to reason about. Is there a more straightforward way?

; Find the Hardy-Ramanujan number, which is the smallest positive
; integer that is the sum of the cubes of two positivie integers in
; two seperate ways.
(define (hardy-ramanujan-number)
  (let ((how-many-sum-of-2-positive-cubes
          ; while i^3 + 1 < n/1
          ;     tmp := exact_floor(cube-root(n - i^3))
          ;     if n = i^3 + tmp^3 or n = i^3 + (tmp + 1) ^3 then count := count + 1
          ; return count
          (lambda (n)
            (let ((cube (lambda (n) (expt n 3)))
                  (cube-root (lambda (n) (inexact->exact (expt n 1/3)))))
              (let iter ((i 1) (count 0))
                (if (> (+ (expt i 3) 1) (/ n 2))
                    count
                    (let* ((cube-i (cube i))
                           (tmp (floor (cube-root (- n cube-i)))))
                      (iter (+ i 1)
                        (+ count
                          (if (or (= n (+ cube-i (cube tmp)))
                                  (= n (+ cube-i (cube (+ tmp 1)))))
                              1
                              0))))))))))
    (let iter ((n 1))
      (if (= (how-many-sum-of-2-positive-cubes n) 2)
          n
          (iter (+ 1 n))))))


texts: Library to verify GTINs of various lengths

texts:
I'm writing a library to verify GTINs (GTIN-8, GTIN-12, GTIN-13, GTIN-14) and calculate their check digits. The calculation of the check digits don't differ from type to type, so I can use the same code for all types of GTINs.

My question: Should I use separate classes for each type of GTIN or should I store the length into an instance attribute?

I have listed two options (simplified):

Option #1

import re

class GTIN:
    def __init__(self, gtin):
        self.gtin = self.parse(gtin)

    @classmethod
    def parse(cls, gtin):
        parsed_gtin = cls.sanitize(gtin)
        if not cls.check_format(parsed_gtin)
            return None
        return parsed_gtin

    @classmethod
    def sanitize(cls, gtin):
        return re.sub(r'[\s\-]+', '', gtin)

    @classmethod
    def check_format(cls, gtin):
        if re.match(cls.FORMAT, gtin):
            return True
        return False

class GTIN8(GTIN):
    FORMAT = r'^[0-9]{7}[0-9?]{1}$'

class GTIN12(GTIN):
    FORMAT = r'^[0-9]{11}[0-9?]{1}$'

The given GTIN string can contain a ? if the check digit should be calculated.

Option #2

import re

class GTIN:
    ALLOWED_LENGTHS = [8, 12, 13, 14]

    def __init__(self, gtin):
        self.gtin = self.parse(gtin)

    @classmethod
    def parse(cls, gtin):
        parsed_gtin = cls.sanitize(gtin)
        if not cls.check_format(parsed_gtin)
            return None
        return parsed_gtin

    @classmethod
    def sanitize(cls, gtin):
        return re.sub(r'[\s\-]+', '', gtin)

    @classmethod
    def check_format(cls, gtin):
        if len(gtin) in cls.ALLOWED_LENGTHS:
            self.length = len(gtin)
        else:
            return False

        format = r'^[0-9]{{{}}}[0-9?]{{1}}$'.format(self.length - 1)
        if re.match(format, gtin):
            return True
        return False


texts: Popping from a list in state while a condition is true

texts:
I'm dealing with data that stores its state as a String, treating the string like a stack. I also have to combine that with error handling.

To that end, I'm using the type StateT String Maybe a. I have a function to pop and to push a Char from and to the string:

pop :: StateT String Maybe Char
pop = do
    x:xs <- get
    put xs
    return x

push :: Char -> StateT String Maybe ()
push x = do
    xs <- get
    put (x:xs)
    return ()

I wrote a function to repeatedly pop from the string while the characters being popped fulfilled a condition. It behaves as follows:

> runStateT (popWhile (<'a')) "HELLO world"
Just ("HELLO ","world")

> runStateT (popWhile (>'a')) "HELLO world"
Just ("","HELLO world")

My implementation is the following:

popWhile :: (Char -> Bool) -> StateT String Maybe [Char]
popWhile f = do
    s <- get
    if null s
        then return []
        else popAgain

    where
        popAgain = do
            x <- pop
            if f x
                then liftM (x:) (popWhile f)
                else push x >> return []

But that seems pretty bulky, and has two if then else's in it. Is there a better way to write this function?


texts: Approximating constant π² to within error

texts:
This function takes as input float error and approximates constant π² to within error by computing this sum, term by term, until the difference between the new and the previous sum is less than error. The function should return the new sum.

$$ \pi^2 = 8 + \dfrac{8}{3^2} + \dfrac{8}{5^2} + \dfrac{8}{7^2} + \dfrac{8}{9^2} + \cdots $$

Example:

approxPIsquared(0.0001)

Result is 9.855519952254232

My working solution is shown below:

def approxPIsquared(error):
    prev = 8
    new =0
    n = 3
    while (True):
        new = (prev + (8 / (n * n)))
        diff = new - prev
        if (diff <= error):
            break
        prev = new
        n = n + 2

    return new

Is this a good solution or is there a better way to do this?


texts: Group-wise deviations from means / centering with dplyr vs. data.table

texts:
I am trying in R to "center" a matrix (i.e. remove mean) group-wise (i.e. remove group means for each variable).

Input is a matrix (including the grouping variable), and output is the same matrix, where columns are now group-wise centered (possibly excluding now grouping variable).

I tried 3 solutions:

Using dplyr: use group_by(cell) and mutate_all(funs(. - mean(.)))
Using data.table: dt[, lapply(.SD, function(x) x - mean(x)), by= cell]
Using data.table: same as above, but in 2 steps: instead of over-writing variables, 1) add mean variables as new columns, 2) then compute differences, splitting the original matrix as two different matrices.

Results in terms of speed are: 3 < 2 < 1. (3) being faster than (2) is surprising (as (2) is just overwriting variables, not adding)... I suspect it could be from the fact that using function(x) x - mean(x) prevents data.table to use an optimised version of the mean function.

My questions are:

Any way I can speed up some of the code?
How can I understand (3) is faster than (2)? Can I get (2) to be faster?

library(tidyverse)
library(data.table)

## function (1)
center_dplyr <- function(x) {
  x %>%
    group_by(cell) %>%
    mutate_all(funs(. - mean(.))) %>%
    ungroup() %>%
    dplyr::select(-cell)
}

## function (2)
center_dt_1 <- function(x) {
  x <- as.data.table(x)
  setkey(x, cell)
  res <- x[, lapply(.SD, function(x) x - mean(x)), by= cell][, -"cell"]
  as.data.frame(res)
}

## function (3)
center_dt_2 <- function(x) {
  x <- as.data.table(x)
  x_names <- colnames(x)[colnames(x) !="cell"]
  x_names_new <-  paste(x_names, "mean", sep="_")

  setkey(x, cell)
  x[,  paste(x_names, "mean", sep="_"):= lapply(.SD, mean, na.rm = TRUE), by = cell]
  res <- x[, x_names, with=FALSE] - x[, x_names_new, with=FALSE]
  as.data.frame(res)
}

## Data
T = 6;
N = 10^4
set.seed(123)
sim_df <- data.frame(A = sample(c(0,1), N * T, replace = TRUE),
                      B1 = sample(c(0,1), N * T, replace = TRUE),
                      B2 = rnorm(N),
                      cell = rep(1:N, each = T))

ans_dplyr <- center_dplyr(x=sim_df)
ans_dt1 <- center_dt_1(sim_df)
ans_dt2 <- center_dt_2(sim_df)

all.equal(ans_dt1, ans_dplyr, check.attributes = FALSE)
all.equal(ans_dt2, ans_dplyr, check.attributes = FALSE)

### Benchmark:

library(microbenchmark)

## small
sim_df_s <- sim_df[1:1000,]
bench_small <-  microbenchmark(ans_dplyr = center_dplyr(sim_df_s),
                           ans_dt1 = center_dt_1(sim_df_s),
                           ans_dt2 = center_dt_2(sim_df_s),
                           times = 10)

bench_large <- microbenchmark(ans_dplyr = center_dplyr(sim_df),
                              ans_dt1 = center_dt_1(sim_df),
                              ans_dt2 = center_dt_2(sim_df),
                              times = 10)

bench_all <- rbind(bench_small %>% summary %>% mutate(data_size = "small"),
                   bench_large %>% summary %>% mutate(data_size = "large")) %>%
  select(data_size)

bench_all


texts: Newsfeed app for allowing custom Reddit feeds

texts:
I'm currently working on a newsfeed app (see it live here or its files on GitHub) that lets a user create a custom Reddit feed. The user adds the subreddits they'd like to view, and then can view them in this Angular dashboard.

I'd really appreciate any type of feedback on what I may improve on. I'm under the impression that my controller is doing too much, so I've started looking into creating custom directives and using 'controller' or 'link' functions (or should I put more logic into factories?). But getting started has been a bit of challenge and I'd appreciate some help.

(function() {

  var Controller = function ($scope, Factory) {

  // This is the default set of reddits
    $scope.reddits = ['worldnews', 'science', 'technology', 'futurology', 'zenhabits'];

    $scope.timeline = [{
      label: 'Today',
      query: '/top.json?sort=top&t=day'
      }, {
      label: 'This week',
      query: '/top.json?sort=top&t=week'
      }, {
      label: 'This month',
      query: '/top.json?sort=top&t=month'
      }, {
      label: 'This year',
      query: '/top.json?sort=top&t=year'
      }, {
      label: 'All time',
      query: '/top.json?sort=top&t=all'
    }];

    $scope.timeRange = $scope.timeline[0];
    $scope.timeQuery = $scope.timeRange.query;
    $scope.sidebar = true;

  // Gets and Displays feed when selected
    $scope.getFeed = function(feedName, timeSpan) {

      $scope.feed = [];

      Factory.getFeed(feedName, timeSpan)
        .success(function(posts) {
          var j = posts.data.children.length;
            for (var i = 0; i < j; i++) {
              $scope.feed.push(posts.data.children[i].data);
            }
          });

      $scope.selectedFeed = feedName;
      $scope.sidebar = true;
    };

  // Changes the time that is being used for sorting posts
    $scope.sortBy = function(timeSpan) {
      $scope.timeQuery = timeSpan;
      $scope.getFeed($scope.selectedFeed, $scope.timeQuery);
    };

  // Loads Default feed on page load
    function init() {
      $scope.savedFeed = Factory.sessionInfo($scope.reddits);
      $scope.getFeed($scope.savedFeed[0], $scope.timeQuery);
    }
    init();

  // Adds feeds to Dashboard
    $scope.addFeed = function (feedName) {

      if ($scope.savedFeed.indexOf(feedName) == -1){
        $scope.savedFeed.push(feedName);
      } else {
        alert('Looks like that feed already exists!');
      }

      Factory.saveToLocal('reddit', $scope.savedFeed);
      $scope.getFeed(feedName);
      $scope.addFeedInput = '';
    };

  // Removes feed from Dashboard
    $scope.removeFeed = function(feedName) {
      var index = $scope.savedFeed.indexOf(feedName);
      $scope.savedFeed.splice(index, 1);

      Factory.saveToLocal('reddit', $scope.savedFeed);
    };

  };

  Controller.$inject = ['$scope', 'Factory'];

  angular.module('contentApp')
    .controller('Controller', Controller);

}());


texts: Recursively generating the look-and-say sequence

texts:
I have a pattern where every number is counted by the number of repetitions. A new resulting number is formed by adding that repetition to the front of that value. The resulting pattern would look like this.

1
11
21
1211
111221

so:

indexnumbercomment
0      1
 one +  1 ->11
1      11       two + 1 -> 21
2      21       one + 2 + one + 1 -> 1211

etc...

I was given a number 4, and I needed to produce the resulting number 1211.

My approach was to use a recursive function that used every subsequent iteration starting from 0 to evaluate every resulting value until I reached my target iteration.

Runtime Complexity: I decremented the number recursively O(N) as I carried the resulting evaluation result.

At every recursive step, I produced every result by walking the resulting values, counting the repetitions as I went along. I stored every key-value pairs along an Index represented by a synecdochic key in a line of contiguous repetition. I tallied the repetitions until I had a key-value pair at the intersection of every index.

I then assembled the value by swapping the key values pairs at every index into a new object array which I used to repeat the process. O(C)

I then used reduce to format the results and repeat the process O(F)

O(N *C +F) = O(N^2)

space complexity is O(N^2) since the amount of space needed to process doubles on every resulting iteration.

Are my Time and Space analysis correct, did I miss a much simpler approach where I might have been able to take advantage of Fibonacci, XOR or some other simpler mathematical approach?  and could this have been done better programmatically by using some other type of data structure, or could it have been written in some other concise way?

function countStay(num) {
  if (num === 1) {
    return 1
  }

  return drill(num, [1])
}

function drill(exitCount, result) {
  const map = {
      0: {}
    },
    arr = [];
  let count = 0,
    index = 0;
  result = result.reduce((acc, a, i, aa) => {
    if (aa[i - 1] && aa[i] && a !== aa[i - 1]) {
      index += 1
      count = 0
      map[index] = {
        [a]: count
      }
    }
    if (((map || {})[index] || {})[a] && count !== 0) {
      map[index][a] = count += 1
      arr[index] = [count, a]
    }
    if (!((map || {})[index] || {})[a] && count === 0) {
      count += 1
      map[index] = {
        [a]: count
      }
      arr[index] = [count, a]
    }
    return acc = {
      arr
    }
  }, {})

  result = join(result)
  exitCount--
  if (exitCount <= 1) {
    return result.join('')
  }
  return drill(exitCount, result)
}

function join(result) {
  return result = result.arr.reduce((acum, a) => acum.concat(a), [])
}
console.log(countStay(4))


texts:
Purpose

Implement a solution that returns the values in the Nth row of Pascal's Triangle where N >= 0.

Math

First three rows of Pascal's Triangle:

    1
  1   1
1   2   1
...
...

These row values can be calculated by the following methodology:

For a given non-negative row index, the first row value will be the binomial coefficient where n is the row index value and k is 0).
The next row value would be the binomial coefficient with the same n-value (the row index value) but incrementing the k-value by 1, until the k-value is equal to the row index value.

Implementation

There are two things the calculator would need in order to operate correctly:

A Binomial Coefficient Calculator, which it would depend on directly
A Factorial Calculator, which the Binomial Coefficient Calculator would depend on directly

public class FactorialCalculator {

  public static int calculateFactorial(int n) {
    if (n < 0) {
      throw new IllegalArgumentException("n value should be non-negative");
    }

    int factorialValue = 1;

    if (n == 0) {
      return factorialValue;
    }

    for (int multiplier = n; multiplier > 0; multiplier--) {
      factorialValue *= multiplier;
    }

    return factorialValue;
  }
}

public class BinomialCoefficientCalculator {

  public static int calculateBinomialCoefficient(int n, int k) {
    if (n < 0) {
      throw new IllegalArgumentException("n value cannot be negative");
    }

    if (k < 0) {
      throw new IllegalArgumentException("k value cannot be negative");
    }

    if (n < k) {
      throw new IllegalArgumentException("n value cannot be less than k value");
    }

    return FactorialCalculator.calculateFactorial(n) / (FactorialCalculator.calculateFactorial(k) * FactorialCalculator.calculateFactorial(n - k));
  }
}

public class PascalsTriangleRowValuesCalculator {

  public static List<Integer> calculateRowValues(int rowIndex) {
    if (rowIndex < 0) {
      throw new IllegalArgumentException("row index must be non-negative");
    }

    List<Integer> rowValues = new ArrayList<>();
    for (int k = 0; k <= rowIndex; k++ ) {
      rowValues.add(BinomialCoefficientCalculator.calculateBinomialCoefficient(rowIndex, k));
    }
    return rowValues;
  }
}


texts:
Constructive criticism is required for the 2 methods below.  I'm trying to develop better OO skills.

 // Set up scanner to allow for searching of modules
public static String searchModule() {
    Scanner scan;
    System.out.print("Search module code: ");
    scan = new Scanner(System.in);
    String searchModule = scan.nextLine().trim();
    return searchModule;
}

// Search modules and return all students enrolled on it
public static void moduleStudentSearch(Set<Module> modules, Set<Student> students) {
    String searchModule = searchModule();

    for (Module module : modules) {
        if (searchModule.equalsIgnoreCase(module.getName())) {
            Iterator it = students.iterator();
            while (it.hasNext()) {
                Student student = (Student) it.next();
                if (student.getModules().contains(module)) {
                    System.out.printf("%s ", student.getName());
                }
            }
        }
    }
}


texts:
I'm writing a simulator which checks how many balls we need to occupy every box or how many balls we need for any box has at least 2 balls (birthday paradox). I wrote the script in python and it is so slow. My friend wrote a program in C++ and the script is much faster. For boxes_max_num = 1000 it takes few minutes when in my python script it takes 'eternity'.

There is my code:

import numpy as np
import matplotlib.pyplot as plt

def check_every_box_is_occupied(boxes):
    for box in boxes:
        if box == 0:
            return False
    return True

def check_birthday_paradox(boxes):
    for box in boxes:
        if box >= 2:
            return True
    return False

def main():
    number_of_tests = 250
    birthday_paradox_graph = [[], []]
    every_box_is_occupied_graph = [[], []]
    boxes_max_num = 1000
    for number_of_boxes in range(10, boxes_max_num + 1, 1):
        print(number_of_boxes)
        average_frequency_birthday_paradox = 0
        average_frequency_every_box_is_occupied = 0
        for index in range(number_of_tests):
            number_of_balls = 1
            boxes = np.array([0] * number_of_boxes)
            while True:
                boxes[np.random.randint(number_of_boxes)] += 1
                if check_birthday_paradox(boxes):
                    average_frequency_birthday_paradox += number_of_balls
                    break
                number_of_balls += 1
            number_of_balls = number_of_boxes
            boxes = np.array([0] * number_of_boxes)
            while True:
                boxes[np.random.randint(number_of_boxes)] += 1
                if check_every_box_is_occupied(boxes):
                    average_frequency_every_box_is_occupied += number_of_balls
                    break
                number_of_balls += 1

        plt.rcParams.update({'font.size': 15})
        birthday_paradox_graph[0].append(number_of_boxes)
        birthday_paradox_graph[1].append(average_frequency_birthday_paradox / number_of_tests)
        every_box_is_occupied_graph[0].append(number_of_boxes)
        every_box_is_occupied_graph[1].append(average_frequency_every_box_is_occupied / number_of_tests)
    plt.figure(1)
    plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')
    plt.title("Conajmniej jedna urna ma conajmniej dwie kule")
    plt.xlabel("Liczba urn")
    plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
    plt.figure(2)
    plt.title("Wszystkie urny są zapełnione")
    plt.xlabel("Liczba urn")
    plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
    plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')
    plt.show()

if __name__ == '__main__':
    main()

Can you help me to improve the code to make it faster? Is it possible in raw python?


texts:
I'm creating a program that averages four numbers - three from a file and one from user input. Simple enough. But the catch is, the professor is going to be deliberately trying to break the program.

I'd like advice in any regard, but remember the focus is on robustness.

import java.util.*;
import java.io.*;

public class average {
    public static void main (String[] args) throws IOException{
        double[] nums = new double[4];
        nums = inputHandler();
        System.out.println("Average " + findAverage(nums));

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

    public static double findAverage(double[] nums){
        double average = 0.0;
        final double N = 4.0;

        for(int i = 0; i < N; i++){
            average += nums[i] / N;
        }

        return average;
    }

    public static double[] inputHandler() throws IOException{
        Scanner input = new Scanner(System.in);
        double[] nums = new double[4];
        double[] fileNums = new double[3];

        // get first three numbers from file
        System.out.print("Enter the name of the file which contains the first three numbers: ");
        fileNums = fileInput(input.nextLine());
        System.out.println();

        // copy numbers from fileNums[] to nums[]
        for(int i = 0; i < 3; i++){
            nums[i] = fileNums[i];
        }

        //get last number from user input
        System.out.print("Enter the fourth number: ");
        nums[3] = userInput(input.nextLine());
        System.out.println();

        input.close();

        return nums;
    }

    public static double[] fileInput(String fileName) throws IOException{
        double[] nums = new double[3];

        System.out.println();

        File file = new File(fileName);

        if(!file.isFile()){
            System.err.println("ERROR: File does not exist.");
            System.exit(-1);
        }

        System.out.println(fileName + ":");

        Scanner input = new Scanner(file);
        String cur = "";

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

            if(!input.hasNext()){
                System.err.println("ERROR: File does not contain enough numbers.");
                System.exit(-1);
            }

            cur = input.next();

            System.out.println("Number " + (i + 1) + ": " + cur);

            if(cur.matches("-?\\d+(\\.\\d+)?")){ //regex ensures numeric input
                if(Double.parseDouble(cur) < 1.7e308){
                    nums[i] = Double.parseDouble(cur);
                }
                else{
                    System.err.println("ERROR: Number too large");
                    System.exit(-1);
                }
            }
            else{
                System.err.println("ERROR: Non numeric input. Please check your file and try again.");
                System.exit(-1);
            }
        }

        input.close();

        return nums;
    }

    public static double userInput(String userInput){
        double num = 0;

        if(userInput.matches("-?\\d+(\\.\\d+)?")){ //regex ensures input is numeric
            num = Double.parseDouble(userInput);
        }
        else{
            System.err.println("ERROR: Non numeric input. Please check your file and try again.");
            System.exit(-1);
        }

        return num;
    }
}


texts: Comparison to infinity when checking if a point is above a line

texts:
I have a function that is being called in a tight loop. I've profiled my code and this is where my largest bottleneck is. The function is fairly simple: it checks if a point in (x,y) form is above a line in (slope, intercept) form.

The problem is, it also has to deal with the case where the slope is positive infinity, and the intercept gives the x-intercept. In this case, the function should return True if the point is to the right of the line.

Here's the function written out how it was when I noticed the bottleneck:

def point_over(point, line):
    """Return true if the point is above the line.
    """
    slope, intercept = line
    if slope != float("inf"):
        return point[0] * slope + intercept < point[1]
    else:
        return point[0] > intercept

On my machine, this is how fast it runs:

>>> timeit("point_over((2.412412,3.123213), (-1.1234,9.1234))",
           "from __main__ import point_over", number = 1000000)
1.116534522825532

Since this function is being called a lot, I've inlined it to avoid the function call overhead. The inlined version is fairly simple:

point[0] * line[0] + line[1] < point[1] if line[0] != float('inf') else point[0] > line[1]

And performs similarly in timeit:

>>> timeit("point[0] * line[0] + line[1] < point[1] if line[0] != float('inf') else point[0] > line[1]",
           "point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000)
0.9410096389594945

However, this one line of code is still hogging the largest proportion of execution time in my code, even after being inlined.

Why does the comparison to float('inf') take longer than a number of calculations as well as a comparison? Is there any way to make this faster?

As an example of what I'm claiming, here are the speeds of two parts of my ternary statement separated and timed:

>>> timeit("line[0] != float('inf')",
           "point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000)
0.528602410095175
>>> timeit("point[0] * line[0] + line[1] < point[1]",
           "point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000)
0.48756339706397966

My primary question is why it takes so long to do the comparison to infinity. Secondary is any tips on how to speed these up. Ideally there exists some magical (even if incredibly hacky) way to half the execution time of this line, without dropping down to C. Otherwise, tell me I need to drop down to C.


texts:
I started this exercise with NumPy with a goal to find neighbors and return the new matrix. I want to get your feedback. Here's an example from this website. It looks like it's \$O(N^2)\$, and I'm adding a internal loop to look around neighbors.

import numpy as np
import pprint

world = np.array([[0, 0, 0, 0, 0],
                  [0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 0],
                  [0, 0, 0, 0, 0]])

pprint.pprint(world)
size = world.shape[0]

def next_state(world):
    """

    :param world:
    :return:
    """
    size = world.shape[0]
    neighbors = np.zeros(shape=(size, size), dtype=int)
    new_world = np.zeros(shape=(size, size), dtype=int)
    neighbor_count = 0
    # Ignore edges: start xrange: in 1
    for rows in xrange(1, size - 1):
        for cols in xrange(1, size - 1):
            # Check neighbors
            for i in [-1, 0, 1]:
                for j in [-1, 0, 1]:
                    # Condition to not count existing cell.
                    if rows + i != rows or cols + j != cols:
                        neighbor_count += world[rows + i][cols + j]
                        neighbors[rows][cols] = neighbor_count

            if neighbors[rows][cols] == 3 or (world[rows][cols] == 1 and neighbors[rows][cols] == 2):
                new_world[rows][cols] = 1
            else:
                new_world[rows][cols] = 0
            neighbor_count = 0

    pprint.pprint(neighbors)
    return new_world

print next_state(world)


texts: Converting a list to an array when list has quotes and embedded comma

texts:
This function converts a list to an array when list has quotes and embedded comma:

array function convertRow(required string lstRow) {

    var arResult = [];
    var arTemp = ListToArray(arguments.lstRow, ',', true);

    var quoteMode = false;
    var startQuote = false;

    for (var i in arTemp) {

        if (i CONTAINS '"' && not quoteMode) { startQuote =  true; }

        if (startQuote) {
            ArrayAppend(arResult, replace(i, '"', ''));

            startQuote = false;
            quoteMode = true;
        }
        else if (quoteMode) {
            arResult[ArrayLen(arResult)] &= "," & replace(i, '"', '');

            if (i CONTAINS '"') quoteMode = false;
        }
        else
            ArrayAppend(arResult, i);
    }

    writedump(lstRow);
    writedump(arResult);

    return arResult;
}


texts:
I have started to learn C. At the time of writing I don't know anything about the language. The following I wrote today in a few hours. Though I do have a lot of programming experience, I find C hard to learn. That may be only a temporary impression, however.

The purpose of the following function is to determine if the string, whatever its length is, contains an integer number. There might be many ways, and/or I might have done some rookie mistakes.

#include <stdbool.h> // bool type, true / false values, ...
#include <stdio.h> // printf()
#include <ctype.h> // isdigit()
#include <string.h> // strlen(), strncmp(), ...

bool string_contains_integer(const char *str)
/*
    This function iterates through an array of chars,
    and checks each character to be a digit.

    Returns true if the string contains a number (string of digits);
    Returns false if the string contains another character(s).

    Starting "-" gets ignored, as we accept negative numbers too.
*/
{
    // I'd like to avoid repeated strlen() calls
    int string_length = strlen(str);

    // if the string is empty, return right away
    if (string_length == 0)
        return false;

    bool negative_sign = false;

    // iterate through all characters in the string
    for (int i = 0; i < string_length; i++)
    {
        // extract character on index
        char chr = str[i];

        // repeated presence of negative sign is handled here
        if (strncmp("-", &chr, 1) == 0)
        {
            // if the negative sign gets detected
            // for the second time, return right away
            if (negative_sign)
                return false;

            // once a negative sign is detected, we make note of it here
            negative_sign = true;

            // now we want to skip the check for a digit
            continue;
        }

        // this is actually the core part checking on digits
        if (!isdigit(chr))
            return false;
    }

    // If we got here, then all the characters are digits,
    // possibly starting with a negative sign.
    return true;
}

int main()
{
    // the function can handle very big numbers as shown here
    if (string_contains_integer("-123456789123456789123456789123456789123456789123456789123456789"))
    {
        printf("%s\n", "PASS: Input is a number.");
    }
    else
    {
        printf("%s\n", "FAIL: Input is not a number!");
    }
}

This program I compile on Linux Mint 19.1 as follows:

gcc-8 -std=c18 -Wall -Wextra -Werror -Wpedantic -pedantic-errors -o bigInteger bigInteger.c

Would you be that kind to review the code? However, there might be alternative ways of doing the same thing, you may, of course, suggest them, but my primary goal now is to check upon my learning curve and to fix bugs of course, optimize this code, etc.


texts: Creating a list containing the rank of the elements in the original list

texts:
I don't really know how to explain what I'm looking for in a way that makes sense, but here goes:

Say I have a list
$$L=(4,7,9,10,6,11,3)$$
What I want to produce is a corresponding list
$$ K = (1,3,4,5,2,6,0)$$

where element K[i] has the value of the 'rank' of the element for the corresponding location in L. So the higher the number the higher the rank, starting from rank 0 for the smallest number in L

The code I have written for this is:

x = [4,7,9,10,6,11,3]
index = [0]*len(x)

for i in range(len(x)):
    index[x.index(min(x))] = i
    x[x.index(min(x))] = max(x)+1

and it works, but I just feel it looks horrible, and was wondering if there might exist a more aesthetic way.


texts:
This function finds links from Clyp.it and offers users a link to embed the content. Please let me know what you think of it. It works, but probably has some redundancies and inefficiencies.

$(document).ready(function() {
    var clyplinks = $('a[href^="https://clyp.it/"]').filter(function() {
        return this.innerHTML.match(/(https:\/\/clyp.it\/)([\w]{8})/);
    });
    $(clyplinks).each(function(index) {

        var x = null;
        var id = $(this).attr("href").split("it/")[1];
        var e = $(' [embed]').insertAfter($(this));
        e.click(function(evt) {
            evt.preventDefault();
            if (x != 1) {
                $(this).after('

')
                $(e).html(' [remove]')
                x = 1;
                console.log('embed' + x + ' ' + index);
            } else {
                $('#clyp' + id + index).detach();
                $(e).html(' [embed]')
                x = null;
                console.log('yay' + x + ' ' + index);

            }

        });

    });
});

https://clyp.it/5e0dmibw

JSFiddle:

https://jsfiddle.net/1svgq6g4/


texts: javascript property extractor optimisation

texts:
This is a very simple nested property extractor. I wonder if it can be optimised further?

/**
 * Extract nested property from object. If nested property cannot be reached, return value of rescue
 * @param obj Object
 * @param path Can be dot-separated  string or array
 * @param rescue (optional) default value. Defaults to null
 */
function extract(obj, path, rescue){

    if (typeof obj === "object" && path){

        var elements = typeof path === "string" ? path.split(".") : path;

        if (typeof elements.shift === "function"){

             var head = elements.shift();

             if (obj.hasOwnProperty(head)){

                return (elements.length === 0) ? obj[head] : extract(obj[head], elements, rescue);

             } // if

         } // if

    } // if

    return rescue || null;

} // extract

var noob = {k1 : {k11 : {k111 : "v1"}}, k2 : { k21 : "v2"}};

console.log(extract(noob, 'k1.k11')); // {k111 : "v1"}
console.log(extract(noob, 'k1.k11.k111')); // v1
console.log(extract(noob, ['k1', 'k11', 'k111'])); // v1
console.log(extract(noob, 'k1.k11.kx')); // null
console.log(extract(noob, 'k2')); //  k2 : { k21 : "v2"}
console.log(extract(noob, 'k2.k21.k22')); // null
console.log(extract(noob, 'k1.k11.k22', "ZUT")); // ZUT
console.log(extract(noob, '', "ZUT"));  // ZUT
console.log(extract(false, '', "ZUT"));  // ZUT


texts: Handling a PUT API call to write to a database using promises

texts:
The following function is accepting PUT connection to a server API, checks authorization to write and then performs write to a database.

The eslint linting tool complains saying "avoid nesting promises" and "Each then() should return a value or throw". I'm new to promises and I am not sure how to improve my code.

app.put('/api/v0/note/:id', (req, res) => {
  const id = req.params.id;
  const uid = req.user ? req.user.uid : null;
  return user_can_edit_note(uid, id).then(yes => {
    if (yes) {
        return db.collection('notes').doc(id).update({
          title: req.body.title,
          text: req.body.text,
          author_uid: req.user ? req.user.uid : null,
          updated_on: admin.firestore.Timestamp.now()
        }).then(() => {
          return res.json({
            ok: "ok"
          });
        });
    } else {
      return res.status(403).json({
        error: "Permission Denied",
        note_id: id
      });
    }
  }).catch((err) => {
    console.error(err);
    return res.status(500).json({error: String(err)});
  });
});


texts: Counting ways to divide a word into palindrome blocks

texts:
I wrote this program as a solution to the 2015 British Informatics Olympiad question on "block" palindromes.
Brief overview of the task:

A palindrome is a word that shows the same sequence of letters when reversed.
If a word can have its letters grouped together in two or more blocks (each containing one or more adjacent letters) then it is a block palindrome if reversing the order of those blocks results in the same sequence of blocks.
For example, using brackets to indicate blocks, the following are block palindromes:

BONBON can be grouped together as (BON)(BON);
ONION can be grouped together as (ON)(I)(ON);
BBACBB can be grouped together as (B)(BACB)(B) or (BB)(AC)(BB) or (B)(B)(AC)(B)(B)

Note that (BB)(AC)(B)(B) is not valid as the reverse (B)(B)(AC)(BB) shows the blocks in a different order.
TASK: Write a program which reads in a word of between 2 and 10 (inclusive) uppercase letters.
You should output a single number, the number of different ways the input can be grouped to show it is a block palindrome.

What tips do you have for improving my solution:
# theonlygusti's solution to Question 1(a)

word = input()

if not (2 <= len(word) <= 10):
    print("Your input must be between 10 and 2 characters, inclusive.")
    exit()

if not word.upper() == word:
    print("Your input must be all uppercase, e.g. BBACBB")
    exit()

if not word.isalpha():
    print("Your input must contain only letters, this means characters like numbers and spaces are not allowed.")
    exit()

def number_of_block_palindrome_groupings(string):
    total_groupings = 0
    for i in range(1, len(string)//2+1):
        if (string[:i] == string[-i:]):
            total_groupings += 1 + number_of_block_palindrome_groupings(string[i:-i])
    return total_groupings

print(number_of_block_palindrome_groupings(word))


texts: type/class __repr__ formatter for Python objects

texts:
I am building a list of Python objects that I use fairly regularly that have a length property, (len, 'len') and I was trying to determine the best way to simplify the type/class formatter that the object uses.  For example:
 type([]), returns "< type 'list'>" and type(collections.Counter()) returns "< class 'collections.Counter'> "

I had assumed that the formatter that was used could be accessed simply and the extraneous information removed to facility a particular documentation format that I prefer.  In this situation, I had hoped to be able to remove '< type ... >' or '< class ... >' from the resultant output.  The kludge that I have come up with entails parsing the string into its components and returning the portion I want.  To ensure generality, for objects that I may not currently use, I had hoped for a better solution.

Insights regarding options to this issue, or more general comments would be appreciated.  The line in question is flagged with a comment.  Apologies, if I am not supposed to included doc information with posted scripts.

"""
Script:   empty_tests.py
Modified: 2015-05-25
Purpose:
  checks on objects that I use, that have a __len__ property
Notes:
- collections.OrderedDictionary and other classes in collections behave
  in a similar fashion
- for NumPy arrays, use size property rather than __len__
"""
import numpy as np
import collections
c0 = collections.Counter()
c1 = collections.Counter([0])
objs = [ [],[1],(),(1),{},{1:"one"},"","1",None,True,1,False,0,c0,c1 ]
is_empty = [ True  if not i else False for i in objs ]
t = [ type(i).__name__ for i in objs ]            # correct based on comment
#t = [str(type(i)).split("\'")[1] for i in objs ] # line in question
print("\n{:<15} {:<6} {:<10}".format("Object","Empty","Type"))
for i in range(len(objs)):
    print("{:<15} {:<6} {:<10s}".format(objs[i],str(is_empty[i]),t[i]))

Output with the above...the commented out line worked

Object          Empty  Type
[]              True   list
[1]             False  list
()              True   tuple
1               False  int
{}              True   dict
{1: 'one'}      False  dict
                True   str
.... etc

I have tried ....

>>> type([])
<type 'type'>
>>> repr(type([]))
<type 'list'>"
>>> str(type([]))
<type 'list'>"
>>> print str(type([])), repr(type([]))
<type 'list'> <type 'list'>
>>>

EDIT
the "name" property wasn't listed where I thought it would be, so if the object has a "format" property, check there.

>>> help(type(object).__format__)
Help on method_descriptor:
__format__(...)
    default object formatter
>>> dir(type(object).__format__)
    ['__call__', '__class__', '__delattr__', '__doc__', '__format__',
     '__get__', '__getattribute__', '__hash__', '__init__', '__name__',
     '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__',
     '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
    >>>


texts: Representing vehicles and their components

texts:
I am working on a project that needs to represent different kinds of vehicles, components of these vehicles and actual parts of the components.

So far I have this code:

class Vehicle
{
public:
    /* Public interface */

    //ctor
    Vehicle(int id, int year, int mileage, int weight, int length, int width, int height, int wheelbase,
        const QString& date, const QString& type, const QString& maker, const QString& model, const QString& color, const QString& plate);

    //copy/move
    Vehicle(const Vehicle&) = delete;
    Vehicle(Vehicle&&) = delete;
    Vehicle& operator=(const Vehicle&) = delete;
    Vehicle& operator=(Vehicle&&) = delete;

    //dtor
    virtual ~Vehicle();

    //getters
    inline int getId() const { return m_id; }
    inline int getYear() const { return m_year; }
    inline int getMileage() const { return m_mileage; }
    inline int getWeight() const { return m_weight; }
    inline int getLength() const { return m_length; }
    inline int getWidth() const { return m_width; }
    inline int getHeight() const { return m_height; }
    inline int getWheelbase() const { return m_wheelbase; }

    inline const QString& getDateReceived() const { return m_date_received; }
    inline const QString& getType() const { return m_type; }
    inline const QString& getMaker() const { return m_maker; }
    inline const QString& getModel() const { return m_model; }
    inline const QString& getColor() const { return m_color; }
    inline const QString& getPlate() const { return m_plate; }

    inline const QList<QImage*>& getImages() const { return m_images; }
    inline const QImage& getThumbnail() const { return m_thumbnail; }

protected:
    /* Protected methods */

    //adds another component to this vehicle
    inline void addComponent(Component* c)
    {
        m_components << c;
    }

private:
    /* Private data members */

    QList<Component*> m_components;

    int m_id;
    int m_year;
    int m_mileage;
    int m_weight;
    int m_length;
    int m_width;
    int m_height;
    int m_wheelbase;

    QString m_date_received;
    QString m_type;
    QString m_maker;
    QString m_model;
    QString m_color;
    QString m_plate;

    QList<QImage*> m_images;
    QImage m_thumbnail;
};

class Car : public Vehicle
{
public:
    /* Public interface */

    //ctor
    Car();

    //copy/move
    Car(const Car&) = delete;
    Car(Car&&) = delete;
    Car& operator=(const Car&) = delete;
    Car& operator=(Car&&) = delete;

    //dtor
    virtual ~Car();

private:
    /* Private data members */

    Body* m_body;
    Brake* m_brake;
    Direction* m_direction;
    Engine* m_engine;
};

I also have Moto and Bike classes publicly inheriting from Vehicle, each of them having their own components. Then, each component derives from Component and has several parts (deriving from Part, i.e. a Body has Wings, Capote, etc). Both Component and Part inherit from AbstractComponent.

First off, is this bad design? How can it be improved?

Secondly, I have a question about creating the specific vehicle objects. Should Car's constructor require the same parameters as Vehicle plus others? How about its components? Should I pass to the constructor pointers to already created Components, or should the Components be created in Car's constructor?


texts: Angular 6+ Conditionally Chained HTTP Calls

texts:
I have a number of async calls that get chained conditionally based on the previous data dependency. I.e. perform call A -> if the result is defined/not an error execute a side effect, if not perform another call.

I originally started with nested subscribes but I was told that is not a good practice. Next I moved to rxjs operations (which I believe are function compositions in this context) and used tap, as we have side-effects. This still looks pretty ugly, wondering if there are any suggestions to improve on this (One thing that I am aware of is I can abstract the general pattern into a

if(undefined) callback else side-effect

function. Appreciate any other feedback

this.userService.expandUser().pipe(
         tap((user: User) => { //flatMap equivilant of Scala
              if(user == undefined){
                this.userService.setUndefined();
                this.bandService.expandBand().pipe(
                  tap((band: Band) => {
                     if(band == undefined){
                       this.bandService.setUndefined()
                       this.shadowService.checkShadowsStatus().pipe(
                           tap(result => {
                                if(!result){
                                  this.shadowService.createShadowUser().pipe(
                                      tap(result => {
                                        this.shadowService.shadowSet = true;
                                      })
                                    )
                                }else{
                                  this.shadowService.shadowSet = true;
                                }
                             })
                         )
                     }else{
                       this.bandService.setBand(band)
                     }
                  })
                )
              }else{
                this.userService.setUser(user)
              }
         })
      )


texts:
I was trying to find a way to redirect to different pages on authorization and authentication failure. I found this to be a possible solution.

However, I ended with a different solution by myself. It seems to work fine, however, I am not sure if it is the right thing to do.

I created a custom Authorize Attribute that redirects to an action if the request is Authenticated but not Authorized.

public class HandleAuthorizeAttribute : AuthorizeAttribute {
        public static string GlobalUnAuthorizationUrl { get; set; }

        private const string DefaultUnAuthorizationUrl = "~/Account/UnAuthorized";
        private static readonly char[] RolesSeparator = { ',' };

        public string UnAuthorizedUrl { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            if(httpContext.User.Identity.IsAuthenticated) {
                if(string.IsNullOrEmpty(Roles)) {
                    return true;
                } else {
                    var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);
                    var authorizedRoles = Roles.Split(RolesSeparator);

                    var common = rolesOfUser.Intersect(authenticatedRoles);

                    if(common.Count() == 0) {
                        httpContext.Response.Redirect(
                            string.Format("{0}?{1}={2}", ActiveUnAuthorizedUrl, "requestUrl", httpContext.Request.Url.AbsoluteUri));
                        return false;
                    }

                    return true;
                }
            } else {
                return false;
            }
        }

        private string ActiveUnAuthorizedUrl {
            get {
                if(!string.IsNullOrEmpty(UnAuthorizedUrl)) {
                    return UnAuthorizedUrl;
                }
                if(!string.IsNullOrEmpty(GlobalUnAuthorizationUrl)) {
                    return GlobalUnAuthorizationUrl;
                }
                return DefaultUnAuthorizationUrl;
            }
        }
    }

Is it alright to redirect to a URL in the middle of a non-action method? Does it have any potential drawbacks?


texts: Counting average protein length from a proteome fasta file

texts:
this code is counting the average protein length (number of amino acids) across the proteome of some microbes.

As it stands the code takes a very very long time to run, I think I'm being very inefficient somewhere but not 100% sure where.

The way I run the code is using a bash-loop (using find for each example of particular file type, like *.faa) like this:

for FAA in $(find . -name "*.faa")
do
    python proteinlengthgen.py $FAA
done

My code:

from Bio import SeqIO
import sys
from collections import Counter

def species_name_function(infile):
    for record in SeqIO.parse(infile, "fasta"):
        speciesname = record.description.split('[', 1)[1].split(']', 1)[0]
    return speciesname

if __name__ == '__main__':
    frequency = []
    infile = sys.argv[1]
    avgproteinlength = 0
    totalproteinlength = 0
    fastacounter = 0

    for fasta in SeqIO.parse(open(infile), "fasta"):
        dna = str(fasta.seq)
        freq = Counter(dna)
        fastacounter = fastacounter + 1
        frequency.append(freq)
        species_name = species_name_function(infile)

        genomesize = freq['G'] + freq['A'] + freq['L'] + freq['M'] + freq['F'] + freq['W'] + freq['K'] + freq['Q'] + freq['E'] + freq['S'] + freq['P'] + freq['V'] + freq['I'] + freq['C'] + freq['Y'] + freq['H'] + freq['R'] + freq['N'] + freq['D'] + freq['T']

        listofbases = ['G', 'A', 'L', 'M', 'F', 'W', 'K', 'Q', 'E', 'S', 'P', 'V', 'I', 'C', 'Y', 'H', 'R', 'N', 'D', 'T']

        totalproteinlength = genomesize + totalproteinlength

    avgproteinlength = totalproteinlength / fastacounter

    towrite = str(avgproteinlength) + '\t' + species_name + '\t' + '\n'

    with open("proteinlength.csv", "a") as myfile:
        myfile.write(towrite)

Example of a subset of input file (I cannot use a whole one as they are very big):

>WP_013179448.1 DNA-directed RNA polymerase [Methanococcus voltae]
MYKILTIEDTIRIPPKMFGNPLKDNVQKVLMEKYEGILDKDLGFILAIEDIDQISEGDIIYGDGAAYHDTTFNILTYEPE
VHEMIEGEIVDIVEFGAFIRLGPLDGLIHISQVMDDYVAFDPQREAIIGKETGKVLEKGDKVRARIVAVSLKEDRKRGSK
IALTMRQPALGKLEWLEDEKLETMENAEF
>WP_013179449.1 DNA-directed RNA polymerase subunit E'' [Methanococcus voltae]
MARKGLKACTKCNYITHDDFCPICQHETSENIRGLLIILDPVNSEVAKIAQKDIKGKYALSVK
>WP_013179451.1 30S ribosomal protein S24e [Methanococcus voltae]
MDIKVVSEKNNPLLGRKEVKFALKYEGATPAVKDVKMKLVAILNANKELLVIDELAQEFGKMEANGYAKIYESEEAMNSI
EKKSIIEKNKIVEEAEEAQE
>WP_013179452.1 30S ribosomal protein S27ae [Methanococcus voltae]
MAQKTKKSDYYKIDGDKVERLKKSCPKCGEGVFMAEHLNRFACGKCGYMEYKKNEKAEKEE
>WP_013179453.1 hypothetical protein [Methanococcus voltae]
MNELNELKNPDKIDGKNNNTKNNNNNNNKDSNTENSITEIIKADNETQDNLSDLCVLEDIKTLKSKYKVYKTSKYLTKKD
INNIIEKDYDEIIMPQSIYKLLNEKNKSSMEKLRLCGIIVKTTDNVGRPKKITKYDKDKIKELLVDGKSVRKTAEIMDMK
KTTVWENIKDCMNEIKIEKFRKMIYEYKELLIMQERYGSYVESLFLELDIYINNEDMENALEILNKIIIYVKSEDKKD
>WP_013179454.1 integrase [Methanococcus voltae]
MKNKRINNNQKSKWETMRTDVINTQRNQNINSKNKQYRVKKHYCKEWLTKEELKVFIETIEYSEHKLFFKMLYGMALRVS
ELLKIKVQDLQLKEGVCKLWDTKTDYFQVCLIPDWLINDIKEYIALKSLDSSQELFKFNNRKYVWELAKKYSKMAELDKD
ISTHTFRRSRALHLLNDGVPLEKVSKYLRHKSIGTTMSYIRITVVDLKQELDKIDDWYEL
>WP_013179455.1 hypothetical protein [Methanococcus voltae]
MNTQNAIKKTLKTSKVNKNISNVIIGYSAILLDTYSNNKNLLLVKYDKLFKGFLNSSSITEKQYNKLYDTVLNSLF
>WP_013179456.1 hypothetical protein [Methanococcus voltae]
MVVKLVKISNGGYVSSLELKRINDIILSQLTNEFTIKDIVNMYSNKYDDCNNNAIAQKTRRLLNNHIESGVFTVRNALKN
KKIYKFKDVFVPASAGDTNTSLLFYSTSMKNSNHIEKQKKNNNKYNTNVNKPTITPDQIRVMAGIVNNPQIKSLKKERFK
SILHLNCKHMLNEEDRTELLENFKEYIIKASSQNLVLERTRYHKNKPKYITFPYLTRFTNSKQLKRQLAQYNCIFEQKAI
KYNRGVHLTLTTDPKLFRNIYEANKHFSKAFNRFMSFLSKRNKDVNGKSRRPVYLAAYEYTKSGLCHAHILIFGKKYLLD
QRVITQEWSRCGQGQIAHIYSIRRDGINWIYGRARPEEIQTGEYKNANEYLKKYLVKSLYSELDGSMYWAMNKRFFTFSK
SLKPAMMKRPKPEKYYKFVGIWTDEEFTDEINQAFKTGIPYDEIKKIHWKNLNNGLSCG
>WP_013179457.1 hypothetical protein [Methanococcus voltae]
MVRGRYPVFSGFKKFNKINLGKEKRNEGVYKYYNQDKTLLYVGVSNEVKLRLLSAYYGRSDYAVLENKKKLRQNIAYYKV
KYCGLDQARKIEHRIKKQCKYNLN

Output of code:

302.7408088235294   Methanococcus voltae


texts:
This function receives an HTMLElement as an argument and returns true if the tag is on the screen and false otherwise.

function isTagVisible(tag) {
    var box;

    box = tag.getBoundingClientRect();

    if (box.left > 0) {
        if (box.left >= window.innerWidth) {
            return false;
        }
    }

    if (box.right <= 0) {
        return false;
    }

    if (box.top > 0) {
        if (box.top >= window.innerHeight) {
            return false;
        }
    }

    if (box.bottom <= 0) {
        return false;
    }

    return true;
}


texts:
Root to leaf path sum equal to a given number
Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found.

I have written 3 solutions: one recursive, one using 2 stacks (DFS), and last one using 2 queues (BFS). I am looking for improvements and suggestions.
    // Recursive version
    public static boolean hasPathSum1 (Node root, int sum) {
          if (root == null) {
              return false;
          }
          if(root.left == null && root.right == null && root.data == sum) {
                return true;
          }
          return hasPathSum1(root.left, sum - root.data) ||
                 hasPathSum1(root.right, sum - root.data);
    }
    //===========================================================================
        // Iterative version (DFS) - Using 2 Stacks
        public static boolean hasPathSum2 (Node root, int sum) {
            if (root == null) {
                return false;
            }
        Stack<Node> nodes = new Stack<Node>();
        Stack<Integer> values = new Stack<Integer>();

        nodes.push(root);
        values.push(root.data);

        while (!nodes.isEmpty()) {
            Node current = nodes.pop();
            int sumValue = values.pop();

            if (current.left == null && current.right == null && sumValue == sum) {
                    return true;
            }
            if (current.left != null) {
                nodes.push(current.left);
                values.push(current.left.data + sumValue);
            }
            if (current.right != null) {
                nodes.push(current.right);
                values.push(current.right.data + sumValue);
            }
        }
        return false;
    }
//========================================================================
    // Iterative version (BFS) - Using 2 queues
    public static boolean hasPathSum3 (Node root, int sum) {
        if(root == null) {
            return false;
        }
        Queue<Node> nodes = new LinkedList<Node>();
        Queue<Integer> values = new LinkedList<Integer>();

        nodes.add(root);
        values.add(root.data);

        while(!nodes.isEmpty()){
            Node current = nodes.remove();
            int sumValue = values.remove();

            if(current.left == null && current.right == null && sumValue == sum){
                return true;
            }
            if(current.left != null){
                nodes.add(current.left);
                values.add(current.left.data + sumValue);
            }
            if(current.right != null){
                nodes.add(current.right);
                values.add(current.right.data + sumValue);
            }
        }
        return false;
    }


texts:
I am a golang novice... I am trying to write an application that takes in many requests - up to a sustained 10000 HTTP posts/sec and post the payload to two back-ends in parallel (5 second timeout).  A canned message is returned to the client, it doesn't matter whether the backed end returns a response or errors out, the same response text is sent to the client.

I have a first crack at it below.  I'm not worried about error handling yet.  My thinking is that I can make each back-end call asynchronous using goroutines and let the go runtime deal with queuing/threads for the go routines.  I simply need to perform the post and log the result, there is no communication between goroutines. I have had others guide me to using channels, but given that I don't need to return any data back from the post I'm not sure I need them.

Here is my first very simple crack at it.  Please make any suggestions on the code and approach!

package main

import (
    "fmt"
    "github.com/go-chi/chi"
    "net/http"
    "io/ioutil"
    "bytes"
    "time"
)

func main() {
    r := chi.NewRouter()
    r.Post("/", func(w http.ResponseWriter, r *http.Request) {
        handlePost(w, r);
    })

    http.ListenAndServe(":3000", r)

}

func handlePost(w http.ResponseWriter, r *http.Request) {
    body, _ := ioutil.ReadAll(r.Body)
    fmt.Fprintf(w, "dummy response will go here");
    go callBackend("http://backend1", body)
    go callBackend("http://backend2", body)
}

func callBackend(url string, body []byte) {

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
    req.Header.Set("Content-Type", "application/xml")

    client := &http.Client{
        Timeout: time.Second * 5,
    }
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Sprintf("backend [%s] response status: %s", url, resp.Status)
    fmt.Println("backend response Headers:", resp.Header)
    responsebody, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("backend response Body:", string(responsebody))

}


texts:
I'm creating a system and I'm using EF with Linq. I create my Model (.edmx) and using it, I generated my database and my classes. Like the Usuario (user in Portuguese going to keep the names in Portuguese to avoid some misleading).

namespace SistemaBox.Model
{
    public partial class Usuario
    {
        public int Codigo { get; set; }
        public string Nome { get; set; }
        public string Sobrenome { get; set; }
        public string Senha { get; set; }
        public DateTime DataCriacao { get; set; }
        public DateTime DataUltimoLogin { get; set; }

        public virtual PermissaoGrupo CodigoPermissaoGrupo { get; set; }
    }
}

After this, I create my controller class:

namespace SistemaBox.Controller
{
    [Serializable]
    public class ZUsuario : Usuario
    {
        String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        /// <summary>
        /// Cadastro e edição
        /// </summary>
        public void Cadastro()
        {
            if (Codigo != null && Codigo > 0)
            {
                // Cadastro
                using (DataContext db = new DataContext(connString))
                {
                    Table<Usuario> Usuarios = db.GetTable<Usuario>();
                    var query =
                        from usr in Usuarios
                        where usr.Nome == "Test"
                        select usr;

                    foreach (var usr in query)
                        Console.WriteLine("id = {0}, City = {1}", usr.Codigo, usr.Nome);
                }
            }
            else
            {
                // Edição

            }
        }
    }
}

Please ignore the fact that the class name is record and I'm doing a select. It is just for tests.

My question is about the controller. Is the right way to declare the connection String as global:

String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

and use the using like I'm doing?


texts:
I am trying to improve the time running of this code. Some dummies variable is defined and it is just some part of a lot of lines of code, but I tried it with dummies variables. It takes too much in higher size of etas and Nx. I would like to know if there is a better way to calculate dfdeta.

matlab

format long;
%%constant
A=1.0;
B=1.0;
ngrain=70;%grains number

NxNy = 512*512; %domain
etas = rand(NxNy,70));
sum=zeros(NxNy,1);
eta = etas;

for jgrain=1:ngrain

 if(jgrain ~= igrain)
      sum = sum +etas( :,jgrain).^2;
 end%if

end%for

dfdeta = A*(2.0*B* eta .*sum +eta.^3 - eta);


texts:
There are my shapes (for example):

public abstract class Shape
{
  protected int _id;
  protected string _description;

  public abstract string ToXml();
}

public sealed class Triangle : Shape
{
  public int TriangleId { get { return _id; } set { _id = value; } }
  public string TriangleDescription { get { return _description; } set { _description = value; } }
  public ConsoleColor color { get; set; }

  public override string ToXml()
  {
    // First implementation
    throw new NotImplementedException();
  }
}

public sealed class Circle : Shape
{
  public int CircleId { get { return _id; } set { _id = value; } }
  public string CircleDescription { get { return _description; } set { _description = value; } }
  public int Radius { get; set; }

  public override string ToXml()
  {
    // Second implementation
    throw new NotImplementedException();
  }
}

public sealed class Square : Shape
{
  public int SquareId { get { return _id; } set { _id = value; } }
  public string SquareDescription { get { return _description; } set { _description = value; } }
  public int Edge { get; set; }

  public override string ToXml()
  {
    // Third implementation
    throw new NotImplementedException();
  }
}

Client have to choose one kind of shape to get xml-view:

public enum ShapeType
{
  Triangle,
  Circle,
  Square
}

public class Module
{
  public string GetXml( ShapeType type, int id )
  {
    switch( type )
    {
      case ShapeType.Circle:
        return DB.GetEntity( id ).ToTypedEntity<Circle>().ToXml();
      case ShapeType.Square:
        return DB.GetEntity( id ).ToTypedEntity<Square>().ToXml();
      case ShapeType.Triangle:
        return DB.GetEntity( id ).ToTypedEntity<Triangle>().ToXml();
    }
  }
}

As you can see, there are too much the same code parts that are matching enumerations with shape's types. It is not good.

How can I avoid it?


texts: UIView position updates based on device motion via RxSwift

texts:
I've created a simple function to work as a level, where the dot on screen is centered when the device is completely flat. It changes position based on device orientation. I use RxSwift to update the position of the dot. I'm relatively new to RxSwift, so I'm worried that I'm not using it correctly or to its full value.
I also don't understand capturing self all that well, so please feel free to analyze that as well.
Any input is appreciated!
class ViewController: UIViewController {

    @IBOutlet var levelDot: UIView!
    var positiveMax: (x: CGFloat, y: CGFloat)!

    override func viewDidLoad() {
        levelDot.center = self.view.center
        super.viewDidLoad()
        positiveMax = (view.frame.maxX, view.frame.maxY)
        initGryo()
    }

    fileprivate func initGryo() {
        let pitch = PublishSubject<Double>()
        let roll = PublishSubject<Double>()
        let motion = CMMotionManager()
        guard motion.isDeviceMotionAvailable else { return }
        motion.deviceMotionUpdateInterval = 1/60
        motion.startDeviceMotionUpdates()
        let gyroTimer = Timer(fire: Date(), interval: 1/60, repeats: true, block: { timer in
            if let attitude = motion.deviceMotion?.attitude {
                let yModifier: CGFloat = 1.3 // modifier is to make small changes seem bigger on the screen

                _ = pitch.map( { (self.positiveMax!.y + CGFloat($0)*self.positiveMax!.y * yModifier) })
                    .map( {$0 / 2} )
                    .subscribe(onNext: { centerY in

//prevent dot from moving off screen
                        guard centerY < self.positiveMax.y else {
                            self.levelDot.center.y = self.positiveMax.y
                            return
                        }
                        guard centerY > 0 else {
                            self.levelDot.center.y = 0
                            return
                        }
//dot position -- does this capture self? would making levelDot a weak var prevent this?
                        self.levelDot.center.y = centerY

                    })
                pitch.onNext(attitude.pitch)

                let xModifier: CGFloat = 1.15 // modifier is to make small changes seem bigger on the screen
                _ = roll.map( { (self.positiveMax!.x + CGFloat($0)*self.positiveMax!.x*xModifier) })
                    .map({ $0 / 2 })
                    .subscribe(onNext: { centerX in
//prevent dot from moving off screen
                        guard centerX < self.positiveMax.x else {
                            self.levelDot.center.x = self.positiveMax.x
                            return
                        }
                        guard centerX > 0 else {
                            self.levelDot.center.x = 0
                            return
                        }
//dot position
                        self.levelDot.center.x = centerX
                    })
                roll.onNext(attitude.roll)
            }
        })
        RunLoop.current.add(gyroTimer, forMode: .default)

    }

}


texts: Mapping/parsing database table data to output data

texts:
I have currently implemented this simple example of a database to output for a REST API to show the way information is being parsed, mapped and serialized starting from database data converting it to JSON. This solution currently works fine, but the problem comes from the fact that it makes use of PHP tricks (like calling a function from a string) which I really do not approve of. Do you think there is a better way/pattern to implement/split this solution?

class DataMapper {
    /**
     * @var array
     */
    private $rawData;

    /**
     * @var array
     */
    private $parsedData;

    /**
     * @var array
     */
    private $mapping = [
        'dbField1' => 'outputField1',
        'dbField2' => ['outputField2' => ['double']],
        'dbField3' => ['outputField3' => ['double', 'dollars']]
    ];

    public function __construct(array $data) {
        $this->rawData = $data;
        $this->mapData();
    }

    /**
     * @param $value
     * @return mixed
     */
    private function double($value) {
        return $value * 2;
    }

    /**
     * @param $value
     * @return string
     */
    private function dollars($value) {
        return $value . "$";
    }

    // Yes, I know the methods shouldn't be here but it rather be decoupled in another class and
    // injected with a DI but I wrote it like this just as an example
    private function mapData() {
        foreach($this->mapping as $dbFieldName => $content) {

            if(isset($this->rawData[$dbFieldName])) {

                if(is_string($content)) {
                    $this->parsedData[$content] = $this->rawData[$dbFieldName];
                } else
                if (is_array($content)) {
                    $frontFieldName = key($content);
                    $functionsArray = reset($content);
                    $value = $this->rawData[$dbFieldName];

                    foreach($functionsArray as $functionName) {
                        $value = $this->{$functionName}($value);
                    }
                    $this->parsedData[$frontFieldName] = $value;
                }
            }
        }
    }

    /**
     * Simple getter
     * @return array
     */
    public function getParsedData() {
        return $this->parsedData;
    }
}

// Usually the data comes from the DB so it would be in some kind of Row Set structure
$data = ['dbField1' => 1, 'dbField2' => 1, 'dbField3' => 1];
// The data is handed to the Holder which parses it
$dm = new DataMapper($data);
// The data is parsed so it can be
echo json_encode($dm->getParsedData());

You can experiment with it here.

I would highly appreciate it if you could give me pointers to how this could be made better programming to interfaces instead of simple strings; using composition, dependency injections, and maybe separation of the mapper functions in some abstract factories.