Monday, January 03, 2022
Bias and Variance in ML
Ruminating on high dimensional data
In simple terms, dimensions of a dataset refer to the number of attributes (or features) that a dataset has. This concept of dimensions of data is not new and quite common in the data warehousing world as explained here.
Many datasets can have a large number of features (variables/attributes) such as healthcare data, signal processing, bioinformatics. When the number of dimensions are staggeringly high, ML calculations become extremely difficult. It is also possible that the number of features can exceed the number of observations (or records in a dataset) - e.g. microarrays, which measure gene expression, can contain hundreds of samples/records, but each record can contain tens of thousands of genes.
In such highly dimensional data, we experience something called as the "Curse of dimensionality" - i.e. all records appear to be sparse and dissimilar in many ways, which prevents common data organization strategies from being efficient. The more dimensions we add to a data set, the more sparse the data becomes and this results in an exponential decrease in the ML model performance (i.e. predictive capabilities).
A typical rule of thumb is that there should be at least 5 training examples for each dimension in the dataset. Another interesting excerpt from Wikipedia is given below:
In machine learning and insofar as predictive performance is concerned, the curse of dimensionality is used interchangeably with the peaking phenomenon, which is also known as Hughes phenomenon. This phenomenon states that with a fixed number of training samples, the average (expected) predictive power of a classifier or regressor first increases as the number of dimensions or features used is increased but beyond a certain dimensionality it starts deteriorating instead of improving steadily.
To handle high dimensional datasets, data scientists typically perform various data dimension reduction techniques on the datasets - e.g. feature selection, feature projection, etc. More information about dimension reduction can be found here.
Thursday, December 30, 2021
Ruminating on ONNX format
Open Neural Network Exchange (ONNX) is an open standard format for representing machine learning models. While there are proprietary formats such as pickle (for Python) and MOJO (for H20 AI), there was a need to drive interoperability.
ONNX defines a common set of operators - the building blocks of machine learning and deep learning models - and a common file format to enable AI developers to use models with a variety of frameworks, tools, runtimes, and compilers. ONNX also provides a definition of an extensible computation graph model and each computation dataflow graph is structured as a list of nodes that form an acyclic graph. Nodes have one or more inputs and one or more outputs. Each node is a call to an operator. The entire source code of the standard is available here - https://github.com/onnx/
Thus ONNX enables an open ecosystem for interoperable AI models. The ONNX Model Zoo is a collection of pre-trained, state-of-the-art models in the ONNX format that can be easily reused in a plethora of AI frameworks. All popular AI frameworks such as TensorFlow, CoreML, Caffe2, PyTorch, Keras, etc. support ONNX.
There are also opensource tools that enable us to convert existing models into ONNX format - https://github.com/onnx/onnxmltools
ML Data Preparation - Impute missing values
In any AI project, data plumbing/engineering takes up 60-80% of the effort. Before training a model on the input dataset, we have to cleanse and standarize the dataset.
One common challenge is around missing values (features) in the dataset. We can either ignore these records or try to "impute" the value. The word "impute" means to assign a value to something by inference.
Since most AI models cannot work with blanks or NaN values (for numerical features), it is important to impute values of missing features in a recordset.
Given below are some of the techniques used to impute the value of missing features in the dataset.
- Numerical features: We can use the MEAN value of the feature or the MEDIAN value.
- Categorical features: For categorical features, we can use the most frequent value in the training dataset or we can use a constant like 'NA' or 'Not Available'.
Wednesday, December 29, 2021
Computer Vision Use Cases
viso.ai has published a series of interesting posts, where they list down a number of potential usecases of computer vision (CV) across various industries.
Posting a few links below:
https://viso.ai/applications/computer-vision-in-manufacturing/
https://viso.ai/applications/computer-vision-in-retail/
https://viso.ai/applications/computer-vision-in-healthcare/
Jotting down a few usecases, where we see traction in the industry:
- Quality inspection: CV can be used to inspect the final OEM product for quality defects - e.g. cracks on the surface, missing component in a PCB, dents on a metal surface, etc. Google has launched a specialized service for this called as Visual Inspection AI.
- Process monitoring: CV can ensure that proper guidelines are being followed during the manufacturing process - e.g. In meat plants, are knives steralized after each cut?, Are healthcare workers wearing helmets and hand gloves? Do workers keep the tools back in the correct location? You can also measure the time spent in specific factory floor areas to implement 'Lean Manufacturing'.
- Worker safety: Is a worker immobile for quite some time (potential accident?), Are they too many workers in a dangerous factory area? Are workers wearing proper protective gear? During Covid times, monitor the social distancing between workers and ensure compliance.
- Inventory management: Using drones (fitted with HD cameras) or even a simple smartphone, CV can be used to count the inventory of items in a warehouse. They can also be used for detecting unused space in the warehouse and automate many tasks in the supply chain.
- Predictive maintenance: Deep learning has been used to find cracks in industrial components such as spherical tanks and pressure vessels.
- Patient monitoring during surgeries: Just have a look at the cool stuff done by Gauss Surgical (https://www.gausssurgical.com/) With AI-enabled, real-time blood loss monitoring, Triton identifies four times more hemorrhages.
- Machine-assisted Diagnosis: CV can help radiologists in more accurate diagnosis of ailments and detect patterns and minor changes far better than humans. Siemens Healthineers is doing a lot of interesting AI work to assist radiologists. More info can be found here -- https://www.siemens-healthineers.com/digital-health-solutions/artificial-intelligence-in-healthcare
- Home-based patient monitoring: Detect human fall scenarios in old patients - at home or in elderly care centers.
- Retail heat maps: Test new merchandising strategies and experiment with various layouts.
- Customer behavior analysis: Track how much time a user has spent looking at a display item. What is the conversion rate?
- Loss prevention: Detect potential theft scenarios - e.g. suspicious behavior.
- Cashierless retail store: Amazon Go !
- Virtual mirrors: Equivalent of SnapChat filters where you can virtually try the new fashion.
- Crowd managment: Detect unsual crowds in public spaces and proactively take action.
Thursday, December 23, 2021
Ruminating on Stochastic vs Deterministic Models
The below article is an excellent read on the difference between stochastic forecasting and deterministic forecasting.
https://blog.ev.uk/stochastic-vs-deterministic-models-understand-the-pros-and-cons
Snippets from the article:
"A Deterministic Model allows you to calculate a future event exactly, without the involvement of randomness. If something is deterministic, you have all of the data necessary to predict (determine) the outcome with certainty.
Most financial planners will be accustomed to using some form of cash flow modelling tool powered by a deterministic model to project future investment returns. Typically, this is due to their simplicity. But this is fundamentally flawed when making financial planning decisions because they are unable to consider ongoing variables that will affect the plan over time.
Stochastic models possess some inherent randomness - the same set of parameter values and initial conditions will lead to an ensemble of different outputs. A stochastic model will not produce one determined outcome, but a range of possible outcomes, this is particularly useful when helping a customer plan for their future.
By running thousands of calculations, using many different estimates of future economic conditions, stochastic models predict a range of possible future investment results showing the potential upside and downsides of each."
Tuesday, December 14, 2021
Ruminating on Memory Mapped Files
Today, both Java and .NET have full support for memory mapped files. Memory mapped files are not only very fast for read/write operations, but they also serve another important function --- they can be shared between different processes. This enables us to use memory mapped files as shared data store for IPC.
The following excellent articles by Microsoft and MathWorks explains how to use memory mapped files.
https://docs.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files
https://www.mathworks.com/help/matlab/import_export/overview-of-memory-mapping.html
Snippets from the above articles:
A memory-mapped file contains the contents of a file in virtual memory. This mapping between a file and memory space enables an application, including multiple processes, to modify the file by reading and writing directly to the memory.
Memory-mapped files can be shared across multiple processes. Processes can map to the same memory-mapped file by using a common name that is assigned by the process that created the file.
Accessing files via memory map is faster than using I/O functions such as fread and fwrite. Data is read and written using the virtual memory capabilities that are built in to the operating system rather than having to allocate, copy into, and then deallocate data buffers owned by the process.
Memory-mapping works best with binary files, and in the following scenarios:
- For large files that you want to access randomly one or more times
- For small files that you want to read into memory once and access frequently
- For data that you want to share between applications
- When you want to work with data in a file as if it were an array
Due to limits set by the operating system, the maximum amount of data you can map with a single instance of a memory map is 2 gigabytes on 32-bit systems, and 256 terabytes on 64-bit systems.
Ruminating on TTS and ASR (STT)
Advances in deep neural networks have helped us build far more accurate voice bots. While adding a voice channel to a chatbot, there are two important services that are required:
1) TTS (text to Speech)
2) ASR/STT (Automatic Speech Recognition or Speech to Text)
For TTS, there are a lot of commerical cloud services available ---- few examples given below:
- https://aws.amazon.com/polly/
- https://azure.microsoft.com/en-us/services/cognitive-services/text-to-speech/#overview
- https://cloud.google.com/text-to-speech
- https://www.nuance.com/en-gb/omni-channel-customer-engagement/voice-and-ivr/text-to-speech.html
Similary for speech recognition, there are many commercial services available:
- https://aws.amazon.com/transcribe/
- https://azure.microsoft.com/en-us/services/cognitive-services/speech-to-text/
- https://cloud.google.com/speech-to-text
- https://www.nuance.com/en-gb/dragon.html
- https://www.speechly.com/
- MaryTTS: http://mary.dfki.de/
- Kaldi Speech recognition - https://kaldi-asr.org/doc/
- SoX sound processing - http://sox.sourceforge.net/
- Open Source Wrapper API - https://github.com/codeforequity-at/botium-speech-processing
- NVIDIA TTS - https://github.com/NVIDIA/tacotron2
- NVIDIA Speech Synthesis - https://github.com/NVIDIA/waveglow
- Mozilla TTS - https://github.com/mozilla/TTS
- Mozilla Speech to Text - https://github.com/mozilla/DeepSpeech
- Facebook STT - https://github.com/flashlight/wav2letter
Friday, September 24, 2021
Ruminating on R&D investment capitalization
When organizations invest in R&D activities, there are accounting rules for claiming tax credits. The reason governments give tax credits is to encourage innovation thorough R&D spending.
Earlier, the accounting rules mandated all R&D investments to be shown as "expenses" on the Profit and Loss (P&L) statement in the same year, the investments were made. But this poses a problem as the return of a R&D investment could be over multiple future years. Also R&D investments can vary widely every year and its net profit can be significantly higher or lower because of the timing of R&D spending.
Hence in the new accounting rules, instead of treating R&D investments as an "expense" in the P&L statement, it is treated as an "Asset" in the balance sheet. This is referred to as "Capitalizing the R&D expense".
Once the R&D investment is treated like an "Asset", the company can claim amortization (or depreciation) benefits on it over multiple years. For example - A software firm has invested 1 MM USD in R&D to build a product in 2021. The economic life of the built product is 5 years. The company can then amortize/depreciate the capitalized R&D expenses equally over the five-year life. This amortized amout per year is a line item in the yearly P&L statement.
A good explanation of this concept is given here - https://corporatefinanceinstitute.com/resources/knowledge/accounting/capitalizing-rd-expenses/
Wednesday, September 08, 2021
Ruminating on Systems Thinking
Systems Thinking is an approach towards problem solving that emphasizes the fact that most systems are complex and do not have a linear cause-effect relationship. We need to view the problem as part of a wider dynamic system and understand how different parts interact or influence one other.
The crux of systems thinking is the ability to zoom out and look at the big picture (holistic view) - to understand the various factors or perspectives that play a role.
By steering away from linear thinking into systems thinking, we will make better decisions in all aspects of business. System thinking also helps us to think in terms of ecosystems and not just be confined by traditional boundaries.
The following video is an excellent tutorial on Systems Thinking - https://youtu.be/GPW0j2Bo_eY
Other good links showing examples of system thinking:
- Use of DDT for mosquitos: https://thesystemsthinker.com/making-the-jump-to-systems-thinking/
- Systems thinking for water services - e.g. understanding the impact of rainfall, educating customers to improve the quality of wastewater, external factors such as new building development, rising river levels, etc : https://www.waterindustryjournal.co.uk/united-utilities-rolls-out-systems-thinking-approach-to-wastewater-network-management
Wednesday, September 01, 2021
Ruminating on Data Drift and Concept Drift
Quite often, the performance (accuracy of prediction) of a AI model degrades with time. One of the reasons this happens is due to a phenomenon called as "Data Drift".
So what exactly is Data Drift?
Data Drift can be defined as any change to the structure, semantics or statistical properties of data - i.e. model input data.
- Changes to structure of data: New fields being added or old field deleted. This could happen because of a new upgrade to a upstream system, a new sensor, etc.
- Changes to semantics of data: A new upstream system is sending temperature in F and not C.
- Changes to statistical properties of data: Changes to the atmospheric pressure threshold levels due to environmental changes. There could be also data quality issues such as a bug in upstream system that delivers junk data.
To maintain the accuracy of our AI models, it is imperative that we measure and monitor Data Drift. Our machine learning infrastructure needs to have tools that automatically detect data drift and can pin-point the features that are causing the drift.
Changes to the underlying statistical properties of data is also called as "Concept Drift". A classic example of this is the current pandemic. The "behaviour" or "concept" has changed after the pandemic - e.g. models that predict the amount of commute time are no longer valid. Models that forecasted the number of the cosmetic surgeries in 2021 are no longer valid.
Most of the hyperscalers provide services that enable us to monitor data drift and take proactive actions. The below links provide some examples of cloud services for data drift:
https://docs.microsoft.com/en-us/azure/machine-learning/how-to-monitor-datasets?tabs=python
Thursday, February 04, 2021
Process Discovery vs. Process Mining
The first step in automation is to gain a complete understanding of the current state business processes. Often enterprises do not have a knowledge base of all their existing processes and hence identifying automation opportunities becomes a challenge.
There are two techniques to address this challenge:
Process Discovery
Process Discovery tools typically record an end-user's interactions with the business applications. This recording is then intelligently transformed into process maps, BPMN diagrams and other technical documentation. The output from the Process Discovery tool can also be used to serve as a foundation for building automation bots. Given below are some examples of Process Discovery tools:
- https://www.atos-syntel.net/insights-and-resources/publications/syntbots-process-recorder
- https://www.uipath.com/product/task-capture
- https://www.automationanywhere.com/products/discovery-bot
- https://www.blueprism.com/products/process-assessment-tool/
Process Mining
Process Mining is all about extracting knowledge from event data. Today all IT systems and applications emit event logs that can be captured and analysed centrally using tools such as Splunk or ELK stack. As one can imagine, the biggest drawback of Process Mining is that it would not work if your legacy IT systems do not emit logs/events.
By analysing event data, Process Mining tools can model business process and also capture information on how the process performs in terms of latency, cost and other KPIs (from the log/event data).
Given below are some examples of Process Mining tools:
- https://www.uipath.com/product/task-mining & https://www.uipath.com/product/process-mining
- https://www.celonis.com/solutions/celonis-snap
- https://www.abbyy.com/timeline/
- https://fluxicon.com/disco/
Tuesday, February 02, 2021
Ticket Triaging with AI
The below link is a comprehensive article that introduces "ticket traiging" and also explains how AI can be used to automate this important step.
https://monkeylearn.com/blog/how-to-implement-a-ticket-triaging-system-with-ai/
Some snippets from the article:
"Automated ticket triaging involves evaluating and directing support tickets to the right person, quickly and effectively, and even sorting tickets in order of importance, topic or urgency. Triage powered by Natural Language Processing (NLP) technology is well-equipped to understand support ticket content to ensure the right ticket gets to the right agent.
NLP can process language like a human, by reading between the lines and detecting language variations, to make sense of text data before it categorizes it and allocates it to a customer support agent. The big advantages of using NLP is that it can triage faster, more accurately and more objectively than a human, making it a no-brainer for businesses when deciding to switch from manual triage to auto triage."
Wednesday, December 16, 2020
Ruminating on JAB (Java Access Bridge)
Quite often, we need to build automation around Java desktop apps. The default MS UI automation framework would not be able to identify Java UI components (based on Swing).
Hence we need to use a bridge..and this technology is called as JAB (Java Access Bridge). Using the JAB dll on windows, you can access Java client UI controls and build your automation use-case. All commercial tools such as UiPath, AA also use JAB behind the scenes for Java desktop automation.
Google has also released a cool tool called "Access Bridge Explorer" that can allows exploring, as well as interacting with, the Accessibility tree of any Java applications that uses the Java Access Bridge to expose their accessibility features,
Wednesday, October 28, 2020
Finding the .NET version on windows
In Java, you can execute a simple command "java -version", but unfortunately it is not so straightforward in .NET.
The below stackoverflow thread shows some commands that can be leveraged to find out the .NET version - https://stackoverflow.com/questions/1565434/how-do-i-find-the-net-version
The commands which worked for me on Win10 are as follows:
Command Prompt (cmd):
dir /b /ad /o-n %systemroot%\Microsoft.NET\Framework\v?.*
The above command will list down all versions of .NET except v4.5 and above.
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\full" /v version
The above command will work for .NET versions v4.5 and above.
PowerShell:
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | gp -name Version,Release -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version, Release
The above powershell command is the most versatile and will list down all versions.
Saturday, October 24, 2020
Ruminating on Ontology
Friday, October 02, 2020
Ruminating on Automation (RPA) Security Risks
Intelligent automation & RPA can drive operational efficiencies at organizations and help boost the productivity of enterprise resources. But there is also a risk of cyber-attacks as bots introduce a new attack surface for hackers.
Without proper measures, enterprises may face increased risk exposure due to bots. The following recommendations would enable organizations to mitigate the risk of such security attacks.
- Secure Vault: All credentials required by the bot to execute tasks on applications should be securely stored in a Vault (e.g. CyberArk or HashiCorp Vault). This ensures that the target application credentials are not stored by the bot and only accessed at runtime by the bot from the vault.
- Least Privilege Access: bots should not be given a blanket access to perform all operations, but should be given only appropriate access as required for the automation usecases - e.g. many automation usecases would entail 'read-only' access to databases/applications.
- Selecting appropriate Automation use-cases: While down-selecting automation usecases, it would be good to have 'Security Risk' as an parameter for assessment. If a bot needs admin access across multiple applications to perform critical business functions, then the organization can decide to NOT automate this usecase and handover the case to a knowledge worker. The bot can enable this smooth transition to humans (via a workflow or case management tool).
- Change Bot passwords/secure keys: As a security best practice, change the passwords and secure keys for the bots (and machines where bots run) regularly (e.g. once a month).
- Security Testing of Bots: Ultimately bots are also software components and we need to make sure that the bots undergo both static code security analysis and runtime security testing.
- Audit Trail & Proactive Monitoring: The automation framework should provide a detailed audit log of all bot activities. Each and every step executed by the bot should be available for forensic audit if required. Proactive monitoring of this audit log can also be automated to quickly alert users of any anomaly pattern or security breach.
- Governance Framework - Last but not the least, it is important to setup a proper governance framework for bot lifecycle management. The governance framework should clearly define the roles and responsibilities and the proper process to be followed for the entire bot lifecycle.
Thursday, August 27, 2020
Automating API creation over existing data-sources
If you need to quickly build REST APIs over existing data in excel sheets, RDBMS, NoSQL data stores; then the DreamFactory toolkit is immensely helpful.
DreamFactory is available under the Apache 2 license and you can host it on your public/private cloud platforms. Just with a few clicks, you will have a complete secure API service available to perform CRUD operations on your data. DreamFactory runs on the Apache LAMP stack ((Linux, Apache, MySQL, PHP/Perl/Python).
Besides generating the APIs, DreamFactory can also dynamically generate a Client SDK for HTML5 frameworks like jQuery, AngularJS, and Sencha, and a code library for native clients like iOS, Windows 8, and Android.
DreamFactory also has a toolkit to convert your SOAP webservices into REST APIs - https://www.dreamfactory.com/resources/video/how-turn-any-soap-web-service-rest-api/
It also has a cool feature called DataMesh wherein we can create virtual foreign key relationships between tables in the same database or between completely different databases without altering your schema or writing any code. Create, read, update, or delete objects and related objects with a single API call.
DreamFactory also automatically creates Swagger API documentation and has basic API Management capabilities built in (e.g. rate limiting)
Displaying PDF, Word, PPT docs on web pages
If you need to display documents in PDF, Word or PPT formats on your web application, then the following JavaScript toolkit will come to your rescue.
ViewerJS - https://viewerjs.org/
ViewerJS uses 2 other JS libraries behind the scenes - PDF.js (http://mozilla.github.io/pdf.js/) and WebODF (https://webodf.org/)
Any document that is following the Open Document Format (ODF) can be rendered using ViewerJS. All Office 365 files now follow the ODF format.
Wednesday, August 12, 2020
Ruminating on the hype around hyper-automation
So what exactly is hyper-automation?
In simple terms 'Hyper-Automation' is going beyond plain RPA. In RPA, the bot just mimics what a human would do.
But in hyper-automation, along with the RPA tool, we use other technologies like AI/ML, workflow engine, rules engine to automate E2E process flows. Thus we make the business process more streamlined and robust ---- essentially better than what the human was doing.
Even Process Discovery Tools are considered to be an important part of the hyper-automation journey. Process Discovery Tools enable us to understand the current state business processes and offers suggestions on streamlining it. It does not make sense to automate a fragmented process, but we should first streamline the process, remove redundancies and then automate it.
Example - A bot reading an unstructured email and understanding its intent, extracting relevant data points from it (AI) and completing the requested transaction via a desktop app (RPA).
Wednesday, June 24, 2020
Ruminating on Asynchronous Request-Reply pattern over HTTP
- The client sends a request and receives an HTTP 202 (Accepted) response.
- The client sends an HTTP GET request to the status endpoint. The work is still pending, so this call also returns HTTP 202.
- At some point, the work is complete and the status endpoint returns 302 (Found) redirecting to the resource.
- The client fetches the resource at the specified URL.
Sunday, May 31, 2020
Ruminating on Mutual Authentication
- Peer-2-Peer: Create a client certificate for each agent. Import this cert into the trust store of the server.
- Root cert derived client certifications: Create a client root certificate and using this root certificate, create/derive client certs for each agent. Then you just have to import the client root certificate into the server trust store ( and not of all the agents).
Thursday, May 28, 2020
Ruminating on Azure RTOS
- The most important characteristic of an RTOS is size. RTOS size is typically in KB, whereas general purpose OS is in MB or GB. Because of this size, RTOS can be used in the smallest of devices...even battery powered ones - e.g. fitness wearables, medical implants, etc. So essentially RTOS is great for constrained/smaller devices.
- RTOS is "real-time" because the OS responds to real time events in a deterministic time frame. An RTOS guarantees that certain actions can happen on IoT devices within defined time limits - a feature called as determinism.
- The size of Azure RTOS can scale down all the way to 2KB. A cloud connected RTOS would take 50KB.
- Azure RTOS also brings in best-of-class security with multiple security certifications.
- The complete source code of Azure RTOS is open-source and available on GitHub at https://github.com/azure-rtos
Sunday, May 24, 2020
Open DataSets
- https://www.openml.org/search?type=data
- https://archive.ics.uci.edu/ml/index.php
- https://www.reddit.com/r/datasets/
- http://academictorrents.com/browse.php
- https://www.opendatanetwork.com/
- https://www.data.gov/
- https://github.com/BuzzFeedNews/everything#standalone-datasets
- https://github.com/fivethirtyeight/data
- https://data.world/community/open-community/
- https://www.kaggle.com/datasets
Saturday, April 18, 2020
Performance instrumentation via DataDog
- Using StatsD: StatsD is a network daemon that runs on the Node.js platform and listens for statistics, like counters and timers, sent over UDP or TCP and sends aggregates to one or more pluggable backend services (e.g., Graphite, DataDog). StatsD is very popular and has become a de facto standard for collecting metrics. Opensource libraries are available in all popular languages to define and collect metrics. More information on StatsD can be found here - https://github.com/statsd/statsd.
- Using DogStatsD: DogStatsD is a custom daemon by DataDog. You can consider it as an extension over StatsD with support for many more metric types. This daemon needs to be installed on the node where you need to collect metrics. If a DataDog agent is already installed on the node, then this daemon is started by default. DataDog has also provided a java library for interfacing with DogStatsD. More information can be found here - https://docs.datadoghq.com/developers/dogstatsd/
- Using DataDog HTTP API: DataDog also exposes a REST API that can be used to push metrics to the DataDog server. But it does not make sense to push each and every metric using HTTP. We would need some kind of aggregator on the client side that would collate all data for a time period and then make a HTTP call to DataDog server. https://docs.datadoghq.com/api/
- Using JMX: DataDog agent can read data pushed to JMX console from JMX beans. Hence if you are already using JMX, then this is a good option to explore. https://docs.datadoghq.com/integrations/java/
- Using DropWizard bridge: If you are already using the popular DropWizard metrics library, then the developers at Coursera have created a neat opensource library that acts as a bridge between DropWizard and DataDog - https://github.com/coursera/metrics-datadog
- Using Micrometer Metrics Facade: If you are using Spring Boot, then this is the best seamless option available for you. Spring Boot Actuator has default support for Micrometer facade library and already provides a DataDogRepository implementation that can be used to push metrics to DataDog. The advantage of using Micrometer facade library is that we can switch to any other metrics backend easily - e.g. switching from DataDog to AWS CloudWatch. Also we can have composite repository wherein we can publish the same metrics to multiple backends.
https://git.io/JfJD8
Wednesday, April 15, 2020
Kafka poll() vs heatbeat()
But in latest versions of Kafka Consumer, a dedicated background heartbeat thread is started. This heartbeat thread sends periodic heartbeats to the broker to say -"Hey, I am alive and kicking!..I am processing messages and will poll() soon again".
Thus the newer versions of Kafka decouple polling functionality and heartbeat functionality. So now we have two threads running, the heartbeat thread and the processing thread (polling thread).
The heartbeat frequency is defined by the session.timeout.ms property (default = 10 secs)
Since there is a separate heartbeat thread now, the authors of Kafka Consumer decided to set the default for the polling timeout as INTEGER_MAX. (attribute: max.poll.interval.ms)
Hence no matter how long the processing takes (on the processing/polling thread), the Kafka broker will never consider the consumer to be dead. Only if no poll() request is received after INTERGER_MAX time, then the consumer would be considered dead.
.
Caveat: If your processing has a bug - (e.g. infinite loop, processing has called a third-party webservice and is stuck, etc.), then the consumer will never be pronounced dead and the messages will start getting piled up in that partition. Hence, it may be a good idea to set a realistic time for the polling() interval, so that we can rebalance the messages to other consumers.
The following 2 stackoverflow discussions were extremely beneficial to us to help us understand the above.
https://stackoverflow.com/questions/47906485/max-poll-intervals-ms-set-to-int-max-by-default
https://stackoverflow.com/questions/39730126/difference-between-session-timeout-ms-and-max-poll-interval-ms-for-kafka-0-10-0
Wednesday, January 22, 2020
Converting Java libraries to .NET DLLs
ikvmc -target:library {mylib.jar} ------- will create mylib.dll
Java libraries for SSH and Powershell automation
JSCH : http://www.jcraft.com/jsch/
JSch is a pure Java implementation of SSH2 and once you connect to a Linux server, you can execute all commands. A good tutorial is available here - https://linuxconfig.org/executing-commands-on-a-remote-machine-from-java-with-jsch
jPowerShell: https://github.com/profesorfalken/jPowerShell
This is a simple Java API that allows to interact with PowerShell console. Sample code below:
Saturday, June 08, 2019
On @Cacheable annotation of Spring
But it is important to not that the caching will NOT work if you are calling method is in the same class !
This happens because Spring injects a proxy at runtime to implement caching and if you are making calls to cacheable methods from the same class, the proxy is not used.
More information on this thread - https://stackoverflow.com/questions/16899604/spring-cache-cacheable-not-working-while-calling-from-another-method-of-the-s
Sunday, April 14, 2019
Ruminating on Digital Twin
Digital Twin of an Asset
Let's take for example a digital replica of a fixed asset like a CNC machine or a moving asset like a truck. Using the power of IoT, we could create a digital twin of the asset on the cloud that would have the same 'state' as the asset on the field
Once you have the digital twin of an asset on the cloud, you can realize business value from it in the following broad areas:
- Remote Monitoring and Diagnostics - using sensor data
- Predictive Maintenance - using ML
- Enhancing Product Quality - using closed loop engineering and integrating your PLM data and Field Service data with IoT data
- Transforming Consumer Experience - understand how consumers are using your products and build new differentiated digital capabilities such as hyper-personalization, etc.
