texts:
Learn You a Haskell gives an exercise to implement the following function:

-- make a function that simulates tossing a function 3 times
import System.Random

tossCoin3 :: Int -> (Bool, Bool, Bool)
tossCoin3 x =
    let (num1, gen1) = random (mkStdGen x)   :: (Int, StdGen)
        (num2, gen2) = random (gen1)         :: (Int, StdGen)
        (num3, _)    = random (gen2)         :: (Int, StdGen)

    in (convertToBool num1, convertToBool num2, convertToBool num3)
    where convertToBool y = if y `mod` 2 == 0 then True else False

I would've mapped a list of [num1, num2, num3] with the convertToBool, and then convert to a 3-tuple. But then I saw this post.

Please critique my implementation.


texts:
I am trying to implement a class for the Node of a Tree in C++ in order to represent an HTML structure.
It is not complete by a shot, but i'd still like an opinion.

TreeNode.h :

#ifndef TreeNode_H
#define TreeNode_H

#include <string>
#include <vector>

class TreeNode
{
    private:
        std::string textContent;
        std::string tagName;

        TreeNode *parent;

        std::vector<TreeNode *> children;

        int countNodesRec(TreeNode *root, int& count);

    public:
        TreeNode();
        TreeNode(std::string iTextContent, std::string iTagName);

        void appendChild(TreeNode *child);
        void setParent(TreeNode *parent);

        void popBackChild();
        void removeChild(int pos);

        bool hasChildren();
        bool hasParent();

        TreeNode* getParent();
        TreeNode* getChild(int pos);

        int childrenNumber();
        int grandChildrenNum();

        std::string getTextContent();
        std::string getTagName();
};

#endif

TreeNode.cpp :

#include "TreeNode.h"
#include <string>
#include <vector>
#include <iostream>

TreeNode::TreeNode() {};

TreeNode::TreeNode(std::string iTextContent, std::string iTagName) :
    textContent(iTextContent),
    tagName(iTagName),
    parent(NULL)
{}

int TreeNode::countNodesRec(TreeNode *root, int& count)
{
    TreeNode *parent = root;
    TreeNode *child = NULL;

    for(int it = 0; it < parent->childrenNumber(); it++)
    {
        child = parent->getChild(it);
        count++;
        //std::cout<<child->getTextContent()<<" Number : "<<count<<std::endl;
        if(child->childrenNumber() > 0)
        {
            countNodesRec(child, count);
        }
    }

    return count;
}

void TreeNode::appendChild(TreeNode *child)
{
    child->setParent(this);
    children.push_back(child);
}

void TreeNode::setParent(TreeNode *theParent)
{
    parent = theParent;
}

void TreeNode::popBackChild()
{
    children.pop_back();
}

void TreeNode::removeChild(int pos)
{
    if(children.size() > 0) {
        children.erase(children.begin()+ pos);
    }
    else {
        children.pop_back();
    }
}

bool TreeNode::hasChildren()
{
    if(children.size() > 0)
        return true;
    else
        return false;
}

bool TreeNode::hasParent()
{
    if(parent != NULL)
        return true;
    else
        return false;
}

TreeNode * TreeNode::getParent()
{
    return parent;
}

TreeNode* TreeNode::getChild(int pos)
{
    if(children.size() < pos)
        return NULL;
    else
        return children[pos];
}

int TreeNode::childrenNumber()
{
    return children.size();
}

int TreeNode::grandChildrenNum()
{
    int t = 0;

    if(children.size() < 1)
    {
        return 0;
    }

    countNodesRec(this, t);

    return t;
}

std::string TreeNode::getTextContent()
{
    return textContent;
}

std::string TreeNode::getTagName()
{
    return tagName;
}

Sample code :

#include <iostream>
#include <vector>
#include "TreeNode.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

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

    TreeNode *itr = NULL;

    TreeNode *node = new TreeNode("k", "p");
    node->appendChild(new TreeNode("test1", "testag"));
    node->appendChild(new TreeNode("test2", "testag"));
    node->appendChild(new TreeNode("test3", "testag"));

    itr = node->getChild(0);

    itr->appendChild(new TreeNode("test1a", "testtag"));
    itr->appendChild(new TreeNode("test1b", "testtag"));
    itr->getChild(0)->appendChild(new TreeNode("test1aa", "testtag"));

    itr = node->getChild(1);
    itr->appendChild(new TreeNode("test2a", "testtag"));
    itr->appendChild(new TreeNode("test2b", "testtag"));

    itr->getChild(0)->appendChild(new TreeNode("test2aa", "testtag"));

    std::cout<<node->grandChildrenNum();

    return 0;
}


texts: Using CSS grid to align content in a non responsive div

texts:
My job is to supervise a junior developer, but I am mainly a javascript developer and my CSS skills are a bit basic. However, I spotted some things in his CSS code that seem unorthodox to me. He committed some CSS code similar to  the one I post here:

        John
        John is an elephant

            1000 kg
            10 years old

         ...

And the sass:

.label-item {
  margin: .8rem;
  display: grid;
  grid-template-columns: 4.4rem 1fr 1.8rem;
  grid-gap: 0 1rem;
  background-color: grey;
  align-items: center;
  width: 300px;
  height: 80px;
  position: relative;

  .label-image-container {
    width: 50px;
    height: 50px;
    display: inline-block;

    img {
      max-width: 50px;
      max-height: 50px;
      float: left;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      height: auto;
    }
  }

  .label-info {
    display: grid;
    position: relative;
    grid-gap: .3rem;

    .label-name {
      font-size: 1.2rem;
      line-height: 1.5rem;
      height: 1.4rem;
    }
    .description, .size, .age {
      font-size: 1rem;
      display: inline-block;
      float: left;
    }

    .age {
      margin-left: .8rem;
      float: right;
    }
}
  .more-button {
    height: 100%;
    background-color: black;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    grid-row-end: span 1;
  }
}

this is a codepen of this code:
https://codepen.io/anon/pen/QXadMP

My questions are:

a. Is grid positioning appropriate to alight and place elements inside a div that is not the main website container. I know that it works, but is this best practice?

b. Is nested grids considered to be best practice (.label-info inside .label item)?

c. Is using 'display: flex' appropriate to use just to align the content of a div in center?


texts: How can I make this tax calculator cleaner?

texts:
I recently created this Income Tax calculator based off your filing status (Single, or Married Filing Jointly) and which tax bracket you fall into for the 2020 tax year, taking into account the Standard deduction. I know the code is a little robust, but the math checks out as compared to several other tax calculators. I first posted it on Stack Overflow, which I now know was not the place for this, but please give any constructive advice you have.

How can I make this cleaner, as in, accomplish the same task with less code? Or if you have a different/more efficient way of writing any of this, I'm also interested.
Update: Thank you everyone for your advice and input! I'll be taking this back to the whiteboard and making the suggested changes as I learn more. Your time and advice is appreciated, immensely!

marital_status = input("Filing Status (M / S): ")
household_income = int(input("household income: "))

if marital_status == "M":
    standard_deduction = "24800"
    # marrital standard deduction
elif marital_status == "S":
    standard_deduction = "12400"
    # single standard deduction

taxable_income = int(household_income) - int(standard_deduction)

married_bracket_caps = [19750, 80250, 171050, 326600, 414700, 622050]
    # the above rates are the max dollar amount in the Married-filing-joint tax bracket(m/j)
single_bracket_caps = [9875, 40125, 85525, 163300, 207350, 518400]
    # the above rates are the max dollar amount in the filing Single tax bracket

if marital_status == "M":
    bracket = married_bracket_caps
elif marital_status == "S":
    bracket = single_bracket_caps
#if M is entered, the future tax rates will abide by the m/j tax rates; #if
    # S is entered than the taxt rates will abide by the Filing Single tax rates.
    #   ie. enter: M, the first tax rate will be "19750", computed as

if taxable_income <= int(bracket[0]):
    tax = taxable_income * .1
elif taxable_income <= int(bracket[1]):
    tax = (int(bracket[0]) * .1)+(.12*(taxable_income - int(bracket[0])))
elif taxable_income <= int(bracket[2]):
    tax = (int(bracket[0]) * .1)+(.12*(int(bracket[1]) - int(bracket[0])))+(.22 * (taxable_income - int(bracket[1])))
elif taxable_income <= int(bracket[3]):
    tax = (int(bracket[0]) * .1)+(.12*(int(bracket[1]) - int(bracket[0])))+(.22 * (int(bracket[2]) - int(bracket[1])))+(.24 * (taxable_income - int(bracket[2])))

print("taxable income: ", taxable_income)
print("owed in Federal tax: ", tax)

Note: The brackets for this calculator only go up four brackets because if I didn't want to do all the way up if I was going to need to rewrite it anyway. Again, thanks!


texts: Inventories of iPods for different countries

texts:
We were given two countries, namely Brazil and Argentina. Both had one inventory each with 100 iPods in them. The cost of an iPod in Brazil was 100/unit and in Argentina it was 50/unit. But to get iPods form Argentina, you also had to pay 400/10units. Now they give us some number and we had to find out which purchase would be cheaper.

#include<iostream.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
class country
{
  public:
    int name;
    int items,unit;
    float cost,price;

  public:
    country();
    void purchase(std::string,int);
    void setData(int,int,float,float, int);
};
country::country()
{
}
void country::setData(int name,int items,float cost,float price,int unit)
{
  name=name;
  items=items;
  cost=cost;
  price=price;
  unit=unit;
}
void country::purchase(std::string a, int b)
{
  float custCost=0;
  std::cout<<a;
  cout<<"item"<<name;
  if(b<=items)
  {
    items=items-b;
    custCost=cost*b;
    cout<<name<<":"<<items<<":"<< custCost;
  }

}
int main()
{
  country t[2];
  t[0].setData(0,100,100,0,0);
  t[1].setData(1,100,50,400,20);
  std::string a;
  int b,con;
  cout<<"enter the country";
  std::cin>>a;
  cout<<"enter the items needed";
  cin>>b;
  if(a=="brazil")
    con=0;
  else con=1;
  t[con].purchase(a,b);

  getch();
  return 0;
}

It works but I am not totally satisfied with my design as I feel it's too cumbersome. Specifically, if I change the price etc., code changes have to be made.


texts: Improving Fibonacci recursion with BigIntegers

texts:
I've been tasked with making a fast Fibonacci recursive method that uses BigInteger to calculate REALLY big numbers. However, to calculate numbers past 30 it takes almost a MINIMUM of 60 seconds each time. Unfortunately, I have to use some type of recursion in my method even though the iteration way is WAY faster.

public static BigInteger theBigFib(int b) {
        BigInteger[] a = new BigInteger[100000];
        if(b < 2) {
            return BigInteger.ONE;
        }

        if(a[b] != null) {
            return a[b];
        }

        a[b] = theBigFib(b - 1).add(theBigFib(b - 2));
        return a[b];
    }

I have a loop in my main that runs the the method from values 20 to 30.

public static void main(String[] args) {
        final long start = System.nanoTime();
        for (int i = 20; i <= 30; i++) {
            System.out.println(theBigFib(i));
        }
    //  System.out.println(theBigFib(35));  Takes way too long
        final long end = System.nanoTime();
        System.out.println("This program took " + ((end - start) / 1000000000) + " second(s) to run.");
    }

Here are the results from the console. This is from the 2nd time running it which the first time came out to be 443 seconds.

10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
This program took 227 second(s) to run.

I find this topic of recursion and program efficiency to be super interesting so I'm open to all suggestions. Only thing I cannot use is external libraries. :)


texts: Time Limit Exceeds [HS11DIVS] - How to make it faster?

texts:
Here is the question. From SPOJ [HS11DIVS]. Now , the problem is that my code works perfectly for small numbers. But when it comes to Large numbers , the time limit exceeds.
I am not getting any hint on how to make it more efficient. The code is simple enough to understand. I mean its a pretty basic question but difficult to make it efficient.

  For given integers a and b we need to find how many integers in the range [a,b] are divisible by a number x, and have the additional property that the sum of their digits lies in the ,range [l,r] for given l,r.

  Input

  In the first line you're given a and b ( 1 <= a <= b < 10^100 ). In
  the second line you're given three positive integers x ( 1 <= x <= 10
  ), l, r ( 1 <= l <= r <= 1,000 ).

  Output

  In the first and only line output the result modulo 1,000,000,007.

And this is my attempt to the question.

UPDATED :

#include <stdio.h>

int sumOfDigits(int number)
{
  int sum=0;
  while(number!=0)
  {
     sum = sum + (number%10);
     number = number/10;
  }
  return sum;
}

/* UPDATED SEGMENT */

unsigned long long int first(unsigned long long int a,unsigned long long int b,int x)
{
  unsigned long long int m = a%x;
      a = a - m + x;
      return a;
}

int main (void)
{
  unsigned long long int a, b;
  int x, l, r;
  int counter=0,sum;
  scanf("%llu %llu", &a, &b);
  scanf("%d %d %d", &x, &l, &r);
  a = first(a,b,x);   // gives the first number divisible by x.
  while(a<=b)
  {
    sum = sumOfDigits(a);
    if(l<=sum && r>=sum) // check if sum of digits lies b/w l&r.
    {
        counter+=1;
    }
    a+=x;     // increment a by multiples of x.
  }
  printf("%d", counter);
  return 0;
}

Where am i being inefficient? I even calculated the first number divisible by x , and then assign it to a , and then increase a by multiples of x ( a+=x; ).

Here is a sample output :

  Input:
      1 100 5 10 50

  Output:   5


texts:
I was trying to solve this problem.

  Problem Statement

  You are given a pointer to the root of a binary tree. Print the top
  view of the binary tree.  You only have to complete the function.

For example :

     3
   /   \
  5     2
 / \   / \
1   4 6   7
 \       /
  9     8
Top View : 1 -> 5 -> 3 -> 2 -> 7

I figured that the answer could be obtained by keeping on going till the leftmost node recursively and then traverse the tree till the rightmost node from the root.

Although I have managed to solve this problem I feel that my solution is just a little hack and not the best possible solution. The function I had written is

/*
struct node
{
    int data;
    node* left;
    node* right;
};

*/
void top_view(node * root)
{
   static node* temp = root;
   if(root == NULL)
    {
    return;
   }
   top_view(root->left);
   cout<<root->data<<" ";
   if(root == temp)
      {
      root = root->right;//Don't want to print the root element twice
      while(root != NULL)
         {
         cout<<root->data<<" ";
         root = root->right;
      }
   }
}


texts: Shopping cart logic for authenticated users and guests

texts:
I am tasked with cleaning up someone else's Objective-C code, and will admit it is not my language of choice. I am not sure if this is a valid question but was hoping someone could double check my attempt to clean up a method written by someone else, and make sure I didn't miss some minor detail or over simplify the code.

The original method written by someone else

if([[UserManager sharedManager]isUserLoggedIn] && ([APPDELEGATE isCommerceZone]))// Auth and commerce
    {
        [self showPopUpAddToCartOrExpressOrder:NO];

        UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, _addToCartOrExpressOrderView);

    }
    else if([[UserManager sharedManager]isUserLoggedIn] && (![APPDELEGATE isCommerceZone])) // Auth and noncommerce
    {
          [self onModifyItemDone:nil];

    }
    else if (![[UserManager sharedManager]isUserLoggedIn] && ([APPDELEGATE isCommerceZone]))// guest and commerce
    {
        [self showPopUpAddToCartOrExpressOrder:YES];
       UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, _addToCartOrExpressOrderView);

    }
    else if (![[UserManager sharedManager]isUserLoggedIn] && (![APPDELEGATE isCommerceZone]))// guest and noncommerce
    {
        /// Do nothing

    }

My revision

if([APPDELEGATE isCommerceZone])
    {

        [self showPopUpAddToCartOrExpressOrder:![[UserManager sharedManager]isUserLoggedIn]];

        UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification,_addToCartOrExpressOrderView);

    } else if([[UserManager sharedManager]isUserLoggedIn]) // Auth and noncommerce
    {
        [self onModifyItemDone:nil];
    }

In Objective-C, is this the equivalent to saying this boolean equals the opposite of this other boolean?

[self showPopUpAddToCartOrExpressOrder:![[UserManager sharedManager]isUserLoggedIn]];


texts: API with security through a private and public key

texts:
I want to make users login into an app. The code on my server serves a "token". This is based on a salt that is saved for each user, the login date, expDate and the userId. That value is hashed by the main key and that result is sent back to the user. If the app needs some data the token and user ID is sent to the server to decrypt it. Is this a solid approach? The server uses SSL.

public $secret = "898appxp132m}]23E";

function generateApiKey($userId){

    //generate the salt, experation date, and login date
    $salt = base64_encode(openssl_random_pseudo_bytes(128, $secure));
    while(!$secure){
        $salt = base64_encode(openssl_random_pseudo_bytes(128, $secure));
    }

    $loginDate = date("Y-m-d");
    $expDate = date("Y-m-d");

    //insert at the database
    $this->load->model("Api_Model");
    $this->Api_Model->insertApiInformation($userId,$salt,$loginDate,$expDate);

    //generate the actual public key
    $userSalt = $salt . hash("sha512", $userId . $loginDate . $expDate . $salt);

    return hash("sha512", $userSalt . $this->secret . $userId);
}

function verifyApiKey($publicHash, $userId){

    //insert at the database
    $this->load->model("Api_Model");
    $info = $this->Api_Model->getApiInformation($userId);

    //generate the actual public key
    $userSalt = $info[0]->user_token . hash("sha512", $userId . $info[0]->date_login . $info[0]->date_expires . $info[0]->user_token);

    if(hash("sha512", $userSalt . $this->secret . $userId) == $publicHash){
        return $this->generateApiKey($userId);
    } else {
        return false;
    }
}

I have changed my code a bit since the token is guessable. I thought that maybe it's better to change the code on each request when the previous code was valid. And I have used SHA512 for a longer token.


texts: Encapsulating logging and throwing exceptions into a method. Bad practice?

texts:
original code example

if (var1 == null) {
    String msg = "var 1 is null";
    logger.log(msg);
    throw new CustomException(msg);
}
if (var2 == null) {
    String msg = "var 2 is null";
    logger.log(msg);
    throw new CustomException(msg);
}
if (var3 == null) {
    String msg = "var 3 is null";
    logger.log(msg);
    throw new CustomException(msg);
}
return var3.toString(); // ok

new code

if (var1 == null) {
    logMessageAndThrowException("var 1 is null");
}
if (var2 == null) {
    logMessageAndThrowException("var 2 is null");
}
if (var3 == null) {
    logMessageAndThrowException("var 3 is null");
}
return var3.toString(); // NetBeans warn me here for a NPE

void logMessageAndThrowException(String msg) throws CustomException {
    logger.log(msg);
    throw new CustomException(msg);
}

Is this a bad practice or NetBeans just are not able to understand the code?


texts:
I have created a code for filtering a list of strings and redisplaying this list. I check if string is starting with a certain letter.
It seems to work, but I wonder if I did all right? Havent I forgot about something?

public class AlternateRowArrayAdapter extends ArrayAdapter
{
    private int[] colors;
    private List<String> list = null;
    private ArrayList<String> arrayList;

    public AlternateRowArrayAdapter(@NonNull Context context, @LayoutRes int layout,
                                    @IdRes int textViewResourceId, @NonNull List<String> objects)
    {
        super(context, layout, textViewResourceId, objects);
        colors = new int[] {ResourcesCompat.getColor(context.getResources(), R.color.white, null) ,
                            ResourcesCompat.getColor(context.getResources(), R.color.lmsLightGrey, null)};
        this.list = objects;
        this.arrayList = new ArrayList<>();
        this.arrayList.addAll(this.list);
    }
    /**
     * Display rows in alternating colors
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        int colorPos = position % colors.length;
        view.setBackgroundColor(colors[colorPos]);
        return view;
    }

    @Nullable
    @Override
    public Object getItem(int position)
    {
        return list.get(position);
    }

    public void filter(String letter)
    {
        letter = letter.toLowerCase();
        list.clear();
        if (letter == null || letter == "")
        {
            list.addAll(arrayList);
        }
        else
        {
            for (String item : arrayList)
            {
                if (item.toLowerCase().startsWith(letter))
                {
                    list.add(item);
                }
            }
        }
        notifyDataSetChanged();
    }

Also it supposed to be dual color rows - but this part works fine.

I have forgot about this part:

@Override
public int getCount()
{
    return filteredItems.size();
}

Without this in getItem there was an OutOfRangeException


texts: Python implementation for contains pattern in text

texts:
This is an implementation of contains, which returns a boolean indicating whether a pattern occurs in text.

I encountered this question while I was implementing find_all_index. For example, contains('abc', 'b') returns True and contains('abc', 'c') returns True.

I ran the following unit test cases, and it passed against all test cases, so the code seems to be working fine.

Implementation

Test

def contains(text, pattern):
    assert isinstance(text, str), 'text is not a string: {}'.format(text)
    assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)

    """create a pattern variable name """
    pattern = list(pattern)
    p_len = len(pattern)

    clean_text = list(filter(str.isalnum, text))
    t_len = len(clean_text)

    print("Searching contains")
    for i in range(t_len):
        # If the first letter matches, check the rest of string
        if clean_text[i] == pattern[0]:

            for j in range(p_len):
                if i+j >= t_len:
                    return False
                if pattern[j] != clean_text[i+j]:
                    break
                if j == p_len-1:
                    return True

    return False

def test_string_algorithms(text, pattern):
    found = contains(text, pattern)
    print('contains({!r}, {!r}) => {}'.format(text, pattern, found))

def main():
    test_string_algorithms(text, pattern)

if __name__ == '__main__':
    main()


texts: Monty Hall Problem in Javascript ES6 and React

texts:
Any suggestions for optimization are appreciated!

import React, { Component } from 'react';

export default class Trial extends Component {
  constructor(props) {
    super(props);
    this.state = {
      wins: 0,
      losses: 0,
      false_doors: []
    };
    [...Array(1000000)].forEach(() => {
      this.newTrial();
    });
  }
  newTrial() {
    this.state.choices = this.setupChoices();
    this.state.first_choice = this.chooseRandom(0, 2);
    this.state.door_revealed = this.revealDoor();
    this.state.second_choice = this.secondChoice();
    this.state.second_choice === this.state.correct_door ? this.state.wins++ : this.state.losses++;
  }
  setupChoices() {
    switch (this.chooseRandom(0, 2)) {
      case 0:
        this.state.correct_door = 0;
        this.state.false_doors = [1, 2];
        return [true, false, false];
      case 1:
        this.state.correct_door = 1;
        this.state.false_doors = [0, 2];
        return [false, true, false];
      case 2:
        this.state.correct_door = 2;
        this.state.false_doors = [0, 1];
        return [false, false, true];
    }
  }
  chooseRandom(min, max) {
    return Math.floor(Math.random() * (max-min+1) + min);
  }
  revealDoor() {
    if (this.state.first_choice === this.state.correct_door) {
      return this.state.false_doors[this.chooseRandom(0, 1)];
    } else {
      for ( let door of this.state.false_doors ) {
        if ( door !== this.state.first_choice ) { return door; }
      }
    }
  }
  secondChoice() {
    switch (this.props.type) {
      case 'switcher':
        for ( let door of [0, 1, 2] ) {
          if ( door !== this.state.first_choice && door !== this.state.door_revealed ) {
            return door;
          }
        }
      case 'non-switcher':
        return this.state.first_choice;
    }
  }
  render() {
  return (

      {this.props.type}

Wins: {this.state.wins}, Losses: {this.state.losses}

  );
  }
}


texts: Scraping website for book listings, checking if database contains relevant listings, and displaying result in a Django view

texts:
This code works but is very slow.  I am scraping a website for urls for various books, and then checking to see if we have complete records of those books in our database.  After I process the URL to get the book info, I see if we have it in our database.  If we don't, I move on, that's fine.  If we do, I need to check that we have a matching BookTextVer type; that foreign keys to the book, and filters on an attribute from the URL.  If we have it, great; if not, I add it to my list of dictionaries to eventually pass to the django template.

def book_missing(request):
    data = []
    books = book.objects.all()
    sitemap = "www.sitemap.com"
    page = requests.get(sitemap)
    tree = objectify.fromstring(page.content)
    regex = re.compile("books-(\d+)([A-Za-z]+)(\d+)([A-Za-z]+)")
    for node in tree.getchildren():
        book_url = node.book.text
        # e.g. https://www.sitemap.com/fdsys/pkg/books-27hr200nf/content-detail.html
        m = regex.search(book_url)
        object_type_cd = m.groups()[1]  # hr
        book_num = m.groups()[2]  # 200
        book_type = m.groups()[3]  # nf
        try:
            book = books.get(book_num=book_num,
                             object_type_cd_id=object_type_cd.upper())
        except book.DoesNotExist:
            pass
        if (BookTextVer.objects.filter(
            book=book,
            book_text_ver_type__short_name=book_type.upper()).exists()):
            pass  # matching book type exists, no processing needed
        else:
            data.append({"book": object_type_cd.upper() + book_num,
                         "book_type": book_type.upper()})
    context = {
        'data': data,
    }
    return render(request, 'etl/reports/gpo-book-missing.html', context)


texts: Implementing a Stack in Java for a technical interview

texts:
This code is based off the Stack implementation in Chapter 3 of Cracking The Coding Interview. I modified the code to make it compile and give me the correct output. I'd appreciate any feedback on code style and correctness, assuming that I write this code in a technical interview.

The pseudocode from Cracking the Coding Interview, which is implemented using a linked list:

class Stack {

    Node top;

    Object pop() {
        if (top != null) {
            Node item = top.data;
            top = top.next;
            return item;
        }
        return null;
    }

    void push(Object item) {
        Node t = new Node(item);
        t.next = top;
        top = t;
    }

    Object peek() {
        return top.data;
    }
}

My code:

public class Stack {
    Node first;
    Node last;

    public Stack(Node f, Node l) {
        first = f;
        last = l;
        first.next = last;
    }

    public Stack() {
        first.next = last;
    }

    public void push(Object data) {
        if(first == null) {
            first = new Node(data, null);
        }
        else {
            last.next = new Node(data, null);
            last = last.next;
        }

    }

    public Object pop() {
        if(first == null) {
            return -1;
        }
        else {
            Object item = last.data;
            Node cur = first;
            while (cur.next.next != null) {
                cur = cur.next;
            }
            last = cur;
            return item;
        }
    }

    public Object peek() {
        if(first == null) {
            return -1;
        }
        Object item = last.data;
        return item;
    }

    public static void main(String[] args) {
        Stack stack = new Stack(new Node(1, null), new Node(2, null));
        stack.push(3);
        System.out.println(stack.peek() == 3);
        stack.pop();
        System.out.println(stack.peek() == 2);
    }

    private static class Node {
        Object data;
        Node next;

        private Node(Object d, Node n) {
            data = d;
            next = n;
        }
    }
}


texts:
I wrote a function that I use to preprocess pandas dataframes before running them through a machine learning model. The function works perfectly, however I don't think it's the most pythonic way to write it.

This function accepts a list of words:

['here', 'is', 'a','sample', 'of','what','the','function','accepts']

def clean_text(x):

    stopwords_english = stopwords.words('english')

    for i,word in enumerate(x):
        if word.lower() in stopwords_english:
            x[i] = ''
        else:
            for punct in "/-'":
                x[i] = word.replace(punct, ' ')
            for punct in '&':
                x[i] = word.replace(punct, f' {punct} ')
            for punct in '?!.,"#$%\'()*+-/:;<=>@[\\]^_`{|}~' + '“”’':
                x[i] = word.replace(punct, '')
    return x

Here I am using enumerate to change the value inside of the list. I would have assumed a more pythonic way of doing it would be writing it as follows:

def clean_text(x):

    stopwords_english = stopwords.words('english')

    for word in x:
        if word.lower() in stopwords_english:
            word = ''
        else:
            for punct in "/-'":
                word = word.replace(punct, ' ')
            for punct in '&':
                word = word.replace(punct, f' {punct} ')
            for punct in '?!.,"#$%\'()*+-/:;<=>@[\\]^_`{|}~' + '“”’':
                word = word.replace(punct, '')
    return x

The function is being called as follows:

train['question_text'].progress_apply(lambda x: clean_text(x))

Where train is a pandas dataframe and 'question_text' is a column in the dataframe.

Is my current implementation the most pythonic way, or is there a better way?


texts:
I have the following two methods which handle the liking and unliking of posts in my Rails application:

def create
  @post = Post.find(params[:id])
  if @post.present?
    @like = Like.new(user_id: current_user.id, post_id: @post.id)
    if @like.save
      redirect_to post_redirect(@post), :notice => 'Liked!'
    else
      redirect_to post_redirect(@post), :alert => 'An error prevented you from liking this post!'
    end
  else
    redirect_to post_redirect(@post), :alert => 'Invalid post!'
  end
end

def destroy
  @post = Post.find(params[:id])
  if @post.present?
    @like = Like.where(user_id: current_user.id, post_id: @post.id).first
    if @like.destroy
      redirect_to post_redirect(@post), :notice => 'Unliked!'
    else
      redirect_to post_redirect(@post), :alert => 'An error prevented you from unliking this post!'
    end
  else
    redirect_to p, :alert => 'Invalid post!'
  end
end

They both check that the post exists first and then creates or destroys the like record containing the post id and user id and redirects to the post with a message depending on the outcome.

In the Like model I prevent duplicate likes with: validates :user_id, uniqueness: {scope: :post_id}

However the methods feel quite bloated... is there a better way to handle this?


texts: Using Collectors.toList instead of forEach and a new ArrayList

texts:
I have the following Java 8+ code (on Java 14).  I have a (terminal) forEach call and I am adding each mapped object to a newly created ArrayList.
Is there a more idiomatic way this could be rewritten using Collectors.toList() and potentially flatMap?
public List<SearchSuggestion> suggest() {
   List<Watchlist> watchlists = someService.findAll();
   List<SearchSuggestion> suggestions = new ArrayList<>();

   watchlists.forEach(watchlist -> watchlist.getWatchlistItems()
            .forEach(watchlistItem -> {
                suggestions.add(mapToSearchSuggestion(watchlistItem.getInstrument()));
            })
   );
   return suggestions;
}

private SearchSuggestion mapToSearchSuggestion(Instrument instrument) {
    return SearchSuggestion.builder()
            .symbol(instrument.getSymbol())
            .build();
}


texts: Using std::array to implement variadic construction of class with list-of-self as subclass

texts:
I have a situation with a base class for whom a container of itself is a subclass.  So a Block of Item has various ways in which it acts like an Item itself.  I want to be able to initialize Block as Block {foo, baz, bar...} in a variadic syntax.

Here are the twists:

When a Block is constructed, the parameters in the initialization list are not simply Items.  (Imagine some represent two items... while others might just be a different meaning for the literal types passed in.) To simplify the example I am suggesting that constructing an Item from a C-string literal is not available to the user... but that a Block initialization list would know what to do with that in context.
I'm trying to avoid creating std::vector in the course of the initialization, and instead building a std::array for as near-zero runtime overhead as I can get. Each element in the Block initialization should be constructed (or copy constructed) just once in the process; right in place in the array... though this array is only needed temporarily.  As far as I can tell, this rules out std::initializer_list and I must use a variadic function.

The basic idea is to create a class that has containership of an Item which is a friend of Item... here called Listable. It has its own set of constructors:

class Item {
    friend class Listable;
    friend class Block;
    Item (char const *) { std::cout << "Istring\n"; }
    Item (void *, size_t) { std::cout << "Iblock\n"; }
public:
    Item (Item const &) { std::cout << "Icopy\n"; }
    Item (float) { std::cout << "Ifloat\n"; }
};

class Listable {
    Item item;
public:
    Listable (Item const & i) : item (i) { std::cout << "Litem\n"; }
    Listable (const char * s) : item (s) { std::cout << "Lstring\n"; }
    Listable (float f) : item (f) { std::cout << "Lfloat\n"; }
};

class Block : public Item {
protected:
    Block (Listable * l, size_t c) : Item (l, c) { std::cout << "Bpointer\n"; }

    template<size_t N>
    Block (std::array<Listable, N> a) : Block (&a[0], N) { std::cout << "Barray\n"; }

public:
    template<typename... Ts>
    Block (Ts const & ...t) : Block (std::array<Listable, sizeof...(t)>{t...})
        { std::cout << "B\n"; }
};

Here is a usage, showing a string not working for the construction of an Item while the Block knows how to handle it. The goodItem is the only one that needs to be copied, as its original instance was not constructed in-place in an array slot:

#include <iostream>
#include <array>

/* #include the classes above */

int main() {
    auto goodItem = Item {10.20};
    auto goodBlock = Block {goodItem, "blue", "red", 3.04};
    /* auto misplacedItem = Item {"purple"}; */     // errors, correctly...
}

I compiled with no warnings with:

  g++ -pedantic -Wall -Wsign-conversion -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror -Wno-unused --std=c++11 test.cpp -o test

This output is what I wanted to see:

Ifloat
Icopy
Litem
Istring
Lstring
Istring
Lstring
Ifloat
Lfloat
Iblock
Bpointer
Barray
B

Can anyone spots any problems or suggestions for improvement on this technique?


texts: Function to remove specified html tags from string

texts:
I recently wrote this function that, when supplied a string and an array of element types, will remove those element types from the string.

As you could imagine this is a very very simple function, but I wanted to get opinions on speed, functionality, and any other comments anyone can come up with that can improve this function.

<?

    $str = <<<STRING
        Chocolate is very
Chocolate
!
        England is very
City
!
        England is my
city

        England is my
city

        England is my city
        Name

STRING;

    echo htmlentities(removeTags($str, array("b", "div", "span")));

    function removeTags($str, $tags) {

        $tagsString = "";
        foreach($tags as $key => $v) {
            $tagsString .= $key == count($tags)-1 ? $v : "{$v}|";
        }

        $patterns = array("/(<\s*\b({$tagsString})\b[^>]*>)/i", "/(<\/\s*\b({$tagsString})\b\s*>)/i");
        $output = preg_replace($patterns, "", $str);

        return $output;

    }

?>


texts: Is it a valid use case of using java.util.MissingResourceException?

texts:
I have a factory method that returns an Object based on a argument passed to it :

public class Factory {
   private Map<String,CustomObject> objectMap;

   public CustomObject getObject(String key){
       if(objectMaps.containsKey(key)) return objectMap.get(key);
       throw new MissingResourceException("Object not found",CustomObject.class.getName(),key);
   }
}

I wanted an opinion on whether the use of java.util.MissingResourceException is valid. I don't want create a custom exception for above scenario. I want to use one of the existing ones. If possible which other existing exception can be used in above case. I was thinking of IllegalStateException,but it didn't seem the right choice.


texts: Transform a vector with the FFI in Haskell

texts:
In Haskell, I want to apply a transformation to each element of a vector using the FFI. I am rather ignorant in C, I am more or less novice in Haskell and this is the first time I use storable vectors in Haskell.

This is what I did, taking the transformation \x -> x+1 as an example. The C file:

double* bar (int n, double *arr){
    double* y;
    y = (double*) calloc(n, sizeof(double));
    for(int i=0; i<n; i++)
      y[i] = arr[i]+1;
    return y;
}

The Haskell code:

import Foreign.C.Types
import Foreign (newForeignPtr)
import qualified Data.Vector.Storable as SV

foreign import ccall "bar" c_bar :: CInt -> Ptr CDouble -> Ptr CDouble

haskellBar :: SV.Vector CDouble -> IO (SV.Vector CDouble)
haskellBar sv = do
    let n = SV.length sv
    ptr <- SV.unsafeWith sv (return . (c_bar (fromIntegral n)))
    fptr <- newForeignPtr_ ptr
    return $ SV.unsafeFromForeignPtr0 fptr n

This works, but as I'm almost ignorant in C and new to storable vectors, I really don't know whether it's a good way and I would appreciate some advice.

I'm also new to the FFI by the way, and I don't know if I should write foreign import ccall safe/unsafe (I have not understood the role of safe/unsafe), or whether safe/unsafe is useless here.


texts:
I am trying to build object identity in PHP so that when I have a collection of objects, each one can have a string as identifier and all of these identifiers are afterwards combined to form an unique md5 to represent the "identity of a collection".

Why? So that I can choose to skip re-execution of code when it's not needed:

interface SomeTestInterface
{
    public function testFunction();
}

abstract class Identifiable
{
    public function __toString()
    {
        $identity_shards = array_merge( get_object_vars( $this ), class_implements( $this ) );

        $identity_string = '';

        foreach( $identity_shards as $identity_shard_key => $identity_shard_value ) {
            $identity_string .= (string) $identity_shard_key . (string) json_encode( $identity_shard_value );
        }

        return md5( get_class( $this ) . $identity_string );
    }
}

class SomeBaseClass extends Identifiable implements SomeTestInterface
{
    public function __construct( $number )
    {
        $this->number = $number;
        $this->thing = 'a';
        $this->other_thing = ['a','b','c',1,2,3,];
    }

    public function testFunction()
    {
        return 'a';
    }
}

This is testable with:

for( $i = 1; $i < 10000; $i++ ) {
    $class = new SomeBaseClass( $i );
    (string) $class;
}

For me, PHP 7.3 and WordPress, this takes ~100ms to execute.

My micro-decisions:

I need json_encode on $identity_shard_value because you can't cast an array to string, for example. json_encode is both fast in my experience and knows how to deal with it all.
I chose to make this an abstract class because json_encode doesn't have access to scoped classes, as such, it cannot encode what it can't find, so I must be able to access $this though it's weird because even in the abstract class, I still can't encode it, but I should be able to.

My main concerns with this is if I really need all these items to build my object identity or if there's another, faster way. 10000 objects in 0.1ms, although very good on its own, doesn't necessarily scale.

In essence, every single object that implements Identifiable in a collection that a module of my framework has will have an identity that I will then combine into a final "collection identity" to later do a check such as:

$collection_identity = getCollectionIdentity( $collection ); //MD5 computed from the identity of all these objects

if( $collection_identity != getCollectionIdentityByName( 'some_collection' ) {
    setCollectionIdentity( 'some_collection', $collection_identity );
    //re-execute code
} else {
 retrieveDataFromStorage();
}

As you can see, it checks if there was a change to the objects / collection and if so, it re-executes all the other code, but if not, it just retrieves what that "other code" generated in the past and as such, this is a way to use persistent storage to skip execution of heavy code.


texts:
I need help identifying any significant design issues with some code I have generated to track status updates.

I have a big task A which contains multiple small tasks and each of these small tasks updates the status of A in the data store.

This is how I've implemented:
For each type of Task A(A can be of multiple types), I'll create an enum class implementing the interface  StatusTask given below.

And then, I'll call StatusTask.Chain.start(starting enum object, param);

public interface StatusTask<T, V extends Enum<V> & StatusTask<T,V>>
{
    public V execute(T t) throws Exception;

    public void fail(Exception e) throws Exception;

    public static class Chain
    {
        public static <T,V extends Enum<V> & StatusTask<T,V>> void start(V v, T t)
        {
            V n = null;
            try
            {
                n = v.execute(t);
            }
            catch(Exception e)
            {
                v.fail(e);
            }

            if(n == null || n == v)
            {
                return;
            }

            start(n, t);
        }
    }
}

Do you see any significant flaws with this design?
Is there a better design to handle such a scenario?

Example Scenario: Fetching a file and processing it. Following are the task-status:
(0. Initial task. Move to Task 1.)

Send Request and mark status as Sent Request
Successful Response Received and mark status as Response Received and move to task 4
Error Response Received and mark status as Response Received
If file present, then mark status as Processing and execute step 4 else step 5
Mark status as File not available and exit
Parse file. If no error, goto step 7 else step 8
Mark status as File parsing succeeded and do something.....
Mark status as File parsing failed and exit


texts: Batch Gradient Descent running too slowly


texts: Shifting records in SQL Database while sorting with algorithm

texts:
I have a table in a SQL Server database, which holds information of some images, and the relevant gallery of them. The columns are like:

ImageId, GalleryId, Order

I have a unique key on GalleryId-Order columns, that is, each image should have a unique order in its gallery.

A business requirement is to change the place (order) of an image, inside the gallery. For example, image at the order of 16, might be replaced at the new order 7. However, all the images should shift, if necessary, to provide space for this sorting operation. In this example, images with the order 7, 8, 9, ..., 15 should shift forward one level, so that the place 7 would become empty for the mentioned image.

I've written a procedure for this:

create procedure MoveImage(@imageId int, @newOrder int)
as
begin
    -- Finding the related gallery
    declare @galleryId int;
    select @galleryId = GalleryId
    from Images
    where ImageId = @imageId

    -- Finding the count of images inside this gallery
    declare @mediaCount int;
    select @mediaCount = COUNT(ImageId)
    from Images
    where GalleryId = @galleryId

    -- Finding the current order of the image
    declare @currentOrder int;
    select @currentOrder = [Order]
    from Images
    where ImageId = @imageId

    -- Temporary shifting the current media to one order above all, to bypass the 'Each Media Should Have a Unique Order in its Gallery' unique index
    update Images
    set [Order] = @mediaCount + 1
    where ImageId = @imageId

    -- Shifting all media of the gallery between the current order and the new order, one order forward, or backward
    if @newOrder < @currentOrder
    begin
        update Images
        set [Order] = [Order] + 1
        where GalleryId = @galleryId and [Order] >= @newOrder and [Order] <= @currentOrder
    end
    else
    begin
        update Images
        set [Order] = [Order] - 1
        where GalleryId = @galleryId and [Order] <= @newOrder and [Order] >= @currentOrder
    end

    -- Inserting the image at the specified order
    print @newOrder
    update Images
    set [Order] = @newOrder
    where ImageId = @imageId
end
go

It works, just fine (at least as much as I've tested it). However, I don't feel Okay with this procedure, I think it might become easier and more effective. Can anyone improve this T-SQL code?

PS: parameters are checked before being passed to this procedure, so presume that there is nothing wrong with parameters, like negative @newOrder, etc.


texts:
I hava a question similiar with mege in Python but I am trying to write Java code.
Here is my code:
The input is: The first line - a number of arrays (k); Each next line - the first number is the array size, next numbers are elements.

Max k is 1024. Max array size is 10*k. All numbers between 0 and 100. Memory limit - 10MB, time limit - 1s. Recommended complexity is k ⋅ log(k) ⋅ n, where n is an array length.

Example input:

4
6 2 26 64 88 96 96
4 8 20 65 86
7 1 4 16 42 58 61 69
1 84

Example output:

1 2 4 8 16 20 26 42 58 61 64 65 69 84 86 88 96 96

I get memory limit errors.
I use System.gc() to clear the memory but I recieve timeout error

Here is my code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TaskFSolution {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int k = Integer.valueOf(reader.readLine());

        short[][] arrays = new short[k][];

        int arrayLength = 0;
        int[] minPositionInArrays = new int[k];
        for (int i = 0; i < k; i++) {
            String str = reader.readLine();
            String[] elements = str.split(" ");
            arrays[i] = new short[Short.valueOf(elements[0]) + 1];
            for (int j = 0; j < elements.length; j++) {
                arrays[i][j] = Short.valueOf(elements[j]);
            }
            arrayLength += Short.valueOf(elements[0]);
            minPositionInArrays[i] = 1;

            if (arrayLength % 100 == 0) {
                System.gc();
            }
        }

        reader.close();

        StringBuilder sb = new StringBuilder();
        int currentArrayNumber = 0;
        int currentPositionInArray = minPositionInArrays[currentArrayNumber];
        while (arrayLength > 0) {
            short currentMinValue = 101;
            for (int i = 0; i < k; i++) {
                if (minPositionInArrays[i] <= arrays[i][0] && currentMinValue >= arrays[i][minPositionInArrays[i]]) {
                    currentMinValue = arrays[i][minPositionInArrays[i]];
                    currentArrayNumber = i;
                    currentPositionInArray = minPositionInArrays[i] + 1;
                }
            }
            sb.append(currentMinValue + " ");
            minPositionInArrays[currentArrayNumber] = currentPositionInArray;
            arrayLength--;
        }

        System.out.println(sb.toString().trim());
    }
}


texts: Changing html element with click event: how to restore default state of element using jQuery if/else statement

texts:
I have a click event that calls a function (below, txtResize) which makes some CSS changes to html text. (Acts on Text of 3 unique elements).

Q: What is the best way to refactor this code to limit excessive if/else usage, AND restore the original state of ALL text elements once the user clicks away from this section?

Here is the partially working, ugly function:

 function txtResize() {

        var clicked = this.id;

        if (clicked == "Text1")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text2, #Text3").css("opacity", "0.2");
        }
        else if (clicked == "Text2")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text1, #Text3").css("opacity", "0.2");
        }
        else if (clicked == "Text3")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text1, #Text2").css("opacity", "0.2");
        }
         // code above is ok, below does not work

        else if ( !(clicked == "Text1") && !(clicked == "Text2") && !(clicked == "Text3") )
        {
            $("#Text1, #Text2, #Text3").css("opacity", "1");  // return to default state
        }

 };


texts: Implementing a Simple "MoneyAccount" in CoffeeScript

texts:
Please critique this CoffeeScript code. Is it idiomatic?

MoneyAccount = (balance = 0) ->
  obj = {
    withdraw: (x) ->
      if balance < x
        throw new Error("not enough funds in account")
      else
        balance -= x
        console.log "withdrew funds."
        x
    deposit: (x) ->
      if (typeof x isnt 'number' || x < 0)
        throw new Error("bad deposit amount " + x)
      else
        balance += x
    printBalance: ->
      console.log balance
  }
  obj


texts:
I have been trying to learn c++ for the sake of being comfortable with a second language. I found a project that seemed relatively easy, although it may not be implemented perfectly, it was a simple project.
I create a std::map<double, std::string>, which will represent the tax rate as a double, and the required income as a string. A user will input their income and the maximum amount of taxes to be paid in dollars will be returned. Here is the code:
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <map>
#include <iomanip>

double TaxesDue(double &income);
double HighestRate(double &income);

std::map<double, std::string> taxRate =
{
    {  0.35, "499999" },
    {0.31, "349999"},
    {0.25,"249999"},
    {0.21,"169999"},
    {0.18,"119999"},
    {0.14,"79999"},
    {0.10,"44999"},
    {0.05,"29999"}
};

int main()
{
    double income;

    std::cout << "Enter your income: " << std::endl;
    std::cin >> income;

    double taxesDue = TaxesDue(income);
    std::cout << taxesDue << std::endl;
}

double TaxesDue(double &income)
{
    double totalTaxes = 0.0;
    double taxDiff = 0.0; //as taxes are calculates, subtract the income

    double highestRate = HighestRate(income);

    for (double i = income; i > 29999; )//knowing the lowest tax rate is 0.05
    {
        taxDiff = (income - std::stod(taxRate[highestRate]));
        totalTaxes += (highestRate * taxDiff);
        i -= taxDiff;
        highestRate = HighestRate(i);
    }

    return totalTaxes;
}

double HighestRate(double &income)
{
    /*
    std::map<double, std::string> taxRate =
    {
        {  0.35, "499999" },
        {0.31,"349999"},
        {0.25,"249999"},
        {0.21,"169999"},
        {0.18,"119999"},
        {0.14,"79999"},
        {0.10,"44999"},
        {0.05,"29999"}
    };
    */

    if (income > std::stod(taxRate[0.35]))
    {
        return 0.35;
    }
    if (income > std::stod(taxRate[0.31]))
    {
        return 0.31;
    }
    if (income > std::stod(taxRate[0.25]))
    {
        return 0.25;
    }
    if (income > std::stod(taxRate[0.21]))
    {
        return 0.21;
    }
    if (income > std::stod(taxRate[0.18]))
    {
        return 0.18;
    }
    if (income > std::stod(taxRate[0.14]))
    {
        return 0.14;
    }
    if (income > std::stod(taxRate[0.10]))
    {
        return 0.10;
    }
    if (income > std::stod(taxRate[0.05]))
    {
        return 0.05;
    }

    return 0.0;
}

My biggest thing is trying to improve the HighestRate(double &income) method. How should I convert the if (income > std::stod(taxRate[x])) to make the code better? Meaning, are there any libraries that I could use to find 'where value > then this std::map value'?
Also I think that I should probably change the std::map<double, std::string> to std::map<double, double>.


texts:
Out of curiosity I was discovering the potential of the Ellipsis object in Python (...), and I discovered it doesn't do a whole lot except for a handful of minor features. In an effort to make it useful, I decided to create the most fancy-pants constructor for a list that I could.

The function, super_list, takes an arbitrary number of arguments to be added to the list. Here are the features:

super_list(multiple, arguments, provided) -> Generates a list using the arguments provided. If an argument doesn't follow any of the special features below, it is just appended to the array at the proper nesting level. This example returns [multiple, arguments, provided], a list of the arguments.
super_list(5, ..., 9) -> Takes advantage of the Ellipsis object to create something that looks like "x to y", or a range. This particular example would produce a list containing [5,6,7,8,9], the number between 5 and 9.
super_list(arg, array.move_up, higher_arg, array.move_down, lower_arg) -> Sets the nesting level inside the list. Including array.move_up or array.move_down moves up or down one level of nesting in the list. This example produces [arg, [higher_arg], lower_arg], moving up and down the array chain with array.move_up and array.move_down.

One last big example:

super_list("first level", 5, ..., 9, array.move_up, array.move_up, "second level", 10, ..., 15, array.move_down, "down one level")

produces

['first level', 5, 6, 7, 8, 9, [['second level', 10, 11, 12, 13, 14, 15], 'down one level']]

So this is my current implementation:

def get_in_list(lst, indexes):
  """Gets an item in a nested list by a list of indexes."""
  return functools.reduce(operator.getitem, indexes, lst)

def super_list(*args):
  """Special initialization syntax for lists."""
  curr_index = []
  result = []
  for index, item in enumerate(args): # Iterate over args with indexes
    el_type = type(...) # Type of the Ellipsis object
    if isinstance(item, el_type): # Case: Ellipsis range generator
      if index == 0:
        get_in_list(result, curr_index).append(item)
      else:
        get_in_list(result, curr_index).extend(list(range(args[index-1]+1, args[index+1])))
    elif item == array.move_up: # Case: move up one level in list
      get_in_list(result, curr_index).append([])
      curr_index.append(len(get_in_list(result, curr_index))-1)
    elif item == array.move_down: # Case: move down one level in list
      try:
        curr_index.pop()
      except IndexError: # Silently catch if user tries to move down too far in the list
        pass
    else: # Case: No special syntax - regularly append item to list
      get_in_list(result, curr_index).append(item)
  return result

get_in_list is a function used to get an item at a list of indexes. This means that a[0][1] == get_in_list(a, [0, 1]).

My questions:

Is it too messy?
Is anything too long and could be implemented in a shorter way?
Is the program too confusing, and do you think it could be more verbose?

And obviously, any other comments you may want to add are appreciated. Thanks in advance!


texts:
This is some prototype code for a spin-lock for my toy operating system.  Bear in mind this means there are no standard library routines to fall back on.  It's also for C++11 compilation and will only ever be compiled by the GNU G++ compiler.

The primary use for this is in the scheduler and other code that accesses the process table.

I think there are lots of ways of getting this wrong, and some of them aren't obvious. So it'd be great to have a second pair of eyes on it.

Firstly the locking code itself in NASM x86 asm:

; *******************************
; void spin_lock(uint32 * p);
;
global __kspin_lock
__kspin_lock:
    push ebp
    mov ebp, esp        ; we might as well the the stack frame right?

    mov eax, [ebp + 8]  ; eax contains address of uint32 used for the lock
    mov ecx, 1

.tryacquire             ; try and get the lock.
    xchg ecx, [eax]
    test ecx, ecx
    jz .acquired        ; if the lock wasn't 0 (unlocked) repeat.

.pauseloop
    pause               ; see 'About PAUSE' below
    test dword [eax], 1
    jne .pauseloop
    jmp .tryacquire

.acquired
    pop ebp
    ret

And secondly a class that wraps it a little.  (I will eventually then wrap this with an RAII class to release the lock automatically when it goes out of scope).

#pragma once
#include <std_types.h>

extern "C" {
/** These routines probably shouldn't be used directly. */
void __kspin_lock(uint32 *p);
};

/**
 * SpinLock provides a crude locking mechanism based around an atomic
 * exchange of a variable in memory.
 *
 * The SpinLock loops, swapping the value 1 for the value in lock.
 * Each time it checks to see if the value retrieved from lock is now 0,
 * if it is it knows that lock now contains 1, and it holds the lock.
 *
 * To ensure all spinlocks reside in a unique cache line the spinlock
 * is aligned to 64 bytes and is 64 bytes in size.  This avoids two
 * processes competing for ownership of the same 64 byte cache line,
 * which could be bad for performance.
 */
class __attribute__((aligned(64))) SpinLock
{
public:
    SpinLock()
        : lock_value(0)
    {}

    void lock()
    {
        __kspin_lock(&lock_value);
    }

    void release()
    {
        __kspin_lock_release(&lock_value);
    }

private:
    static void __kspin_lock_release(uint32 *p)
    {
        *p = 0;
    }

    /* Difficult to know whether it makes sense to copy a spinlock.
     * It might be practical to copy it but always 0 the lock for
     * the copy. */
    SpinLock(const SpinLock &) = delete;
    SpinLock & operator=(const SpinLock &) = delete;
    /* padded to ensure it's on a unique cache line. */
    uint32 lock_value;
    char reserved[64 - sizeof(uint32)];
};

I also think this code could use some through tests, especially on performance, but that might be rather a case of profiling in place in the kernel.  Any suggestions welcome.

Incidentally - I'm also thinking that it's going to be useful to add some additional debugging and profiling features to the code.  For example, and probably only while running a debug build:

How frequently was the lock contended.
Which thread owns the lock.
Is the lock held by this thread (this would allow functions to check that the lock is held by a calling function properly).


texts:
(I originally asked this on Stack Overflow and was directed here)

So I have 2 classes, one is a PyQT window widget, and the other class is a stack which holds a dictionary pointing to all of the window objects.

Log Window:

from PyQt5.QtWidgets import QTreeView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from Log.Controllers.Routines.log_get_next_default_index_routine import get_next_nefault_index

class LogWindow(QTreeView):
    def __init__(self,
                 model=None,
                 index=get_next_default_index(),
                 title=None):

        super().__init__()
        self.model = model
        self.index = index
        self.title = title
        self.set_title(title)

    def set_model(self,model):
        if model is not None:
            self.model = model
        else:
            self.model = QStandardItemModel()
        self.setModel(self.model)

    def set_index(self,index):
        if index is not None:
            self.index = index
        else:
            self.index = log_coordinator.get_next_default_index()

    def set_title(self,title):
        if title is not None:
            self.setWindowTitle(title)
        else:
            self.setWindowTitle('Log Window %s' % self.index)

Log Stack:

class LogWindowStack():
    def __init__(self,index=None,log_window=None, log_window_bundle=None):
        self.stack = {}
        self.default_index_counter = 0

        self.populate_index(index,log_window,log_window_bundle)

    def populate_index(self,index,log_window,log_window_bundle):
        if index or log_window is not None:
            self.stack[index] = log_window
        elif log_window_bundle is not None:
            for index,log_window in log_window_bundle:
                self.stack[index]=log_window

    def increment_default_index_counter(self):
        self.default_index_counter = ++self.default_index_counter

There is also a controller which both creates, modifies, and passes values to the constructors of these 2 classes.

Log Controller/Coordinator:

from Log.Controllers.Routines.log_insert_log_entry_routine import insert_log_entry
from Log.Objects.log_entry_obj import LogEntry
from Log.Objects.log_window_obj import LogWindow
from Log.log_window_stack_instance import log_window_stack

def create_log_windows(log_window_indexs):
    log_window_bundle = {}
    if log_window_indexs is not None:
        for index in log_window_indexs:
            log_window_bundle[index] = LogWindow(index=index)
    return log_window_bundle

def create_log_entry(log_entry):
    return LogEntry(log_entry)

def insert_assigned_log_entries(log_window_entry_bundle=None):
    if log_window_entry_bundle is not None:
        for log_window_index,log_entry in log_window_entry_bundle.items():
            insert_log_entry(log_window_index,log_entry)

def distribute_log_entries(log_window_indexs=None,log_entries=None):
    if log_window_indexs or log_entries is not None:
        for index in log_window_indexs:
            for log_entry in log_entries:
                insert_log_entry(index,log_entry)

def push_to_log_window_stack(log_window_bundle):
    for index,log_window in log_window_bundle.items():
        log_window_stack.stack[index] = log_window

def present_log_window_stack(log_window_indexs):
    for index in log_window_indexs:
        log_window_stack.stack[index].show()

def window_index_exists(log_window_index):
    key_exists = False
    for key in log_window_stack.stack.keys():
        if log_window_index == key:
            key_exists = True
    return key_exists

Does this design look sloppy or riddled with potential errors down the line? How can I improve it?


texts: A very small crawler created using class

texts:
I've created a crawler using class. This crawler is able to scrape a certain webpage. Total data out there is 249 and the data are displayed there through different pages. I tried to make it accurately. Here is what I did.

import requests
from lxml import html

class wiseowl:

    def __init__(self, start_url):
        self.start_url = start_url
        self.links = [self.start_url]    # a list of links to crawl
        self.storage = []

    def crawl(self):           # calling get_link for every link in self.links
        for link in self.links :
            self.get_link(link)

    def get_link(self,link):
        print('Crawling: ' + link)
        url = "http://www.wiseowl.co.uk"
        response = requests.get(link)
        tree = html.fromstring(response.text)
        for items in tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']"):
            name = items.xpath(".//a/text()")[0]
            urls = url + items.xpath(".//a/@href")[0]
            docs = name , urls
            self.storage.append(docs)
            next_page = tree.xpath("//div[contains(concat(' ', @class, ' '), ' woPaging ')]//*[@class='woPagingItem' or @class='woPagingNext']/@href")    # get links form 'woPagingItem' or 'woPagingNext' #
            for npage in next_page:
                if npage and url + npage not in self.links :    # avoid getting the same link twice
                    self.links += [url + npage]

    def __str__(self):
        return "{}".format(self.storage)

crawler=wiseowl("http://www.wiseowl.co.uk/videos/")
crawler.crawl()
for item in crawler.storage:
    print(item)


texts: Minimal stack from unsigned int to track boolean values wtih bits

texts:
This grew out of a need to track sequential ctrl+shift+Left/Right-arrow keypress events on a gtk editor. It is a small stack implementation for boolean values (for LEFT, RIGHT) that uses the bits of a predefined array of unsigned for storage. The amount of storage is determined by the constant STKMAX which simply specifies the number of unsigned elements in the array. The reason for using this as opposed to some builtin GtkStack, etc. was simply for storage efficiency where only 32+ bits were needed, compared to Gtk's traditional over-allocation for minimal data structures.

Here, I'm not that concerned with whether I used unsigned where uint32_t would be better, but more whether there is anything inherently wrong with packing bits and indexing the various array elements that make up the stack storage that I may be overlooking. I've thought through it and the logic and implementation seems sound -- but I could have easily missed something that will come back to bite me.

With that, here's the code and a short driver that intentionally attempts to add more than the stack will hold to validate stack-full behavior:

#include <stdio.h>

#ifndef CHAR_BIT
# define CHAR_BIT  8
#endif

enum { LEFT, RIGHT, STKMAX = 4 };

typedef struct {
    unsigned int kp[STKMAX], idx;   /* array for stack, bit-index */
} selstack;

/** zero the stack values */
void stack_clear (selstack *s)
{
    s->idx = 0;
    for (int i = 0; i < STKMAX; i++)
        s->kp[i] = 0;
}

/** stack_push set bit at index to 0 or 1 based on v.
 *  increment bit-index after setting bit.
 */
int stack_push (selstack *s, int v)
{
    /* total bits, bits per-array-element, array index */
    unsigned arrbits = (sizeof s->kp) * CHAR_BIT,
        elebits = (sizeof s->idx) * CHAR_BIT,
        arridx = s->idx/elebits;

    if (s->idx == arrbits) {
        printf ("stack full, index: %u\n", s->idx);
        return 0;
    }

    if (v)  /* set bit at index */
        s->kp[arridx] |= (1u << (s->idx % elebits));
    else    /* clear bit at index */
        s->kp[arridx] &= ~(1u << (s->idx % elebits));

    return ++s->idx;
}

/** stack_pop - decrement index, get bit at index, clear bit. */
int stack_pop (selstack *s)
{
    if (!s->idx) {
        printf ("stack empty, index: %u\n", s->idx);
        return -1;
    }

    /* number of bits per-array-element, decrement index */
    unsigned elebits = (sizeof s->idx) * CHAR_BIT,
        arridx = --s->idx/elebits,
        /* get bit value at index */
        v = (s->kp[arridx] >> (s->idx % elebits)) & 1;

    /* zero bit at index */
    s->kp[arridx] &= ~(1u << (s->idx % elebits));

    return v;
}

/** stack_last - get bit for last pushed value. */
int stack_last (selstack *s)
{
    if (!s->idx) {
        printf ("stack empty, index: %u\n", s->idx);
        return -1;
    }

    /* number of bits per-array-element, computed index */
    unsigned elebits = (sizeof s->idx) * CHAR_BIT,
        arridx = (s->idx - 1)/elebits;

    /* return bit at index */
    return (s->kp[arridx] >> ((s->idx - 1) % elebits)) & 1;
}

int main (void) {

    int v;
    selstack s;
    stack_clear (&s);

    for (int i = 0; i < 132; i++)
        if (i < 32 || (64 <= i && i < 96))
            stack_push (&s, RIGHT);
        else
            stack_push (&s, LEFT);

    while ((v = stack_pop (&s)) >= 0)
        printf ("popped[%3u] : %s\n", s.idx, v ? "RIGHT" : "LEFT");

    return 0;
}

Let me know if there are any gotchas I'm not picking up on.


texts: Populating a view showing data from user contacts

texts:
I am using a QSqlRelationalTableModel model_contacts to populate a view that shows all necessary data from the contacts of the user.

Today, I need to add a QPushButton that generates a list of all contacts that do not have an email address.

I try to replicate the Model-View approach as much as possible, but the function of this QPushButton seems so straightforward to me, that I am tempted to simply use a QSqlQuery SELECT * FROM t_contacts WHERE email IS NULL OR email = '';.

Am I making a mistake?

In the constructor:

model_contacts = new QSqlRelationalTableModel(ui->contactsTable);
model_contacts->setEditStrategy(QSqlTableModel::OnManualSubmit);
model_contacts->setTable("t_contacts");

// Populate the model
if (!model_contacts->select())
{
    showError(model_contacts->lastError());
    return;
}

ui->contactsTable->setModel(model_contacts);

Function for QPushButton:

void on_pushButton_contactsWithoutEmail_clicked()
{
    qDebug() << "create CSV-file with all contacts that have no emailaddresses";

    // TODO: how to do this in the Model/View approach?

    QSqlQuery query;
    query.exec("SELECT name, address FROM t_contacts WHERE (email IS NULL OR email = '')");
    while (query.next())
    {
        int i = 0;
        QString name = query.value(i++).toString();
        QString address = query.value(i++).toString();
        qDebug() << name << address;
    }
}


texts: creating a concreate implemetation inside a method

texts:
I have this code:

public bool IsWorkAddedWIthConcreteImplementation()
{
    SomeAgentClass agentClass = new SomeAgentClass();
    bool param1 = true;
    string param2 = "Hello";
    DataTable dt1 = agentClass.ProvideData(param1, param2);
    SimpleDAl da = new SimpleDAl();
    DataTable dt = da.ProvideData(dt1);
    bool isDataSentSuccessfully = agentClass.SendDataToClient(dt);
    IUnImplementedInterface dalInterface = new SimpleDAl();
    if (dalInterface.ReturnMeTrue(dt1))
    {
        return true;
    }
    else
    {
        return false;
    }

}

And the implementation

 IUnImplementedInterface dalInterface = new SimpleDAl();

Should I have passed the interface as a parameter to method or in the class constructor?
What will happen to the method signature or class constructor signature if more interfaces are introduced ?

Update:

In the actual implementation new SimpleDal() class is replaced by DaFactory.GetUnImplementedInterface(), which is returning me the concrete instance of IUnImplementedInterface.

Now the DaFactory is using Activator.CreateInstance() in order to give me correct instantiation.

Update2

One thing I forgot to tell was, that I am passing the DaFactory instance in the constructor of this class, and later using this factory instance to create concrete IUnImplementedInterface instance.

Update3 and Solution

Finally my code structure will now be having a IUnImplementedInterface instance in the class rather than the Factory instance.So now the caller of this class will have to pass the correct concrete implementation of this interface in its constructor.


texts:
Microcontroller receive data on uart and call parser_i2c function when user presses enter
e.g. parser_i2c(I2C scan)
I want to parse following input from user communicated through uart
I2C scan
I2C read read_adress
I2C Write Write_address data
I have wrote following code
        void parser_i2c(unsigned char str[20])
    {
       //unsigned char str[20]
       unsigned char s[2] = " ";
       unsigned char *token;
       unsigned char output[10][10] ;
        U8 i_i2c=0;
       /* get the first token */
       token = strtok(str, s);

       /* walk through other tokens */
       while( token != NULL ) {
      //    printf( " %s\n", token );
        strcpy(output[i_i2c],token);

         i_i2c++ ;
          token = strtok(NULL, s);

       }
     if(!(strcmp(output[0],"I2C")))
      {
         if(!(strcmp(output[1],"READ")))
            {
                if(*output[2]!='\0')
                {
                i2c_read(output[2]) ;
                }
                else{

                        printf(COLOR_RED "Bad command" COLOR_RESET);

                }
            }
         else if(!(strcmp(output[1],"WRITE")))
         {
            if(((*output[2])||(*output[3]))!='\0')
            {
            i2c_write(output[2],output[3]);
            }
            else{

                        printf(COLOR_RED "Bad Command" COLOR_RESET);

            }
         }

         else if(!(strcmp(output[1],"SCAN")))
         {
         i2c_scan();
         }
         else{

                        printf(COLOR_RED "Bad Command" COLOR_RESET);

         }

      }
      else {
                            printf(COLOR_RED "Bad Command" COLOR_RESET);

      }
memset(output, '\0', 10*sizeof(arr[0]));

    }

How to improve it ? in terms of reducing code lines and code size and memory utilization ? or any other way to parse ? Is there any basic library available ?


texts: Computing the profit or loss from a list of trades

texts:
I am coming from C# and I am learning how to use Python more seriously.

So I decided to try a little side project to help me see how much I earn (or lose) from my trades on the stock market.

I would like some advice about how I structured my project, in C# I am used to put each class in its own file, but I read that in Python we work with module, so I put several classes in the trades.py module. But does it make sense to put the trade importer in the same module as the calculator?

Here is a screenshot of my project hierarchy so far:

and a description of the files:

trades.py

import calculator.trades as t

from enum import Enum
import numpy as np

class TradeType(Enum):
    Buy = 1
    Sell = -1

class Trade:
    def __init__(self, id, trade_date, type, quantity, price, currency_id, company_id, account_id):
        self.id = id
        self.type = type
        self.account_id = account_id
        self.company_id = company_id
        self.currency_id = currency_id
        self.trade_date = trade_date
        self.quantity = quantity
        self.price = price

class TradePnlCalculator:
    def compute_pnl(self, trades):
        signed_quantities = np.array([-1 * t.type.value * t.quantity for t in trades])
        prices = np.array([t.price for t in trades])
        return np.dot(signed_quantities, prices)

class TradeImporter:
    def load_trades(self):
        # TODO Read the trades from a file
        return []

test_tradePnlCalculator.py

from unittest import TestCase

from calculator.trades import Trade, TradeType, TradePnlCalculator
import datetime

class TestTradePnlCalculator(TestCase):

    def setUp(self):
        now = datetime.datetime.now()
        self.trade1 = Trade(1, trade_date=now, type=TradeType.Buy, quantity=100,
                            price=34.5, currency_id=1, company_id=1, account_id=1)
        self.trade2 = Trade(2, trade_date=now, type=TradeType.Sell, quantity=100,
                            price=37.4, currency_id=1, company_id=1, account_id=1)

        self.calculator = TradePnlCalculator()

    def test_compute_pnl_returns_zero_when_there_is_no_trades(self):
        self.assertEquals(0, self.calculator.compute_pnl([]))

    def test_compute_pnl_returns_negative_flow_for_single_buy_trade(self):
        self.assertEquals(-3450, self.calculator.compute_pnl([self.trade1]))

    def test_compute_pnl_returns_positive_flow_for_single_sell_trade(self):
        self.assertEquals(3740, self.calculator.compute_pnl([self.trade2]))

    def test_compute_pnl_returns_correct_value_for_cancelling_trades(self):
        self.assertEquals(3740-3450, self.calculator.compute_pnl([self.trade1, self.trade2]))

run.py

importer = t.TradeImporter()
trades = importer.load_trades()

calculator = t.TradePnlCalculator()
pnl = calculator.compute_pnl(trades)

print('The profit for the trades is {} euros'.format(pnl))


texts:
I've written a little program to calculate pi using the Nilakantha series:

  For this formula, take three and start alternating between adding and subtracting fractions with numerators of 4 and denominators that are the product of three consecutive integers which increase with every new iteration. Each subsequent fraction begins its set of integers with the highest one used in the previous fraction. Carry this out even a few times and the results get fairly close to pi. (http://www.wikihow.com/Calculate-Pi)

I don't really understand other ways of calculating pi, or they take too long to perform.

echo "Enter scale please"
read SCALE
VALUE=2
PI=3
FITNESS=1
while true
do
PI=$(echo "scale=$SCALE;$PI+(4/($VALUE*($VALUE+1)*($VALUE+2)))-(4/(($VALUE+2)*($VALUE+3)*($VALUE+4)))" | bc)
VALUE=$(($VALUE+4))
FITNESS=$(($FITNESS+1))
echo "###############"
echo "--> $FITNESS // $VALUE"
echo "$PI"
done

I would really like to know how to detect when I get the same output multiple times, so I can tell the program to terminate when it has reached the most accurate version of pi possible.

Also if you have other suggestions on how to improve the code and/or know a better way of calculating pi (with some explanation), I would like to hear.


texts: Handling multiple optional parameters in Spring

texts:
I have an endpoint in my RestAPI which can receive 3 optional parameters and then find information in the database with these parameters, also it is possible to combine the parameters. So, in my controller I take a Map<String, Object> which contains these parameters and then pass it to the service level, where I check which parameters were passed and then I call a specific DAO method, depends on which combination of parameters do I have. Params A and B are of type String, and C is a Map. So in the service level it looks like this:
public Set<ResultEntry> getByParameters(Map<String, Object> query) {
    Set<ResultEntry> result = new HashSet<>();
    if (query.containsKey("a") && query.containsKey("b") && query.containsKey("c")) {
        result.addAll(myDao.getByABC(
                (String) query.get("a"), (String) query.get("b"),
                (Map<String, String>) query.get("c")
        ));
    } else if (query.containsKey("a") && query.containsKey("b") && !query.containsKey("c")) {
        result.addAll(myDao.getByAB(
                (String) query.get("a"), (String) query.get("b")
        ));
    } else if (query.containsKey("a") && !query.containsKey("b") && query.containsKey("c")) {
        result.addAll(myDao.getByAC(
                (String) query.get("a"), (Map<String, String>) query.get("c")
        ));
    } else if (!query.containsKey("a") && query.containsKey("b") && query.containsKey("c")) {
        result.addAll(myDao.getByBC(
                (String) query.get("b"), (Map<String, String>) query.get("c")
        ));
    } else if (query.size() == 1 && query.containsKey("a")) {
        result.addAll(myDao.getByA((String) query.get("a")));
    } else if (query.size() == 1 && query.containsKey("b")) {
        result.addAll(myDao.getByB((String) query.get("b")));
    } else if (query.size() == 1 && query.containsKey("c")) {
        result.addAll(myDao.getByC((Map<String, String>) query.get("c")));
    }
    return result;
}

Everything works fine, but I feel like this is not the best way to deal with such situations, using if-statements for each possible combination, so how can I improve it?


texts:
I sometimes write decorators to cache results I get from a repository or I write other caches... I don't want to write another cache anymore. I'd like to have something that'll work for anything. I've build a test-cache that I could use to replace other caches. It provides just the most basic methods.

public class Cache
{
    private readonly IDictionary<object, (object Value, DateTime CreatedOn, TimeSpan Timeout)> _cache = new Dictionary<object, (object Value, DateTime CreatedOn, TimeSpan Timeout)>();

    public TResult Get<TResult>(object key, Func<TResult> get, TimeSpan timeout)
    {
        if (_cache.TryGetValue(key, out var t) && !HasTimedout(t.CreatedOn, t.Timeout))
        {
            return (TResult)t.Value;
        }

        var value = get();
        _cache[key] = (value, DateTime.UtcNow, timeout);

        return value;

        bool HasTimedout(DateTime createdOn, TimeSpan currentTimeout) => DateTime.UtcNow - createdOn > currentTimeout;
    }

    public async Task<TResult> GetAsync<TResult>(object key, Func<TResult> get, TimeSpan timeout)
    {
        return await Task.Run(() => Get<TResult>(key, get, timeout));
    }

    public void Clear() => _cache.Clear();

    public bool Remove(object key) => _cache.Remove(key);
}

On its own this is not very useful yet so I have a few extensions for it that help me to create keys which are tuples so that I can use their comparer that compares all properties and not the object reference:

public static class CacheExtensions
{
    public static TResult Get<TResult>(this Cache cache, Func<TResult> get, TimeSpan timeout)
    {
        return cache.Get<TResult>(null, get, timeout);
    }

    public static TResult Get<T1, TResult>(this Cache cache, T1 arg1, Func<T1, TResult> get, TimeSpan timeout)
    {
        return cache.Get<TResult>((arg1), () => get(arg1), timeout);
    }

    public static  TResult Get<T1, T2, TResult>(this Cache cache, T1 arg1, T2 arg2, Func<T1, T2, TResult> get, TimeSpan timeout)
    {
        return cache.Get<TResult>((arg1, arg2), () => get(arg1, arg2), timeout);
    }
}

Example usage:

var cache = new Cache();

cache.Get(2, 4, (x, y) => 3, TimeSpan.FromSeconds(4)).Dump("New");
cache.Get(2, 4, (x, y) => 4, TimeSpan.FromSeconds(4)).Dump("Cached");
Thread.Sleep(5000);
cache.Get(2, 4, (x, y) => 5, TimeSpan.FromSeconds(4)).Dump("Timedout");

Output:

New
3

Cached
3

Timedout
5

What do you think of it?


texts: T-SQL Getting Sequential events with first even criteria

texts:
I have a query I am writing where I want output if a person has some service provided, then I want all the services they had provided after that and I don't want the individual returned if that is the only service they had (the criteria service)

I have some example data:

In this instance above I would not want the last row.

The code I have, I feel is verbose at best. I am confident it works but I think it could be written better.

This will get some sample data

declare @bmh_plm_ptacct_v as table (
    med_rec_no varchar(10)
    , ptno_num varchar(10)
    , adm_date date
    , dsch_date date
    , hosp_svc varchar(5)
)

insert into @bmh_plm_ptacct_v
values('123456','123456748','2017-12-18','2018-01-12','PSY'),
('123456','123456789','2018-01-17','2018-01-18','EME'),
('123456','123456889','2018-01-19','2018-01-21','EME'),
('123456','123478978','2018-01-25','2018-01-25','EME'),
('123456','123457979','2018-05-21','2018-05-21','EME'),
('123456','123458988','2018-06-03','2018-06-04','EME'),
('123456','123458989','2018-07-27','2018-08-14','PSY'),
('123456','123458990','2018-09-23','2018-09-24','EME'),
('123456','123459999','2018-09-25','2018-09-30','PSY')

declare @vReadmits as table (
    [index] varchar(10)
    , interim int
    , [readmit] varchar(10)
)

insert into @vReadmits
values('123458990','25','123459999')

declare @hosp_svc_dim_v as table (
    hosp_svc varchar(50)
    , hosp_svc_name varchar(100)
        , orgz_cd varchar(10)
)

insert into @hosp_svc_dim_v
values('PSY','Pyschiatry','s0x0'),
('EME','Emergency Department','s0x0')

SELECT Med_Rec_No
, PtNo_Num
, Adm_Date
, Dsch_Date
, hosp_svc
, CASE
    WHEN B.READMIT IS NULL
    THEN 'No'
    ELSE 'Yes'
    END AS [Readmit Status]
, [Event_Num] = ROW_NUMBER() over(partition by med_rec_no order by ADM_date)
, [PSY_Flag] = CASE WHEN hosp_svc = 'PSY' THEN '1' ELSE '0' END

INTO #TEMPA

FROM smsdss.bmh_plm_ptacct_v AS A
LEFT OUTER JOIN smsdss.vReadmits AS B
ON A.PtNo_Num = b.[INDEX]
    AND B.INTERIM < 31

WHERE Dsch_Date >= '01-01-2018'
AND dsch_date < '12-31-2018'

ORDER BY Med_Rec_No, A.Adm_Date
;

SELECT A.*
INTO #TEMPB
FROM #TEMPA AS A
WHERE A.hosp_svc = 'PSY'
;

SELECT B.*
INTO #TEMPC
FROM #TEMPA AS B
WHERE B.hosp_svc != 'PSY'
AND B.Med_Rec_No IN (
    SELECT DISTINCT Med_Rec_No
    FROM #TEMPB
)
;

SELECT Med_Rec_No
, PtNo_Num
, Adm_Date
, Dsch_Date
, hosp_svc
, [Readmit Status]
, Event_Num
, PSY_Flag
, [Keep_Flag] = ROW_NUMBER() OVER(PARTITION BY MED_REC_NO ORDER BY ADM_DATE)

INTO #TEMPD

FROM (
    SELECT B.*
    FROM #TEMPB AS B

    UNION ALL

    SELECT C.*
    FROM #TEMPC AS C
    WHERE C.Med_Rec_No IN (
        SELECT ZZZ.Med_Rec_No
        FROM #TEMPB AS ZZZ
        WHERE ZZZ.Med_Rec_No = C.Med_Rec_No
        AND C.Event_Num > ZZZ.Event_Num
    )
) AS A

ORDER BY MED_REC_NO, Event_Num
;

SELECT A.Med_Rec_No
, A.PtNo_Num
, CAST(A.ADM_DATE AS DATE) AS [Adm_Date]
, CAST(A.Dsch_Date AS DATE) AS [Dsch_Date]
, A.hosp_svc
, HS.hosp_svc_name
, A.[Readmit Status]
, A.Event_Num
, A.Keep_Flag

FROM #TEMPD AS A
LEFT OUTER JOIN SMSDSS.hosp_svc_dim_v AS HS
ON A.hosp_svc = HS.hosp_svc
    AND HS.orgz_cd = 'S0X0'
WHERE A.Med_Rec_No IN (
    SELECT DISTINCT ZZZ.MED_REC_NO
    FROM #TEMPD AS ZZZ
    WHERE Keep_Flag > 1
)

DROP TABLE #TEMPA;
DROP TABLE #TEMPB;
DROP TABLE #TEMPC;
DROP TABLE #TEMPD;


texts: Beginner's LINQ exercise to print the odd numbers in descending order

texts:
I'm going through C# Operators which led me to more specifically Lambda Expressions (C# Programming Guide). I've modified one of the examples from just getting the .Count to printing out the odd numbers. Is there anything I can do to simplify my code? Should I "method chain" oddNumbers and oddDescending together? I've left them apart since I'm just learning and seeing them separate is easier for me to understand right now.

class Program
{
    public static void Main(string[] args)
    {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
        var oddNumbers = numbers.Where(x => x % 2 == 1);
        var oddDescending = oddNumbers.OrderByDescending(x => x);

        foreach (int odd in oddDescending)
        {
            Console.WriteLine(odd);
        }
    }
}


texts:
I am learning c++ and read why we can't use realloc() in std::vector, but i think we can use realloc() for pods, so here is my attempt to write std::vector like class template specialized for PODs

#include <malloc.h>
#include <stdexcept>
#include <type_traits>

namespace gupta {
namespace detail {
namespace podvector {
template <typename T> inline auto malloc(size_t elm_count) {
  return ::malloc(elm_count * sizeof(T));
}

template <typename T> inline auto realloc(void *old_block, size_t elm_count) {
  return ::realloc(old_block, elm_count * sizeof(T));
}
} // namespace podvector
} // namespace detail

template <typename PodType,
          typename = std::enable_if_t<std::is_pod<PodType>::value>>
class podvector {
public:
  using value_type = PodType;
  using size_type = size_t;
  using pointer = value_type *;
  using const_value_pointer = const value_type *;

  ~podvector() {
    if (m_memory)
      free(m_memory);
  }

  podvector(size_type initial_size = 0) {
    alloc(initial_size);
    m_size = initial_size;
  }

  podvector(size_type initial_size, const value_type &value)
      : podvector(initial_size) {
    for (auto &v : *this)
      v = value;
  }

  podvector(const podvector &other) : podvector(other.m_size) {
    for (size_type i = 0; i < m_size; i++)
      m_memory[i] = other.m_memory[i];
  }

  podvector(const podvector &&other)
      : m_memory{std::move(other.m_memory)},
        m_capacity{std::move(other.m_capacity)}, m_size{
                                                     std::move(other.m_size)} {
    // other.m_memory = nullptr;
    other.alloc(0);
  }

  podvector &operator=(const podvector &rhs) {
    if (this != &rhs) {
      resize(rhs.m_size);
      for (size_type i = 0; i < rhs.m_size; i++)
        m_memory[i] = rhs[i];
    }
    return *this;
  }

  podvector &operator=(podvector &&rhs) {
    if (this != &rhs) {
      this->~podvector();
      m_memory = std::move(rhs.m_memory);
      m_capacity = std::move(rhs.m_capacity);
      m_size = std::move(rhs.m_size);
      // rhs.m_memory = nullptr;
      rhs.alloc(0);
    }
    return *this;
  }

  void resize(size_type new_size) {
    if (new_size > m_size)
      change_capacity(new_size);
    m_size = new_size;
  }

  void reserve(size_type new_capacity) {
    if (m_capacity < new_capacity)
      change_capacity(new_capacity);
  }

  void push_back(const value_type &new_elm) {
    if (m_size + 1 > m_capacity)
      change_capacity(std::min(m_capacity * 2, 1));
    m_memory[m_size++] = new_elm;
  }

  void pop_back() { m_size--; }

  auto size() const { return m_size; }
  auto capacity() const { return m_capacity; }
  pointer begin() { return m_memory; }
  const_value_pointer begin() const { return m_memory; }
  pointer end() { return m_memory + m_size; }
  const_value_pointer end() const { return m_memory + m_size; }
  value_type &operator[](size_type pos) { return m_memory[pos]; }
  const value_type &operator[](size_type pos) const { return m_memory[pos]; }

private:
  pointer m_memory;
  size_type m_size, m_capacity;
  void alloc(size_type capacity) {
    m_capacity = capacity;
    m_size = 0;
    m_memory =
        static_cast<pointer>(detail::podvector::malloc<value_type>(capacity));
    if (!m_memory)
      throw std::bad_alloc{};
  }
  void change_capacity(size_type new_capacity) {
    m_capacity = new_capacity;
    void *new_memory =
        detail::podvector::realloc<value_type>(m_memory, new_capacity);
    if (!new_memory)
      throw std::bad_alloc{};
    m_memory = static_cast<pointer>(new_memory);
  }
};

} // namespace gupta


texts:
I tend to write code, with very few comments, and few line breaks. I'm currently just a student at a University. I've had professors tell me one way or another to comment, but I have a hard time with more ambiguous tasks.

I have a misc. snippet of code, written by me in C++. I'm not looking for revisions on it or anything. Just how, in your professional field, would you go about commenting it?

CString Socket::recvln()
{
    int size, count;
    char* result;

    OSFactory::lockMutex(recvLock);
    size = recvBuffer.size();
    result = new char[size+1];
    for (count = 0; count < size; count++)
        if (recvBuffer.at(count) == '\n')
            break;
        else
            result[count] = recvBuffer.at(count);

    if (count >= size) // Should never >= size if '\n' found
        count = 0;
    result[count] = '\0';
    recvBuffer.erase(recvBuffer.begin(), recvBuffer.begin()+count);
    OSFactory::unlockMutex(recvLock);

    std::string _result = result;
    delete[] result;
    return _result;
}

Again, this is just a misc. method I have. I'm just trying to understand how other people would go about commenting code. There are tons of tutorials out there, but many even have you comment getter/setter methods, and to me that's really really pointless. Many times it's very clear that setName(std::string), for example, sets the Name!

So, I'm just trying to have a better grasp on real life commenting, versus text-book answers. For some reason this is really hard for me, and I'm sure it should benefit other people as well.


texts: Modeling a classroom with teacher and students using the mediator pattern in Go

texts:
I've made this implementation of a classroom with teacher and students using mediator pattern. Mediator is the teacher and colleague are studends.

Main function is the following. Main function creates a teacher and then she says will teach to some students. Finally, she try to spread a concept and a student will tell what he (or she) have learned.

func NewClassMate(name string) Student {
    return &ClassMate{name, "meeting 1", ""}
}

func main() {

    teacher := Teacher{}

    student := NewClassMate("Mario")

    teacher.TeachesTo(student)
    teacher.TeachesTo(NewClassMate("Demo"))
    teacher.TeachesTo(NewClassMate("Mattia"))
    teacher.TeachesTo(NewClassMate("Simone"))

    fmt.Println(len(teacher.attendees))
    fmt.Println(student.Forum())

    teacher.Spread("Message sent to everyone")

    fmt.Println(student.Learned())

}

Teacher

Teacher implementation is trivial. Teacher knows all students and spread lessons.

type Teacher struct {
    students []Student
}

func (m *Teacher) TeachesTo(c Student) {
    m.students = append(m.students, c)
}

func (m *Teacher) Spread(message string) {
    for _, a := range m.students {
        a.Learn(message)
    }
}

Student

Also student is very simple. It take part in a class, learns and say what he have learned.

type ClassMate struct {
    lastMessage string
    forum       string
}

func (a *ClassMate) Class() string {
    return a.forum
}

func (a *ClassMate) Learn(message string) {
    a.lastMessage = message
}

func (a *ClassMate) Learned() string {
    return a.lastMessage
}

Mediator and Colleagues

Finally here we can see interface I chosenm according to the pattern.

type Student interface {
    Class() string
    Learn(message string)
    Learned() string
}

type Mediator interface {
    TeachesTo(c *Student)
    Spread(messqger string)
}


texts: Finding the number of vowels in a string

texts:
I'm new to Java and is trying to solve the beginners problem of finding out the number of vowels in a string. I was just wondering if there is any alternatives to any of the steps that can improve efficiency as well as simplicity.

import java.util.Arrays;
import java.util.Scanner;

public class CountVowels{

    public static void main(String[] args) {
        Scanner sc1 = new Scanner(System.in);
        String userInput = sc1.next();
        sc1.close();
        CountVowels cv1 = new CountVowels();
        int numberOfVowels = cv1.countingVowels(userInput);
        System.out.println(numberOfVowels);
    }

    public int countingVowels(String s1){
        String lowerCaseString = s1.toLowerCase();
        int vowelCount = 0;
        for (int i = 0; i < lowerCaseString.length(); ++i){
            Character charCharacter = lowerCaseString.charAt(i);
            char[] vowels = {'a', 'e', 'i', 'o', 'u'};
            if(Arrays.binarySearch(vowels, charCharacter) >= 0){
                vowelCount += 1;
            }
        }
        return vowelCount;
    }
}


texts:
I have been working on this code to meet the best OOP standards for production. The code is working but I wish to make this a more efficient code. Could someone help me out here to make this efficient using best practices of ruby.
class Item
  @@items = {}
  def initialize(name, price)
    @@items[name] = price
  end

  def self.all
    @@items
  end
end

class SaleItem
  @@sale_items = {}
  def initialize(name, units, price)
    @@sale_items[name] = { 'units' => units, 'price' => price }
  end

  def self.all
    @@sale_items
  end
end

class PriceCalculator
  def initiate_billing
    input = get_input.split(',').map(&:strip)
    @purchased_items = input
    if @purchased_items.any?
      quantity = count_items
      price = calculate_bill(quantity)
      display_bill(price, quantity)
    else
      puts "First add items to generate bill"
    end
  end

  private

    def get_input
      puts "Please enter all the items purchased separated by a comma"
      response = gets.chomp
    end

    def count_items
      @purchased_items.inject(Hash.new(0)) do |quantity, item|
        quantity[item] += 1
        quantity
      end
    end

    def calculate_bill(quantity)
      quantity.map do |item,value|
        items = Item.all[item]
        sale_items = SaleItem.all[item]
        value = if sale_items.nil?
         quantity[item] * items
        else
         (((quantity[item]/sale_items['units'])) * sale_items['price']) + ((quantity[item] % sale_items['units']) * items)
        end
        [item, value]
      end.to_h
    end

    def display_bill(price, quantity)
      billing_items = quantity.each_with_object(price) do |(key,value), billing_items|
        billing_items[key] = {'units' => value, 'price' => price[key]}
      end

      total_price = billing_items.inject(0) do |total, (item,value)|
        total + value['price']
      end

      actual_price = quantity.inject(0) do |total, (item,units)|
        total + (units * Item.all[item])
      end

      puts "Item     Quantity      Price"
      puts "--------------------------------------"
      billing_items.each do |item, value|
        puts "#{item.ljust(10)} #{value['units']}           $#{value['price'].round(3)}"
      end
      puts "Total price : $#{total_price.round(3)}"
      puts "You saved $#{(actual_price - total_price).round(3)} today."
    end
end

begin
  Item.new('milk', 3.97)
  Item.new('bread', 2.17)
  Item.new('banana', 0.99)
  Item.new('apple', 0.89)

  SaleItem.new('milk',2,5.00)
  SaleItem.new('bread',3,6.00)

  price_calculator = PriceCalculator.new
  puts price_calculator.initiate_billing
end

```