Best practise for handling hardware and software updates

Im part of a developement team working with machines. Recently due to increased demand for our product our team has grown to double its size during the past 1.5 years.

My question is regarding to what the best practise should be for keeping track of all our software updates. Let me explain. The machines are constantly improved hardware wise which means that we developers sometimes need to tweak the codebase a little. This in the end leads to the problem that we have a bunch of different, but similar, hardware configurations and a bunch of different, but similar, code packages.

As we grow this becomes a real issue keeping track of what update is pushed into which machine. Also, sometimes an update might need to be recoded a little to fit a certain machine. What i am looking for is, if there exists, a best practise or maybe even a project tool that helps my team to remember what goes where. Right now we are using an improvised board in Monday but we will outgrow it soon and need something more tangible in the long run.

Java: How do I read integer from the standard input, while handling error cases in a sophisticated way?

I want to read a simple integer from the console. But what if the user enters a string instead of an integer? How should I handle this case in a good manner? This is my code:

public static void main( String[] args )     {         Scanner keyboard = new Scanner(System.in);         System.out.println( "Please, enter the number of orders: " );         int orders = -1;         if (keyboard.hasNextInt()) {             orders = keyboard.nextInt() ;          } else {             System.out.println("Sorry, couldn't understand you!");         }     } 

Obviously it works, bit I am concerned that this solution was posted in 2010… is there a better way to handle such situation?

Prevent duplicate event handling

What is the best way of preventing of events from being handled more than once?

Imagine a system where customers can place orders and when successful an OrderCreated event is raised. There are some separate processes which listen to events on a message bus.

One process is to send an email to the customer, assume there is a requirement that the customer MUST be sent an email.

I imagine the email sending process would work in the following way:

  1. Send email
  2. Persist handled id
  3. Acknowledge the message bus

But if persisting the handled id fails the customer would get multiple emails.

The only other solution I thought of was to do the following:

  1. Persist attempt to handle event id
  2. Send email
  3. Persist handled event id
  4. Acknowledge the message bus

This would allow me to check whether the event was attempted to be handled before, and if so raise some error and ask a human whether to try and resend.

Are there any better ways to handle problems like these? I feel like this sort of thing would be a common problem but I can’t find a robust solution.

Design pattern that can be used for checking and handling a change in version number for incoming JSON message into data stream?

I have a Spark Streaming Job which processes messages coming from Kafka.

My incoming json that I process sort of looks like

{"sv" : 1.0, "field1" : "some data"} 

The only thing I do is put these in a MYSQL database.

However, I need to process these messages differently based on the schema version number!

For instance, I may get data that looks like the below in the same stream

{"sv" : 1.0, "field1" : "some data"}  {"sv" : 1.1, "field1" : "some data", "field2" : "new data"}  {"sv" : 1.2, "field1" : "some data", "field2" : "new data", "field3" : "data"} 

Now what I do is I have a function that formats the data for me like so

  def formatData(json: String): Option[Data] = {      var outputData: Option[Data] = None      val jsonObject = new JSONObject(json)      outputData = formatDataBasedOnSchemaVersion(jsonObject)      outputData    } 

and another function that formats based on a schema version number

  private def formatDataBasedOnSchemaVersion(jsonObject: JSONObject): Option[Data] = {      val outputData = {       jsonObject.getDouble("sv") match {         case 1.0 => Some(formatVersion_1_0(jsonObject))         case 1.1 => Some(formatVersion_1_1(jsonObject))         case 1.2 => Some(formatVersion_1_2(jsonObject))         case x: Double => logger.warn("No formatter found for schema version: " + x); None       }     }      outputData   } 

An example of my format function can look like

  private def formatVersion_1_2(jsonObject: JSONObject): Data = {      val f1 = jsonObject.getString("field1")     val f2 = jsonObject.getString("field2")     val f3 = jsonObject.getString("field3")      val data = Data(f1,f2,f3)      data    } 

In the format_1_0 function, all I do is pull out the “field1” parameter.

My Data class is simple DTO it just looks like

case class Data(field1: String, field2: String, field3: String) 

If I get schema version 1.0, field2 and field3 are left blank and inserted into the DB as blank values.

The problem is, I have to hard code in the schema version numbers like “1.0”, “1.1” etc.. and design a new method to pull out the extra fields. So for every schema change, I have to edit the code and add a new method to pull out the new data. So is there any better pattern I can use that can handle this? Or maybe a framework? I’ve heard of ORM would this help with that problem or would I still need to make similar code changes for schema version changes?

Data structure for handling intervals

I am trying to create a data structure for handling the subsets of the real line of the form $ [x,y)$ . That is, suppose $ X \subseteq \mathbb{R}$ and the data structure supports two types of operations: $ add(X, [x,y))$ and $ remove(X,[x,y))$ . Each of these two queries return the number of disjoint semi-intervals in $ X$ . For instance,

> add(X, [2, 10)) > 1 > add(X, [3, 9)) > 1 > add(X, [-1, 1)) > 2 > remove(X, [2, 10)) > 1 

I suspect that this can be realised with binary search tree, however I could not properly invent the behaviour. I still suspect this can be done in such a way that each query works in $ O(\log n)$ time, where $ n$ is the total number of queries. Can you please suggest anything?

Have apache run a script before handling request

I want to have Apache run a script every time it gets a request. To be clear I want apache to serve the actual file and just have this script called right before Apache handles the request (I have my own script that needs to do some custom logging).

I tried:

 <VirtualHost *:80>     ServerName voice1.example.org     DocumentRoot /var/www/html/     <directory "/">             Script GET "/test.php"     </directory>     ErrorLog /var/log/httpd/dovid.log     LogLevel info     CustomLog /var/log/httpd/dovid.access.log combined 

as well as

 <VirtualHost *:80>     ServerName voice1.example.org     DocumentRoot /var/www/html/     <directory "/">              Action pre-script /var/www/html/test.php             SetHandler pre-script     </directory>     ErrorLog /var/log/httpd/dovid.log     LogLevel info     CustomLog /var/log/httpd/dovid.access.log combined 

Both don’t seem to work. What am I doing wrong?

Argument handling for subclasses that use both `__init__` and `__new__`

I am making a subclass of a well-established python class: pendulum.Period, which overrides both __new__ and __init__ (it does this because it is subclassing the python builtin class timedelta, which uses __new__).

In my case, I want my class to handle a wider range of arguments than the superclass. The only way I have managed to get the code to work is to duplicate my handling code in both __new__ and __init__ — this is because, per the documentation, the arguments passed to __new__ are then passed to the __init__ of the new instance, unaltered.

The result is repeated code execution. Is this avoidable?

from pendulum import Period, Date  def _toDate(val):     """     Convert various inputs into a Date     """     if isinstance(val, int) or isinstance(val, float):         return Date.fromtimestamp(val)     elif isinstance(val, tuple):         return Date(*val)     return Date(val.year, val.month, val.day)   class MyInterval(Period):         def __new__(cls, start, end, inclusive=True, **kwargs):         start = _toDate(start)         end = _toDate(end)          if inclusive:             end = end.add(days=1)          return super(MyInterval, cls).__new__(cls, start, end, **kwargs)      def __init__(self, start, end, inclusive=True, **kwargs):         """         Creates a pendulum Period where the interval is limited to whole          days. Both are cast to dates, then the end date is incremented by          one day if inclusive=True         :param start: cast to date         :param end: cast to date         :param inclusive: [True] whether the last day of the interval should           be included (increments by 1 day)         """         start = _toDate(start)         end = _toDate(end)          if inclusive:             end = end.add(days=1)          super(MyInterval, self).__init__(start, end, **kwargs) 

Why is my TRY CATCH block in SQL Server immediately exiting on error completely ignoring the remaining code in the block, including my error handling?

Below is a snippet of my TRY/CATCH logic within a stored procedure with error handling (I did not include all of the DECLARE statements). This is being ran within a stored procedure, however I am simply testing this in a session via SSMS (would this affect the behavior?). I did stumble across this thread, but do I have to go to these lengths to simply capture errors?

BEGIN TRY DECLARE @sql varchar(1000); SET @sql = 'select 1/0'; EXEC(@sql); -- On Error the remaining TRY/CATCH below is compeltely ignored I discovered. DECLARE @error int; SET @error = @@error; IF @error > 0  BEGIN      SET @raisemessage = 'SQL Backup Error: ' + cast(@rc as varchar(10));          RAISERROR (@raisemessage, 16,1);  END END TRY  BEGIN CATCH     SET @errormessage = ERROR_MESSAGE();     IF @errormessage is null         SET @errormessage = ''         SET @errorstring = @errorstring + 'Database: ' + @name + '  Error: ' + @errormessage + char(10) + char(10); END CATCH 

Can anyone explain the shortcomings of this TRY/CATCH block? Does this not work in T-SQL?

Handling anonymous orders in custom commerce module

Drupal: 8.7.2 Commerce: 2.13

I have a custom module set up that adds the following functionality to Commerce:

  1. It prevents the user from adding more than one item to their cart. If they try to add a second item, it removes the first item from their cart and adds the second item.

  2. When clicking “Add to Cart”, it redirects the user to a confirmation page.

  3. On that page is a button that links to the order’s checkout page.

I am handling all of these via queries that use the user ID and order ID to pull the correct order/cart information.

This all works great for logged in users. Most of our customers will be anonymous, though. It does work for anonymous users, but my concern is that if multiple anonymous users are placing orders at the same time, their carts will get mixed up, because all anonymous users have a UID of 0.

How can I better differentiate between anonymous user’s carts? Is there a way to store their IP in the database, and then use that?

Here is my module’s code:

commerce_custom.module (handles removing first item from cart, redirecting to confirmation page):

<?php   use Drupal\Core\Form\FormStateInterface; use Drupal\commerce_order\Entity\Order; use Symfony\Component\HttpFoundation\RedirectResponse;  /**  * Implements hook_form_FORM_ID_alter().  */ function commerce_custom_form_commerce_order_item_add_to_cart_form_alter(&$  form, FormStateInterface $  form_state, $  form_id) {    $  form['actions']['submit']['#value']='Sponsor';    $  form['#validate'][] = 'commerce_custom_form_validate';    $  form['actions']['submit']['#submit'][] = 'commerce_custom_cart_alter_redirect'; }  function commerce_custom_form_validate(array &$  form, FormStateInterface $  form_state) {      $  user = \Drupal::currentUser()->id();     $  connection = \Drupal::database();     $  query = $  connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft'", [':user' => $  user]);     $  result = $  query->fetchAll();     //dpm($  result);      $  cart_count = $  result[0]->quantity;     $  order_id = $  result[0]->order_id;      if ($  cart_count > 0 && $  order_id) {         $  order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($  order_id);         $  items = $  order->getItems();         foreach($  items as $  item_key => $  item) {             $  order->removeItem($  item);             $  item->delete();         }     } }  function commerce_custom_cart_alter_redirect(&$  form, FormStateInterface $  form_state) {   $  responce =  new RedirectResponse('/how-it-works');   $  responce->send(); } 

ContinueCheckoutBlock.php (creates block with button linking to checkout page):

<?php  namespace Drupal\commerce_custom\Plugin\Block; use Drupal\Core\Block\BlockBase;  class ContinueCheckoutBlock extends BlockBase {     public function build() {          $  user = \Drupal::currentUser()->id();         $  connection = \Drupal::database();         $  query = $  connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft'", [':user' => $  user]);         $  result = $  query->fetchAll();         $  order_id = $  result[0]->order_id;          return array(             '#type' =>'markup',             '#markup' => '<a href=checkout/' . $  order_id . '/order_information class=button>Continue</a>',         );    } }