texts:
I am quite new to PHP, and with the help of a few tutorials have made this login system.

However I know its not as efficient and compact as it could be, also I am looking for ways to improve the security of this system. As I noticed when testing that If I simply changed the url from the login page, I could bypass the whole login process without having to login. I'm not really sure how I would go about fixing this, I tried creating session variables at the bottom of the script but not really sure if this is the way to go about it.

I would be very grateful for any feedback and if someone could help me improve this code, to make it more secure and maybe more efficient?

<?php

session_start();

if (isset($_POST['submit'])) {

    require_once 'config.php';

    $username = mysqli_real_escape_string($connect, $_POST['username']);
    $password = mysqli_real_escape_string($connect, $_POST['password']);

    //Error handlers
    //Check if inputs are empty
    if (empty($username) || empty($password)) {
        header("Location: ../index.php?login=empty");
        exit();
    } else {
        $sql = "SELECT * FROM users WHERE username='$username'";
        $search = mysqli_query($connect, $sql);
        $validate = mysqli_num_rows($search);
        if ($validate < 1) {
            header("Location: ../index.php?login=error");
            exit();
        } else {
            if ($row = mysqli_fetch_assoc($search)) {
                //De-hashing the password
                $hashcheck = password_verify($password, $row['password']);
                if ($hashcheck == false) {
                    header("Location: ../index.php?login=error");
                    exit();
                } elseif ($hashcheck == true) {
                    //Log in the user here
                    $_SESSION['u_id'] = $row['userid'];
                    $_SESSION['u_first'] = $row['firstname'];
                    $_SESSION['u_last'] = $row['lastname'];
                    $_SESSION['u_email'] = $row['email'];
                    $_SESSION['u_uid'] = $row['username'];
                    header("Location: ../home.php");
                    exit();
                }
            }
        }
    }
} else {
    header("Location: ../index.php?login=error");
    exit();
}
?>


texts: Table join in DAO and delegating ResultSet reading

texts:
I'm wondering if (and how) this idea could come to bite me in the future.

I was thinking that I should take away the responsability from any given DAO to know how to load a different object from a joined resultset, besides from not needing to know the names used in the database itself.

(Here is a very simplified - working - )

Example

Let's say I have Cards and Clients. Not really important but, each client will only be able to use one card at a time.

The join example is in CardDAO -> getCardList() method.

Tables

Card Table Data

+---------+----------------+
| card_id | card_client_id |
+---------+----------------+
|       1 | 1              | // Card 1 used by client 1
|       2 | NULL           | // Card 2 available
+---------+----------------+

Client Table Data

+-----------+-------------+
| client_id | client_name |
+-----------+-------------+
|         1 | Client X    |
|         2 | Client Y   |
+-----------+-------------+

Codes

Simplified and reduced (Exceptions, Connections, closes(), etc). Also, Card and Client classes are just POJOs, like so:

public class Client {
    private int id;
    private String name;
    // Getters & setters
}

public class Card {
    private int id;
    private Client client;
    // Getters & setters
}

ClientDAO

public class ClientDAO{
    public static final String table = "tb_client";
    // Column names as defined in the table
    public static final String id = "client_id";
    public static final String name = "client_name";

    // Other methods

    public static Client loadClient(ResultSet rs){
        Client client = new Client();
        client.setId(rs.getInt(ClientDAO.id));
        client.setName(rs.getString(ClientDAO.name));
        return client;
    }
}

CardDAO

public class CardDAO{
    public static final String table = "tb_card";
    // Column names as defined in the table
    public static final String id = "card_id";
    public static final String client = "card_client_id";

    // Other methods

    public List<Card> getCardList(){
        List<Card> cards = new ArrayList<Card>();
        // Sql could be just concat too
        String sql = String.format("SELECT ca.*, cl.* FROM %s AS ca INNER JOIN %s AS cl ON ca.%s = cl.%s WHERE ca.%s is not null",
                CardDAO.table,
                ClientDAO.table,
                CardDAO.id,
                ClientDAO.id,
                CardDAO.client);

        PreparedStatement pstn = this.con.prepareStatement(sql);
        ResultSet rs = pstn.executeQuery();
        while (rs.next()) {
            cards.add(CardDAO.loadCard(rs));
        }
        return cards;
    }

    public static Card loadCard(ResultSet rs){
        Card card = new Card();
        card.setId(rs.getInt(CardDAO.id)); // Don't know the column name, it doesn't matter here
        // CardDAO doesn't need to know how to load Client, just 'SELECT' everything and delegate a loader
        card.setClient( ClientDAO.loadClient(rs) );
        return card;
    }
}

On a side note, this would be the generated query:

SELECT ca.*, cl.* FROM tb_card AS ca INNER JOIN tb_client AS cl ON ca.card_id = cl.client_id WHERE ca.card_client_id is not null

Some things I already thought:

Increased complexity when writing queries;
Need to always load all the columns from a given table to make it possible for the loadXClass method to be called (can't select specific fields, only everything);
What if there are more levels to it? Example: the client has an address that is linked to an Address table, so I'd have to include it in the query and join every time so the code doesn't fail, even when not using it.

What are your thoughts?


texts: Finding the Bayesian estimates for the top 100 products on NutraPlanet

texts:
This code fetches reviews for the top 100 products on NutraPlanet, finds the Bayesian estimate for each average review, then prints out all reviews sorted by that Bayesian estimate.

How can I improve this code (correctness, elegance, best practices, etc)?

<?php

// echo "Remove exit from script to run."; exit;

define("MINIMUM_NUMBER_OF_VOTES_TO_SAVE_PRODUCT", 2);

$locations = array("http://www.nutraplanet.com/top_100");

$reviewUrlFragments = array_unique(getReviewUrlFragments($locations));

$products = getProducts(
        $reviewUrlFragments,
        MINIMUM_NUMBER_OF_VOTES_TO_SAVE_PRODUCT);

calculateBayesianEstimate($products);

usort($products, function ($a, $b) {
    if ($a["bayesian_estimate"] == $b["bayesian_estimate"]) {
        return 0;
    }
    return ($a["bayesian_estimate"] < $b["bayesian_estimate"]) ? 1 : -1;
});

printReviews($products);

function getReviewUrlFragments($locations) {
    $reviewUrlFragments = array();

    foreach($locations as $location) {
        $page = @file_get_contents($location);

        preg_match_all("%/product/(.*?)\.html%is", $page, $matches);

        $reviewUrlFragments = array_merge($reviewUrlFragments, $matches[1]);
    }

    return $reviewUrlFragments;
}

function getProducts($productReviewUrlFragments, $minimumNumberOfVotesToSaveProduct) {
    $products = array();

    foreach($productReviewUrlFragments as $productReviewUrlFragment) {
        $reviewUrl = "http://www.nutraplanet.com/manufacturer/" . $productReviewUrlFragment . "/reviews";

        $page = @file_get_contents($reviewUrl);

        preg_match_all("%&nbsp;(.*?)	%is", $page, $matches);

        $product = array();
        $product['name'] = "http://www.nutraplanet.com/product/".$productReviewUrlFragment.".html";

        $votes = getVotes($matches[1]);

        $product["vote_distribution"] = $votes["votes"];
        $product["review_average"] = $votes["average"];
        $product["num_votes"] = $votes["num_votes"];

        // Only add if there is a vote for the product
        if ($product["num_votes"] >= $minimumNumberOfVotesToSaveProduct) {
            $products[] = $product;
        }
    }

    return $products;
}

function getVotes($match) {
    $votes = array();
    $sum_votes = 0;
    $total_votes = 0;
    $vote_star = 1;

    // In ascending order, 1-star to 5
    foreach($match as $vote_count) {
        $votes[] = $vote_count;
        $total_votes += $vote_count;
        $sum_votes += ($vote_count * $vote_star++);
    }

    $product["votes"] = $votes;
    $product["average"] = ($total_votes < 1) ? 0 : ($sum_votes / $total_votes);
    $product["num_votes"] = $total_votes;

    return $product;
}

function calculateBayesianEstimate(&$products) {
    // See bottom of page: http://www.imdb.com/chart/top
    $m = getMinNumberOfVotes($products);
    $C = getAverageReviewAverage($products);

    for ($i = 0, $len = count($products); $i < $len; $i++) {
        $R = $products[$i]["review_average"];
        $v = $products[$i]["num_votes"];
        $products[$i]["bayesian_estimate"] = (($v / ($v+$m)) * $R) + (($m / ($v+$m)) * $C);
    }
}

function getAverageReviewAverage($products) {
    $total = 0;

    foreach($products as $product) {
        $total += $product["review_average"];
    }

    return $total / count($products);
}

function getMinNumberOfVotes($products) {
    foreach($products as $product) {
        if (!isset($minVote) || ($product["num_votes"] < $minVote)) {
            $minVote = $product["num_votes"];
        }
    }

    if (!isset($minVote)) {
        $minVote = 0;
    }

    return $minVote;
}

function printReviews($products) {
    echo "
";
    foreach($products as $product) {
        $product["vote_distribution"] = implode("	", $product["vote_distribution"]);
        $product = implode("	", $product);
        echo "
" . $product . "
";
    }
    echo "
";
}
?>


texts:
My app has a feature that when you click the new data button, HTML is loaded to the page via ajax.  Because I am using AJAX, all events I want to add has to be bound using the on() method.

There are 4 on('click') functions that are bound to 4 different HTML elements:

// save data
$('#container').on( {
    click: function() {
       // save code here
    }
}, "a.save_data" );

// cancel data
$('#container').on( {
    click: function() {
       // cancel code here
    }
}, "a.cancel_data" );

// edit data
$('#container').on( {
    click: function() {
        // edit code here
    }
}, "a.edit_data" );

// delete data
$('#container').on( {
    click: function() {
        // delete code here
    }
}, "a.delete_data" );

Each of these functions share multiple jQuery wrappers to select certain elements within the HTML:

$(this).closest('div.content_wrap');
$(this).closest('div.Content');

Please note: The reason I am using selectors such as $(this).closest() is because the user has the ability to add the same HTML multiple times on to the page.

First, is there a better way to organize all of the on() functions?  Maybe combine them into one object OR create a function?

Second, because all 4 functions use the same jQuery wrappers, is there any way to declare them in a variable globally somewhere, so i don't keep retyping them.  I wasn't able to figure out how declare variables with $(this) and apply it to more than one function.

To me, how I am doing it doesn't seem very DRY and I was wondering if someone can help me better organize this.


texts: Preparing search criteria and results to be e-mailed

texts:
I'm getting data to fill out an e-mail template, and I'm wondering if this method is too long. How could I refactor it?

sub getEmailData
{
    my $self = shift;

    my $defs = QuickContentFunction::Simple::QuerySearchFieldDefinitions->new();

    my $phParams = decode_json($self->parameters);
    my @aFields = split(/~/, $phParams->{sFields});
    my @aCategories = split(/~/, $phParams->{sCategories});
    my @aValues = split(/~/, $phParams->{sValues});
    my @aConditions = split(/~/, $phParams->{sConditions});

    my $sSummary = $phParams->{sSummary};
    $sSummary =~ s/\'//g;
    my @aSummary = split(/\d/, $sSummary);

    my $phData = { name => $self->name };

    my $mapping = $self->getOperatorMapping();
    for (my $i = 0; $i < scalar(@aFields); $i++) {
        my $phFieldInfo = $defs->getFieldHash( $aCategories[$i], $aFields[$i]);

        my $value = $aValues[$i];
        if ($phFieldInfo->{value_displays}) {
            $value = @{$phFieldInfo->{value_displays}}[$value];

        } elsif ($phFieldInfo->{value_keys}) {
            $value = @{$phFieldInfo->{value_keys}}[$value];
        }

        push( @{$phData->{conditions}}, {
            field    => $phFieldInfo->{field_display},
            operator => $mapping->{$phFieldInfo->{field_type}}->{$aConditions[$i]},
            value    => $value,
            postfix  => $aSummary[$i+1] || undef
        } );
    }

    $phData->{mode} = lc($phParams->{sMode});
    if ($self->hasResults()) {
        $phData->{deals} = \@{decode_json($self->result)};
    }

    return $phData;
}


texts:
I was given a question during interview, and I decided to code it up and learn the difference way to implement this problem. Find the Maximum Sum of a Contiguous Subsequence in a List. I was wondering if you can code review the different ways of solving this problem.

Given a list consisting of both positive and negative integers, find the maximum sum among all the contiguous subsequences of the input list.
Write a function that takes in a list of integers and returns the maximum sum.

#  Example:   input = [6, -1, 3, 5, -10]
#             output = 13 (6 + -1 + 3 + 5 = 13)

another example.

#maxSubArraySum([-1,-2,3,4,5]) ==> 12

#maxSubArraySum([1,2,3,-2,5]) ==> 9

my first solution

def maxSubArraySum(arr):

    max_so_far =arr[0]
    curr_max = arr[0]

    for i in range(1,len(arr)):
        curr_max = max(arr[i], curr_max + arr[i])
        max_so_far = max(max_so_far,curr_max)

    return max_so_far

# Driver function to check the above function
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print"Maximum contiguous sum is" , maxSubArraySum(a)

my second solution
Dynamic programming solution

def maxSubArraySum(nums):
  if not nums: return 0
  n = len(nums)
  s = [0] * n
  res, s, s_pre = nums[0], nums[0], nums[0]
  for i in xrange(1, n):
      s = max(nums[i], s_pre + nums[i])
      s_pre = s
      res = max(res, s)
  return res

it passes all the test

# input: count {List} - keeps track out how many tests pass and how many total
#        in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
#        indicating if test passed
# output: {None}
def expect(count, name, test):
    if (count is None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    error_msg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception as err:
        error_msg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if error_msg is not None:
        print('       ' + error_msg + '\n')

print('max_consecutive_sum Tests')
test_count = [0, 0]

def test():
    example = max_consecutive_sum([6, -1, 3, 5, -10])
    return example == 13

expect(test_count, 'should work on example input', test)

def test():
    example = max_consecutive_sum([5])
    return example == 5

expect(test_count, 'should work on single-element input', test)

def test():
    example = max_consecutive_sum([])
    return example == 0

expect(test_count, 'should return 0 for empty input', test)

def test():
    example = max_consecutive_sum([-1, 1, -3, 4, -1, 2, 1, -5, 4])
    return example == 6

expect(test_count, 'should work on longer input', test)

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')

max_consecutive_sum Tests
  1)    true : should work on example input
  2)    true : should work on single-element input
  3)    true : should return 0 for empty input
  4)    true : should work on longer input
PASSED: 4 / 4


texts:
This program creates a text index of 3 different files in Python. While this works correctly, I am still a beginner in Python. I used a list of class objects. Can this code be further optimised?

class ListNode :
    def __init__(self,w,docslist) :

        self.word = w
        self.docslist = []
        self.docslist.append(docslist)

TextIndex = []

def Search(word,TextIndex) :

    for i in TextIndex :
        if i.word == word :
            return TextIndex.index(i)
        else :
            continue

    return -1

def Create(docs) :
    for d in docs :
        words = []
        for line in d :
            line = line.split()
            for word in line :
                if word not in words :
                    words.append(word)

            for word in words :

                node = ListNode(word,d.name)

                j = Search(word,TextIndex)

                if j == -1 :
                    TextIndex.append(node)

                else :
                    TextIndex[j].docslist.append(d.name)

def Display() :
    TextIndex.sort(key=lambda x: x.word, reverse=False)
    for i in TextIndex :
        print (i.word,i.docslist)

def main() :

    try :
        with open(r"C:\Users\Anonymous\Documents\words1.txt") as a, open(r"C:\Users\Anonymous\Documents\words2.txt") as b,       open(r"C:\Users\Anonymous\Documents\words3.txt") as c :
        docs = [a,b,c]
        Create(docs)

        Display()

    except IOError as e :
        print ('Operation Failed: %e' %e.strerror)

if __name__ == '__main__':
    main()


texts: A bitwise common prefix algorithm in Python

texts:
Is my algorithm slow because it has problems? Or, is any bitwise common prefix solution not going to give me the performance I'm looking for?

After profiling my algorithm, I found that over 60% of the time was spent on one line len(os.path.commonprefix((item1, item2))). I'm only looking for the length of the prefix

To solve this I tried to write a bitwise prefix solution

def bit_prefix(a, b):
    min_len = min(len(a), len(b))
    if min_len > 0:
        x = str(bin(
            int(a[::-1].encode('hex'), 16) ^ int(b[::-1].encode('hex'), 16)))
        y = x.strip('0')
        if len(y) is 1:
            return min_len
        else:
            return (len(x) - len(y)) / 8
    else:
        return 0

I've only gotten a marginal improvement in speed with long prefixes

a = 'a' * 1000000 + 'z'

b = 'a' * 900000 + 'z'

timeit.timeit(lambda: bit_prefix(a, b), number=100)
Out[34]: 6.340372534867129

timeit.timeit(lambda: len(os.path.commonprefix((a, b))), number=100)
Out[35]: 7.5483549056534684

print bit_prefix(a, b), len(os.path.commonprefix((a, b)))
900000 900000

And my algorithm performs more poorly with short prefixes

a = 'aaz'

b = 'az'

timeit.timeit(lambda: bit_prefix(a, b), number=1000000)
Out[42]: 3.968956086175467

timeit.timeit(lambda: len(os.path.commonprefix((a, b))), number=1000000)
Out[43]: 1.1592788235707303

print bit_prefix(a, b), len(os.path.commonprefix((a, b)))
1 1

If my algorithm isn't broken and a bitwise solution won't give me the performance boost I'm looking for, can you refer me to a common prefix solution that would outperform os.path.commonprefix?

Here's the bit_pefix profile

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    29                                           @profile
    30                                           def bit_prefix(a, b):
    31     36140        81099      2.2      4.2      min_len = min(len(a), len(b))
    32     36140        49386      1.4      2.5      if min_len > 0:
    33     36140        49739      1.4      2.6          x = str(
    34     36140        47846      1.3      2.5              bin(
    35     36140        47232      1.3      2.4              int(
    36     36140        89499      2.5      4.6              a[::-1]
    37     36140       242994      6.7     12.5              .encode('hex'),
    38     36140       164442      4.6      8.4              16)
    39                                                       ^
    40     36140        49601      1.4      2.5              int(
    41     36140        88745      2.5      4.6              b[::-1]
    42     36140       216488      6.0     11.1              .encode('hex'),
    43     36140       504425     14.0     25.9              16)))
    44     36140       187571      5.2      9.6          y = x.strip('0')
    45     36140        61027      1.7      3.1          if len(y) is 1:
    46                                                       return min_len
    47                                                   else:
    48     36140        67507      1.9      3.5              return (len(x) - len(y)) / 8
    49                                               else:
    50                                                   return 0

Update

I've created another algorithm that seems to be faster than others. Here's the Code Review for that.


texts: Simple function returning 1 if the Mean = Mode, or 0 if not

texts:
I'm trying to get better at javascript and have built a simple function that returns 1 if the mode is equal to the mean, and 0 if not. You can enter an array of numbers into the function:

// tests
meanMode([1,2,3]); - returns 0
meanMode([4,4,4,6,2]); - returns 1
meanMode([4,4,4,6,6,6,2]); - returns 0

To clarify, the mean is the middle number in the array, and mode most occurring number.

When I was writing this, I wondered whether I create too many variables and overcomplicate things. The problems I thought I might be making are:

There are too many variables
It's confusing and over complex
It can be hard to retrace my logic and know what the code does and why it's there

I have a few questions that I hope better coders than myself can answer, as I'm relatively new to javascript:

Was using a counts variable necessary?
Are all variable keywords (const & let) optimal?
Is it wise to include comments to describe what the code does?
Was declaring the mode variable before assigning its value the best way? Its value depends on a condition

Before writing this I wrote a brief logic plan as follows:

Mode:

var uniqueVals with unique vals (set)
for each unique value (uniqueVals.map), count no of occurrences in arr (filter.length) & store as an array
if all values are identical, return 0, otherwise get the most frequent & store in variable (there may be cases with no mode)

Mean:

sum all numbers
divide by no of numbers

And:

if unique values length is same as arr length, return 0
if mean = mode, return 1

When people write programming, is it usually best to have a detailed plan to follow? I wonder whether there are any best practices that I could follow to improve my coding ability.

function meanMode(arr) {
    let uniqueVals = Array.from(new Set(arr));
    let counts = uniqueVals.map(function (c, i, a) {
        return arr.filter(function (c2) {
            return c2 == c
        }).length
    }); // [3,1,1]

    if (arr.every(sameValues)) {
        return 0;
    } else {
        var mode;

        // if highest number in counts appears just once, then there is a mode
        if ((counts.filter(function (x) { return x == (Math.max(...counts)) }).length) == 1) {
            mode = uniqueVals[counts.indexOf(Math.max(...counts))]; // scope issue?
        } else {
            return 0;
        }

        const mean = (arr.reduce(function (a, c) { return a + c })) / (arr.length);

        if (mode == mean) {
            return 1;
        } else {
            return 0;
        }
    }

    function sameValues(c, i, a) {
        return c == a[0];
    }
}


texts: Token Bucket context manager for rate limiting async calls

texts:
I've written a class that implements something akin to the token bucket algorithm so that I may rate limit aysnc HTTP requests made from my application.

The code works but I'm still not sure if it feels 'right', maybe just because I am new to async programming in Python.

Specific concerns:

It feels weird/bad how the state (self.last, self.tokens) is managed (or not managed) meaning checks in the _refill method.
Maybe I shouldn't be using a context manager (__aenter__ and __aexit__) for this.
I'm not sure if I should be doing any cleaning-up in __aexit__
Implementation of the algorithm may not be 100% faithful as I am waiting until the bucket is empty before refilling as a batch . I think this may be OK because only one token can be consumed per request.

"""
Typical usage example:
    async def rateLimitedTask(bucket):
        await bucket.removeToken() #wait for token
        #do the task which has now been rate limited
        ...

    async with TokenBucket(2, 1/5) as bucket:
        #make arbitrary async calls to rateLimitedTask()
        ...
"""

import asyncio
import time
from collections import deque

class TokenBucket():
    """Context manager which provides a token bucket.

    Attributes:
        tokens (collections.deque): The tokens (which manifest as timestamps)
                                    in reverse chronological order.
        last (float):               The most recent token consumed.
        rate (float):               See __init__ arg `tokensPerS`.
        capacity (int):             See __init__ arg `capacity`.
        sleepDuration (float):      See __init__ arg `refillSleepS`.

    """

    def __init__(self, capacity=1, tokensPerS=1.0, refillSleepS=0.1):
        """Initialises the TokenBucket context manager.

        Args:
            capacity (int, optional):       The maxiumum tokens the bucket can
                                            hold. Larger is burstier.
                                            Defaults to 1.
            tokensPerS (float, optional):   The average replenishment rate in
                                            tokens per second.
                                            Defaults to 1.
            refillSleepS (float, optional): If not enough time has passed
                                            to refill; how many seconds to
                                            sleep before trying again.
                                            Defaults to 0.1.
        """
        self.capacity = capacity
        self.rate = tokensPerS
        self.last = None
        self.tokens = deque([])
        self.sleepDuration = refillSleepS

    def hasTokens(self):
        return len(self.tokens) > 0

    def isEmpty(self):
        return len(self.tokens) < 1

    async def _refill(self):
        """Refill the empty bucket back up to capacity.

        Is called only when the bucket is empty.
        The tokens themselves are timestamps of when the token was created.
        Uses monotonic time to safeguard against system clock changes.
        """
        if self.last: #prevents unnecessary run on virgin execution
            while self.capacity / (time.monotonic() - self.last) > self.rate:
                await asyncio.sleep(self.sleepDuration)
                if self.hasTokens():
                    return #another call filled the bucket already

        for _ in range(self.capacity):
            self.tokens.appendleft(time.monotonic())

    async def removeToken(self):
        """Removes a token from the bucket and returns void.

        If the bucket is empty it will await its refill before returning.
        """
        if self.isEmpty():
            await self._refill()

        self.last = self.tokens.pop()

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc, tb):
        pass

Any help would be much appreciated.


texts:
I'm trying to implement Adagrad in Python. For learning purposes, I am using matrix factorisation as an example. I'd be using Autograd for computing the gradients.

My main question is if the implementation is fine.

Problem description

Given a matrix A (M x N) having some missing entries, decompose into W and H having sizes (M x k) and (k X N) respectively. Goal would to learn W and H using Adagrad. I'd be following this guide for the Autograd implementation.

NB: I very well know that ALS based implementation are well-suited. I'm using Adagrad only for learning purposes

Customary imports

import autograd.numpy as np
import pandas as pd

Creating the matrix to be decomposed

A = np.array([[3, 4, 5, 2],
                   [4, 4, 3, 3],
                   [5, 5, 4, 3]], dtype=np.float32).T

Masking one entry

A[0, 0] = np.NAN

Defining the cost function

def cost(W, H):
    pred = np.dot(W, H)
    mask = ~np.isnan(A)
    return np.sqrt(((pred - A)[mask].flatten() ** 2).mean(axis=None))

Decomposition params

rank = 2
learning_rate=0.01
n_steps = 10000

Gradient of cost wrt params W and H

from autograd import grad, multigrad
grad_cost= multigrad(cost, argnums=[0,1])

Main Adagrad routine (this needs to be checked)

shape = A.shape

# Initialising W and H
H =  np.abs(np.random.randn(rank, shape[1]))
W =  np.abs(np.random.randn(shape[0], rank))

# gt_w and gt_h contain accumulation of sum of gradients
gt_w = np.zeros_like(W)
gt_h = np.zeros_like(H)

# stability factor
eps = 1e-8
print "Iteration, Cost"
for i in range(n_steps):

    if i%1000==0:
        print "*"*20
        print i,",", cost(W, H)

    # computing grad. wrt W and H
    del_W, del_H = grad_cost(W, H)

    # Adding square of gradient
    gt_w+= np.square(del_W)
    gt_h+= np.square(del_H)

    # modified learning rate
    mod_learning_rate_W = np.divide(learning_rate, np.sqrt(gt_w+eps))
    mod_learning_rate_H = np.divide(learning_rate, np.sqrt(gt_h+eps))
    W =  W-del_W*mod_learning_rate_W
    H =  H-del_H*mod_learning_rate_H

While the problem converges and I get a reasonable solution, I was wondering if the implementation is correct. Specifically, if the understanding of sum of gradients and then computing the adaptive learning rate is correct or not?


texts: Combinatorics challenge solved it Python

texts:
The easiest way to explain this problem is to show these two test cases:
assert solution('ABC') == ['A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC']
assert solution('ABCD') ==  ['A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD']

my solution is below:
def subsolution(lst, length):
    return [lst + [x] for x in·
            range(lst[-1]+1, length)]

def solution(symbols):
    length = len(symbols)
    result = [[[x] for x in range(length)]]
    while True:
        subres = []
        for x in result[-1]:
            subres.extend(subsolution(x, length))
        if not subres:
            break
        result.append(subres)
    result = [ item for sublist in result
        for item in sublist
    ]
    result = [
        ''.join(symbols[s] for s in el)
        for el in result
    ]
    return result


texts:
I've been thinking about making Javascript Prototypes that represent HTML elements.
For example a form prototype with build in ajax requests and form element prototypes. Or a list with list item prototypes.

I think that the biggest benefit of this approach is that it reduces repetitive code.

Here is an example of what I have in mind.

var LightParticle = function() {
    this.setWidth(10);
    this.setHeight(10);
    this.setTop(0);
    this.setLeft(0);
    this.setPosition("absolute");
    this.setBackground("white");
    this.setClassName("LightParticle");
};

LightParticle.prototype = {
    setWidth : function(width) {
        this.width = width;
    },
    getWidth : function() {
        return this.width;
    },
    setHeight : function(height) {
        this.height = height;
    },
    getHeight : function() {
        return this.height;
    },
    setTop : function(top) {
        this.top = top;
    },
    getTop : function() {
        return this.top;
    },
    setLeft : function(left) {
        this.left = left;
    },
    getLeft : function() {
        return this.left;
    },
    setBackground : function(background) {
        this.background = background;
    },
    getBackground : function() {
        return this.background;
    },
    setClassName : function(className) {
        this.className = className;
    },
    getClassName : function() {
        return this.className;
    },
    setElement : function(element) {
        this.element = element;
    },
    getElement : function(element) {
        return this.element;
    },
    setPosition : function(position) {
        this.position = position;
    },
    getPosition : function(position) {
        return this.position;
    },
    setSize : function(size) {
        this.setWidth(size);
        this.setHeight(size);
    },
    getStyle : function() {
        return {
            position: this.getPosition(),
            width : this.getWidth(),
            height : this.getHeight(),
            top : this.getTop(),
            left: this.getLeft(),
            background: this.getBackground()
        }
    },
    getView : function() {
        var element = $("

");
        element
        .addClass(this.getClassName())
        .css(this.getStyle());
        this.setElement(element);
        return element;
    },
    pulsate : function (speed) {
        var height = this.getHeight();
        var width = this.getWidth();
        var top = this.getTop();
        var left = this.getLeft();
        if(this.getElement().height() == height) {
            height = height * 4;
            width = width * 4;
            top = top - (height/2);
            left = left - (width/2);
        }
        $(this.getElement()).animate({
            "height":height,
            "width": width,
            "top": top,
            "left":left
        }, speed);
        var that = this;
        setTimeout(function(){
            that.pulsate(speed);
        }, speed);
    }
}

function addRandomParticle() {
    try {
        var particle = new LightParticle();
        var seed = Math.floor(Math.random() * 70) + 1;
        particle.setBackground("#" + Math.floor((Math.abs(Math.sin(seed) * 16777215)) % 16777215).toString(16));
        particle.setSize(Math.floor(Math.random() * 70) + 10);
        particle.setTop(Math.floor(Math.random() * $(window).height()));
        particle.setLeft(Math.floor(Math.random() * $(window).width()));
        $('#canvas').append(particle.getView());
        particle.pulsate(Math.floor(Math.random() * 2000) + 500);
    } catch(error) {
        console.log(error.message);
    }
}

$(document).ready(function() {
    try {
        for(var i = 0; i < 100; i++) {
            addRandomParticle();
        }
    } catch(error) {
        console.log(error.message);
    }
});

So far I'm not satisfied with the getters and setters since they have no datatype validation.

Does anyone have any idea how I can improve this? Or does someone know a completely better approach to reduce javascript code/events?


texts:
I'm pretty new to Java and programming in general and I'm doing practice problems from my textbook over the summer to try to get ahead. This is a simple program that finds the largest value in a 2D array. I'm just looking for feedback on the organization of my code as well as any improvements I can make so that I can build solid habits going forward.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter the number of rows and columns in the array: ");

    //Creates a temporary two-dimensional array whose size is the next two inputed integers
    double[][] temp = new double[input.nextInt()][input.nextInt()];

    //Populates the temp array with inputed values
    System.out.println("Enter the array: ");
    for(int i=0; i < temp.length; i++) {
        for(int j=0; j < temp[0].length; j++) {
            temp[i][j] = input.nextDouble();
        }
    }
    input.close();

    //Creates a new Location object that is equal to the object returned from the locateLargest() method call
    Location location = Location.locateLargest(temp);

    System.out.println("The location of the largest element is " + location.maxValue + " at (" + location.row + ", " + location.column + ")");

    }
}

public class Location {
    public int row=0, column=0;
    public double maxValue = 0;

    public Location() {
    }

    /*
     * Accepts a two-dimensional array as the parameter.
     * Creates a new Location object.
     * Returns a Location object with maxValue at position (0,0) unless a larger value is found.
     */
        public static Location locateLargest(double[][] a) {
        Location location = new Location();
        location.maxValue=a[0][0];

            for(int i = 0; i < a.length; i++) {
                for(int j=0; j < a[i].length; j++) {
                    if(a[i][j] > location.maxValue) {
                        location.maxValue = a[i][j];
                        location.row = i;
                        location.column = j;
                    }
                }

            }

            return location;
       }

    }


texts: Insert a Node at the Tail of a Linked List

texts:
I've solved this question, but have a small question. In the while loop we check if (temp->next != NULL), why wouldn't work if we check (temp != NULL). Isn't it the same, both checks will get us to the end of the linked list? Also any code review is appreciated!

  You are given the pointer to the head node of a linked list and an
  integer to add to the list. Create a new node with the given integer.
  Insert this node at the tail of the linked list and return the head
  node. The given head pointer may be null, meaning that the initial
  list is empty.

/*
  Insert Node at the end of a linked list
  head pointer input could be NULL as well for empty list
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Insert(Node *head,int data)
{
  // creates a temp to hold the last node and set last's data and next
    Node *last = new Node;
    last->data = data;
    last->next = NULL;
    // if the linked list is empty then set head = last
    if (head == NULL) {
        head = last;
    } else { // if the linked list is not empty
        // creates a temp node and sets it to head
        Node *temp = new Node;
        temp = head;
        // uses temp to find the last node
        // Why do we have to use temp->next here instead of temp? wouldn't it be the same?
        while (temp->next != NULL) {
            temp = temp->next;
        }
        // appends the last node with last
        temp->next = last;
    }
    // returns head of linked list
    return head;
}


texts:
I have been learning c++ for a few weeks now and I attempted this problem on Hackerrank Delete a node. I am aware of a similar post Delete a linked list node but the code seems more of a C structure than a C++ structure. Please feel free to suggest areas of Improvement and shorter way of writing this if any exists. Here is excerpt of the question

  You’re given the pointer to the head node of a linked list and the
  position of a node to delete. Delete the node at the given position
  and return the head node. A position of 0 indicates head, a position
  of 1 indicates one node away from the head and so on. The list may
  become empty after you delete the node.

  Input Format  You have to complete the Node* Delete(Node* head, int position) method which takes two arguments - the head of the
  linked list and the position of the node to delete. You should NOT
  read any input from stdin/console. The position will always be at least 0
  and less than the number of the elements in the list.

  Output Format  Delete the node at the given position and return the head of the updated linked list. Do NOT print anything to
  stdout/console.

  Sample Input

  1 --> 2 --> 3 --> NULL, position = 0  1 --> NULL , position = 0

  Sample Output

  2 --> 3 --> NULL NULL

/*
  Delete Node at a given position in a linked list
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Delete(Node *head, int position)
{
  // Complete this method
    Node *temp = head;
    if(position == 0){
        head = head->next;
        return head;
    }
    Node *temp2 = head;
    for(int i = 0 ; i < position-1; i++){
        temp2 = temp2->next;
    }
      temp = temp2->next->next;
      temp2->next = temp;
    return head;
}


texts:
I have a form. When I click the save button, I want to create an object from the data and pass that info to HTML elements on the same page (div.form_content).

I decided, instead of creating a variable for each HTML element to create an array of HTML elements.  I know the first HTML element is going to contain the first object property, the second html element will contain the second obj property, and so on...

What I have done below seems a little repetitive and not very DRY, and I was wondering if someone could recommend a better way.  For example, if my form has to grow to 12 input fields, what I am doing now would be pretty clunky.  I tried running a loop to prevent the line-by-line assignments, but couldn't figure it out. (By the way, I needed to create an object from the form data because I will need to stringify it to JSON notation to pass to the server, but I got that part.)

$('#save').click(function() {

    var form_Array = $('form').serializeArray();

    // Create an Array of HTML elements
    var el_Array = $('div.form_content').children();

    // create empty object
    var obj = {};

    // loop through serialized form object and assign new object keys from this.name and their values from this.value
    $.each(form_Array, function() {
        obj[this.name] = this.value;
    });

    // populate the html elements with contents of the newly created object
    $(el_Array[0]).html(obj.fname);
    $(el_Array[1]).html(obj.lname);
    $(el_Array[2]).html(obj.phone);
    $(el_Array[3]).html(obj.fax);

});


texts:
I had a task to create simple audio player. So far I managed to do functionalities and all that is needed. Other part of same task was to make it semantic and modular.

I read some blog posts and articles about semantic but I am not sure how to do it in right way.

player();

  function player(){

    music = new Audio('http://www.w3schools.com/tags/horse.mp3');

  }

  $('.button__play').click(function(event){
    event.preventDefault();
    music.play();
  });
  $('.button__pause').click(function(event){
    event.preventDefault();
    music.pause();
  });
  $('.button__stop').click(function(event){
    event.preventDefault();
    music.pause();
    music.currentTime = 0;
  });

  $('.button__repeat, .button__rate').click(function(event){
    event.preventDefault();
    $(this).toggleClass('button__active');
  });
.player{
  background: #eaeaea;
  width: 360px;
  font-family: 'Arial', sans-serif;
  font-size: 16px;
}
.cover{
  width: 100%;
  height: 160px;
  overflow:hidden;
}
.cover__img{
  width: 100%;
  height: auto;
  display:block;
}
.container{
  padding: 0.500em;
}
.info{
  margin: 1em 0;
}
.info:after{
  content: '';
  clear: both;
  display: table;
}
.song{
  list-style: none;
  margin:0;
  padding: 0;
  float: left;
  width: 75%;
}
.progress{
  height: 0.250em;
  width: 100%;
  background: orangered;
  margin: 1em 0;
  postion: relative;
}
.progress__bar{
  height: 0.250em;
  width: 20%;
  background: lightblue;

}
.button{
  display: inline-block;
  text-decoration: none;
  padding: 0.250em 0.500em;
}
.button__play{
  background: orangered;
  color: white;
}
.button__pause, .button__stop{
  font-size: 0.750em;
  background: gray;
  color: white;
}
.button__repeat, .button__rate{
  color: gray;
}
.button__active{
  color: red;
}

forest

rain

        rate

      play
      pause
      stop
      repeat


texts: MySQLi-extension class (parameterized queries)

texts:
I've written some code today to be able to dynamically execute prepared statements/parameterized queries.

I need a fresh pair of eyes to look through my code for eventual performance gains that can be made.

I've tested the code on up to 20 parameters without problems.

For formatting I use this: {0:i}, with position of argument and type of argument

class p_mysqli extends mysqli
{
    public function __construct($host = 'localhost', $user = null, $pass = null, $db = null, $port = null, $socket = null)
    {
        @parent::__construct($host, $user, $pass, $db, $port, $socket);
    }

    public function QueryParam($sql)
    {
        // Find all parameters to be bound
        preg_match_all("/{(\d{1,}:.)}/", $sql, $matches);

        $noStripped = $matches[0];
        $sql = str_replace($noStripped, "?", $sql);
        $params = $matches[1];

        $queryTypes = Array();
        $queryParams = Array();
        $statement = $this->stmt_init();
        $statement = $this->prepare($sql);
        if(!$statement)
            die("Error on prepare: " . $this->error);

        if(count($params) > 0)
        {
            // Get params and pop SQL-query from array
            // This is also the part I'm wondering about..
            $arguments = func_get_args();
            $arguments = array_reverse($arguments);
            array_pop($arguments);
            $arguments = array_reverse($arguments);

            for($i = 0; $i < count($params); $i++)
            {
                $lp = preg_split("/:/", $params[$i]);
                $queryTypes[] = $lp[1];
                $queryParams[] = &$arguments[$lp[0]];
            }

            $query = Array();
            $query[0] = join("", $queryTypes);
            $query = array_merge($query, $queryParams);

            $stateRet = call_user_func_array(array(&$statement, 'bind_param'), $query);

            if(!$stateRet)
                die("Error on parameterbindning: " . $statement->error);
        }
        $statement->execute() or die("Error on execute: " . $statement->errno);
        $ret = $statement->get_result();
        $statement->close();
        return $ret;
    }
}

Example usage:

$indb->queryParam("SELECT COUNT(*) counted_column_test FROM users WHERE userid != {0:i} AND disabled = {2:b} AND email = {1:s}", 1, "this@email.net", false);


texts:
I need to model simple account data structure. The user should be able:

to add a transaction
get information about transaction
take all transaction of some type
sum a transaction and all its children

class AccountModel(object):
    def __init__(self):
        self.types = {}
        self.amounts = {}
        self.parent_to_chilren = {}
        self.children_to_parent = {}
        self.of_type = {}

    def add(self, id, amount, type, parentId=None):
        assert(
            not(id in self.amounts),
            'there is already a transaction with such id'
        )
        self.amounts[id] = amount
        self.of_type[id] = type

        lstOfType = self.types.get(type, [])
        lstOfType.append(id)
        self.types[type] = lstOfType

        if parentId:
            self.children_to_parent[id] = parentId
            lstOfChilren = self.parent_to_chilren.get(parentId, [])
            lstOfChilren.append(id)
            self.parent_to_chilren[parentId] = lstOfChilren

    def get(self, id):
        return (
            self.amounts[id], self.of_type[id],
            self.children_to_parent.get(id, None)
        )

    def get_list_by_type(self, type):
        return self.types[type]

    def sum(self, id):
        lst = self.parent_to_chilren.get(id, [])
        res = self.amounts[id]
        for i in lst:
            res += self.sum(i)
        return res

And the tests:

import unittest

from challenge import AccountModel
class AccountModelTestCase(unittest.TestCase):

    def setUp(self):
        self.model = AccountModel()

    def test_can_add_a_transaction_and_get_information(self):
        self.model.add(1, 10, 'car')
        self.assertEqual(
            self.model.get(1),
            (10, 'car', None),
        )

    def test_can_add_a_transaction_and_get_information_with_parent_id(self):
        self.model.add(1, 10, 'car')
        self.model.add(2, 10, 'car', 1)
        self.assertEqual(
            self.model.get(2),
            (10, 'car', 1),
        )

    def test_can_add_few_transactions_of_a_different_type_and_them(self):
        self.model.add(1, 10, 'car')
        self.model.add(2, 15, 'shopping')
        self.model.add(3, 18, 'car')
        self.assertItemsEqual(
            self.model.get_list_by_type('car'),
            [1, 3]
        )

    def test_can_add_few_transactions_of_a_different_type_and_calc_sum(self):
        self.model.add(1, 10, 'car')
        self.model.add(2, 15, 'shopping', 1)
        self.model.add(3, 18, 'car')
        self.assertEqual(
            self.model.sum(1),
            25
        )
        self.assertEqual(
            self.model.sum(2),
            15
        )
        self.assertEqual(
            self.model.sum(3),
            18
        )

    def test_can_add_few_transactions_parent_of_parent_of_parent(self):
        self.model.add(1, 10, 'car')
        self.model.add(2, 15, 'shopping', 1)
        self.model.add(3, 18, 'car', 2)
        self.assertEqual(
            self.model.sum(1),
            43
        )
        self.assertEqual(
            self.model.sum(2),
            33
        )

if __name__ == '__main__':
    unittest.main()

The questions:

Is there a more effective (in terms of used memory) implementation?
Is there a way to change a data structure and provide more effective (in terms of complexity) sum function implementation?


texts: Generating sorted array in descending order

texts:
I have a method that generates a sorted array with random values in a given range. I wanted to make a method that does this but in descending order.

The easiest way to accomplish this is to call the first method that generates a sorted array and then reverse it. I believe the simplest way to reverse the array is to call Collection.reverse() while the array is still an ArrayList.

To accomplish this I added a new method that just generates the ArrayList but it seems a little unnatural and the code is getting messy:

/**
 *
 * @param length length of array to be generated
 * @param minVal minimum value (inclusive) that may be used in array
 * @param maxVal maximum value (inclusive) that may be used in array
 * @return array with random values but in sorted order
 */
public static int[] generateSorted(final int length, final int minVal, final int maxVal)
{
    return randomArrayList(length, minVal, maxVal).stream().mapToInt(i -> i).toArray();
}

public static int[] generateReverseSorted(final int length, final int minVal, final int maxVal)
{
    ArrayList<Integer> data = randomArrayList(length, minVal, maxVal);
    Collections.reverse(data);
    return data.stream().mapToInt(i -> i).toArray();
}

/**
 *
 * @param length length of arrayList to generate
 * @param minVal minimum value (inclusive) that can appear in list
 * @param maxVal maximum value (inclusive) that can appear in list
 * @return  arrayList containing elements in sorted order
 */
private static ArrayList<Integer> randomArrayList(final int length, final int minVal, final int maxVal)
{
    ArrayList<Integer> data = new ArrayList<>(length);

    for (int i = 0; i < length; i++)
    {
        int rndNum = getRandomVal(minVal, maxVal);
        int insertionPoint = Collections.binarySearch(data, rndNum);
        data.add((insertionPoint > -1 ? insertionPoint : - insertionPoint - 1), rndNum);
    }

    return data;
}

One thing I'm wondering is what exactly is a helper method? I assume it's a small method that helps another with a complex task, so would randomArrayList() be called a helper method? I'm hesitant because I had to offload the majority of the work to it, so now it does more work than the methods that call it do.

The other thing is I'm having trouble knowing how to name the array that is to be filled with random values, I can't think of a better name than data.

Last thing, should the variable data be in the local scope of the method or should it be a member variable of the class? I would never have more than one array I'm using at a time, for example I wouldn't have sorted and reverse sorted array I need to hold on to the values to after I use them once.

How do I make the code cleaner?


texts: Possible issues and best practices for this piece of code

texts:
public class NANDFunction : FunctionInfo
{
    public override string Name { get { return "NAND"; } }
    public override int MinArgs { get { return 2; } }
    public override int MaxArgs { get { return 2; } }

    public override object Evaluate(object[] args)
    {
        bool arg0 = CalcConvert.ToBool(args[0]);
        bool arg1 = CalcConvert.ToBool(args[1]);
        return ((arg0 != arg1) || (!arg0 && !arg1));
    }
}

What do you think of this code?


texts:
(Largest block)
Given a square matrix with the elements 0 or 1, write a program to find a maximum square submatrix whose elements are all 1s. Your program should prompt the user to enter the number of rows in the matrix. The program then displays the location of the first element in the maximum square submatrix and the number of the rows in the submatrix.

Here is a sample run:

Enter the number of rows in the matrix:
5

Enter the matrix row by row:
1 0 1 0 1
1 1 1 0 1
1 0 1 1 1
1 0 1 1 1
1 0 1 1 1

The maximum square submatrix is at (2, 2) with size 3

My solution is this:
(I didn't make it prompt an input because my computer hasn't arrived and the ide on my phone can't use text files as input. I didn't want to type in all the numbers to try different inputs.)
public class Main {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 0, 1, 0, 1},
            {1, 1, 1, 0, 1},
            {1, 0, 1, 1, 1},
            {1, 0, 1, 1, 1},
            {1, 0, 1, 1, 1}
        };

        //Check each location for sub-squares
        int[] largestBlock = new int[3];
        int maxSize = 0;
        for (int i = 0; i < matrix.length - 1; i++) {
            for (int j = 0; j < matrix[i].length - 1; j++) {
                int squareSize = 0;
                while (isSquare(i, j, squareSize, matrix)) {
                    squareSize++;
                }

                if (squareSize > maxSize) {
                    largestBlock[0] = i;
                    largestBlock[1] = j;
                    maxSize = squareSize;
                }
            }
        }

        largestBlock[2] = maxSize + 1;
        System.out.println("The first largest sub-square is located at (" + largestBlock[0]
          + ", " + largestBlock[1] + ") and is of size " + largestBlock[2]);
    }

    public static boolean isSquare(int row, int column, int squareSize, int[][] matrix) {
        int size = squareSize + 2;

        if (row + size - 1 >= matrix.length || column + size - 1 >= matrix.length)
            return  false;

        for (int i = row; i < row + size; i++) {
            for (int j = column; j < column + size; j++) {
                if (matrix[i][j] != 1)
                    return false;
            }
        }
        return true;
    }
}


texts: Scraping web data using asynchronous request

texts:
I've written a script using python to grab different categories from a webpage. I used "grequests" in my scraper to perform the activity. My intention here was to perform the action swiftly making asynchronous HTTP requests. My scraper is running flawlessly and collecting data as it should. However, in case of performance, I'm not sure it is giving the optimum. Any suggestion to make it better will be highly appreciated.

import grequests ; from lxml import html

main_link = "http://quotes.toscrape.com/"

def toscrape_scraper(item_link):
    storage = [item_link]      # Depositing link as a list
    response = (grequests.get(req) for req in storage)
    for req in grequests.map(response):                #Sending requests
        tree = html.fromstring(req.text)
        for titles in tree.cssselect("span.tag-item a.tag"):
            grabbing_docs(main_link + titles.attrib['href'])

def grabbing_docs(base_link):
    vault = [base_link]          # Storing links as a list
    res = (grequests.get(req) for req in vault)
    for hreq in grequests.map(res):               #Sending requests
        root = html.fromstring(hreq.text)
        for soups in root.cssselect("div.quote"):
            quote = soups.cssselect("span.text")[0].text
            author = soups.cssselect("small.author")[0].text
            print(quote, author)

    next_page = root.cssselect("li.next a")[0].attrib['href'] if root.cssselect("li.next a") else ""
    if next_page:
        page_link = main_link + next_page
        grabbing_docs(page_link)  #Reusing the newly collected paginated links

toscrape_scraper(main_link)


texts: Open a text file and remove any blank lines

texts:
I have the following functions which help me to open a text file and remove any blank (empty) lines:

def fileExists(file):
    try:
        f = open(file,'r')
        f.close()
    except FileNotFoundError:
        return False
    return True
def isLineEmpty(line):
    return len(line.strip()) < 1
def removeEmptyLines(file):
    lines = []
    if not fileExists(file):
        print ("{} does not exist ".format(file))
        return
    out = open(file,'r')
    lines = out.readlines()
    out.close()
    out = open(file,'w')
    t=[]
    for line in lines:
        if not isLineEmpty(line):
            t.append(line)
    out.writelines(t)
    out.close()

As you can see I open a file 2 times. One for reading and one for writing. Is there anything I can to to improve this code?


texts:
I built this 4 classes where the Main is the one responsible for setting and getting the variables. I am using PHP7.1. Please let me know on how to make this more amazing or maybe using trait. How does my classes look? Is it professionally made? what do you guys think? thank you very much!

<?php

class Main
{
    // Parameters
    protected $first_name;
    protected $middle_name;
    protected $last_name;

    public function first_name($first_name)
    {
        $this->first_name = $first_name;
        return $this;
    }

    public function middle_name($middle_name)
    {
        $this->middle_name = $middle_name;
        return $this;
    }

    public function last_name($last_name)
    {
        $this->last_name = $last_name;
        return $this;
    }
}

class Cpc extends Main
{
    public function __construct()
    {
        echo 'this cpc construct
';
    }

    public function generateCpc()
    {
        echo 'this cpc generated
';
        echo $this->first_name." ".$this->middle_name." ".$this->last_name;
        echo '
';
    }
}

class Basetable extends Cpc
{
    public function __construct()
    {
        echo 'this basetable construct
';
    }

    public function generateBasetable()
    {
        echo 'this basetable generated
';
        echo $this->first_name." ".$this->middle_name." ".$this->last_name;
        echo '
';
    }
}

class Layer extends Basetable
{
    public function __construct()
    {
        echo 'this layer construct
';
    }

    public function generateLayer()
    {
        echo 'this layer generated
';
        echo $this->first_name." ".$this->middle_name." ".$this->last_name;
        echo '
';
    }
}

class Master extends Layer
{
    public function __construct()
    {
        echo 'this Master construct
';
    }

    public function generate()
    {
        $this->generateCpc();
        $this->generateBasetable();
        $this->generateLayer();

        echo 'this master generated
';
        echo $this->first_name." ".$this->middle_name." ".$this->last_name;
        echo '
';
    }
}

$o = new Master();
$o->first_name('ken dan')->middle_name('sunico')->last_name('tinio')->generate();

?>


texts: Check if three arrays contains the same element

texts:
Do 3 arrays contain a common element, if they contain output it.
For example: [1,2,3], [2,3], [2,4] -> answer = 2

let arr1 = [1, 3, 11, 32, 44, 99];
let arr2 = [4, 12, 15, 99];
let arr3 = [4, 11, 13, 15, 23, 43];

function searchThreeSameNum(arr1, arr2, arr3) {
    let i = 0;
    let j = 0;

    while (1) {
        if (i == arr1.length || j == arr2.length) {
            return 'No equal numbers';
        }

        if (arr1[i] < arr2[j]) {
            i++;
            continue;
        } else if (arr1[i] > arr2[j]) {
            j++;
            continue;
        } else if (arr1[i] == arr2[j])
            for (let k = 0; k < arr3.length; k++) {
                if (arr1[i] == arr3[k])
                    return arr1[i];
            }

        return 'No equal numbers';
    }
}

I will be glad if you give me any tips to improve my code. Thanks in advance.
Sorry, I'm not an English speaker.


texts: Singly Linked list implementation in C++

texts:
How can I improve this code
Please tell proper indentation and usage of camel-case.

#include <iostream>
using std::cout;
struct Node
{
    int data;
    Node* next;
};
Node* Create(int data){
    Node* root=new Node();
    root->data=data;
    root->next=NULL;
    Node* head=root;
    return head;
}
void push_back(int data,Node* head){
    if(!head->next)
    {
        Node* newNode=new Node();
        newNode->data=data;
        newNode->next=NULL;
        head->next=newNode;
    }
    else
        push_back(data,head->next);
}
Node* push_front(int data,Node* head){
    Node* newNode=new Node();
    newNode->data=data;
    newNode->next=head;
    head=newNode;
    return head;
}
void pull_back(Node* head){
    Node* temp=head;
    if(!temp->next)
        delete temp;
    else
        pull_back(temp->next);
}
Node* pull_front(Node* head){
    Node* temp=head->next;
    delete head;
    Node* NewHead=temp;
    return NewHead;
}
void print(Node* head){
    while(head)
        cout<<head->data<<" ",
        head=head->next;
    cout<<"\n";
}
Node* Reverse(Node* head)
{
    Node* prev   = NULL;
    Node* current = head;
    Node* next;
    while (current != NULL)
    {
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    head = prev;
    return head;
}
int Search(int data,Node* head,int count=1){
    if(head->data==data)
        return count;
    if(!head->next)
        return -1;
    return Search(data,head->next,count+1);
}
Node* MakeCircular(Node* head)
{
    Node* temp=head;
    while(!temp->next)
        temp=temp->next;
    temp->next=head;
    return head;
}
bool DetectCircle(Node* head){
    //using floyd's cycle
    Node* fast=head;
    Node* slow=head;
    if(!(slow && slow->next))return false;
    while(fast && fast->next){
        slow=slow->next;
        fast=fast->next->next;
        if(slow==fast)
            return true;
    }
    return false;
}
int main(int argc, char const *argv[])
{
    Node* head=Create(12);
    push_back(32,head);
    push_back(123,head);
    head=push_front(-21,head);
    print(head);
    head=Reverse(head);
    print(head);
    return 0;
}


texts: Targeting string to wrap with HTML element to italicize

texts:
Objective
I set up my page to dynamically wrap  tags around a targeted keyword (string) on a title.
Background
When I worked on the static parts of the website, I could manually wrap that word. But Some parts of the page will be generated by the server, so if the word appears in the title, I need it wrapped so that it shows up as italicized.
For the sake of an example, let's say that if the keyword is "cool" then it needs to be converted to cool if it appears in a title, which in this case is class "exec-company"

<?php the_field('company') ?>

Lets say the output was this HTML

Cool company

I followed along to this tutorial. Which advised on using jQuery and showed this sample
var oldString = 'john',
newString = 'John',
newText = $('p').text().replace(RegExp(oldString,"gi"),newString);

$('p').html(newText);

I modified to this so that it is always uppercase, and always italicized
var oldString = 'cool',
newString = 'COOL',
newText = $('.exec-company').text().replace(RegExp(oldString,"gi"),newString);

$('.exec-company').html(newText);

On codepen, I made a demo which produced this.

but wondering if this was the best way to approach this problem. Especially since the solution won't really scale well since the word is used site wide.


texts: Simplest quick sort using one 19-line function

texts:
This will later be be posted on my website to explain quick sort so I would like how I could improve the readability and simplicity of this demo class. I do not like my use of the stack (meaning this recursion cannot process a list with millions of values).

How could I reduce the stack impact? I think the best way would be not to use as many ArrayList instances. However, I don't know how else because I cannot use lists like int[] list because I do not know their size and surely if I just make it too big the loops will be bigger and take longer.

Here is the class in question:

import java.util.ArrayList;
import java.util.Random;

public class QuickSort {

    static Random r = new Random();

    public static void main(String[] args) {
        int listsize = 100000, range = 100000;
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<listsize; i++)
            list.add(r.nextInt(range));
        sort(list);
        System.out.println(list);
    }

    public static ArrayList<Integer> sort(ArrayList<Integer> list) {
        if (list.size() <= 1)
            return list;
        int rotationplacement = r.nextInt(list.size());
        int rotation = list.get(rotationplacement);
        list.remove(rotationplacement);
        ArrayList<Integer> lower = new ArrayList<Integer>();
        ArrayList<Integer> higher = new ArrayList<Integer>();
        for (int num : list)
            if (num <= rotation)
                lower.add(num);
            else
                higher.add(num);
        sort(lower);
        sort(higher);

        list.clear();
        list.addAll(lower);
        list.add(rotation);
        list.addAll(higher);
        return list;
    }
}


texts: Send parameter to server and reload page

texts:
My first ASP.NET MVC 6 / jQuery web site - the site header has a "Change Language" selector (named LanguagePicker) - this is actually placed in a _Layout view, a container shared by all views.

When users change the language, I need to save that in the db, and reload current page, with language changed.

I have this on client-side:

$('#LanguagePicker').selectpicker('val', '@CultureHelper.GetCurrentLanguage()');
$('#LanguagePicker').on('change', function () {
            var currentPageUrl = 'TODO'; // Get current Url here
            window.location = "/Base/ChangeLanguage/" +
                $('.selectpicker option:selected').val() +
                "?returnUrl=" + currentPageUrl ;
        });
    });

Is there a better way to do this, both in client side code and in server side? Ideally, the purpose is to send a newLanguage param to the server, save to db, and then refresh the current page so that the resources associated with the new language are displayed. it should obviously work from whatever page it is triggered.


texts:
Dynamically growing arrays are a type of array. They are very useful when you don't know the exact size of the array at design time. First you need to define an initial number of elements. (Wikipedia)

I have written a Python solution and converted it to Cython.
Cython can be used to improve the speed of nested for loops in Python.
Where my Cython code is slightly faster.
My Cython solution is obviously not the fastest.
I am trying to perform a nested for loop similar to the one in my Python code as fast as possible in Cython.

It would help to have some experience in C, which I don't.
The main problem that I ran into is that Cython has different scoping rules to Python.
Since C and Python have different scoping rules.
In other words, we cannot create a new vector in the loop and assign it to the same name.

My solution works but is too slow.
Can anyone improve Cython code above by using a more C like approach.
Python
import numpy as np

my_list = [1,2,3]
n = 10
a = 0.5

Estimate_1_list = []
Estimate_2_list = []

for l in my_list:

    # Resizable matrices
    a_mat = np.zeros((l,n+1),float)
    b_mat = np.zeros((l,n+1),float)

    for i  in range(n):
        t = i*a

        for j in range(l):

            # Fill matrices
            a_mat[j,i+1] = a_mat[j,i+1] + np.random.random()

            b_mat[j,i+1] = a_mat[j,i+1]/(2*t+3)

    # Append values of interest to use at different values of matrix size
    Estimate_1_list.append(np.mean(a_mat[:,n]))
    Estimate_2_list.append(np.std(a_mat[:,n]))
results = [Estimate_1_list,Estimate_2_list]

Cython
import cython
# Load cython extension
%load_ext Cython

%%cython
import numpy as np

def my_function(list my_list, int n, int a ):
cdef list Estimate_1_list = []
cdef list Estimate_2_list = []
cdef int l,i,t,j
for l in my_list:

    # Resizable matrices (could I use memory view?)
    a_mat = np.zeros((l,n+1),float)
    b_mat = np.zeros((l,n+1),float)

    for i  in range(n):
        t = i*a

        for j in range(l):

            # Fill matrices
            a_mat[j,i+1] = a_mat[j,i+1] + np.random.random()

            b_mat[j,i+1] = a_mat[j,i+1]/(2*t+3)

    # Append values of interest to use at different values of matrix size
    Estimate_1_list.append(np.mean(a_mat[:,n]))
    Estimate_2_list.append(np.std(a_mat[:,n]))

# Return results
results = [Estimate_1_list,Estimate_2_list]
return results

Tests
# Test cython to show that the function is running
my_list = [1,2,3]
n = 10
a = 0.5
my_function(my_list, n, a)

[[0.13545224609230933, 0.6603542545719762, 0.6632002117071227],
 [0.0, 0.19967544614685195, 0.22125180486616808]]


texts:
I've been trying to look for a better way in which a user has up to 5 inputs in which they can search for results in a database.

I have 2 EditTexts in which the user can have alphanumeric values and 3 Spinners. As you can see in the code, it's badly designed in the way it consists of if or else if statements which is just horrible, but it works.

What would be the best way to avoid long if or else if statements and be able to pick and choose what you would like to search for in the database? I know there is the switch but does that not just take a value and return the result of something on the one case?

if(tag != "" && name != "" && breed != "Breed" && sex != "Sex"){
    cursor = cupboard().withDatabase(sqLiteDatabase).query(Cattle.class)
            .withSelection("tag LIKE ? AND name LIKE ? AND breed LIKE ? AND sex LIKE ?", tag, name, breed, sex)
            .getCursor();

    if(cursor.getCount() < 1){
        Toast.makeText(getContext(), "Sorry, No Cattle with those details!", Toast.LENGTH_LONG).show();
    }

} else if (tag == "" && name == "" && breed == "Breed"){
    cursor = cupboard().withDatabase(sqLiteDatabase).query(Cattle.class)
            .withSelection("sex LIKE ?", sex)
            .getCursor();
    if(cursor.getCount() < 1){
        Toast.makeText(getContext(), "Sorry, No Cattle with those details!", Toast.LENGTH_LONG).show();
    }

} else if (breed != "Breed"){
    cursor = cupboard().withDatabase(sqLiteDatabase).query(Cattle.class)
            .withSelection("breed LIKE ?", breed)
            .getCursor();
    if(cursor.getCount() < 1){
        Toast.makeText(getContext(), "Sorry, No Cattle with those details!", Toast.LENGTH_LONG).show();
    }

} else if (sex != "Sex"){
    cursor = cupboard().withDatabase(sqLiteDatabase).query(Cattle.class)
            .withSelection("sex LIKE ?", sex)
            .getCursor();
    if(cursor.getCount() < 1){
        Toast.makeText(getContext(), "Sorry, No Cattle with those details!", Toast.LENGTH_LONG).show();
    }

} else if (tag == "" && name == "" && sex == "Sex"){
    cursor = cupboard().withDatabase(sqLiteDatabase).query(Cattle.class)
            .withSelection("breed LIKE ?", breed)
            .getCursor();
    if(cursor.getCount() < 1){
        Toast.makeText(getContext(), "Sorry, No Cattle with those details!", Toast.LENGTH_LONG).show();
    }

}


texts: Determining the state of matter for some substances

texts:
I am new to React and still getting a handle on props and state. I tried
 to adopt the example of lifting state from
the React Docs
 and add the feature of different criteria by liquid type for evaluating these values.

Here is the JSBin version.

const liquidNames = {
  w: "Water",
  eth: "Ethanol"
};

var liquidInventory = {ethanol: {
  name: "Ethanol",
  freezing: -173.2,
  boiling: 173.1
}, "water": {
  name: "Water",
  freezing: 0,
  boiling: 212
}};

//test function to determine 'state of matter'
function LiquidState(props){
  var liquid = props.liquidType;
  if (props.temperature >= liquidInventory[liquid].boiling){
    return
 Boiling {liquid}

  } else if (props.temperature <= liquidInventory[liquid].freezing){
    return
 Frozen {liquid}

  } else {
    return
 You have liquid {liquid}

  }
}

//component to present the inputs and values of each water and ethanol
class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const liquidType = this.props.liquidType;
    return (

      <fieldset>
        <legend>Enter Temperature for {liquidType}: </legend>
        <input value={temperature}
          onChange={this.handleChange} />
          < LiquidState liquidType={liquidType} temperature={temperature} />
      </fieldset>

    );
  }
}

//parent Temperature component that holds overall program state
class Temperature extends React.Component {
  constructor(props) {
    super(props);
    this.testWater = this.testWater.bind(this);
    this.testEthanol = this.testEthanol.bind(this);
    this.state = {
      temperature: '',
      liquidType: ''
    };
  }

  testWater(temperature) {
    this.setState({temperature})
  }

  testEthanol(temperature) {
    this.setState({temperature})
  }

  render() {
    const liquidType = this.state.liquidType;
    const temperature = this.state.temperature;
    return (

        <TemperatureInput
          temperature={temperature}
          liquidType={'water'}
          onTemperatureChange={this.testWater}  />
         <TemperatureInput
          temperature={temperature}
           liquidType={'ethanol'}
          onTemperatureChange={this.testEthanol}  />

    );
  }
}

ReactDOM.render(
  <Temperature />,
  document.getElementById('root')
);


texts: Delete the node at index i from its current position and insert it after node at index j

texts:
I was trying to create a function to delete the node at index i from its current position and insert it after node at index j from a std::vector<Node> nodes. These container is logically a circular container of nodes, that is there's no actual first or last node, i.e. after nodes.back() comes nodes[0].

I really need this function not to have bugs and to be as performant as possible, so I'm asking here your help to a further check and for eventual suggestions to improve its performance.

So, this is the function:

/*
 * Delete the node at index i from its current position
 * and insert it after node at index j.
 * */
void SimpleSolution::shift(const int i, const int j) {

    assert_not_out_of_bounds({i, j});

    int x;

    if (j < i) { // ranges [i, end] and [start, j]

        for (x = i; x < nodes.size() - 1; ++x) {
            std::swap(nodes[x], nodes[x + 1]);
        }

        std::swap(nodes[0], nodes.back());

        for (x = 0; x < j; ++x) {
            std::swap(nodes[x], nodes[x + 1]);
        }

    } else { // range [i, j]

        if (i != j) {

            for (x = i; x < j; ++x) {
                std::swap(nodes[x], nodes[x + 1]);
            }

        } else { // i == j

            // i and j are the last elements
            if (i == (nodes.size() - 1)) {
                std::swap(nodes[0], nodes.back());
            } else { // equivalent to std::swap(nodes[i], nodes[i + 1])
                std::swap(nodes[i], nodes[j + 1]);
            }
        }

    }

}

I'm not looking for "idiomatic" C++, but for correctness and performance, but if idiomatic also means correctness and performance, then perfect.

Here's the assert_not_out_of_bounds method:

void SimpleSolution::assert_not_out_of_bounds(const std::initializer_list<int> indices) const {
    for (int i : indices) {
        if (i < 0 || i >= nodes.size()) {
            throw std::out_of_range("i is out of the range");
        }
    }
}


texts: Is this an appropriate use of abstract classes and inheritance?

texts:
This is a simple app that starts the webcam either in color or in grayscale mode depending on what the user wants:

The grayscale camera is implemented via the GrayVideo class and the color camera through ColorVideo. I wanted to have a common show_current_frame for both the ColorVideo and GrayVideo objects. That show_current_frame gets the current frame from the process method and displays it in the GUI. Since the color and the grayscale videos need different frame processing, I needed to have different process methods for ColorVideo and GrayVideo. So, I thought of having a Video class with an abstract process method.

Is this a decent use of abstract classes and inheritance?
What other problems and possible improvements do you see in my code?
Or is the design wrong in the first place?

import cv2
from abc import ABC, abstractmethod

class Video(ABC):

    def __init__(self, source):
        self.capture = cv2.VideoCapture(source) # If source = 0 the webcam starts

    def get_raw_frame(self):
        # Get a bolean and current frame (numpy array) from the webcam
        ret, frame = self.capture.read()
        if ret:
            return frame

    @abstractmethod
    def process(self):
        # Method to process frames.
        # Method will be overwritten by subclasses
        pass

    def show_current_frame(self):
        # Get processed frame and show it in the GUI
        current_frame = self.process()
        cv2.imshow('Live', current_frame)

    def end(self):
        # Releases webcam and closes GUI window
        self.capture.release()
        cv2.destroyAllWindows()

class ColorVideo(Video):

    def process(self):
        # Since raw frames are in color, there's no processing needed
        return self.get_raw_frame()

class GrayVideo(ColorVideo):

    def process(self):
        # Grayscaling the raw frames
        raw_frame = self.get_raw_frame()
        gray = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)
        return gray

user_preference = input('Enter "c" for color, or "g" for grayscale: ')

if user_preference == 'c':
    video = ColorVideo(source=0)
if user_preference == 'g':
    video = GrayVideo(source=0)

while True:
    video.show_current_frame()

    if cv2.waitKey(1) & 0xFF == ord('q'):
        video.end()


texts:
This was a basic anagram problem. Take an input word, find all its permutations, then check a dictionary file to see what if any of those are real words.

Dictionary file

My input data:

8
lasting
lameness
severer
lapse
alerting
medical
tasking
crates

My answer:

3 3 3 5 4 4 3 6

The code works slowly, as in, it took maybe a minute.  Aside from any other criticism, I'm curious to the following:

Why are these two so different in speed? Casting as String was much faster:

String current = (String) iter.next();

and

String current = iter.next().toString();

Is there a smarter way than looping through the dictionary every single time for every permutation of a word?
Is there a better data structure for the dictionary than an ArrayList?  If so, why?

    package com.secryption.CA127Anagrams;

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

/**
 * Created by bmarkey on 11/26/15.
 */

public class Anagrams {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Scanner inFile;
        System.out.println("Enter Data: ");
        int testCases = Integer.parseInt(in.nextLine());
        ArrayList<String> dictionary = new ArrayList<>();

        try {
            File file = new File("/home/me/words.txt");
            inFile = new Scanner(file);

            while (inFile.hasNextLine()) {
                dictionary.add(inFile.nextLine());
            }
            inFile.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < testCases; i++) {
            int counter = 0;
            String inputStr = in.nextLine();

            Set<String> allCombos = getPermutations(inputStr);

            Iterator iter = allCombos.iterator();

            while (iter.hasNext()) {
                String current = (String) iter.next();
//              String current = iter.next().toString();
                for( int j = 0; j < dictionary.size(); j++) {
                    if (current.equals(dictionary.get(j))) {
                        counter++;
                    }
                }
            }
            System.out.print((counter - 1) + " ");
        }

    }

    public static Set<String> getPermutations(String str) {
        Set<String> permResult = new HashSet<String>();

        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            permResult.add("");
            return permResult;
        }

        char firstChar = str.charAt(0);
        String rem = str.substring(1);
        Set<String> words = getPermutations(rem);

        for (String newString : words) {
            for ( int i = 0; i <= newString.length(); i++) {
                permResult.add(permCharAdd(newString, firstChar, i));
            }
        }
        return permResult;
    }

    public static String permCharAdd(String str, char c, int j) {
        String first = str.substring(0, j);
        String last = str.substring(j);
        return first + c + last;
    }
}


texts:
How do I handle multi-tenancy with routes in ASP.NET MVC?

The application is a multitenant ASP.NET MVC 3 application. Tenants are identified based on hostname so this does not interfere with routing.

Other important information:

The application has a number of features (or plugins). These are essentially other web projects with their own controllers, views and routes.
ASP.NET MVC routing serves as our entry point into these features.
One key point is that all the features function the SAME way for all tenants. The variable is whether the tenant is actually subscribed to the feature.

So imagine we have a "blog" feature with a route like so:

/blog/{instance}/posts

When our application starts we register the routes of all "routable" features. However, we need to ensure that this route is only matched if the tenant is subscribed to that feature.

Currently I'm doing this with a custom route:

private readonly IFeatureMetadata feature;

public FeatureRoute(IFeatureMetadata feature, string url, RouteValueDictionary defaults, IRouteHandler handler) :
    base(url, defaults, handler)
{
    if (feature == null)
        throw new ArgumentNullException("feature");
    this.feature = feature;
}

public override RouteData GetRouteData(System.Web.HttpContextBase httpContext)
{
    var routeData = base.GetRouteData(httpContext);

    if (routeData == null)
        return null;

    var context = DependencyResolver.Current.GetService<ISiteContext>();
    var site = context.GetSite();
    var matchedInstances = site.FeatureInstances.Where(f => f.Feature.FeatureType == feature.FeatureType);

    if (!matchedInstances.Any())
        return null;

    if (routeData.Values["instance"] == null)
    {
        routeData.Values["instance"] = matchedInstances.First().Id;
    }

    return routeData;
}

One thing that I need to cater for is routes that do not specify an instance.

For example, a tenant may have one or more blogs. If he only has one then outgoing routes should just generate:

http://[domain]/blog/posts

If he has more than one then we should generate:

http://[domain]/blog/{instance}/posts

Currently I'm handling this by registering 2 routes (one with the {instance} parameter and one without). In the code above you can see that if the instance parameter doesn't exist in RouteData we just add the id of the first matched feature instance.

This is then sufficient for me to make a call to my blog service:

GetPosts(int featureInstanceId);

While everything "works", I'm looking for feedback on my implementation. As a freelance developer this seems to be the only way I can get my code reviewed.


texts:
I am just trying to use Rust so I will be thankful for all remarks and corrections:

fn selection_sort(array: &mut [i32]) {

    let mut min;

    for i in 0..array.len() {

        min = i;

        for j in (i+1)..array.len() {

            if array[j] < array[min] {
                min = j;
            }
        }

        let tmp = array[i];
        array[i] = array[min];
        array[min] = tmp;
    }
}

fn main() {

    let mut values = [ 5, 8, 4, 1, 7, 2, 3, 6 ];
    println!("Hello, world! The value is {:?}", values);

    selection_sort(&mut values);
    println!("Hello, world! The value is {:?}", values);
}


texts:
Inspired by this question, I decided to rewrite this code in Scheme, as I'm working through SICP right now. Any feedback welcome.

#lang racket

;assume cup, is-empty?, refill and drink are operations understood by the environment

(define (coffee cup)
        (if (is-empty? cup)
        (coffee (refill cup))
        (drink cup)))


texts: Basic calculator program in Python as a beginner

texts:
I'm a beginning coding and this is my very first Python program - a basic calculator. I would very much appreciate any recommendations or fixes!

if restart != "Y":
        print("It was a pleasure calculating with you!")
        time.sleep(1)
        print("\nGoodbye!")
        time.sleep(1)
        sys.exit()

# Modules:

import time     # Provides time-related functions
import sys      # Used to exit the program when needed

# Operations:

def add(num1, num2):
    #   Returns the sum of num1 and num2
    return num1 + num2

def sub(num1, num2):
    #   Returns the difference of num1 and num2
    return num1 - num2

def mul(num1, num2):
    #   Returns the product of num1 and num2
    return num1 * num2

def div(num1, num2):
    #   Returns the quotient of num1 and num2
    try:
        return num1 / num2
    except ZeroDivisionError:
        # Handles division by zero
        print("Division by zero cannot be done. You have broken the universe. Returning zero...")
        return 0

def exp(num1, num2):
    #   Returns the result of num1 being the base and num2 being the exponent
    return num1 ** num2

# Run operational functions:

def run_operation(operation, num1, num2):
    # Determine operationz
    if operation == int("1"):
        print("Adding...\n")
        time.sleep(1)
        print(num1, "+", num2, "=", add(num1, num2))
    elif operation == int("2"):
        print("Subtracting...\n")
        time.sleep(1)
        print(num1, "-", num2, "=", sub(num1, num2))
    elif operation == int("3"):
        print("Multiplying...\n")
        time.sleep(1)
        print(num1, "*", num2, "=", mul(num1, num2))
    elif operation == int("4"):
        print("Dividing...\n")
        time.sleep(1)
        print(num1, "/", num2, "=", div(num1, num2))
    elif operation == int("5"):
        print("Exponentiating...\n")
        time.sleep(1)
        print(num1, "^", num2, "=", exp(num1, num2))
    else:
        print("I don't understand. Please try again.")
        time.sleep(1)

def main():
    while True:                   # Loops if user would like to restart program
        valid_input = False
        while not valid_input:    # Loops if user enters an invalid input. Avoids error
            try:
                # Acquire user input
                num1 = (int(input("What is number 1? ")))
                num2 = (int(input("What is number 2? ")))
                operation = int(input("What would you like to do? \n1. Addition, 2. Subtraction, 3. Multiplication, "4. Division, 5. Exponentiation \nPlease choose an operation: "))
                valid_input = True
            except ValueError:      # Handles any value errors
                print("Invalid input. Please try again.")
                time.sleep(1)
        run_operation(operation, num1, num2)
        time.sleep(1)
        # Ask if the user wants to do more calculations or exit:
        restart = (str(input("Would you like to make more calculations? Enter (Y) for yes, or any other character for no. ")))

I'm having a lot of trouble with the code block below. It doesn't recognize "Y" and instead outputs: "It was a pleasure calculating with you! Goodbye!" What could I do?

if restart != "Y":
    print("It was a pleasure calculating with you!")
    time.sleep(1)
    print("\nGoodbye!")
    time.sleep(1)
    sys.exit()

#  Title Sequence
print('\n\nCalculator\n\n')
time.sleep(1)
print('      ---LOADING---\n\n')
time.sleep(2)
print('Hello. I am your personal calculator. \nBEEP BOOP BEEP. \n\n')
time.sleep(1)

#  Calls the main function to start program
main()

# Turns my program into an importable module
if __name__ == '__calculator__':
    main()


texts: Find associated object if exists, otherwise generate it

texts:
I have a simplified model that looks like this:

class Player < ActiveRecord::Base
  has_many :picks

  def pick_for_game(game)
    id = game.instance_of?(Game) ? game.id : game
    pick = picks.find {|pick| pick.game_id == id}
    if !pick
      pick = picks.build(:game_id => id)
    end
    pick
  end
end

The pick_for_game method usually is called a bunch of times when an action is executed. What would be a good way to make this code work efficiently with a list of games?


texts:
I'm attempting to improve my coding style by concentrating on simple and focused OOP client-server interfaces and error handling - atm in the context of designing a Blackjack game.  I'm starting with the Card class that represents an individual card.  I'm looking for any improvements on or flaws with my approach.

#include <sstream>
#include <stdexcept>
#include <string>

class Card
{
public:
    enum Ranks { Ace = 1, Ten = 10, Jack, Queen, King };
    enum Suits { Spades, Hearts, Diamonds, Clubs };

    Card( int rank, int suit ) throw(std::range_error)
    {
            if( rank < 1 || rank > 13 ) {
                    std::stringstream errMsg;
                    errMsg << "Card(): rank '" << rank << "' out of range";
                    throw std::range_error( errMsg.str() );
            } else if( suit < 0 || suit > 3 ) {
                    std::stringstream errMsg;
                    errMsg << "Card(): suit '" << suit << "' out of range";
                    throw std::range_error( errMsg.str() );
            }

            m_rank = rank;
            m_suit = suit;
    }

    int rank() const { return m_rank; }
    int suit() const { return m_suit; }
    std::string str( bool useStrings = false ) const
    {
            std::stringstream ret;
            if( useStrings )
                    ret << sRanks[m_rank] << " of " << sSuits[m_suit];
            else
                    ret << cRanks[m_rank] << cSuits[m_suit];
            return ret.str();
    }

private:
    static const char cRanks[14];
    static const char cSuits[4]
    static const std::string sRanks[14];
    static const std::string sSuits[4];

    int m_rank;
    int m_suit;
};

const std::string Card::sSuits[4] = {"Spades", "Hearts", "Diamonds", "Clubs"};
const std::string Card::sRanks[14] = { "\0", "Ace", "Two", "Three", "Four", "Five",
                    "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
const char Card::cSuits[4] = { 's', 'h', 'd', 'c' };
const char Card::cRanks[14] = { '\0', 'A', '2', '3', '4', '5', '6', '7',
                                '8', '9', 'T', 'J', 'Q', 'K' };

The client can create a card either using the Card enum constants or integers, like

Card card(Card::Ace, Card::Diamonds);
Card card2(0, 3); // throws an exception

I'm dubious on how useful the public enum constants are for client code.  Also, I'm very new to exception programming and I'm not sure if this is a good approach or whether the constructor should throw an exception.  Any improvements or suggestions?


texts: Recursive and Non-recursive SelectionSort

texts:
This is a naive attempt of writing a recursive and non-recursive versions for SelectionSort(). My goal is mainly to present an elegant, easy-to-understand, idiomatic code, and therefore, performance is a distant priority. Please comment away!

// Find the index at which the minimum value
// exists inside the Array
function findMinIndex(a){
    return a.reduce((iMin, x, i, arr) => x < arr[iMin]? i : iMin, 0);
}

// Remove the minimum value from the array
// Return the value removed
function removeMin(a){
    idx = findMinIndex(a);
    minVal = a[idx];   // for [1, -5, 3], minVal = -5
    a.splice(idx, 1);  // [1, -5, 3] -> [1, 3]
    return minVal;
}

// Selection sort, in recursive mode
// As the name suggests, we select and 'splice' it
// away from the array, and recursively
// concatenate it to get the final result
function selectRecursive(a) {
    if (!a.length) return [];   // terminating case
    minVal = removeMin(a);      // remove the smallest
    console.log(v, a);
    return [minVal].concat(selectRecursive(a));
}

var myl = [1, 2, 3, 99, 22, 55, 5];
selectRecursive(myl);

OUTPUT

1 [ 2, 3, 99, 22, 55, 5 ]
2 [ 3, 99, 22, 55, 5 ]
3 [ 99, 22, 55, 5 ]
5 [ 99, 22, 55 ]
22 [ 99, 55 ]
55 [ 99 ]
99 []
[ 1, 2, 3, 5, 22, 55, 99 ]

In addition, a non-recursive (less intuitive in my opinion) version of SelectionSort (using push, slice, splice and the spread operator) is presented below.

function selectionSort(a) {
  var length = a.length;
  for (var i = 0; i < length; i++) {
    a.push(  // select and append at the end
      ...a.splice(
        findMinIndex( // get min in a sliced 'a'
          a.slice(0, length - i)), 1)
    );
  }
  return a;
}


texts: Accessing a subset of keys from a nested dictionary in Python

texts:
I am trying to access data from Coinmarketcap API in Python and came up with the following code:

def fetch_coin_prices(**kwargs):
    """Retrieve cryptocurrency data from CoinMarketCap and return a dictionary
    containing coin names with their current prices.

    Keyword arguments to this function are mapped to the CoinMarketCap API,
    refer to their documentation for their meaning:
    https://coinmarketcap.com/api/
    """
    response = requests.get(
        'https://api.coinmarketcap.com/v2/ticker/',
        params=kwargs
    )
    response.raise_for_status()
    coin_data = response.json()

    return coin_data.get('data', {}).values()

data = fetch_coin_prices(limit=100, start=0, sort='id')

I am trying to write this data to a Redis HMSET that accepts a dictionary and I only want the properties 'id', 'name', 'symbol', 'rank', 'price' and 'volume_24h'. The price and volume properties are nested and therefore I haven't found a way to get everything in 1 go. My redis hmset needs to store data in key value form where key is the coin id and value is the CSV of the current coin.

hmset = {}
fieldnames = ['id', 'name', 'symbol', 'rank' ,'price', 'volume_24h']
for row in data:
    subset = {}
    subset['id'] = row.get('id', None)
    subset['name'] = row.get('name', None)
    subset['symbol'] = row.get('symbol', None)
    subset['rank'] = row.get('rank', None)
    subset['price'] = row.get('quotes', {}).get('USD', {}).get('price', None)
    subset['volume_24h'] = row.get('quotes', {}).get('USD', {}).get('volume_24h', None)

    if all([subset[key] for key in subset]):
        csv_string = io.StringIO()
        csv_writer = csv.DictWriter(csv_string, fieldnames=fieldnames, extrasaction='ignore' , lineterminator=':')
        csv_writer.writerows(data_subset)
        hmset[subset['id']] = csv_string.getvalue()

This is what I have come up with so far but it looks very ugly in my opinion to access keys. Is there a better way to do this?


texts:
I am learning Racket and implemented a BST insert function (insert tree n) where the format for a BST node is (left-tree value right-tree).

Example

'((() 2 ()) 3 ()) is isomorphic to:

      (3)
  (2)    ()
()  ()

Therefore (insert '((() 2 ()) 3 ()) 4) yields ((() 2 ()) 3 (() 4 ())):

      (3)
  (2)    (4)
()  ()  () ()

Implementation

My implementation feels overly complicated.  For example, I used append with cons so that the right-tree for 3, represented by (), would properly become (() 4 ()) after inserting 4.

How can I approach this problem more elegantly or more functionally?

#lang racket

(define (left tree)
  (list-ref tree 0)
  )
(define (value tree)
  (list-ref tree 1)
  )
(define (right tree)
  (list-ref tree 2)
  )
(define (merge left value right)
  (append (cons left '()) (append (cons value '()) (cons right '())))
  )
(define (insert tree n)
  (cond
    [(empty? tree) (append '(()) (cons n '()) '(()))] ; leaf
    [(> (value tree) n) (merge (insert (left tree) n) (value tree)(right tree))] ; internal - go left
    [(< (value tree) n) (merge (left tree) (value tree) (insert (right tree) n))] ; internal - go right
    [(eq? (value tree) n) tree] ; internal - n already in tree
    )
  )

Update

Given the answer to the question, I updated my code:

(define (insert BST n)
  (cond
    [(empty? BST) ; leaf
     (list empty n empty)]
    [(< n (cadr BST)) ; internal - go left
     (list (insert (car BST) n) (cadr BST) (caddr BST))]
    [(> n (cadr BST)) ; internal - go right
     (list (car BST) (cadr BST) (insert (caddr BST) n))]
    [else
     BST]
    )
  )