texts: Wiegand 26-Bit Calculator - Transforming a decimal number into an 26-Bit binary number

texts:
I made a 26-bit binary Wiegand calculator for an ESP32 following this format:

This is "Arduino C" :

unsigned int * getWiegand(unsigned int dec) {
  unsigned int* wiegandNum = new unsigned int[26];

  Serial.println();
  // transform dec number into binary number and store it in binaryNum[]
  int n = 1;
  for(int i = 23; i>=0; i--) {
    int k = dec >> i;
    if (k & 1)
      wiegandNum[n++] = 1;
    else
      wiegandNum[n++] = 0;
  }
  // check for parity of the first 12 bits
  bool even = true;
  for(int i=1;i<13;i++) {
    if(wiegandNum[i] == 1) {
      even = !even;
    }
  }
  // add 0 or 1 as first bit (leading parity bit - even) based on the number of ones in the first 12 bits
  if(even) {
    wiegandNum[0] = 0;
  } else {
    wiegandNum[0] = 1;
  }

  // check for parity of the last 12 bits
  bool odd = false;
  for(int i=13; i<25;i++) {
    if(wiegandNum[i] == 1) {
      odd = !odd;
    }
  }
  // add 0 or 1 as last bit (trailing parity bit - odd) based on the number of ones in the last 12 bits
  if(odd) {
    wiegandNum[25] = 0;
  } else {
    wiegandNum[25] = 1;
  }

  return wiegandNum;
}

void setup() {
  Serial.begin(115200);

  unsigned int* wiegandArray = getWiegand(12679548);
  for(int i=0;i<26;i++) {
    Serial.print(wiegandArray[i]);
  }
}

12679548 will return 01100000101111001011111000 which, based on this online tool is correct.

Execution time for this function is 255 microseconds. I don't know if the time is good or not, but I believe that the code can be improved.

What do you think ?

References:

https://www.arduino.cc/reference/en/language/structure/sketch/setup/
https://www.arduino.cc/reference/en/language/functions/communication/serial/print/


texts: Establishing a TCP connection with async & await

texts:
I'm not really super experienced async/await and working with tasks, so I thought I'd ask for some other opinions.

I'm working with code written by someone else that establishes a TCP connection. It works most of the time. But sometimes it just doesn't, and the connection gets dropped and we don't know about it.

My first suspicion is that it's calling Task.Run(() =>, which goes on to call a method that calls Task.Factory.StartNew(async () =>, which in turn goes to call await Task.Run(() =>.

Does this code look ok to more experienced eyes? Is there anything that could be done to improve it?

public bool StartListening(string ipAddress, int port)
{
    Task.Run(() =>
    {
        _canceller = new CancellationTokenSource();

        _backingTcpListener = new TcpListener(IPAddress.Parse(ipAddress), port);
        _backingTcpListener.Start();

        WaitForConnections(_canceller.Token);
    });

    return true;
}

private void WaitForConnections(CancellationToken cancelToken)
{
    Task.Factory.StartNew(async () =>
    {
        while (!cancelToken.IsCancellationRequested)
        {
            var inner = await Task.Run(() =>
            {
                try
                {
                    return _backingTcpListener.AcceptTcpClient();
                }
                catch (SocketException)
                {
                    // this will be caused by StopListeningAsync
                    return null;
                }
            }, cancelToken);

            if (inner == null)
            {
                // null will be returned when the SocketException is caught above
                return;
            }

            var outer = new TcpSocketClient(inner, _bufferSize);

            var args = new TcpSocketConnectionReceivedEventArgs(outer);

            ConnectionReceived?.Invoke(args);
        }
    }, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}


texts:
This converts a "numerical number" to a text representation, for example:

  convert 1234 --> "One Thousand, Two Hundred Thirty Four"

I'd like general feedback on how it could be make more readable or idiomatic.
There are a few specific points I'd like improved as well. The word lookup functions are a little messy. Each uses a different method of looking up the name depending on how the input relates to the desired name. If they could be generalized, it would be much neater.
It's also not that efficient. It requires a few reversals, all of which are necessary with my current technique; as far as I can tell.

import Data.Char
import Data.List

-- Global names
places  = ["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion"]
ones    = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]
teens   = ["Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
tens    = ["A 1 made it to getTens","Hundred","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"]

-- Word lookup functions
getPlaceName :: Int -> String
getPlaceName place = places !! place

getOnes :: Char -> String
getOnes '0' = ""
getOnes n = let index = (digitToInt n) - 1 in
    ones !! index

getTeens :: String -> String
getTeens n = let r = read n :: Int in
    head $ [x | (i,x) <- (zip [10..] teens), i == r]

getTens :: Char -> String
getTens '0' = ""
getTens n   = let index = (digitToInt n) in
    tens !! index

--Takes a string rep. of a number, reverses it, and groups it into 3-groups
-- 12,000 -> ["000", "21"]
cutIntoGroups :: String -> [String]
cutIntoGroups = reverse . cut [] . reverse
    where
        cut acc []      = acc
        cut acc rest    = let (next,rest') = splitAt 3 rest in
            cut (next : acc) rest'

-- Applies the "rules" to each sub-chunk
applyLocalRules :: String -> String
applyLocalRules revChunk = hund ++ tensNOnes
    where
        (ones,tens,hunds) = toTriple revChunk '0'
        tensNOnes = if tens == '1' then (getTeens [tens,ones])
                        else (getTens tens) ++ (getOnes ones)
        hund = if hunds == '0' then ""
                    else (getOnes hunds) ++ "Hundred"

-- Succeedes each formatted chunk with the place name
applyRules :: [String] -> [String]
applyRules = reverse . map (\(i,g) -> let pName = getPlaceName i in
    applyLocalRules g ++ pName) . zip [0..]

toTriple :: [a] -> a -> (a,a,a)
toTriple [] def = (def,def,def)
toTriple xs def = case xs of
    [x,y,z] -> (x,y,z)
    [x,y]   -> (x,y,def)
    [x]     -> (x,def,def)
    _       -> error "List greater then 3"

addCommasAndConcat :: [String] -> String
addCommasAndConcat = concat . map (\chunk -> chunk ++ ",")

-- Adds spaces before words
addSpaces :: String -> String
addSpaces [] = []
addSpaces left = (h : pre) ++ " " ++ addSpaces post
    where
        (h:t)       = left
        (pre,post)  = break isUpper t

-- Loosely stolen from SO
trim :: String -> String
trim = let t = reverse . dropWhile (not . isAlpha) in
    t . t

-- Main function
convert :: Int -> String
convert = trim . addSpaces . addCommasAndConcat
    . applyRules . cutIntoGroups . show

It should be noted that this is very unsafe in its current form, so I'm only looking for comments regarding the algorithm itself (it crashes ungracefully on negative numbers, non-numbers, and too-large of numbers). I think I'm going to use this module to test out the Either Monad later to fix its safety.


texts: Evaluate joint probability density function of a Markov random field

texts:
The following code evaluates probability mass function for all possible states of a model.

def PDF(size):
    b = np.random.randn(size)
    J = np.random.randn(size, size)

    density_func = np.zeros(2**size)
    states = dec2bin(size)

    for i in range(2**size):
        density_func[i] = np.exp((np.dot(b, states[i,:]) + np.dot(np.dot(states[i],J),states[i])))

    Z = np.sum(density_func)
    density_func = density_func / Z

    return density_func

utility functions

def bitfield(n,size):
    x = [int(x) for x in  bin(n) [ 2 :]]
    x = [0] * (size - len(x)) + x
    return x

def dec2bin(size):
    states = []
    for i in range(2**size):
        binary = bitfield(i, size)
        states.append(binary)
    return np.array(states)

The model is grid graph Markov random field. Each node of the graph can have two states {0, 1}, so the total number of possible states of the model is 2total number of nodes. Each instance of the for loop is calculating the probability of that state. At end I want to calculate the joint probability distribution of all the nodes. The joint probability distribution of this model is as follows

$$
p(\mathbf{x}) = \tfrac{1}{z} exp(\mathbf{b}\cdot\mathbf{x} + \mathbf{x}\cdot\mathbf{J}\cdot\mathbf{x})
$$

\$b\$ and \$J\$ are model parameters and \$x\$ is a vector of present states of the system.

\$Z\$ is the normalizing constant which is calculated by summing up 'values' of each possible state of the system to convert them into probabilities.

When the variable size is greater than 25 the code takes long time to execute. Is there a way to vectorize this code and speed it up?


texts: Discrete random number generator in Python

texts:
Description: I am given a list of possible values, each of which have an associated probability of occurrence.

How could I improve the algorithm that randomly generates a value based on the given distribution? I want to let the number of possible values grow very large. I essentially use the cumulative probabilities in my solution.

import numpy as np, numpy.random

N = 100
possible_values = [x for x in range(N)]
probabilities = np.random.dirichlet(np.ones(N),size=1).tolist()[0]

def sampleValue(possible_values, probabilities):
    U = random.random()
    cum_probs= np.cumsum(probabilities).tolist()
    for i, c in enumerate(cum_probs):
        if U < c:
            return possible_values[i]

testValues = [sampleValue(possible_values, probabilities) for x in range(100000)]

#testing

print('Sample test')
print('Theoretical', probabilities[10])
print('Simulated', testValues.count(10) / 100000)


texts: Prime Number Generator algorithm optimization

texts:
I've implemented a simple program that finds all prime numbers between two integer inputs using Sieve of Eratosthenes, but the online judge is still complaining that the time limit is exceeding. Maybe I'm doing something wrong, but how can I optimize (or debug if necessary) my code?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int t;
    unsigned int i, j, k;
    cin >> t;
    int m, n;
    cin >> m >> n;
    if (n - m <= 100000 && m <= n && 1 <= m && n <= 1000000000)
    {
        int a[n - m + 1];
        for (j = 0; j < n - m + 1; ++j)
        {
            a[j] = m + j;
        }
        for (j = 2; j <= sqrt (n); ++j)
        {
            for (k = 0; k < n - m + 1; ++k)
            {
                if (a[k] % j == 0 && a[k] != 0)
                {
                    break;
                }
            }
            for (; k < n - m + 1; k = k + j)
            {
                if (a[k] != j)
                {
                    a[k] = 0;
                }
            }
        }
        if (a[0] == 1)
        {
            a[0] = 0;
        }
        for (j = 0; j < n - m + 1; ++j)
        {
            if (a[j])
            {
                cout << a[j] << endl;
            }
        }
        cout << endl;
    }
    return 0;
}


texts: Function that uses an exception to check if user exists

texts:
I have a User class that will throw an exception if the userid provided in the parameter does not correspond with a user.

I've written a helper function that will return true or false depending on whether a userid belongs to a user or not, but was wondering if my use of a try {} catch {} to do so is correct:

    private function userExists($userid)
    {
       $user_does_not_exist = false;
       try
       {
          $user = new User($userid);
       }
       catch (Exception $e)
       {
          $user_does_not_exist = true;
       }

       return $user_does_not_exist;
   }

Any and all critique is greatly appreciated.


texts: Loading the JDBC driver jar dynamically from external location

texts:
I have a small project in which I get the URL, username, password, and driver from a text file and I have to fire a query on the database by dynamically reading the jar file in a predefined directory, register the jar, get a connection object and possibly de-register it. Each query may talk to a different database schema or even DBMS. The directory consists of all JDBC driver jars. I need to pick one based on the driver class name that I get from the previously mentioned text file.

I have written the following code so far. Does it has any memory issues or performance issues?

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String dbUrl = "jdbc:mysql://localhost:3306/test";
        String userName = "foo";
        String password = "bar";
        String driverName = "com.mysql.jdbc.Driver";

        final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        String jar = "D:\\Drivers\\mysql-connector-java-5.1.6.jar";

        System.out.println(this.getClass().getClassLoader().getClass() + " is the class loader");
        System.out.println("Before loading the drivers in driver manager are ");
        listDrivers();
        try {
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(loader, new File(jar).toURI().toURL());

            Class<?> classToLoad = Class.forName(driverName, true, loader);
            Driver driver = (Driver) classToLoad.newInstance();
            DriverManager.registerDriver(new DriverShim(driver));
            Connection connection = DriverManager.getConnection(dbUrl, userName, password);
            System.out.println("is Connection null " + (connection == null) + ". After loading the drivers in driver manager are ");
            //Do business specific action
            listDrivers();
            DriverManager.deregisterDriver(driver);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void listDrivers() {
        java.util.Enumeration enumeration = java.sql.DriverManager.getDrivers();
        while (enumeration.hasMoreElements()) {
            Driver driverAsObject = (Driver) enumeration.nextElement();
            System.out.println("Driver: " + driverAsObject + ":" + driverAsObject.getMajorVersion() + ":" + driverAsObject.getMinorVersion());
        }
    }

The dependency DriverShim is obtained from here.

How can one do it better?


texts: Sourcing content from a webpage in an organized manner

texts:
I've written a script in python to grab different title and address from different pages of a website. Firstly the script will collect all the property links from the landing page and then go one layer deep to collect the title and address. When I run my script, I get the results accordingly.

Should it not be a better approach If I call a single function and the rest of the functions work like a chain to produce the same results? If so, what is the right way to do so?

This is the link to that site

Here is the working script:

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = 'https://www.booking.com/searchresults.html?aid=304142;label=gen173nr-1FCAEoggJCAlhYSDNYBGhpiAEBmAExuAEHyAEM2AEB6AEB-AECkgIBeagCAw;sid=7abf6bf275d09e8d4f617d51f4d6c803;class_interval=1;dest_id=102;dest_type=country;dtdisc=0;from_sf=1;group_adults=2;group_children=0;inac=0;index_postcard=0;label_click=undef;no_rooms=1;offset=0;postcard=0;raw_dest_type=country;room1=A%2CA;sb_price_type=total;search_selected=1;slp_r_match=0;src=index;src_elem=sb;srpvid=134253d18d97017e;ss=Ireland;ss_all=0;ss_raw=ireland;ssb=empty;sshis=0&'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}

def get_token():        #getting csrf_token
    r = requests.get(url)
    soup = BeautifulSoup(r.text,"lxml")
    item = soup.select_one("[name='bhc_csrf_token']")['value']

    payload = {
        'bhc_csrf_token': item,
        'logout': 1
    }
    return payload

def make_post(payload):  #making a post http request with the payload and parsing target page links
    res = requests.post(url,data=payload,headers=headers)
    sauce = BeautifulSoup(res.text,"lxml")
    linklist = []
    for elem in sauce.select(".sr_property_block a.hotel_name_link"):
        linklist.append(urljoin(url,elem.get("href").strip()))
    return linklist

def get_info(link): #scraping title and address by using each of the links
    response = requests.get(link,headers=headers)
    soupobj = BeautifulSoup(response.text,"lxml")
    name = soupobj.select_one("h2#hp_hotel_name").get_text(strip=True)
    addr = soupobj.select_one(".hp_address_subtitle").get_text(strip=True)
    print(f'{name}\n{addr}\n')

if __name__ == '__main__':
    for link in make_post(get_token()):
        get_info(link)


texts:
I created a template registry class. It supports custom factory functions and custom constructors. Any kind of feedback is welcome (style, performance, bugs)

registry.hpp:

#ifndef REGISTRY_HPP
#define REGISTRY_HPP

//STL
#include <unordered_map>
#include <memory>

template<typename Key>
class RegistryConstructionError : public std::exception
{
public:
    RegistryConstructionError(const Key &key)   :key(key){}

    const char *what()const throw(){return "Undefined key";}
    const Key key;
};

template<typename Base, typename Key, typename... Args>
class Registry
{
public:
    typedef std::unique_ptr<Base> (*FactoryFunc)(Args... args);

    Registry() = default;
    ~Registry() = default;

    template<typename Derived>
    void registerClass(const Key &key);
    void registerFactory(const Key &key, const FactoryFunc factory);

    std::unique_ptr<Base> construct(const Key &key, Args... args);

private:
    template<typename Derived>
    static std::unique_ptr<Base> constructDerived(Args... args);

    std::unordered_map<Key, FactoryFunc> m_map;

public:
    typedef RegistryConstructionError<Key> ConstrError;
};

#include "registry.tpp"

#endif // REGISTRY_HPP

registry.tpp:

template<typename Base,
        typename Key,
        typename... Args>
template<typename Derived>
void Registry<Base, Key, Args...>::registerClass(const Key &key)
{
    m_map[key] = &constructDerived<Derived>;
}

template<typename Base,
        typename Key,
        typename... Args>
void Registry<Base, Key, Args...>::registerFactory(const Key &key, const FactoryFunc factory)
{
    m_map[key] = factory;
}

template<typename Base,
        typename Key,
        typename... Args>
std::unique_ptr<Base> Registry<Base, Key, Args...>::construct(const Key &key, Args... args)
{
    try{
        return m_map.at(key)(std::forward<Args>(args)...);
    }
    catch(const std::out_of_range &e)
    {
        throw ConstrError(key);
    }
}

template<typename Base,
        typename Key,
        typename... Args>
template<typename Derived>
std::unique_ptr<Base> Registry<Base, Key, Args...>::constructDerived(Args... args)
{
    return std::make_unique<Derived>(std::forward<Args>(args)...);
}


texts: How can I make this C code for checking checksum shorter?

texts:
This is a function for checking if the checksum provided by card[] is valid. card[] contains six pairs of characters. The first five pairs make up a hexadecimal number, and the last pair contains the checksum. The checksum is valid if it is equal to XOR of the first five pairs.

It is working fine, but the code is awful. I was trying to use a nested loop, but it wasn't working. Now I'm getting pairs from card[], converting them into numbers and checking whether the checksum is valid.

bool checksum(char card[])
{
int a=0;
char character0[2];
char character1[2];
char character2[2];
char character3[2];
char character4[2];
char character5[2];
long n0,n1,n2,n3,n4,n5;
char card_number;

    for(int i=0;i<2;i++)
    {
        for(a=0;a<2;a++)
        {
        character0[a]=card[i];
        }
    }
    for(int i=2;i<4;i++)
    {
        for(a=0;a<2;a++)
        {
            character1[a]=card[i];
        }
    }
    for(int i=4;i<6;i++)
    {
        for(a=0;a<2;a++)
        {
            character2[a]=card[i];
        }
    }
    for(int i=6;i<8;i++)
    {
        for(a=0;a<2;a++)
        {
            character3[a]=card[i];
        }
    }
    for(int i=8;i<10;i++)
    {
        for(a=0;a<2;a++)
        {
            character4[a]=card[i];
        }
    }
    for(int i=10;i<12;i++)
    {
        for(a=0;a<2;a++)
        {
            character5[a]=card[i];
        }
    }
    n0 = strtol(character0, NULL, 16);
    n1 = strtol(character1, NULL, 16);
    n2 = strtol(character2, NULL, 16);
    n3 = strtol(character3, NULL, 16);
    n4 = strtol(character4, NULL, 16);
    n5 = strtol(character5, NULL, 16);

if(n0^n1^n2^n3^n4==n5)     return true;
else return false;

}

The input for the example is "1E00EDE5E5F3", so 1E^00^ED^E5^E5 should be F3.

And something is wrong with this code. I see it now, because

if(n0^n1^n2^n3^n4==n5)     return true;
else return false;

is working good, but

if((n0^n1^n2^n3^n4)==n5))     return true;
else return false;

is not working at all.


texts: Getting single element or throwing one of two exceptions

texts:
Sometimes I need to get a single thing from a collection but I'm not very happy with the Single extension. It does not differentiate between empty and more than one element and throws the same InvalidOperationException in both cases. I find it's an important disadvantage and it helps a lot if you know excactly why and exception was thrown.

I want to replace it with my own extension that I currently name Single2 as throwing two different exceptions.

public static T Single2<T>(this IEnumerable<T> source)
{
    var count = 0;
    var single = default(T);
    using (var enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext() && count++ < 1)
        {
            single = enumerator.Current;
        }
    }

    switch ((SearchResult)count)
    {
        case SearchResult.NotFound: throw new EmptySequenceException();
        case SearchResult.SingleMatch: return single;
        default: throw new MoreThanOneElementException();
    }
}

public enum SearchResult
{
    NotFound = 0,
    SingleMatch = 1,
    ManyMatches = 2,
}

The exceptions are very simple:

public class EmptySequenceException : Exception { }
public class MoreThanOneElementException : Exception { }

That's all. What do you think of this new helper? Is there still room for improvement?

Example

This is one of the methods that already uses the new Single2. It's from my ResourceReader and it searches for an embedded resource in an assembly.

public static string FindName<T>([NotNull] this IResourceReader resources, [NotNull] Expression<Func<string, bool>> predicateExpression)
{
    if (resources == null) throw new ArgumentNullException(nameof(resources));
    if (predicateExpression == null) throw new ArgumentNullException(nameof(predicateExpression));

    var predicate = predicateExpression.Compile();

    try
    {
        return
            resources
                .GetResourceNames(typeof(T).Assembly)
                .Where(predicate)
                .Single2();
    }
    catch (EmptySequenceException innerException)
    {
        throw DynamicException.Factory.CreateDynamicException(
            $"ResourceNotFound{nameof(Exception)}",
            $"Expression {predicateExpression.ToString().QuoteWith("'")} does not match any resource in the {typeof(T).Assembly.GetName().Name.QuoteWith("'")} assembly.",
            innerException);
    }
    catch (MoreThanOneElementException innerException)
    {
        throw DynamicException.Factory.CreateDynamicException(
            $"MoreThanOneResourceFound{nameof(Exception)}",
            $"Expression {predicateExpression.ToString().QuoteWith("'")} matches more than one resource in the {typeof(T).Assembly.GetName().Name.QuoteWith("'")} assembly.",
            innerException);
    }
}


texts:
I am adding classes to some legacy code and wondering if there is a more appropriate way to be setting the properties. I am also trying to understand the trade offs, if there is another way to do this.
I'm trying to find out if there is a better way to do this? If there is, why? If there isn't, why is this better than the alternative?

class Foo
{
    public $id;

    public function __construct($id)
    {
        $this->id   = $id;
        $this->getDetails();
    }

    /**
     *
     * Assigns all properties
     *
     */
    public function getDetails()
    {
        $db = Database::getDatabase();

        $sql = "SELECT * FROM foos WHERE id = '{$this->id}' ";
        $result = $db->getRow($sql);

        foreach($result as $key => $value) {
            $this->$key = $value;
        }
    }

}


texts: Implementation of Prim's minimum spanning tree

texts:
Feel free to tell about every possible issue (style, errors, inffective solution etc.) you found. Here is the main part of what I want to be reviewed, through there is some related code on GitHub.

Header

#ifndef PRIM_GRAPH_MST_H
#define PRIM_GRAPH_MST_H

#include <list>
#include "graph.h"

class PrimGraphMstImplementation;

class PrimGraphMst
// class that should find minimum spanning tree (MST) for the given graph
// and then store obtained result as a list of edges and summary weight
{
public:
    PrimGraphMst(const Graph&);
    // all work is actualy done in constructor
    // then we hold obtained result in some immutable fields

    const std::list<Graph::EdgeKey>& edges();
    // returns a list of edges from the given graph that forms MST

    double weight() const;
    // returns MST summary weight

   bool valid() const;
   // checks if obtained mst contains same number of vertices as the given graph
   // it could be wrong if the given graph was not connected

   Graph* makeTreeGraph();
   // construct new graph that have only edges from our MST

   private:
   std::shared_ptr<PrimGraphMstImplementation> impl;
};

#endif // PRIM_GRAPH_MST_H

C++ Source

#include <queue>
#include <cassert>
#include "prim_graph_mst.h"

class EdgeWithPriority
// helper class to use graph eges in priority queue
{
public:
double weight;
Graph::EdgeKey key;

EdgeWithPriority(int x, int y, const Graph& graph)
{
    weight = graph.distance(x, y);
    assert(weight >= 0);
    key = Graph::makeEdgeKey(x, y);
}

bool operator<(const EdgeWithPriority& other) const
// such behavior is needed to use this type in std::priority queue
// where top element is always max element and wee need to retrieve
// edge with the lowest weight
{
    return weight >= other.weight;
}
};

class PrimGraphMstImplementation
{
//actual implementation of Prim's algorithm
public:
PrimGraphMstImplementation(const Graph& graph)  :
    graph(graph),
    summaryWeight(0)
  // we do all the work here in constructor
  // we assume that graph is connected
{
    assert(graph.verticesCount() > 0);
    visitVertex(0);

    while(!pq.empty() && visited.size() < graph.verticesCount())
    {
        EdgeWithPriority element = pq.top();
        pq.pop();

        if(visited.find(element.key.first) == visited.end())
        {
            edges.push_back(element.key);
            summaryWeight += element.weight;
            visitVertex(element.key.first);
        }
        else if (visited.find(element.key.second) == visited.end())
        {
            edges.push_back(element.key);
            summaryWeight += element.weight;
            visitVertex(element.key.second);
        }
        else
        {
            continue;
        }
    }
}

void visitVertex(size_t index)
// helper method marks vertex as visited and adds all it's
// edges to priority queue
{
    visited.insert(index);
    for(size_t other : graph.getVertexNeighbors(index))
    {
        pq.push(EdgeWithPriority(index, other, graph));
    }
}

bool valid() const
// it could be wrong if given graph was not connected
{
    return visited.size() == graph.verticesCount();
}

const Graph& graph;
double summaryWeight;
std::list<Graph::EdgeKey> edges;

private:
std::priority_queue<EdgeWithPriority> pq;
std::set<size_t> visited;
};

PrimGraphMst::PrimGraphMst(const Graph& graph)
{
impl = std::make_shared<PrimGraphMstImplementation>(graph);
}

const std::list<Graph::EdgeKey>& PrimGraphMst::edges()
{
return impl->edges;
}

bool PrimGraphMst::valid() const
{
return impl->valid();
}

double PrimGraphMst::weight() const
{
return impl->summaryWeight;
}

Graph* PrimGraphMst::makeTreeGraph()
{
if(!valid())
    return nullptr;

Graph* result = new Graph(impl->graph.verticesCount());
for(Graph::EdgeKey element : impl->edges)
{
    double weight = impl->graph.distance(element.first, element.second);
    result->connect(element.first, element.second, weight);
}

return result;
}


texts:
I have created this function where it detects the first letter of the string provided. I was hoping if you guys can take a look, give your opinion about it and help me to improve it.

 //This function takes a string and outputs
 //its first letter
 function letterDetector(str){
      //Checking if string is an empty string
      if(str === "" || str === undefined)
      {return ("Please input an argument");}

      var alphabetsArr = "abcdefghijklmnopqrstuvwxyz".split("");
     //making user input to lower case
     var string = str.toLowerCase().replace(/[^0-9a-z]\d+/gi, '');
     var result = alphabetsArr.map(letter => {
     if( string.charAt(0) === letter ){
        //logging out the letter as upper case
        console.log("Your first name letter is" + " " + letter.toUpperCase());
     }
   });
}
letterDetector("Adam"); //output A
letterDetector("£1%Adam"); //output A
letterDetector(""); or letterDetector(); //output Please input an argument


texts:
I am developing a C# program, which performs various tasks in parallel threads. I created a Base task and let all tasks derived from this class execute. I just want to know if this a viable approach which won't cause unforeseen consequences if various tasks run in conjunction.

public abstract class BaseTask
{
     private readonly Timer _taskTimer = new Timer();

    // Derived classes to define thier own time Intervals
    protected abstract double TimerInterval { get; set; }

    public void Start()
    {
        // Set default Timer -- 10 seconds
        TimerInterval = 10000;

        _taskTimer.AutoReset = true;
        _taskTimer.Interval = TimerInterval;
        _taskTimer.Elapsed += ExecuteTask;
        _taskTimer.Start();
    }

    public void Stop()
    {
        _taskTimer.Stop();
    }

    public abstract void ExecuteTask(object sender, ElapsedEventArgs e);
}

// Derived Task Class
 class DerivedTask : BaseTask
 {
   protected override double TimerInterval
    {
        get { return 5000; }
        set {  }
    }

    public override void ExecuteTask(object sender, ElapsedEventArgs e)
    {
        // Do My Derived task operations here
    }
 }

 // Now In Main..
 static void Main()
 {
    DerivedTask dTask = new DerivedTask ();
    _dTask .Start();
 }


texts:
I have implemented the "[ ]" operator in a class that I have created to return values associated with a key (the same concept of a dictionary, except that it's possible to have the same key more than one time). However, looking at my code I don't think it is as efficient as it could be.

public class MyClass
{
    public object[][] Values;

    public MyClass()
    {
        Values = new object[4][];
    }

    public IEnumerable<object> this[string key]
    {
        get
        {
            var results = new List<object>();

            foreach (var value in this.Values)
            {
                if (value[0].ToString() == key)
                {
                     results.Add(value[1]);
                }
             }

            return results;
        }
    }
}

Values can contain a bunch of 2 values arrays.

A small example:

MyClass class = new MyClass();

class.Values[0] = new object[] { "key1", 25 };
class.Values[1] = new object[] { "key2", 3 };
class.Values[2] = new object[] { "key2", 789 };
class.Values[3] = new object[] { "key4", 12 };

and when I do class["key2"], it returns a collection containing 3 and 789.

What do you think of the way I implemented the this[string key] method? Do you think there is a way to do this without iterating on all the objects in the Values array?


texts:
I just finished working on a coding challenge for learning Python 2.7. Essentially, I'm a function that if it is fed a string such as:

"The man drank the drink and ate the bread and forgot the drink"

I get in return:

{'and': {'ate': 1, 'forgot': 1},
 'ate': {'the': 1},
 'bread': {'and': 1},
 'drank': {'the': 1},
 'drink': {'and': 1},
 'forgot': {'the': 1},
 'man': {'drank': 1},
 'the': {'bread': 1, 'drink': 2, 'man': 1}}

In other words, each word (that has a word following it) is a key, and the value is a dictionary of words that come right after, and the number of times that happens. (drink follows the twice in the string, hence the 2 value in its dictionary.

Here's the function I wrote to accomplish this end:

def word_counts(f):
      #Function to remove punctuation, change to lowercase, etc. from incoming string
    def string_clean(file_content):
        fc_new = "".join([i.lower() for i in file_content if i not in string.punctuation])
        fc_new = fc_new.split()
        return fc_new

    f = string_clean(f)
    unique_f = f[:]

    #For next part of function, get the unique words found in string.
    #We'll then run each through the string and find words that follow
    #Pop() the last word, since nothing follows it
    unique_f = list(set(unique_f.pop()))

    result = {}
    for word in unique_f:
        next_word_keeper = {}
        for _ in range(0, len(f)-1):
            if word == f[_]:
                if f[_+1] in next_word_keeper.keys():
                    next_word_keeper[f[_+1]] = next_word_keeper[f[_+1]] + 1
                else:
                    next_word_keeper[f[_+1]] = 1
        result[word] = next_word_keeper
    return result

Feedback appreciated, thanks.


texts:
I have spent all night whipping up this recipe. It's my first Python decorator. I feel like I have a full understanding of how decorators work now and I think I came up with a good object-oriented algorithm to automatically provide memoization. Please let me know what you think.

I made a few quick changes after pasting it in here so please let me know if my changes broke something (don't have an interpreter on hand).

"""This provides a way of automatically memoizing a function. Using this eliminates the need for extra code. Below is an example of how it would be used on a recursive Fibonacci sequence function:

    def fib(n):
        if n in (0, 1): return n
        return fib(n - 1) + fib(n - 2)

    fib = memoize(fib)

That's all there is to it. That is nearly identical to the following:

    _memos = {}
    def fib(n):
        if n in _memos:
            return _memos[n]
        if n in (0, 1):
            _memos[n] = n
            return _memos[n]
        _memos[n] = fib(n - 1) + fib(n - 2)
        return _memos[n]

The above is much more difficult to read than the first method. To make things even simpler, one can use the memoize function as a decorator like so:

    @memoize
    def fib(n):
        if n in (0, 1): return n
        return fib(n - 1) + fib(n - 2)

Both the first and third solutions are completely identical. However, the latter is recommended due to its elegance. Also, note that functions using keywords will purposely not work. This is because this memoization algorithm does not store keywords with the memos as it HEAVILY increases the CPU load. If you still want this functionality, please implement it at your own risk."""
class memoize:

    """Gives the class it's core functionality."""
    def __call__(self, *args):
        if args not in self._memos:
            self._memos[args] = self._function(*args)
        return self._memos[args]

    def __init__(self, function):
        self._memos = {}
        self._function = function

    # Please don't ask me to implement a get_memo(*args) function.

    """Indicated the existence of a particular memo given specific arguments."""
    def has_memo(self, *args):
        return args in self._memos

    """Returns a dictionary of all the memos."""
    @property
    def memos(self):
        return self._memos.copy()

    """Remove a particular memo given specific arguments. This is particularly useful if the particular memo is no longer correct."""
    def remove_memo(self, *args):
        del self._memos[args]

    """Removes all memos. This is particularly useful if something that affects the output has changed."""
    def remove_memos(self):
        self._memos.clear()

    """Set a particular memo. This is particularly useful to eliminate double-checking of base cases. Beware, think twice before using this."""
    def set_memo(self, args, value):
        self._memos[args] = value

    """Set multiple memos. This is particular useful to eliminate double-checking of base cases. Beware, think twice before using this."""
    def set_memos(self, map_of_memos):
        self._memos.update(map_of_memos)


texts: Two reimplementations of the Underscore _.reduce function

texts:
I am working on rewriting the underlying code for some Underscore.js functions. Re-writing the reduce function has been causing a lot of headaches. I have been able to re-write it two different ways, both work, but I was wondering which version is more efficient and if I could improve either one?

Reduce function one:

function reduce(collection, func, accumulator) {
            var i = 0;
            var isCollection = Array.isArray(collection);
            if (arguments.length < 3) {
                isCollection ? accumulator = collection[0] : Object.keys(collection)[0];
                i++;
            }

            if (isCollection) {
                for (; i < collection.length; i++) {
                    accumulator = func(accumulator, collection[i]);
                }
            } else {
                for (var key in collection) {
                    accumulator = func(accumulator, collection[key]);
                }
            }

            return accumulator;
        };

var numbers = [1, 2, 3];

var sum = reduce(numbers, function(total, number){
         return total + number;
       }, 0); // should be 6

console.log(sum);

Reduce function two:

      function reduceTwo(collection, func, accumulator) {
          var args = arguments.length < 3;

          each(collection, (item) => {
              if (args) {
                  accumulator = item;
                  args = false;
              } else {
                  accumulator = func(accumulator, item);
              }
          })
          return accumulator;

      };

      function each(collection, iterator) {
          if (Array.isArray(collection)) {
              for (var i = 0; i < collection.length; i++) {
                  iterator(collection[i], i, collection);
              }
          } else {
              for (var key in collection) {
                  iterator(collection[key], key, collection);
              }
          }

      };
      var numbers = [1, 2, 3]
      var sum = reduceTwo(numbers, function(total, number) {
          return total + number;
      }, 0); // should be 6

      console.log(sum)

EDIT: 1st function does not work on objects so rewrote it and now it works with objects.

var numbers = {a: 1, b: 2, c:3};
       var sum = reduce(numbers, function(total, number){
         return total + number;
       });

function reduce (collection, func, accumulator) {
        var i = 0;
        var isCollection = Array.isArray(collection);
        var keys = Object.keys(collection);
        var length = isCollection ? collection.length : keys.length;

        if (arguments.length < 3) {
            isCollection ? accumulator = collection[0] : accumulator = collection[keys[0]];
            i++;
        }

          for (; i < length; i++) {
                isCollection ? accumulator = func(accumulator, collection[i]) : accumulator = func(accumulator, collection[keys[i]]);
            }

        return accumulator;
    };

console.log(sum);


texts: Program to print a Python list as "a, b, and c"

texts:
I am a beginner (with zero Python experience) working through the book Automate the boring stuff with Python. At the end of Chapter 4, the author provides a review problem.

I was supposed to write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. Ex: 'apples, bananas, tofu, and hot dogs'. My function should be able to work with any list value passed to it.

I pulled together working code for the problem, but I cannot help but feel like there are concepts I am not quite understanding.  My solution is long, compared to the answers for a related Stack Overflow question. I feel that there must be redundant code in my answer. Could I bother someone to please point out obvious logical errors or areas where I use redundant code?

That said, I did include an error checking function (slightly outside the scope of the question) since we briefly learned about try and except usage in the previous chapter, and because I don't like the idea that a capital letter at the beginning of the input is able to break the program.

# defining possible lists
lists = ['cars','favorite foods','family members']
x = ['Hyundai','Acura','Honda','Suzuki','Ford']
y = ['apples','bananas','tofu','hot dogs']
z = ['Mother','Father','Dog','Cat','Grandmother','Grandfather','Cousins','Host family']

# defining functions
def listselection():
    print('The following lists exist within the system. Which would you like to see?')
    print(lists)

def errorchecking():
    global option

    while True:
        try:
            option = str(input())
        except:
            print('Please type letters, not numbers.')
            continue

        if option == 'cars':
            break
        elif option == 'favorite foods':
            break
        elif option == 'family members':
            break
        else:
            print('Please re-enter your selection')

    return option

def listconcatenation():
    global spam
    global listitem

    listitem = 'Here are the items in my list: '

    if option == 'cars':
        spam = x
    elif option == 'favorite foods':
        spam = y
    elif option == 'family members':
        spam = z

    for i in spam:
        if spam.index(i) < (len(spam)-1):
            listitem = listitem + i + ', '
        else:
            listitem = listitem + 'and ' + i + '.'

    return listitem

# run program
listselection()
errorchecking()
listconcatenation()
print(listitem)


texts: Find the pairs of integers that sum to N

texts:
Can it be made faster, and I am a newbie to complexity but I'm pretty sure the average case for this would be O(n). Am I wrong?
Output for the first list should be: (1,9), (2,8), (5,5), (-11,21)

The program finds pairs of an array whose sum is equal to ten.

#find pairs of an array whose sum is equal to ten
#bonus do it im linear time

list1 = [1,1,2,1,9,9,5,5,2,3,745,8,1,-11,21]
list2 = [1,1,1,1,9,9,9,9,2,8,8,8,2,2,0,0,0]
list3 = ["dog", "cat", "penguin", 9, 1]
list4 = []

def find_pairs_sum_n(list1, n):
    set1 = set(list1)
    history = set()

    if not list1:
        print("list is empty")
        raise StopIteration
    if not all(isinstance(n, int) for n in list1):
        print("list must contain only integers")
        raise StopIteration

    for x in set1:
        history.add(x)
        if (n - x) in set1 and (n-x) not in history:
            yield (x, n - x)

        elif x == n/2 and list1.count(n/2) > 1:
            yield (int(n/2), int(n/2))

x = find_pairs_sum_n(list1, 10)
for i in x:
    print(i)

y = find_pairs_sum_n(list2, 10)
for i in y:
    print(i)

z = find_pairs_sum_n(list3, 10)
print(next(z))

w = find_pairs_sum_n(list4, 10)
print(next(w))


texts:
I am working on a bit of a multiple part project, the goal of the project is to have a spreadsheet full of order data (order number, customer data, products ordered, prices etc) merged so that the duplicate information is grouped up.

The above is an example of what the data looks like when it comes in.

I then got it to unmerge so that it looks a little cleaner.

The code used for these two steps was created with much help from this community and looks like this:

Option Explicit

Sub MergeCells()

Dim i As Long, c As Long, col As Variant

Application.DisplayAlerts = False
'Application.ScreenUpdating = false

col = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK")

For c = LBound(col) To UBound(col)
    For i = Cells(Rows.Count, col(c)).End(xlUp).Row - 1 To 2 Step -1
        If Cells(i, col(c)).Value = Cells(i, col(c)).Offset(1, 0).Value And Not IsEmpty(Cells(i, col(c))) Then
            Cells(i, col(c)).Resize(2, 1).Merge
            Cells(i, col(c)).HorizontalAlignment = xlCenter
            Cells(i, col(c)).VerticalAlignment = xlCenter
        End If
    Next i
Next c

Application.DisplayAlerts = True
'Application.ScreenUpdating = True
End Sub

Then this:

Sub fixMergedCells(sh As Worksheet)
'replace merged cells by Center Acroos Selection
'high perf version using a hack: https://stackoverflow.com/a/9452164/78522
Dim c As Range, used As Range
Dim m As Range, i As Long
Dim constFla: constFla = Array(xlConstants, xlFormulas)

Set used = sh.UsedRange
For i = 0 To 1  '1 run for constants, 1 for formulas
    Err.Clear
    On Error Resume Next
    Set m = Intersect(used.Cells.SpecialCells(constFla(i)), used.Cells.SpecialCells(xlBlanks))
    On Error GoTo 0
    If Not m Is Nothing Then
        For Each c In m.Cells
            If c.MergeCells Then
                With c.MergeArea
                    'Debug.Print .Address
                    .UnMerge
                    .HorizontalAlignment = xlCenterAcrossSelection
                End With
            End If
        Next c
    End If
Next i
End Sub

And finally:

Sub fixMergedCells(Optional sh As Variant)

If IsMissing(sh) Then Set sh = ActiveSheet

sh.Cells.UnMerge

End Sub

I am currently working on two final steps, one to make sure that the data that got merged and then split will appear for each relevant line. Then I want to highlight each row that contains an order number so that we can see clearly where one order starts and another ends.

My last step of the plan is to combine all of the codes into one macro, as I want it to be easy for someone to use.

Thanks for reading, I just wanted to share what I've gotten so far and see what y'all think of my plan :)


texts:
Ran across this question today:

  write a class Tool which will have a function void type() that every
  derived class should implement . A function Action() that every
  derived class can override . function init() which is available to
  only Tool and variable Name which will tell which class`s instance is
  this object

Here is my solution (based on other solutions I've found):

#include <typeinfo>

  class Tool{

      public:
           string name;
           Tool() {
                 name = typeid(*this).name();
           };

           virtual void type() = 0;
           virtual void Action();

      private:
           void init();
  };

Could someone double check this please?


texts: Algo for generating a fake, but feasable, dataset

texts:
So, I was working on a dashboard for a potential customer and I needed a fake dataset with employee information to demonstrate. Mainly, I needed to know when the employee arrived the company (first swipe), when he left (last swipe) and the hours he spent in many other areas of the company (ORC is a room, DSP is another, and so on)

Basically, I create a random hour between 8am and 10am and assign this to the first swipe. I do the same for last swipe but in a range from 5pm to 7pm. Then, I calculate how many hours he worked by subtracting one from another.

With this information now I start to calculate how many hours he spent in every area of the company. The ORC is the working room, so I want to keep between 50% to 80% of hours worked there and the rest randomly assign to other areas.

I spent a lot of time in this code, and it's been a while since I created it. It's not the most pythonic code you will ever see, but it worked :D

import calendar
import datetime
import random

def random_hour(start, end):
    hour_rand = random.randint(start, end)
    minutes_rand = random.randint(0, 59)
    return datetime.timedelta(hours=hour_rand, minutes=minutes_rand)

def random_weight(total_working_hours):
    working_hours_per_area = {
        'in_orc': 0,
        'in_cafe': 0,
        'in_dsp': 0,
        'in_kiosk': 0,
        'in_training': 0,
    }

    whole_time = 100
    total_time = datetime.timedelta()

    for i, area in enumerate(working_hours_per_area):
        if whole_time < 0:
            whole_time = 0

        if i == 0:
            rand_time = random.randint(50, 80)
        else:
            rand_time = random.randint(0, whole_time)

        whole_time -= rand_time
        working_hours_per_area[area] = rand_time / 100

    total_aux = sum(working_hours_per_area.values())

    if total_aux < 1.0:
        diff = 1.0 - total_aux
        min_hour = min(working_hours_per_area.keys(), key=(lambda k: working_hours_per_area[k]))
        working_hours_per_area[area] += diff

    for area in working_hours_per_area:
        working_hours_per_area[area] = working_hours_per_area[area] * total_working_hours

    return working_hours_per_area

employees = [
    ['CHI-123', 'CLOVIS TONELADA'],
    ['CHI-456', 'JOSE DA COVA'],
    ['CHI-789', 'EMERSON PEDREIRA'],
    ['CHI-321', 'GREYCE CROQUETE'],
    ['CHI-654', 'ROBERTO PINGA'],
    ['CHI-987', 'CAROLINA DOZE AVOS'],
]

days = []
cal = calendar.Calendar()

for week in cal.monthdatescalendar(2020,9):
    for day in week:
        if day.weekday() < 5:
            days.append(day)

f = open('dataset.csv', 'w+')
f.write('Date;Employee_Name;Employee_Code;First_Swipe;Last_Swipe;Total_Working_Hours;In_ORC;In_Cafe;In_DSP;In_Kiosk;In_Training\n')

for day in days:
    for i in range(0, 6):
        date = day
        employee_name = employees[i][1]
        employee_code = employees[i][0]

        first_swipe = random_hour(8, 10)
        last_swipe = random_hour(17, 19)
        total_working_hours = last_swipe - first_swipe

        working_hours_per_area = random_weight(total_working_hours)
        total_working_hours_per_area = datetime.timedelta(hours=0, minutes=0)

        locals().update(working_hours_per_area)

        write = ';'.join([str(date), employee_name, employee_code, str(first_swipe), str(last_swipe), str(total_working_hours), \
            str(in_orc), str(in_cafe), str(in_dsp), str(in_kiosk), str(in_training)])
        f.write(write + '\n')
f.close()


texts:
I am trying to solve this problem:

  Igor has fallen in love with Tanya. Now Igor wants to show his
  feelings and write a number on the fence opposite to Tanya's house.
  Igor thinks that the larger the number is, the more chance to win
  Tanya's heart he has.

  Unfortunately, Igor could only get v liters of paint. He did the math
  and concluded that digit d requires \$a_d\$ liters of paint. Besides, Igor
  heard that Tanya doesn't like zeroes. That's why Igor won't use them
  in his number.

  Help Igor find the maximum number he can write on the fence.

  Input The first line contains a positive integer v (0 ≤ v ≤ \$10^6\$). The
  second line contains nine positive integers \$a_1\$, \$a_2\$, ..., \$a_9\$
  (1 ≤ \$a_i\$ ≤ \$10^5\$).

  Output Print the maximum number Igor can write on the fence. If he has
  too little paint for any digit (so, he cannot write anything), print
  -1.

https://codeforces.com/problemset/problem/349/B

My solution that works correctly, but times out:

from collections import defaultdict

v = int(input())
a = [int(i) for i in input().split()]
cache = {}

def dfs(v):
    if v in cache:
        return cache[v]
    res = 0
    for i, num in enumerate(a):
        if num == v:
            res = max(res, i+1)
        if num < v:
            x = dfs(v-num)
            if x > 0:
                s = str(i+1) + str(x)
            else:
                s = str(i+1)
            sorted_nums = sorted([str(i) for i in s], reverse=True)
            l = int("".join(sorted_nums))
            res = max(res, l)
    cache[v] = res
    return res

ans = dfs(v)
if ans == 0:
    print(-1)
else:
    print(ans)

How do I optimize it in terms of time complexity?


texts:
I'm trying to create a good way to manage throttling and debouncing  a lot of functions. What I have allows you to group, add and remove functions to instances of Booster. Each instance runs it's own timers and can be manipulated by methods.

Are there any major performance concerns with the approach below? I'm brand new to ES6, scope/context issues, and come from a mostly jQuery background—so I don't know much about performance, memory leaks, etc. Any tips are appreciated.

// booster.js

export default class Booster {

  constructor(method, type, amount, ...fn) {
    this.view = window;
    this.type = type;
    this.amount = amount;
    this.fn = fn ? fn : [];
    this.paused = false;
    this.method = method;
    this.init();
  }

  raf() {
    if (this.view.requestAnimationFrame) {
      this.view.requestAnimationFrame(this.run.bind(this));
    } else {
      this.run().bind(this);
    }
  }

  run() {
    if (0 < this.fn.length) {
      this.fn.forEach(function(fn) {
        fn();
      });
    }
  }

  throttle() {
    this.active = true;
    this.view.addEventListener(this.type, () => {
      if (this.active && !this.paused) {
        this.active = false;
        this.raf();
        this.timeout = setTimeout( () => {
          this.active = true;
        }, this.amount);
      }
    }, false);
  }

  debounce() {
    this.view.addEventListener(this.type, () => {
      if (!this.paused) {
        clearTimeout(this.timeout);
        this.timeout = setTimeout( () => {
          this.raf();
        }, this.amount);
      }
    }, false);
  }

  add(...fn) { this.fn.push(...fn); }
  remove(n) {
    if (n < this.fn.length && n >= 0) {
      this.fn.splice(n, 1)
    } else {
      throw new Error('There are only ' + this.fn.length + ' functions in this Booster.');
    }
  }

  pause()    { this.paused = true;}
  resume()   { this.paused = false; }
  toggle()   { this.paused = !this.paused; }

  init() {
    if      ('throttle' === this.method) { this.throttle(); }
    else if ('debounce' === this.method) { this.debounce(); }
    else { throw new Error('Invalid Booster method. Must be "throttle" or "debounce".'); }
  }
}

usage:

// main.js

import Booster from './classes/booster.js';

let scrollDebouncer1 = new Booster('debounce', 'scroll', 100, myFunction());

scrollDebouncer1.add(myOtherFunction());

scrollDebouncer1.pause();

// etc.


texts:
function reg(email, pass){
            $.ajax({
                url: "uman.php",
                type: "post",
                data:{email: email, password: pass},
                success: function(reply){
                if (reply == "success"){
                    $("#signinup").hide();
                    $("#donesucc").css("display","block");
                    console.log(reply);
                    }
                    if (reply == "duplicate"){
                        $("#signinup").hide();
                        $("#donedupe").css("display","block");
                    }
                }
            })
        }

Anything I should change? The PHP just echos the status of the query and Javascript takes that value and outputs the results through HTML.


texts: PHP Output Block Defining and Best Practices

texts:
I've been rolling around several ideas or approaches in my head, and none seem any more useful or "right" than another. I'm sure this is extremely objective but I'm looking for a close-to-definitive answer on the object oriented approach to large block string storage and output in PHP. Given the following example, how could I change my approach in a way that might cause Zeev Suraski to pat me on the back and say Mazel Tov (beside using HTML5)?

<?php

class OutputConstructor extends ContentRetriever // Or whatever I decide to name it
{

    protected $htmlHeadBlock;

    public function __construct()
    {

        $this->setHtmlHeadBlock();

    }

    protected function setHtmlHeadBlock()
    {

        ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <title><?php echo $this->pageTitle; ?></title>

        <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
        <link rel="icon" href="images/favicon.ico" type="image/x-icon" />

        <meta name="description" content="<?php echo $this->pageDescription; ?>" />
        <meta name="keywords" content="<?php echo $this->pageKeywords; ?>" />

        <link type="text/css" rel="stylesheet" href="css/style.css" />
        <script type="text/javascript" src="js/functions.js"></script>
    </head>
<?php
        $this->htmlHeadBlock = ob_get_clean();

    }

    public function getHtmlHeadBlock()
    {

        return $this->htmlHeadBlock;

    }

} // End of OutputConstructor

?>

The general theme I'm going with in this example class is that on construction, html is stored in a variable via output buffer and then returned by a public method. When evaluating this code, consider that the html will not be static. Page title, description, keywords and the such will be subbed out with dynamic property references. My overall question is: In object oriented programming, ideally where should the output be stored? PHP's DOMDocument class, however useful, doesn't really answer this question for me. Also in this instance, is there any best practice trade-off between using an output buffer and heredoc syntax? Thanks in advance for your guidance!


texts:
I have a working solution for 'Cut the tree' problem but it is not fast enough.

  Problem Statement:

  Atul is into graph theory, and he is learning about trees nowadays. He observed that the removal of an edge from a given tree T will result in the formation of two separate trees, T1 and T2.

  Each vertex of the tree T is assigned a positive integer. Your task is to remove an edge, such that the Tree_diff of the resultant trees is minimized. Tree_diff is defined as the following:

 F(T) = Sum of numbers written on each vertex of a tree T
 Tree_diff(T) = abs(F(T1) - F(T2))

  Input Format:

  The first line will contain an integer \$N\$, i.e. the number of vertices in the tree.

  The next line will contain \$N\$ integers separated by a single space, i.e. the values assigned to each of the vertices.

  The next \$N−1\$ lines contain a pair of integers each, separated by a single space, that denote the edges of the tree.

  In the above input, the vertices are numbered from \$1\$ to \$N\$.

  Output Format:

  A single line containing the minimum value of Tree_diff.

  Constraints:

  \$3≤N≤105\$
  \$1≤\$ number written on each vertex \$≤1001\$

  Sample Input:

6
100 200 100 500 100 600
1 2
2 3
2 5
4 5
5 6

  Sample Output:

400

  Explanation:

  Originally, we can represent tree as

         1(100)
          \
           2(200)
          / \
    (100)5   3(100)
        / \
  (500)4   6(600)

Cutting the edge at 1 2 would result in Tree_diff = 1500-100 = 1400
Cutting the edge at 2 3 would result in Tree_diff = 1500-100 = 1400
Cutting the edge at 2 5 would result in Tree_diff = 1200-400 = 800
Cutting the edge at 4 5 would result in Tree_diff = 1100-500 = 600
Cutting the edge at 5 6 would result in Tree_diff = 1000-600 = 400

  Hence, the answer is 400.

The solution is in Python, with iterative BFS. I could only pass the first five tests and timed out on the rest. Any hints for improving time complexity? Input size can be up to \$100,000\$ vertices.

def find_sum(v, p):
    s = vertices[v-1]
    stack  = [(v,p)]
    while stack:
        v,p = stack.pop()
        for e in adj_list[v]:
            if p != e:
                s += vertices[e-1]
                stack.append((e,v))
    return s

n = int(raw_input())
vertices = map(int, raw_input().split())
adj_list = {}
edges = []
total = sum(vertices)
res = total
for _ in xrange(n-1):
    u, v = map(int, raw_input().split())
    edges.append((u,v))
    if u not in adj_list:
        adj_list[u] = []
    if v not in adj_list:
        adj_list[v] = []
    adj_list[v].append(u)
    adj_list[u].append(v)

for u,v in edges:
    tmp = find_sum(u,v)
    res = min(res, abs(tmp-abs(total-tmp)))
print res


texts: QT - Class For Connecting to Mqtt Broker With QMqttClient

texts:
Task:

Class for connecting to a mqtt broker using QMqttClient and getting notified on connect and disconnect.

Context:

I'm trying to write modern C++ (standard 2011 and up) code - using smart pointers. I have only created small projects for learning C++. I'm not very confident if I'm using those pointers correctly.

The implementation:

The implementation is in the client.h and client.cpp header file. The first code snippet is the client.h one.

#ifndef CLIENT_H
#define CLIENT_H

#include <QString>
#include <QObject>
#include <QtMqtt/QtMqtt>
#include <memory>
#include <iostream>

struct MqttConfig {
    MqttConfig() {
        hostname = "localhost";
        port = 1883;
    }

    QString hostname;
    quint16 port;
};

struct SubscriptionConfig
{
    SubscriptionConfig() = delete;
    SubscriptionConfig(QString t, quint16 q) :
        topic(t), qos(q)
    {}

    QString topic;
    quint16 qos; // quality of service
};

class Client : public QObject
{
    Q_OBJECT

private:
    std::unique_ptr<QMqttClient> mqtt;
    std::unique_ptr<MqttConfig> c;

public:
    Client();
    void connectToSignals();
    void configureClient(std::unique_ptr<MqttConfig>&);
    void connect();

public slots:
    void onConnected()
    { std::cout << "Connected to mqtt broker " << std::endl; }
    void onDisconnected()
    { std::cout << "Disconnected from mqtt broker" << std::endl; }
};

#endif // CLIENT_H

Am I violating the DRY principle (don't repeat yourself) in the method connectToSignals ? And how could I avoid this?

#include "client.h"

Client::Client()
{
    mqtt = std::make_unique<QMqttClient>();
    c = std::make_unique<MqttConfig>();
    configureClient(c);
    connectToSignals();
    connect();
}

void Client::connectToSignals()
{
    QObject::connect(Client::mqtt.get(), &QMqttClient::connected, this,
                     &Client::onConnected);
    QObject::connect(Client::mqtt.get(), &QMqttClient::disconnected, this,
                     &Client::onDisconnected);
}

void Client::configureClient(std::unique_ptr<MqttConfig>& c)
{
    mqtt->setHostname(c->hostname);
    mqtt->setPort(c->port);
}

void Client::connect()
{
    mqtt->connectToHost();
}


texts:
I'm having some trouble improving the Connect 4 game that is made in Python. I was wondering if I could get rid of the global statements and pass the variables between parameters and return its values. Also to put all of this in a class. I was wondering if this is possible.

And any more improvements that I could use would be appreciated a lot. Be gentle since I'm a newbie with Python.

grids = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

check = []

user = 1

# THIS WAS VERSION ONE
# def GridBuilder(x,y):
#     Colum_Count_Str = x
#     Colum_Count = int(Colum_Count_Str)
#     Row_Count_Str = y
#     Row_Count = int(Row_Count_Str)
#
#     Grids = [] * Colum_Count
#
#     for Current_Grid_Insert in range (Colum_Count):
#        Grids.insert(Current_Grid_Insert,[0]*Row_Count)
#
#     return Grids

class FullCapacity_error(Exception):
    pass

def user_def():
    #Change the global vartiables into local variables
    #Define them in the parameters of the functions.
    global user
    if user < 2:
        user = 2
    else:
        user = 1
    return user

def FullCapacity():
    global FullCapacity_error
    while True:
        try:
            if grids[3][userInput - 1] != 0:
                raise FullCapacity_error
            else:
                break
        except FullCapacity_error:
            print("This row is full, try another one!")
            confirmed()

def confirmed():
    PlayTheGame = True
    while PlayTheGame:
        try:
            global userInput
            userInput = int(input("\n Input a coin, player " + str(user) + "(1,4)\n"))
            if 5 > userInput > 0:
                PlayTheGame = False
            else:
                print("This number exceeds the board value.")
        except ValueError:
            print("This number exceeds the board value.")

def placement_def():
    for i in range(0, 4):
        counter = 0
        FullCapacity()
        if grids[i][userInput - 1] == 0:
            grids[i][userInput - 1] = int(user)
            print("\n Current Board\n", grids[3], "\n", grids[2], "\n", grids[1], "\n", grids[0])
            break

def check_def():
    global loop
    global check
    for i in range(0, 4):
        for a in range(0, 4):
            check.append(grids[i][a])
        if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
            print("player " + str(user) + " has won")
            loop = False
            return loop

        else:
            check = []
    for i in range(0, 4):
        for a in range(0, 4):
            check.append(grids[a][i])
        if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
            print("player " + str(user) + " has won")
            loop = False
            return loop

        else:
            check = []

def checkEmpty_def():
    global check
    for i in range(0, 4):
        for a in range(0, 4):
            check.append(grids[i][a])
    if 0 not in check:
        print("full")

def checks_def():
    return check_def() and checkEmpty_def() and diagcheck_def()

def diagcheck_def():
    global loop
    global check
    check = []
    diag = 0
    for i in range(0, 4):
        check.append(grids[diag][diag])
        diag = diag + 1
        if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
            print("player " + str(user) + " has won")
            loop = False
            return loop

    check = []
    diag = 3
    diag2 = 0
    for i in range(0, 4):
        check.append(grids[diag][diag2])
        if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
            print("player " + str(user) + " has won")
            loop = False
            return loop

loop = True

while loop:
    check_def()
    confirmed()
    placement_def()
    checks_def()
    if not loop:
        break
    user_def()


texts: Gathers pair of names (first + last) and separate them into two files

texts:
I'm a beginner in Python programming. Currently, I learn how to work on the files...
I've created a program, which excludes the names (first & last) from each row, that contains both of them. When the pair of names does not include for example the Last Name part, it places n/a in the last_names.txt file.

Like from the file names.txt:

Paul Morgan
James Kowalski
Thomas

sort to two files

firstnames.txt:

Paul
James
Thomas

lastnames.txt:

Morgan
Kowalski
n/a

"""
Program separating first names and last names gathered in pairs from one file and saving them into two files.
"""

"Global Variables:"
allNamesFromFile = []

def names_separator(fileName):
    with open(fileName, "r+", encoding="utf-8-sig") as namesFromFile:
        for names in namesFromFile:
            allNamesFromFile.append(tuple(names.replace("\n", "").split(" ")))
        open("last_names.txt", "w").close() #cleaning the last_names.txt file
        open("first_names.txt", "w").close() #cleaning the first_names.txt file
        lastNamesFile = open("last_names.txt", "a+", encoding="utf-8-sig")
        firstNamesFile = open("first_names.txt", "a+", encoding="utf-8-sig")
        for namesTuples in allNamesFromFile:
            try:
                lastNamesFile.write(namesTuples[1] + "\n")
            except:
                lastNamesFile.write("n/a\n")
            try:
                firstNamesFile.write(namesTuples[0] + "\n")
            except:
                firstNamesFile.write("n/a\n")
    lastNamesFile.close()
    firstNamesFile.close()

print("welcome in the names separator program...")
while True:
    fileName = str(input("Please provide the file name with its extension: "))
    try:
        names_separator(fileName)
        print("operation completed")
        break
    except:
        print("You have provided an incorrect file name...")
        continue

I wonder if there is anything I could improve in this code... I wanted to use list + tuples.
The program works correctly, but I want to review it and maybe improve if it's possible. Maybe I could write it shorter/better, or just its functionality can be optimized?

Thanks in advance.


texts: Postgres query to extract a JSON sub-object from a JSON field

texts:
I have a json field in a table that I want to select certain fields from into a new json field. So far I have this, which works, but I feel may not be optimal:

select to_json(new_obj) from (
    select big_json_field->'json_property_1' as json_property_1,
    big_json_field->'json_property_2' as json_property_2
    from table_with_big_json_field
) as new_obj

Is there a function or method I'm missing to optimize this?


texts:
At the documentation for QGraphicsScene, there is a simple example that does not work as written. I've written a fix that does work, and am curious if it could be improved.

From the docs (does not work as is):

scene = QGraphicsScene()
scene.addText("Hello, world!")
view = QGraphicsView(&scene)
view.show()

Fixed version that does work:

from PySide import QtGui
import sys

class MyFirstScene(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.scene=QtGui.QGraphicsScene(self)
        self.scene.addText("Hello, world!")
        self.view = QtGui.QGraphicsView(self.scene, self)
        self.show()

if __name__=="__main__":
    app=QtGui.QApplication(sys.argv)
    firstScene = MyFirstScene()
    sys.exit(app.exec_())

My question is whether I can simplify this more, making it more like the example in the documentation. I tried doing it without making the scene an attribute of QWidget, which breaks it. But perhaps I'm missing a simpler working implementation of the documentation's skeleton?


texts: Deleting three consecutive numbers in an array

texts:
I am a beginner in programming, started about 2 months ago with Java, changing careers from law.

I have recently applied for an internship but was denied because I failed to do the pre-interview test right.

One of the tasks was to keep deleting 3 consecutive same integers from the array until the list is either empty or has no 3 consecutive same numbers. The assignment can be found here.

Below a description of the task with examples:

  Three brothers walk into a bar. All the beverages are placed in one
  line at the long bar table. The size of each glass is represented in
  an array of integers, glasses. The brothers will drink a round if they
  can find 3 consecutive glasses of the same size. The barman removes
  the empty glasses from the table immediately after each round. Find
  the maximum number of rounds the three brothers can drink.

  For glasses = [1, 1, 2, 3, 3, 3, 2, 2, 1, 1], the output should be
  brothersInTheBar(glasses) = 3. The brothers can start with a round of
  size 3, then after the glasses are cleared, a round of size 2 can be
  formed, followed by a round of size 1. One glass will be left at the
  table.

  For glasses = [1, 1, 2, 1, 2, 2, 1, 1], the output should be
  brothersInTheBar(glasses) = 0. There are no 3 consecutive glasses of
  the same size.

This is my code:

    public int brothersInTheBar(int[] glasses){

    if(glasses.length<=2)
        return 0;

    ArrayList<Integer> glassesAsList = new ArrayList<Integer>();
    Arrays.stream(glasses).forEach(i -> glassesAsList.add(i));

    int counter=0;
    for (int x=0;x<glassesAsList.size()-2;++x){

        if(glassesAsList.get(x) == glassesAsList.get(x+1) && glassesAsList.get(x) == glassesAsList.get(x+2)){
            glassesAsList.remove(x);
            glassesAsList.remove(x);
            glassesAsList.remove(x);
            counter++;
            x=-1;
        }
        if(glassesAsList.isEmpty())
            break;
    }
 return counter;
 }

I sent the email back asking what I did wrong, so I can improve in the future. The response from the company only said that I have to look more into algorithm complexity and that my code is inefficient.

So my question is how to improve my algorithm and what is wrong with it?


texts: A simple project of getting Mars Rover images from NASA API and displaying them in JSON format

texts:
I am learning to program and I have created this simple project in Python where I extract Mars Rover images for a given date from the NASA API:
https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=2021-05-28&camera=NAVCAM&api_key=DEMO_KEY
and display all the images for the last 10 days from the current date in JSON format. The keys are the dates and their values are a list of all the images taken by Mars Rover on that date.
I stored all the images in a file as a cache to avoid exceeding the rate limit to the API (although a local file is not a great choice of caching, but I didn't want to use any libraries for that).
I have got all the output as desired and the project is working fine. However, I am not sure if my design and approach are acceptable, like following Object-Oriented, SOLID, and DRY principles, or if it's really clumsy.
I would like to have someone review my code, and give me honest feedback on my code, whether this is of the standard that interviewers look for.
This is the Github link to the project and if you wish to run the code for yourself, feel free to do so and follow the instructions in the READMe file in the project.
https://github.com/Vivek-Parupudi/nasaApiImages
Thanks in advance!
Sample output (included only a single date for the sake of simplicity):
{
"2021-05-19": [
    "https://mars.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/03123/opgs/edr/ncam/NLB_674737022EDR_F0880366NCAM00253M_.JPG",
    "https://mars.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/03123/opgs/edr/ncam/NLB_674736991EDR_F0880366NCAM00253M_.JPG",
    "https://mars.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/03123/opgs/edr/ncam/NLB_674736907EDR_F0880366NCAM00253M_.JPG" ]

}


texts: BASH Script to Configure Monitors on Linux via xRandR

texts:
My main computer is a laptop which I run i3wm atop Arch Linux. As such, my monitor situation sometimes changes, so I wanted to code a script to configure my monitors based on which ones are connected to the system. The script runs on startup of i3wm.

As for the monitors, sometimes I may not have an external display connected, sometimes I may have an HDMI and a DP display connected, and sometimes I may be at another location with an HDMI and DP display connected but the DP appears as a different output.

The monitors are as follows:

eDP-1 - Internal Display.
HDMI-2 - Either of my secondary displays, which have the same resolution and placement
DP-1 or DP-1-8 - Either of my primary displays, which are the same monitor and placement, but appear as different outputs.

The code is as follows:

#!/usr/bin/env bash

# The xRandR names of my monitors, including the internal laptop monitor / display
readonly MON_INTERNAL='eDP-1'
readonly MON1='DP-1'
readonly MON1_FALLBACK='DP-1-8'
readonly MON2='HDMI-2'

# The resolutiond of the given xRandR monitors / displays. NOTE: $MON1 and $MON1_FALLBACK are the same display, so only one res is needed
readonly MON_INTERNAL_RES='1920x1080'
readonly MON1_RES='2560x1440'
readonly MON2_RES='1680x1050'

main_mon=''
sec_mon=''

# Store a count of how many monitors are connected
mon_count=$(xrandr -q | grep -w 'connected' | wc -l)

# Configure the monitors via xRandR
config_monitors() {
    if [[ "$#" -eq "2" ]]; then
        xrandr --output $1 --primary --mode $2 --rotate normal --pos 0x0
    elif [[ "$#" -eq "4" ]]; then
        xrandr --output $MON_INTERNAL --off --output $1 --mode $2 --pos 1680x0 --right-of $3 --output $3 --mode $4 --pos 0x0 --left-of $1
    fi
}

# Determine which main monitor is available
if [[ $mon_count -gt 1 ]]; then
    # The name of which main monitor is connected (either $MON1 or $MON1_FALLBACK)
    main_mon=$(xrandr -q | grep -w 'connected'| grep "^$MON1\|^$MON1_FALLBACK" | awk '{ print $1 }')
else # fallback to laptop display $MON_INTERNAL because the hardcoded displays aren't connected
    main_mon=$MON_INTERNAL
fi

# Determine whether the secondary HDMI monitor, $MON2 is connected
if [[ $mon_count -gt 1 ]] && [[ $(xrandr -q | grep $MON2 | awk '{ print $2 }') -eq connected ]]; then
    sec_mon=$MON2
fi

# Configure both external monitors if they're set or use the internal display
# TODO: Actual fallback logic for when HDMI display is connected but not the primary DP-x..
if [[ -n $main_mon ]] && [[ -n $sec_mon ]]; then
    config_monitors "$main_mon" "$MON1_RES" "$sec_mon" "$MON2_RES"
else
    config_monitors "$MON_INTERNAL" "$MON_INTERNAL_RES"
fi

Any suggestions on how I could improve the functionality and/or readability of this script are greatly appreciated. This is my first true foray into writing a Bash script that actually serves a usable real-world purpose to me.


texts: Producer consumer that simulates the interaction of threads controlling a hardware device

texts:
I have a producer consumer that simulates the interaction of threads controlling a hardware device.

I have 1 thread controlling the device, 1 thread reading, and 1 thread outputting.  The read is synchronous on the thread while the controlling is asynchronous.

My producer is the thread controlling the device and my consumer is a thread that processes the data. Often the consumer takes about the same amount of time as the producer (ideal), but sometimes it takes more time.

The hope is  that the producer should not produce more than the consumer can process. This is partly due to hardware overflow, the consumer will free a buffer on the device, and partly due to visual latency.

I think the producer should be responsible for regulating the rate of production. I implemented this regulation using a sleep timeout.

I am wondering if this is the best way to do it.

My heuristic for success is the time output of the redraw command, which should be roughly ConsumerTime*8 (maybe 400).

#include <cstdlib>
#include <thread>
#include <condition_variable>
#include <iostream>
#include <atomic>
#include <chrono>
//UTILITY
//
using namespace std;
#if !defined(WIN32)
#include <unistd.h>
void
_sleep (int ms)
{
    usleep (ms * 1000); //convert to microseconds
}
#endif
long long
timestamp ()
{
    auto now = std::chrono::system_clock::now ();
    auto duration = now.time_since_epoch ();
    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count ();
    return millis;
}
//REDRAW
//
bool killRedraw;
bool drawIt;
long long last;
void
redraw ()
{
    cout << "Starting drawing thread" << endl;
    last = timestamp ();
    while (!killRedraw)
    {
        if (drawIt)
        {
            long long now = timestamp ();
            cout << "I drew it:" << now - last << endl;
            last = now;
            drawIt = false;
        }
        _sleep (15);
    }
}
//PRODUCER
//
atomic<int> balance;
bool killProducer;
void
produce ()
{
    cout << "Made one:" << ++balance << endl;
}
void
producer ()
{
    balance = 0;
    cout << "Starting producer thread" << endl;
    while (!killProducer)
    {
        _sleep (40);
        produce ();
        while (balance > 1)
        {
            _sleep (10);
        }
    }
}
//CONSUMER
//
bool killConsumer;
void
consume ()
{
    cout << "Ate one:" << --balance << endl;
}
void
consumer ()
{
    cout << "Starting consumer thread" << endl;
    while (!killConsumer)
    {
        int basetime = 35;
        int noise = rand () % 20;
        _sleep (basetime + noise);
        consume ();
        static int cycle = -1;
        if ((cycle = ++cycle % 8) == 7)
        {
            drawIt = true;
        }
    }
}
//Main
//
int
main (int argc, char** argv)
{
    //
    // Important metric is the "draw it" time, which should be about 8*50
    //
    killProducer = false;
    std::thread tP (producer);
    killConsumer = false;
    std::thread tC (consumer);
    killRedraw = false;
    drawIt = false;
    std::thread tD (redraw);
    _sleep (10000);
    killProducer = true;
    killConsumer = true;
    killRedraw = true;
    tD.join ();
    tP.join ();
    tC.join ();
    //
    return 0;
}


texts: CodeChef's Tree MEX (Minimum Excludant) challenge

texts:
This code is a solution for CodeChef's Tree MEX problem:

  Minimum excludant (or MEX for short) of a collection of integers is
  the smallest non-negative integer not present in the set.

  You have a tree \$ T \$ with \$n\$ vertices. Consider an ordering \$ P=(v_1,\ldots,v_n) \$
  of vertices of \$T\$. We construct a sequence \$A(P)=(a_1,\ldots,a_n)\$ using the
  following process:

  Set all \$a_i=−1\$.
  Process vertices in order \$v_1,\ldots,v_n\$. For the current vertex \$v_i \$ set  \$a_i=\operatorname{MEX}(a_{u_1},\ldots,a_{u_k})\$, where \$u_1,\ldots,u_k\$ is the set of neighbours of
  \$v_i\$.

  For instance, let  \$n=3\$ and \$T\$ be the tree with edges \$(1,2)\$ and
  \$(2,3)\$. Then,  for the ordering \$P=(1,2,3)\$ we obtain the sequence
  \$A(P)=(0,1,0)\$, while    for the ordering \$P=(2,3,1)\$ we obtain
  \$A(P)=(1,0,1)\$.

  Consider all \$n!\$ orders \$P\$. How many different sequences
  \$A(P)\$ can we obtain? Print the answer modulo \$10^9+7\$.

I have created a graph from list of tuples and then calculated mex values for each permutation.

Ex: 3    # 3 vertices
    1 2  # (1,2) edge
    2 3  # (2,3) edge

permutations(1,2,3) ==> we get 6 combinations

For 6 combinations we will get 6 values. I need to print distinct count of that 6 values.

Code:

# https://www.codechef.com/problems/TREEMX

from collections import defaultdict
from itertools import permutations

class Graph:
    """ Graph is data structure(directed). """

    def __init__(self, connections):
        """ Initializing graph with set as default value. """
        self._graph = defaultdict(set)
        self.add_connections(connections)

    def add_connections(self, connections):
        """ Add connections(list of tupules) to graph. """
        for node1, node2 in connections:
            self.add(node1,node2)

    def add(self, node1, node2):
        """ Add node1 and node2 to graph which is initialized with set by default. """
        self._graph[node1].add(node2)
        self._graph[node2].add(node1)

    def get_graph(self):
        return dict(self._graph)

def mex(arr_set):
    mex = 0
    while mex in arr_set:
        mex+=1
    return mex

def process(graph, order):
    a_p = [-1] * len(order)
    for el in order:
        a_p[el-1] = mex([a_p[u-1] for u in graph[el]])
    return a_p

t = int(input())
for _ in range(t):
    v = int(input())
    e = []
    for i in range(v-1):
        e.append(tuple(map(int, input().split())))

    g = Graph(e)
    all_vertices = {s for i in e for s in i}
    result = []
    for p in permutations(all_vertices, v):
        out = process(g.get_graph(), p)
        result.append(out) if out not in result else None

    print(len(result) % ((10**9)+7))

Constraints:

\$1≤T≤10\$
\$1≤n≤10^5\$
\$1≤u_i,v_i≤n\$
\$u_i≠v_i\$

How can I optimize the code, to get rid of the "time limit exceeded" error?


texts: Acquiring the number of contracts for persons

texts:
This script shows the number of contracts for persons. Table Contract has more than 82008 records and Candidate has about 7978.

Could you please suggest improvements for this script?

select ISNULL(CON.ContractCount, 0)
,      CAN.PersoonName
,      ... /* some fields from table Candidate (more than 25) */
from   Candidate CAN
       left join (select PersoonID, COUNT(*) ContractCount
                  from Contract
                  group by PersoonID) CON on CAN.PersoonID = CON .PersoonID
where CAN.Type = 11


texts: Manipulating URL/array to remove the last element

texts:
Is there a better way to do this using chaining?

var url = "www.mycompany.com/sites/demo/t1"
var x = url.split('/');
console.log(x);
var y = x.pop();
console.log(y,x);
var z = x.join("/");
console.log(z);

I tried something like but wouldn't work since pop just returns the last value and not the rest:

 parentUrl = self.attr('Url').split("/").pop().join("/");


texts: Python XML parsing, extraction and renaming files

texts:
I've written some code to:

Parse an XML file.
Extract some strings.
Make copies of the original XML whose names are suffixed with the extracted strings.

Please review this.

from lxml import etree as ET
import re

def create_paramsuffix_copies(xmlfile):

    NSMAP = {"c": "http://www.copasi.org/static/schema"}

    parsed = ET.parse(xmlfile)

    list_of_params = []

    for a in parsed.xpath("//c:Reaction", namespaces=NSMAP):
        for b in a.xpath(".//c:Constant", namespaces=NSMAP):
            list_of_params.append((a.attrib['name'])+'_'+(b.attrib['name']))

    return list_of_params

def add_suffix(xmlfile, name_suffix):

    parsed = ET.parse(xmlfile) #parse xml

    xmlfile = re.sub('.cps', '', xmlfile) #remove suffix

    parsed.write(xmlfile+'_'+name_suffix+'.cps',
                 xml_declaration = True,
                 encoding = 'utf-8',
                 method = 'xml')

modelfile = 'ct.cps'

for a in create_paramsuffix_copies(modelfile):
    add_suffix(modelfile,a)


texts:
I am writing a control panel with Sliders but I think my code is messy and cumbersome, what can I do to improve it?

public class Input_Window extends JFrame {
    JSlider myslideA,myslideB,myslideC,myslideD;

    Input_Window(){
        System.out.println("* Control Window");
        setBackground(Color.GRAY);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Controls");
        setSize(200,400);
        setLocation(1200,250);
        setLayout(new FlowLayout());
        myslideA=slider(0,10,3,1,true,true);
        add(myslideA);
        myslideB=slider(0,10,3,1,true,true);
        add(myslideB);
        myslideC=slider(0,10,3,1,true,true);
        add(myslideC);
        myslideD=slider(0,10,3,1,true,true);
        add(myslideD);
        setVisible(true);
        setFocusable(true);
        requestFocus();
    }

    public final JSlider slider(int min, int max, int def, int maj, boolean ticks, boolean labels){

        JSlider myslide=new JSlider(JSlider.HORIZONTAL,min,max,def);
        myslide.setMajorTickSpacing(maj);
        myslide.setPaintTicks(ticks);
        myslide.setPaintLabels(labels);
        return (myslide);
    }

}


texts: Reusable REST service class for Angular2 in TypeScript

texts:
I am creating an Angular 2 web application using TypeScript. This application performs REST requests to a REST "service". For each REST resource in my service I create a separate "Service" class in Angular2/typescript (e.g., class ServiceA for resource A, class ServiceB for resource B, and so on. Each service class will accept a TypeScript class object that has information about the resource. The user who uses the Service class only deals with resource class instances and not with data serialization etc. All my REST resources support the same actions ('GET', 'POST', etc) and the only difference between them is their api URL and the metadata they might return (right now the 'GET' and 'POST' actions return some metadata in XML format.

The problem is that my REST API has so many resources and I found myself repeating the same Service code again and again. So I decided to refactor the code and have one base Service class that does all the work. Then for each resource I just extend the base class and I also pass the desired serializer through the constructor of the base class. I could ditch the serializer completely and have the serialization code inside the Resource class, but I didn't do so because I want to be able to change the serialization format easily in the future. Furthermore, the service classes that extend the base Service class provide helper functions that do type casting in order to set the correct resource type after the resource creation.

Could you have a look at the code and tell me if I am doing something really wrong? I haven't written any TypeScript or JavaScript in the past and I am afraid that there is a much better solution. In addition I have to mention that initially I tried to use Generics but I kinda failed (Turns out generics are much different than C++ templates). Here is the code:

export class Resource {
}

export class ResourceA extends Resource {
}

// and then ResourceB, ResourceC, and so on.

export class Serializer
{
    public serialize(resource: Resource): string {return null;};
    public deserialize(resourceStr: string): Resource {return null;};
}

export class SerializerA extends Serializer
{
    public serialize(resource: Resource): string {return "serialized resource";};
    public deserialize(resourceStr: string): Resource {return new ResourceA();};
}

// and then SerializerB, SerializerC, and so on.

export class Service
{
    private serializer: Serializer;

    constructor(serializer: Serializer) {
        this.serializer = serializer;
    }

    public getResource(): Resource {
        let incomingData = "some xml or json or whatever.";
        return this.serializer.deserialize(incomingData);
    }

    public postResource(resource: Resource) {
        let outcomingData = this.serializer.serialize(resource);
        // emmit the serialized data string
    }
}

export class ServiceA extends Service
{
    constructor() {
        super(new SerializerA());
    }

    public getResourceOfTypeA(): ResourceA {
        return <ResourceA>this.getResource();
    }

    public postResourceOfTypeA(resource: ResourceA) {
        this.postResource(resource);
    }
}

// and then ServiceB, ServiceC, and so on.

Of course the code is simplified. The full version generates/returns Observables and also uses Angular2's Http module to do the REST/HTTP requests. Any kind of feedback is more than welcome!


texts:
I wonder if there is a more "functional" way of implementing something like this:

@months.zipWithIndex.foreach { case (month, index) =>
    if (index%3 == 0) {

    }
    @month
    if (index%3 == 0) {

    }
}

Can these two if-statements be removed by using something other than foreach?


texts:
So I've attempted this project from hyperskills where you're asked to make a calculator script that can calculate annuity and differentiated payments given that 3 of 4 values are known. I think i went with a real hardcoding way of doing this, as such I would like some advice on making my code more compact and efficient.

import math
import sys

def convert_month_into_years_months(months):
    years, months = divmod(months, 12)
    if years != 1:
        s_year = "s"
    else:
        s_year = ""

    if months != 1:
        s_month = "s"
    else:
        s_month = ""

    if not years:
        return f"You need {months} month{s_month} to repay this credit!"
    elif not months:
        return f"You need {years} year{s_year} to repay this credit!"
    else:
        return f"You need {years} year{s_year} and {months} month{s_month} to repay this credit!"

credit_principal_given = False
period_count_given = False
credit_interest_given = False
monthly_payment_given = False
annuity = False
diff = False

period_count = monthly_payment = credit_principal = credit_interest = 1

command_line = sys.argv
number_of_arguments = len(command_line[1:])
type_of_payment = command_line[1] if number_of_arguments != 0 else None

run = True
if type_of_payment == "--type=diff" and number_of_arguments == 4:
    diff = True
elif type_of_payment == "--type=annuity" and number_of_arguments == 4:
    annuity = True
else:
    run = False

if run:
    for arg in command_line[2:]:
        try:
            if arg[:10] == "--periods=":
                period_count = int(arg[10:])
                period_count_given = True
            elif arg[:10] == "--payment=" and annuity:
                monthly_payment = float(arg[10:])
                monthly_payment_given = True
            elif arg[:11] == "--interest=":
                credit_interest = float(arg[11:])
                credit_interest_given = True
            elif arg[:12] == "--principal=":
                credit_principal = float(arg[12:])
                credit_principal_given = True
        except:
            run = False
            break

    # Checks if any of the values are negative
    values = [period_count ,monthly_payment ,credit_principal ,credit_interest]
    if not all(True if value > 0 else False for value in values):
        run = False

if run:

    nominal_interest_rate = (credit_interest/100)/12

    if annuity:
        if credit_principal_given and monthly_payment_given and credit_interest_given:
            period_count = math.ceil(math.log( (monthly_payment/( monthly_payment - ( nominal_interest_rate * credit_principal ) ) ), 1+nominal_interest_rate ))
            print(convert_month_into_years_months(period_count))

        elif monthly_payment_given and period_count_given and credit_interest_given:
            credit_principal = math.floor(monthly_payment / ( (nominal_interest_rate * (1 + nominal_interest_rate)**period_count )/( (1 + nominal_interest_rate)**period_count - 1) ) )
            print(f"Your credit principal = {credit_principal}!")

        elif credit_principal_given and period_count_given and credit_interest_given:
            monthly_payment = math.ceil(credit_principal * ( (nominal_interest_rate * (1 + nominal_interest_rate)**period_count )/( (1 + nominal_interest_rate)**period_count - 1) ) )
            print(f"Your annuity payment = {monthly_payment}!")

    elif diff:
        sum_diff_payments = 0

        for month in range(1, period_count+1):
            diff_payment = (credit_principal/period_count) + (nominal_interest_rate * (credit_principal - ( (credit_principal * (month-1))/period_count ) ) )
            diff_payment = math.ceil(diff_payment)
            sum_diff_payments += diff_payment

            print(f"Month {month}: paid out {diff_payment}")

    overpayment = round(abs(credit_principal - (period_count * monthly_payment)))
    print(f"\nOverpayment = {overpayment}")

else:
    print("Incorrect parameters")


texts: PDO - configuration, database connection & and using

texts:
I'm currently reading a book and watching some tutorials about PHP with MySQL (PDO), but it is not clear where to put certain things - where to put some code, should I put the connection to the database within try-catch and so on.

So, I'll explain how I started my project and if you could tell me if this is wrong or is there a better way.

In the directory includes I have config.php:

<?php
defined('DB_DNS') ? null : define("DB_DNS", "mysql:host=localhost;dbname=photo_gallery");
defined('DB_USER')   ? null : define("DB_USER", "root");
defined('DB_PASS')   ? null : define("DB_PASS", "");

In the directory includes I have database.php:

 try {
   $connection= new PDO(DB_DNS, DB_USER, DB_PASS);
   $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 } catch(Exception $e) {
    echo "Error: ".$e->getMessage();
    die();
 }

In the directory includes I have user.php with a class named User:

 <?php

 require_once(__DIR__."/../includes/config.php");
 require_once(__DIR__."/../includes/database.php");

 class User
 {
   public function findAllUsers() {
      try {
        global $connection;
        $sql = $connection->prepare("SELECT * FROM users");
        $result = $sql->execute();
        return $result;
      } catch (Exception $e) {
         echo $e->getMessage();
         die();
      }
   }
   public function find_by_id($id = 0) {
      try {
        global $connection;
        $sql = $connection->prepare("SELECT * FROM users WHERE id = :id");
        $result = $sql->execute(array($id));
        return $result->fetch(PDO::FETCH_OBJ);
     } catch (Exception $e) {
        echo $e->getMessage();
        die();
    }
  }
}

Similar to this, some authors do tutorials and courses that I watch.


texts: Convert array of arrays to array without duplicates

texts:
I have the following array, and I want to convert it to an array without duplicates.

const a = [
    {
        items: [
            { outerKey: { innerKey: 1 } },
            { outerKey: { innerKey: 2 } },
            { outerKey: { innerKey: 3 } },
        ],
    },
    {
        items: [
            { outerKey: { innerKey: 3 } },
            { outerKey: { innerKey: 5 } },
            { outerKey: { innerKey: 5 } },
        ],
    },
    {
        items: [
            { outerKey: { innerKey: 1 } },
            { outerKey: { innerKey: 8 } },
            { outerKey: { innerKey: 2 } },
        ],
    },
];

const finalArray = [...new Set(a.reduce((acc, curr) =>  { acc.push(curr.items.map(item => item.outerKey.innerKey)); return acc;} , []).flat())];

console.log(finalArray);

Is there a better approach than this? considering there could be > 1000 items.