Prompting the user to input a data value into an element in a linked list

I’m working through a practice problem that is having me build and modify a linked list over a series of steps. I am particularly interested in knowing if there’s a more elegant way of prompting the user to input a data value for a new element in a linked list (see step 5 below).

I’d also like to know if there’s a better way of counting and returning the number of elements in a linked list.

Practice Problem:

  • Step 4: Add a function trav_and_print to your program that will traverse the linked list and print the values of all of the data members.
  • Step 5: Add code to your program that will add another element to the end of the linked list. Prompt the user for the data value. Call your trav_and_print function, and also from main print the value of last -> data to make sure that the element was added correctly.
  • Step 6: Add another function count_elems that will traverse the linked list, count how many elements there are, and return that count. Test this function by calling it in various places in main, including before there are any elements in the linked list.

My code thus far:

#include <stdio.h> #include <stdlib.h>  typedef struct linked_list {    int data;    struct linked_list *next; }   element;  typedef element * elementptr;  void trav_and_print(elementptr);  int count_elems(elemntptr);  int main() {    elementptr first = NULL;    elementptr last = NULL;    int var = 0;    int NumElems = 0;     /* Create a linked list with one element            */    /* NOTE: the first element is always a special case */     first = (elementptr) malloc(sizeof(element));    last = first;    last -> data = 5;    last -> next = NULL;     /* Add another element to the end of the list */     last -> next = (elementptr) malloc(sizeof(element));    last = last -> next;    last -> data = 12;    last -> next = NULL;     /*Add another element to the end of the list;    user generated number*/     last -> next = (elementptr) malloc(sizeof(element));    last = last -> next;    printf("Enter the data value to add to the linked list: ");    scanf("%d",&var);    last -> data = var;    last -> next = NULL;     trav_and_print(first); //prints the linked list     NumElems = count_elems(first); //traverses and counts the elements in the linked list     printf("Number of elements in the linked list: %d",NumElems);     free(first);    free(last);     return 0; } void trav_and_print(elementptr f) {     elementptr current;      current = f;     if(current == NULL)         printf("There is no linked list!\n");     else         while (current != NULL)     {         printf("The data value is %d\n",current->data);         current = current -> next;     } } int count_elems(elementptr f) {     int count = 0;     elementptr current;     current = f;     while(current != NULL)     {         current = current->next;         count++;     }     return count; } 

How the code be more pythonic

While this code is working fine, I am not sure if this is really well written, and pythonic. Also, I don’t really need ase_mod separate class. I could have done it in the same class, with functions. Kindly comment on this too.

Also, I want to parallelize over X loop, while the magn loop will be serial, with time.sleep(). Can I do that?

#!/usr/bin/env python3  import os, sys import math import as aio from ase.calculators.vasp import Vasp2 from ase import Atoms, Atom import shutil sys.tracebacklimit=None  # Global Variables root = os.getcwd() #Lattice Parameters lats  = ["6.148", "6.3162", "6.387", "6.137"] #MAX3 elements M = ["A", "B", "C", "D"] X = ["E"]  # Magnetic elements magn = ["Type0", "Type.5", "Type1"]  # Class to create vasp inputs. # Aim is to separate problem dependent part and general part class ase_mod():   '''Modules Based on ASE'''   def __init__(self):     self.tposcar=""    def genpos(self,a):     ''' Generate POSCAR:       genpos(argument)       argument: lattice parameter'''     try:       self.tposcar =,"nPOSCAR"))       cell = (self.tposcar.get_cell())       cell[0][0] = a       cell[1][1] = math.sqrt(3)*float(a)       self.tposcar.set_cell(cell, scale_atoms=True)       #  aio.write("POSCAR", tposcar, direct=True)     except:       help(genpos)       sys.exit()    def gen_baseINCAR(self):     '''Generate INCAR:       Here we are generating basic INCAR, common for all loops'''     self.calc = Vasp2(setups='recommended', prec="Accurate", encut=750, ismear=-5,                       sigma=0.01, nelmdl =-8, ispin=2, lreal="AUTO", lvdw=True, isym=2, nsw=200,                       ibrion=1, potim=0.3, lcharg="true", lwave=False, lorbit=11, npar=4,                       ldau=True, lmaxmix=4, ldautype=2, ldaul=[2, -1, -1], ldauu=[3.0, 0.0, 0.0],                       ldauj=[0.0, 0.0, 0.0], ldauprint=2, kpts=[5, 5, 1], istart=0                      )  class main():   def __init__(self, ase_mod):     # Init the ase_mod()     inits = ase_mod()      #Init genpos()     inits.genpos(lats[0])     aio.write("POSCAR", inits.tposcar, "vasp", vasp5=True)      for m in M:       for a in X:         sample= "-".join([m,a])         atomdir=os.path.join(root,sample)         for mag in magn:           magdir = os.path.join(atomdir, mag)           #Create vasp inputs           inits.gen_baseINCAR()           inits.calc.set(directory=magdir)           #  inits.calc.set(magmom=mmom[0])           inits.calc.write_input(inits.tposcar)           shutil.copy2('', magdir)           #  inits.tposcar.set_calculator(inits.calc)           #  print(inits.tposcar.get_magnetic_moment())   if __name__ =="__main__":   main(ase_mod) 

Implementing a Stack container adapter to check whether brackets are balanced

I am a beginner and I wanted to implement my own Stack container adaptor that uses a function that checks whether brackets are balanced or not. I tried implementing the function but I get an error of undefined reference to the Stack. I think this is because I made a wrong function call but I’m not sure. I’d really appreciate any help and corrections.

Header file

#ifndef STACK_H #define STACK_H  #include <iostream> #include <stdexcept>  template <typename T> class Stack {      struct Node {         T data;         Node* next;          Node(T const& data, Node* next)             : data(data), next(next) //initialisation         {}         Node(T&& data, Node* next)   // With C++11 allow move construction             : data(std::move(data)), next(next) //initialisation         {}     };  public:     ~Stack();     void push(T const& data);     void push(T&& data);     // WIth C++ 11 allow move construction     bool empty()const;     int size()const;     T top()const;     void pop();     void print(std::ostream& str = std::cout) const;   private:     Node*root = nullptr;     int elements = 0; };  #endif // STACK_H 

Implementation file

#include "Stack.h"  template<typename T> Stack<T>::~Stack() {     Node* next;     for(Node* loop = root; loop != nullptr; loop = next)     {         next = loop->next;         delete loop;     } }  template<typename T> void Stack<T>::push(T const& data) {     root = new Node(data, root);     ++elements; } template<typename T> void Stack<T>::push(T&& data) {     root = new Node(std::forward(data), root);     ++elements; } template<typename T> bool Stack<T>::empty() const {     return root == nullptr; }  template<typename T> int Stack<T>::size() const {     return elements; }  template<typename T> T Stack<T>::top() const {     if (root == nullptr)     {             throw std::runtime_error("Invalid Action");     }     return root->data; }  template<typename T> void Stack<T>::pop() {     if (root == nullptr)     {            throw std::runtime_error("Invalid Action");     }      Node*   tmp = root;     root    = root->next;     --elements;     delete tmp; }  template<typename T> void Stack<T>::print(std::ostream& str) const {     int id = 0;     for(Node* loop=root; loop != nullptr; loop=loop->next, ++id)     {         str << "Element: " << id << "  = " << loop->data << "\n";     } } 

Driver File

#include <iostream> #include <stdexcept> #include <iostream> #include <string> #include <cstdlib> #include <Stack.h>  using namespace std;  bool areParenthesisBalanced(string expression); int main() {     string expression = "{()}[]";      if(areParenthesisBalanced(expression))     {         cout << "Balanced! ";     }     else     {         cout << "Not Balanced!";     }      return 0; }  bool areParenthesisBalanced(string expression) {     Stack<char>s;     char x;      //Traversing the Expression     for(unsigned int i=0; i < expression.length(); i++)     {         if(expression[i]== '(' || expression[i]== '[' || expression[i]=='{')             {                 //Push the elements in the stack                 s.push(expression[i]);                 continue;             }                 //If current character is not an opening bracket, then it                  //must be a closing bracket.          //So stack cannot be empty at this point         if(s.empty())         {             return false;         }          switch(expression[i])         {         case ')':             //Store the element in a             x =;             s.pop();              if(x=='{' || x == '[')             {                 return false;             }             break;         case '}':             //Store the top element in b             x =;             s.pop();              if(x=='(' || x == '[')             {                 return false;             }             break;          case ']':             //Store the top element in b             x =;             s.pop();              if(x=='(' || x == '{')             {                 return false;             }             break;         }     }     //Check Empty Stack     return(s.empty()); } 

Reference in a nested struct

I would like to find an way to express the append_message() method so that I can hide away the serialisation.

use std::sync::{Arc, Mutex}; const NUM_BUFFERS: usize = 10; const BUF_SIZE: usize = 10;  #[derive(Copy, Clone)] struct Msg<'a> {     channel_id: usize,     msg_id: usize,     seq_id: usize,     end_seq_id: usize,     buf: &'a [u8], }  struct MsgMultiplexer<'a> {     count: usize,     buffers: [Msg<'a>; NUM_BUFFERS], }  struct Connection<'a> {     mplex: Arc<Mutex<MsgMultiplexer<'a>>>, }  impl<'a> Connection<'a> {     fn new_with_buffer() -> Connection<'a> {         let msg = Msg {             channel_id: 0,             msg_id: 0,             seq_id: 0,             end_seq_id: 0,             buf: &[],         };         Connection {             mplex: Arc::new(Mutex::new(MsgMultiplexer {                 count: 0,                 buffers: [msg; NUM_BUFFERS],             })             ),         }     }      // Multiplex the message     fn append_message<'b: 'a>(&self, channel: usize, msg: &'b [u8])     {        let cnt = msg.len() / BUF_SIZE + if msg.len() % BUF_SIZE > 0 { 1 } else { 0 };        for (seq,data) in msg.chunks(BUF_SIZE).enumerate() {         let msg = Msg {             channel_id: channel,             msg_id: 1234,             seq_id: seq,             end_seq_id: cnt,             buf: data,         };         if let Ok(mut mplex) = self.mplex.lock() {             let mcnt = mplex.count;             mplex.buffers[mcnt] = msg;             mplex.count += 1;             if mcnt == NUM_BUFFERS || seq == (cnt - 1) {                 mplex.count = 0;                 self.send();             }         }     } }       fn send(&self) {         // If message is complete OR all buffers used, send (whichever comes first)      }  }  #[cfg(test)] mod tests {     use super::*;      #[test]     fn protocol() {         let msg = Order {             id: 123,             price: 456.5,             size: 42,             asset: Asset::ALUMINIUM,             state: State::CANCEL,         };         let ser = serialize(&msg).unwrap();         let conn = Connection::new_with_buffer();         conn.append_message(123, &ser);     } } 

If I change append_message() to

fn append_message<'b: 'a, T>(&self, channel: usize, msg: &'b [u8]) where     T: Sized + Serialize, {    let ser = serialize(&msg).unwrap();     let cnt = ser.len() / BUF_SIZE + if ser.len() % BUF_SIZE > 0 { 1 } else { 0 };     for (seq, data) in ser.chunks(BUF_SIZE).enumerate() {         let msg = Msg {             channel_id: channel,             msg_id: 1234,             seq_id: seq,             end_seq_id: cnt,             buf: data,         };         if let Ok(mut mplex) = self.mplex.lock() {             let mcnt = mplex.count;             mplex.buffers[mcnt] = msg;             mplex.count += 1;             if mcnt == NUM_BUFFERS || seq == (cnt - 1) {                 mplex.count = 0;                 self.send();             }         }     } } 

I get an expected error that ser does not live long enough because it ties the mssage to the connection; but there’s no need for a message to live that long. I cannot see how to express that fact?

I understand that I could redefine Msg to contain a buf : Vec<u8> instead which solves the problem, but I don’t see the need moving the buffer in this case.

Accordion component with Angular 7

I have to made an accordion-, respectively “zippy”-component using Angular 7.

I’m new to Angular. Just started with it a few weeks ago. But with some Google-usage I was able to implement the required feature.

Here’s the way it looks.

In collapsed state:

Closed accordion

In expanded state:

Opened accordion

Here’s the code which I wrote for the accordion-component:

import {   Component,   OnInit,   Input } from '@angular/core'; import {   Title } from '@angular/platform-browser';  @Component({   selector: 'zippy',   templateUrl: './zippy.component.html',   styleUrls: ['./zippy.component.css'] }) export class ZippyComponent implements OnInit {   @Input() title;   isExpanded = false;   buttonCaption = "Expand";    constructor() {}    ngOnInit() {}    onClickButton() {     this.isExpanded = !this.isExpanded;     this.buttonCaption = this.isExpanded ? "Collapse" : "Expand";   } }
.container {   font-family: Arial, Helvetica, sans-serif;   max-width: 800px;   width: 100%;   margin: auto 2rem;   padding: 3rem 2rem;   border: 1px solid #555;   border-radius: 6px;   text-align: left;   font-size: 2rem;   margin-bottom: 1rem; }  nav {   display: flex;   justify-content: space-between; }  .container a {   text-decoration: none;   padding: 0.4rem 0.6rem;   font-size: 2rem;   color: #555; }  .container a:hover {   cursor: pointer; }  main {   padding: 0.25rem 1rem;   margin-top: 3rem;   background-color: #eee;   border-radius: 6px;   font-size: 1.4rem; }
<div class="container">   <nav>     <div>{{ title }}</div>     <div>       <a href="#" (click)="onClickButton()">         <i class="fas" [ngClass]="(isExpanded) ? 'fa-angle-up' : 'fa-angle-down'"></i>       </a>     </div>   </nav>   <main *ngIf="isExpanded">     <div class="content">       <ng-content></ng-content>     </div>   </main> </div>

The code of ‘app.component.html’:

<div style="text-align:center" class="wrap">   <zippy title="Shipping Details">     <p>Duo dolore sit et clita amet, aliquyam clita sed duo nonumy amet et et et. Rebum amet lorem stet est.</p>     <p>Prose and thy of have days heavenly. Parasites the not unto in so. Delphis yet friend drop cell caught mote, companie a gild favour and.</p>     <p>De quille inouies pieds blonds béni crépuscule les ravie fermentent, béhémots rutilements mer couleurs des de maries pénétra fortes folle. Je de dévorés suivi de. Impassibles liens a a papillon..</p>   </zippy>    <zippy title="Billing Details">     <p>Großer teuren gar im wie freunde du sanft wo, in du wo gar denkst weh liebe so ich dir. Kleinem zu spät du dann ort ort. Nun der denkst gesellschaft.</p>   </zippy> </div>

The functionality works but currently it just changes from collapsed to expanded state at once. It would be cool to have some animation or something similar when it changes. So that one has a “soft” transition.

If someone knows how to transition that I would love to read his / her answer.

All other hints, recommendations and critiques concerning my implementation welcomed as well.

Writing classes to withstand future business logic changes

I have a processor class AbstractProcessor and multiple concrete classes of the same which gets called in order of the business logic.

public Abstract class AbstractProcessor {    public void doProcess(){} } 

The logic in my concrete classes keeps on changing depending on the business requirement. This leads to change in the corresponding test classes and seems to be a tightly coupled approach. Is there a better way to design such classes.

Compiling and throwing simple dynamic excepitons at runtime for JVM

I’ve been using my Dynamic Exception with C# for quite some time already and it saved me a lot of time. This means, I don’t have to create a new exception class for each and every case. I wanted to have the same functionality on Android and in kotlin/java so I can do this:

fun main() {     throw dynamicException("My", "Hallo exception!") // throws MyException } 

The DynamicException.kt file contains most of the code where the dynamicException function first initializes the source-code for the new exception by formatting a String then it uses the JavaCompiler to build the class and call the appropriate construtor. Either with or without the inner exception.

import import java.lang.reflect.Constructor import import import import java.util.* import import import import  fun dynamicException(name: String, message: String, inner: Throwable? = null): java.lang.Exception {     val javaCompiler = ToolProvider.getSystemJavaCompiler()     val diagnosticCollector = DiagnosticCollector<JavaFileObject>()      val values = TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER)     values["name"] = name     var sourceCode = SourceCodeJavaFileObject(         "com.he-dev.$  {name}Exception",         dynamicExceptionSourceCode.smartFormat(values)     )     javaCompiler.getTask(         null,         null,         diagnosticCollector,         null,         null,         arrayListOf(sourceCode)     ).call()      val classLoader = URLClassLoader.newInstance(arrayOf<URL>(File("").toURI().toURL()))      var getCtor: () -> Constructor<out Any> = {         val cls = Class.forName("$  {name}Exception", true, classLoader)         val ctor = if (inner == null) {             cls.getConstructor(         } else {             cls.getConstructor(,         }         ctor.makeAccessible()     }      return if (inner == null) {         getCtor().newInstance(message) as java.lang.Exception     } else {         getCtor().newInstance(message, inner) as java.lang.Exception     } }  fun Constructor<out Any>.makeAccessible(): Constructor<out Any> {     this.isAccessible = true     return this }   val dynamicExceptionSourceCode: String = """ public class {Name}Exception extends java.lang.Exception {     public {Name}Exception(java.lang.String message) {         super(message);     }     public {Name}Exception(java.lang.String message, java.lang.Throwable inner) {         super(message, inner);     } } """.trimIndent()  class SourceCodeJavaFileObject : SimpleJavaFileObject {     private val sourceCode: CharSequence      constructor(className: String, sourceCode: CharSequence) :             super(                 URI.create("string:///" + className.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension),                 JavaFileObject.Kind.SOURCE             ) {         this.sourceCode = sourceCode     }      override fun getCharContent(ignoreEncodingErrors: Boolean): CharSequence {         return sourceCode     } } 

The string formatting is done with a string extension that can replace patterns. I based it on my C# formatter. However, it’s simpler because it doesn’t not support value formatting.

import java.util.*  fun String.smartFormat(values: TreeMap<String, String>): String {     val regex = Regex("""\{(?<name>[a-z][a-z0-9_.-]*)\}""", RegexOption.IGNORE_CASE)     return regex.replace(this) {         var key = it.groups["name"]?.value         if (values.containsKey(key)) values[key]!! else it.value     } } 

Is there anything that can be simplified or made even cleaner?

“Detailed” exception class hierarchy

I’m designing an modular exception class hierarchy to use in various projects. I intend to inherit from std::exception in order to be maximally compatible with any exception-handling code. A design goal is that each exception’s what() method returns a string which contains a base message, which is dependent on the object’s most specific class (i.e. equal for all objects of the class), and an optional instance-specific details message which specifies the origin of the exception.

The two main goals are ease of use (as in when throwing the exceptions), as well as ensuring that writing another exception subclass is as simple and repetition-free as possible.

Base class

The base exception class I wrote is the following. It is conceptually an abstract class, but not syntactically, since I don’t have any virtual method to make pure virtual. So, as an alternative, I made all constructors protected.

/**  * Base class for all custom exceptions. Stores a message as a string.  * Instances can only be constructed from within a child class,  * since the constructors are protected.  */ class BaseException : public std::exception { protected:     std::string message;  ///< message to be returned by what()      BaseException() = default;      /**      * Construct a new exception from a base message and optional additional details.      * The base message is intended to be class-specific, while the additional      * details string is intended to be instance-specific.      *      * @param baseMessage  generic message for the kind of exception being created      * @param details  additional information as to why the exception was thrown      */     BaseException(const std::string &baseMessage, const std::string &details = "") {         std::ostringstream oss(baseMessage, std::ios::ate);         if (not details.empty()) oss << " (" << details << ')';         message = oss.str();     }  public:     /// `std::exception`-compliant message getter     const char *what() const noexcept override {         return message.c_str();     } }; 

The intention of the above design is that any subclass of BaseException defines a constructor that passes a class-specific base message (as the baseMessage paramter) and an optional detail-specifier (as the details parameter) as arguments to BaseException‘s constructor.

Errors & warnings

Since I want to be able to differentiate between general exception “types”, e.g. errors vs. warnings, I’ve made the following two virtually-inherited bases:

class Error: public virtual BaseException {};  class Warning : public virtual BaseException {}; 


Here are some (project-specific) examples of implementing concrete exception subclasses with this design:

/// Indicates that a command whose keyword is unknown was issued class UnknownCommand : public Error { public:     static constexpr auto base = "unrecognized command";     UnknownCommand(const std::string &specific = "") : BaseException(base, specific) {} };   /// Indicates an error in reading or writing to a file class IOError : public Error { public:     static constexpr auto base = "unable to access file";     IOError(const std::string &specific = "") : BaseException(base, specific) {} };   /// Indicates that an algorithm encountered a situation in which it is not well-defined; /// i.e., a value that doesn't meet a function's prerequisites was passed. class ValueError : public Error { public:     static constexpr auto base = "invalid value";     ValueError(const std::string &specific = "") : BaseException(base, specific) {} };  # [...]  

As you can see, the common pattern is

class SomeException : public Error /* or Warning */ { public:     static constexpr auto base = "some exception's generic description";     SomeException(const std::string &details) : BaseException(base, details) {} } 

Usage example

Taking the previous IOError class as an example:

#include <iostream> #include <fstream> #include "exceptions.h"  // all of the previous stuff  void cat(const std::string &filename) {     std::ifstream file(filename);     if (not file.is_open()) throw IOError(filename);     std::cout << file.rdbuf(); }  int main(int argc, char **argv) {     for (int i = 1; i < argc; ++i) {         try { cat(argv[i]); }         catch (std::exception &e) { std::cerr << e.what() << '\n'; }     } } 

In case of calling the program with an inaccessible file path, e.g. the path “foo”, it should output

unable to access file (foo) 

bull and cow game

In a game of Bulls and Cows game, I want to be able to have a list of all guess and be able to remove the item from the list base on the result of each guess made by the AI. For instance, if the first generated guess was 2 bulls and 1 cow. i want to be able to check all the remaining number in the list to see which code match up bulls and 1 cows when the second guess is made. the numbers on the list that do not match should be remove from the list to ensure that each guess is consistance. currently the computer can make a guess when the user provide the secret number. But i need some direction to create a method that house the list of the possible random guess.

public   static int computeCows(String a, String b) {         int countCows=0;         for (int i = 0; i < a.length(); i++) {             for (int j = 0; j < b.length(); j++) {                 if (i != j) {                     if (a.charAt(i) == b.charAt(j)) {                         countCows++;                     }                 }             }         }          return countCows;      }      public static int computeBulls(String a, String b) {         int countBulls=0;          for (int i = 0; i < a.length(); i++) {             if (a.charAt(i) == b.charAt(i)) {                 countBulls++;             }         }         return countBulls;     }       public String generateRandomGuess() {         int randomGuess = 1;         String computerGeneratedGuess = "";         randomGuess = (int) ((Math.random() * 9000) + 1000);         computerGeneratedGuess = Integer.toString(randomGuess);//System.out.print((randomGuess));         return computerGeneratedGuess;     }       public static void main(String[] args) {         String SecretCode = "";         boolean checkpoint = true;         int bulls;         int cows;         int guesses = 1;         Scanner keybord = new Scanner(;         System.out.println("Enter secret code:");         SecretCode = keybord.nextLine();;         BcCount comguess=new BcCount();         BcCount bull=new BcCount();         BcCount cow=new BcCount();            while (checkpoint){              try {                  // System.out.print("Enter guess " + ": \n");                 //String guessedNumber = keybord.nextLine();                   //bulls =computeBulls(guessedNumber, bull.generateRandomGuess() );                 //cows = computeBulls(guessedNumber, cow.generateRandomGuess());                int combulls = computeBulls(SecretCode, bull.generateRandomGuess());                 int comcows = computeCows(SecretCode, cow.generateRandomGuess());                   String cumputerguess = comguess.generateRandomGuess();                  if (guesses >= 7) {                       System.out.println("Computer guess: " + cumputerguess);                     System.out.println(" Result: Bulls = " + combulls + "\tCows = " + comcows + "\n");                       System.out.println("The game was a Draw!");                     System.out.println("The correct computer secret was: " + cumputerguess);                     System.out.println("The correct user secret was: " + SecretCode);                     checkpoint = false;  //                } else if (bull == 4) { //                    System.out.println("You guess: " + guessedNumber); //                    System.out.println(" Result: Bulls = " + bulls + "\tCows = " + cows); //                    System.out.println(" You won with!:)" + "\n");                      checkpoint = false;                  } else {                     System.out.println("Computer guess: " + cumputerguess);                     System.out.println(" Result: Bulls = " + combulls + "\tCows = " + comcows + "\n");                      guesses++;                  }              } catch(NumberFormatException e){                 System.out.println(" Error: your guess should not contain non-digits." + e.getMessage());             } catch(StringIndexOutOfBoundsException e){                 System.out.println(" Error: Make sure your guess is four digit " + e.getMessage());              }       }           }